Merge branch '3.0' into feature/3.0_query_optimize

This commit is contained in:
wangmm0220 2022-08-12 14:41:08 +08:00
commit 61a19b80d7
970 changed files with 13172 additions and 48100 deletions

10
.gitignore vendored
View File

@ -118,4 +118,12 @@ contrib/*
!contrib/test !contrib/test
sql sql
debug*/ debug*/
.env .env
tools/README
tools/LICENSE
tools/README.1ST
tools/THANKS
tools/NEWS
tools/COPYING
tools/BUGS
tools/taos-tools

View File

@ -38,40 +38,21 @@ def pre_test(){
sh ''' sh '''
cd ${WK} cd ${WK}
git reset --hard git reset --hard
git remote prune origin
git fetch
cd ${WKC} cd ${WKC}
git reset --hard git reset --hard
git clean -fxd git clean -fxd
git remote prune origin
git fetch
''' '''
script { script {
if (env.CHANGE_TARGET == 'master') { sh '''
sh ''' cd ${WK}
cd ${WK} git checkout ''' + env.CHANGE_TARGET + '''
git checkout master cd ${WKC}
cd ${WKC} git checkout ''' + env.CHANGE_TARGET + '''
git checkout master '''
'''
} else if(env.CHANGE_TARGET == '2.0') {
sh '''
cd ${WK}
git checkout 2.0
cd ${WKC}
git checkout 2.0
'''
} else if(env.CHANGE_TARGET == '3.0') {
sh '''
cd ${WK}
git checkout 3.0
cd ${WKC}
git checkout 3.0
'''
} else {
sh '''
cd ${WK}
git checkout develop
cd ${WKC}
git checkout develop
'''
}
} }
if (env.CHANGE_URL =~ /\/TDengine\//) { if (env.CHANGE_URL =~ /\/TDengine\//) {
sh ''' sh '''
@ -169,49 +150,24 @@ def pre_test_win(){
bat ''' bat '''
cd %WIN_INTERNAL_ROOT% cd %WIN_INTERNAL_ROOT%
git reset --hard git reset --hard
git remote prune origin
git fetch
''' '''
bat ''' bat '''
cd %WIN_COMMUNITY_ROOT% cd %WIN_COMMUNITY_ROOT%
git reset --hard git reset --hard
git remote prune origin
git fetch
''' '''
script { script {
if (env.CHANGE_TARGET == 'master') { bat '''
bat ''' cd %WIN_INTERNAL_ROOT%
cd %WIN_INTERNAL_ROOT% git checkout ''' + env.CHANGE_TARGET + '''
git checkout master '''
''' bat '''
bat ''' cd %WIN_COMMUNITY_ROOT%
cd %WIN_COMMUNITY_ROOT% git checkout ''' + env.CHANGE_TARGET + '''
git checkout master '''
'''
} else if(env.CHANGE_TARGET == '2.0') {
bat '''
cd %WIN_INTERNAL_ROOT%
git checkout 2.0
'''
bat '''
cd %WIN_COMMUNITY_ROOT%
git checkout 2.0
'''
} else if(env.CHANGE_TARGET == '3.0') {
bat '''
cd %WIN_INTERNAL_ROOT%
git checkout 3.0
'''
bat '''
cd %WIN_COMMUNITY_ROOT%
git checkout 3.0
'''
} else {
bat '''
cd %WIN_INTERNAL_ROOT%
git checkout develop
'''
bat '''
cd %WIN_COMMUNITY_ROOT%
git checkout develop
'''
}
} }
script { script {
if (env.CHANGE_URL =~ /\/TDengine\//) { if (env.CHANGE_URL =~ /\/TDengine\//) {
@ -309,6 +265,7 @@ def pre_test_build_win() {
''' '''
bat ''' bat '''
cd %WIN_CONNECTOR_ROOT% cd %WIN_CONNECTOR_ROOT%
python.exe -m pip install --upgrade pip
python -m pip install . python -m pip install .
xcopy /e/y/i/f %WIN_INTERNAL_ROOT%\\debug\\build\\lib\\taos.dll C:\\Windows\\System32 xcopy /e/y/i/f %WIN_INTERNAL_ROOT%\\debug\\build\\lib\\taos.dll C:\\Windows\\System32
''' '''
@ -327,6 +284,7 @@ def run_win_test() {
bat ''' bat '''
echo "windows test ..." echo "windows test ..."
cd %WIN_CONNECTOR_ROOT% cd %WIN_CONNECTOR_ROOT%
python.exe -m pip install --upgrade pip
python -m pip install . python -m pip install .
xcopy /e/y/i/f %WIN_INTERNAL_ROOT%\\debug\\build\\lib\\taos.dll C:\\Windows\\System32 xcopy /e/y/i/f %WIN_INTERNAL_ROOT%\\debug\\build\\lib\\taos.dll C:\\Windows\\System32
ls -l C:\\Windows\\System32\\taos.dll ls -l C:\\Windows\\System32\\taos.dll

View File

@ -14,97 +14,60 @@
[![Build status](https://ci.appveyor.com/api/projects/status/kf3pwh2or5afsgl9/branch/master?svg=true)](https://ci.appveyor.com/project/sangshuduo/tdengine-2n8ge/branch/master) [![Build status](https://ci.appveyor.com/api/projects/status/kf3pwh2or5afsgl9/branch/master?svg=true)](https://ci.appveyor.com/project/sangshuduo/tdengine-2n8ge/branch/master)
[![Coverage Status](https://coveralls.io/repos/github/taosdata/TDengine/badge.svg?branch=develop)](https://coveralls.io/github/taosdata/TDengine?branch=develop) [![Coverage Status](https://coveralls.io/repos/github/taosdata/TDengine/badge.svg?branch=develop)](https://coveralls.io/github/taosdata/TDengine?branch=develop)
[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/4201/badge)](https://bestpractices.coreinfrastructure.org/projects/4201) [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/4201/badge)](https://bestpractices.coreinfrastructure.org/projects/4201)
[![tdengine](https://snapcraft.io//tdengine/badge.svg)](https://snapcraft.io/tdengine)
简体中文 | [English](README.md) | 很多职位正在热招中,请看[这里](https://www.taosdata.com/cn/careers/) 简体中文 | [English](README.md) | 很多职位正在热招中,请看[这里](https://www.taosdata.com/cn/careers/)
# TDengine 简介 # TDengine 简介
TDengine 是一款高性能、分布式、支持 SQL 的时序数据库Time-Series Database。而且除时序数据库功能外它还提供缓存、数据订阅、流式计算等功能最大程度减少研发和运维的复杂度且核心代码包括集群功能全部开源开源协议AGPL v3.0。与其他时序数据数据库相比TDengine 有以下特点 TDengine 是一款开源、高性能、云原生的时序数据库 (Time-Series Database, TSDB)。TDengine 能被广泛运用于物联网、工业互联网、车联网、IT 运维、金融等领域。除核心的时序数据库功能外TDengine 还提供缓存、数据订阅、流式计算等功能是一极简的时序数据处理平台最大程度的减小系统设计的复杂度降低研发和运营成本。与其他时序数据库相比TDengine 的主要优势如下
- **高性能**通过创新的存储引擎设计无论是数据写入还是查询TDengine 的性能比通用数据库快 10 倍以上,也远超其他时序数据库,而且存储空间也大为节省 - 高性能通过创新的存储引擎设计无论是数据写入还是查询TDengine 的性能比通用数据库快 10 倍以上,也远超其他时序数据库,存储空间不及通用数据库的1/10
- **分布式**通过原生分布式的设计TDengine 提供了水平扩展的能力,只需要增加节点就能获得更强的数据处理能力,同时通过多副本机制保证了系统的高可用 - 云原生通过原生分布式的设计充分利用云平台的优势TDengine 提供了水平扩展能力具备弹性、韧性和可观测性支持k8s部署可运行在公有云、私有云和混合云上
- **支持 SQL**TDengine 采用 SQL 作为数据查询语言,减少学习和迁移成本,同时提供 SQL 扩展来处理时序数据特有的分析,而且支持方便灵活的 schemaless 数据写入 - 极简时序数据平台TDengine 内建消息队列、缓存、流式计算等功能,应用无需再集成 Kafka/Redis/HBase/Spark 等软件,大幅降低系统的复杂度,降低应用开发和运营成本
- **All in One**:将数据库、消息队列、缓存、流式计算等功能融合一起,应用无需再集成 Kafka/Redis/HBase/Spark 等软件,大幅降低应用开发和维护成本 - 分析能力:支持 SQL同时为时序数据特有的分析提供SQL扩展。通过超级表、存储计算分离、分区分片、预计算、自定义函数等技术TDengine 具备强大的分析能力
- **零管理**:安装、集群几秒搞定,无任何依赖,不用分库分表,系统运行状态监测能与 Grafana 或其他运维工具无缝集成 - 简单易用无任何依赖安装、集群几秒搞定提供REST以及各种语言连接器与众多第三方工具无缝集成提供命令行程序便于管理和即席查询提供各种运维工具
- **零学习成本**:采用 SQL 查询语言,支持 Python、Java、C/C++、Go、Rust、Node.js 等多种编程语言,与 MySQL 相似,零学习成本。 - 核心开源TDengine 的核心代码包括集群功能全部开源截止到2022年8月1日全球超过 135.9k 个运行实例GitHub Star 18.7kFork 4.4k,社区活跃。
- **无缝集成**:不用一行代码,即可与 Telegraf、Grafana、EMQX、Prometheus、StatsD、collectd、Matlab、R 等第三方工具无缝集成。
- **互动 Console**: 通过命令行 console不用编程执行 SQL 语句就能做即席查询、各种数据库的操作、管理以及集群的维护.
TDengine 可以广泛应用于物联网、工业互联网、车联网、IT 运维、能源、金融等领域,让大量设备、数据采集器每天产生的高达 TB 甚至 PB 级的数据能得到高效实时的处理,对业务的运行状态进行实时的监测、预警,从大数据中挖掘出商业价值。
# 文档 # 文档
TDengine 采用传统的关系数据库模型,您可以像使用关系型数据库 MySQL 一样来使用它。但由于引入了超级表,一个采集点一张表的概念,建议您在使用前仔细阅读一遍下面的文档,特别是 [数据模型](https://www.taosdata.com/cn/documentation/architecture) 与 [数据建模](https://www.taosdata.com/cn/documentation/model)。除本文档之外,欢迎 [下载产品白皮书](https://www.taosdata.com/downloads/TDengine%20White%20Paper.pdf)。 关于完整的使用手册,系统架构和更多细节,请参考 [TDengine 文档](https://docs.taosdata.com) 或者 [English Documents](https://docs.tdengine.com)。
# 构建 # 构建
TDengine 目前 2.0 版服务器仅能在 Linux 系统上安装和运行,后续会支持 Windows、macOS 等系统。客户端可以在 Windows 或 Linux 上安装和运行。任何 OS 的应用也可以选择 RESTful 接口连接服务器 taosd。CPU 支持 X64/ARM64/MIPS64/Alpha64后续会支持 ARM32、RISC-V 等 CPU 架构。用户可根据需求选择通过[源码](https://www.taosdata.com/cn/getting-started/#通过源码安装)或者[安装包](https://www.taosdata.com/cn/getting-started/#通过安装包安装)来安装。本快速指南仅适用于通过源码安装。 TDengine 目前可以在 Linux、 Windows 等平台上安装和运行。任何 OS 的应用也可以选择 taosAdapter 的 RESTful 接口连接服务端 taosd。CPU 支持 X64/ARM64后续会支持 MIPS64、Alpha64、ARM32、RISC-V 等 CPU 架构。
用户可根据需求选择通过源码、[容器](https://docs.taosdata.com/3.0/get-started/docker/)、[安装包](https://docs.taosdata.com/3.0/get-started/package/)或[Kubenetes](https://docs.taosdata.com/3.0/deployment/k8s/)来安装。本快速指南仅适用于通过源码安装。
TDengine 还提供一组辅助工具软件 taosTools目前它包含 taosBenchmark曾命名为 taosdemo和 taosdump 两个软件。默认 TDengine 编译不包含 taosTools, 您可以在编译 TDengine 时使用`cmake .. -DBUILD_TOOLS=true` 来同时编译 taosTools。
## 安装工具 ## 安装工具
### Ubuntu 16.04 及以上版本 & Debian ### Ubuntu 18.04 及以上版本 & Debian
```bash ```bash
sudo apt-get install -y gcc cmake build-essential git libssl-dev sudo apt-get install -y gcc cmake build-essential git libssl-dev
``` ```
### Ubuntu 14.04
```bash
sudo apt-get install -y gcc cmake3 build-essential git binutils-2.26
export PATH=/usr/lib/binutils-2.26/bin:$PATH
```
编译或打包 JDBC 驱动源码,需安装 Java JDK 8 或以上版本和 Apache Maven 2.7 或以上版本。
安装 OpenJDK 8
```bash
sudo apt-get install -y openjdk-8-jdk
```
安装 Apache Maven
```bash
sudo apt-get install -y maven
```
#### 为 taos-tools 安装编译需要的软件 #### 为 taos-tools 安装编译需要的软件
taosTools 是用于 TDengine 的辅助工具软件集合。目前它包含 taosBenchmark曾命名为 taosdemo和 taosdump 两个软件。
默认 TDengine 编译不包含 taosTools。您可以在编译 TDengine 时使用`cmake .. -DBUILD_TOOLS=true` 来同时编译 taosTools。
为了在 Ubuntu/Debian 系统上编译 [taos-tools](https://github.com/taosdata/taos-tools) 需要安装如下软件: 为了在 Ubuntu/Debian 系统上编译 [taos-tools](https://github.com/taosdata/taos-tools) 需要安装如下软件:
```bash ```bash
sudo apt install build-essential libjansson-dev libsnappy-dev liblzma-dev libz-dev pkg-config sudo apt install build-essential libjansson-dev libsnappy-dev liblzma-dev libz-dev pkg-config
``` ```
### CentOS 7 ### CentOS 7.9
```bash ```bash
sudo yum install -y gcc gcc-c++ make cmake git openssl-devel sudo yum install epel-release
``` sudo yum update
sudo yum install -y gcc gcc-c++ make cmake3 git openssl-devel
安装 OpenJDK 8 sudo ln -sf /usr/bin/cmake3 /usr/bin/cmake
```bash
sudo yum install -y java-1.8.0-openjdk
```
安装 Apache Maven
```bash
sudo yum install -y maven
``` ```
### CentOS 8 & Fedora ### CentOS 8 & Fedora
@ -113,33 +76,33 @@ sudo yum install -y maven
sudo dnf install -y gcc gcc-c++ make cmake epel-release git openssl-devel sudo dnf install -y gcc gcc-c++ make cmake epel-release git openssl-devel
``` ```
安装 OpenJDK 8
```bash
sudo dnf install -y java-1.8.0-openjdk
```
安装 Apache Maven
```bash
sudo dnf install -y maven
```
#### 在 CentOS 上构建 taosTools 安装依赖软件 #### 在 CentOS 上构建 taosTools 安装依赖软件
为了在 CentOS 上构建 [taosTools](https://github.com/taosdata/taos-tools) 需要安装如下依赖软件 #### For CentOS 7/RHEL
```bash ```
sudo yum install zlib-devel xz-devel snappy-devel jansson jansson-devel pkgconfig libatomic libstdc++-static openssl-devel sudo yum install -y zlib-devel xz-devel snappy-devel jansson jansson-devel pkgconfig libatomic libstdc++-static openssl-devel
``` ```
注意:由于 snappy 缺乏 pkg-config 支持 #### For CentOS 8/Rocky Linux
(参考 [链接](https://github.com/google/snappy/pull/86)),会导致
cmake 提示无法发现 libsnappy实际上工作正常。 ```
sudo yum install -y epel-release
sudo yum install -y dnf-plugins-core
sudo yum config-manager --set-enabled powertools
sudo yum install -y zlib-devel xz-devel snappy-devel jansson jansson-devel pkgconfig libatomic libstdc++-static openssl-devel
```
注意:由于 snappy 缺乏 pkg-config 支持(参考 [链接](https://github.com/google/snappy/pull/86)),会导致 cmake 提示无法发现 libsnappy实际上工作正常。
若 powertools 安装失败,可以尝试改用:
```
sudo yum config-manager --set-enabled Powertools
```
### 设置 golang 开发环境 ### 设置 golang 开发环境
TDengine 包含数个使用 Go 语言开发的组件,请参考 golang.org 官方文档设置 go 开发环境。 TDengine 包含数个使用 Go 语言开发的组件,比如taosAdapter, 请参考 golang.org 官方文档设置 go 开发环境。
请使用 1.14 及以上版本。对于中国用户,我们建议使用代理来加速软件包下载。 请使用 1.14 及以上版本。对于中国用户,我们建议使用代理来加速软件包下载。
@ -148,6 +111,12 @@ go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct go env -w GOPROXY=https://goproxy.cn,direct
``` ```
缺省是不会构建 taosAdapter, 但您可以使用以下命令选择构建 taosAdapter 作为 RESTful 接口的服务。
```
cmake .. -DBUILD_HTTP=false
```
### 设置 rust 开发环境 ### 设置 rust 开发环境
TDengine 包含数个使用 Rust 语言开发的组件. 请参考 rust-lang.org 官方文档设置 rust 开发环境。 TDengine 包含数个使用 Rust 语言开发的组件. 请参考 rust-lang.org 官方文档设置 rust 开发环境。
@ -195,7 +164,7 @@ apt install autoconf
cmake .. -DJEMALLOC_ENABLED=true cmake .. -DJEMALLOC_ENABLED=true
``` ```
在 X86-64、X86、arm64、arm32 和 mips64 平台上TDengine 生成脚本可以自动检测机器架构。也可以手动配置 CPUTYPE 参数来指定 CPU 类型,如 aarch64 或 aarch32 等。 在 X86-64、X86、arm64 平台上TDengine 生成脚本可以自动检测机器架构。也可以手动配置 CPUTYPE 参数来指定 CPU 类型,如 aarch64 等。
aarch64 aarch64
@ -203,18 +172,6 @@ aarch64
cmake .. -DCPUTYPE=aarch64 && cmake --build . cmake .. -DCPUTYPE=aarch64 && cmake --build .
``` ```
aarch32
```bash
cmake .. -DCPUTYPE=aarch32 && cmake --build .
```
mips64
```bash
cmake .. -DCPUTYPE=mips64 && cmake --build .
```
### Windows 系统 ### Windows 系统
如果你使用的是 Visual Studio 2013 版本: 如果你使用的是 Visual Studio 2013 版本:
@ -300,24 +257,6 @@ nmake install
sudo make install sudo make install
``` ```
安装成功后,如果想以服务形式启动,先配置 `.plist` 文件,在终端中执行:
```bash
sudo cp ../packaging/macOS/com.taosdata.tdengine.plist /Library/LaunchDaemons
```
在终端中启动 TDengine 服务:
```bash
sudo launchctl load /Library/LaunchDaemons/com.taosdata.tdengine.plist
```
在终端中停止 TDengine 服务:
```bash
sudo launchctl unload /Library/LaunchDaemons/com.taosdata.tdengine.plist
```
## 快速运行 ## 快速运行
如果不希望以服务方式运行 TDengine也可以在终端中直接运行它。也即在生成完成后执行以下命令在 Windows 下,生成的可执行文件会带有 .exe 后缀,例如会名为 taosd.exe 如果不希望以服务方式运行 TDengine也可以在终端中直接运行它。也即在生成完成后执行以下命令在 Windows 下,生成的可执行文件会带有 .exe 后缀,例如会名为 taosd.exe
@ -358,33 +297,14 @@ Query OK, 2 row(s) in set (0.001700s)
TDengine 提供了丰富的应用程序开发接口,其中包括 C/C++、Java、Python、Go、Node.js、C# 、RESTful 等,便于用户快速开发应用: TDengine 提供了丰富的应用程序开发接口,其中包括 C/C++、Java、Python、Go、Node.js、C# 、RESTful 等,便于用户快速开发应用:
- [Java](https://www.taosdata.com/cn/documentation/connector/java) - [Java](https://docs.taosdata.com/reference/connector/java/)
- [C/C++](https://www.taosdata.com/cn/documentation/connector#c-cpp) - [C/C++](https://www.taosdata.com/cn/documentation/connector#c-cpp)
- [Python](https://docs.taosdata.com/reference/connector/python/)
- [Python](https://www.taosdata.com/cn/documentation/connector#python) - [Go](https://docs.taosdata.com/reference/connector/go/)
- [Node.js](https://docs.taosdata.com/reference/connector/node/)
- [Go](https://www.taosdata.com/cn/documentation/connector#go) - [Rust](https://docs.taosdata.com/reference/connector/rust/)
- [C#](https://docs.taosdata.com/reference/connector/csharp/)
- [RESTful API](https://www.taosdata.com/cn/documentation/connector#restful) - [RESTful API](https://docs.taosdata.com/reference/rest-api/)
- [Node.js](https://www.taosdata.com/cn/documentation/connector#nodejs)
- [Rust](https://www.taosdata.com/cn/documentation/connector/rust)
## 第三方连接器
TDengine 社区生态中也有一些非常友好的第三方连接器,可以通过以下链接访问它们的源码。
- [Rust Bindings](https://github.com/songtianyi/tdengine-rust-bindings/tree/master/examples)
- [.Net Core Connector](https://github.com/maikebing/Maikebing.EntityFrameworkCore.Taos)
- [Lua Connector](https://github.com/taosdata/TDengine/tree/develop/examples/lua)
# 运行和添加测试例
TDengine 的测试框架和所有测试例全部开源。
点击 [这里](https://github.com/taosdata/TDengine/blob/develop/tests/How-To-Run-Test-And-How-To-Add-New-Test-Case.md),了解如何运行测试例和添加新的测试例。
# 成为社区贡献者 # 成为社区贡献者
@ -393,7 +313,3 @@ TDengine 的测试框架和所有测试例全部开源。
# 加入技术交流群 # 加入技术交流群
TDengine 官方社群「物联网大数据群」对外开放,欢迎您加入讨论。搜索微信号 "tdengine",加小 T 为好友,即可入群。 TDengine 官方社群「物联网大数据群」对外开放,欢迎您加入讨论。搜索微信号 "tdengine",加小 T 为好友,即可入群。
# [谁在使用 TDengine](https://github.com/taosdata/TDengine/issues/2432)
欢迎所有 TDengine 用户及贡献者在 [这里](https://github.com/taosdata/TDengine/issues/2432) 分享您在当前工作中开发/使用 TDengine 的故事。

179
README.md
View File

@ -20,78 +20,49 @@ English | [简体中文](README-CN.md) | We are hiring, check [here](https://tde
# What is TDengine # What is TDengine
TDengine is a high-performance, scalable time-series database with SQL support. Its code including cluster feature is open source under [GNU AGPL v3.0](http://www.gnu.org/licenses/agpl-3.0.html). Besides the database, it provides caching, stream processing, data subscription and other functionalities to reduce the complexity and cost of development and operation. TDengine differentiates itself from other TSDBs with the following advantages. TDengine is an open source, cloud native time-series database optimized for Internet of Things (IoT), Connected Cars, and Industrial IoT. It enables efficient, real-time data ingestion, processing, and monitoring of TB and even PB scale data per day, generated by billions of sensors and data collectors. TDengine differentiates itself from other TSDBs with the following advantages.:
- **High Performance**: TDengine outperforms other time series databases in data ingestion and querying while significantly reducing storage cost and compute costs, with an innovatively designed and purpose-built storage engine. - High-Performance: TDengine is the only time-series database to solve the high cardinality issue to support billions of data collection points while out performing other time-series databases for data ingestion, querying and data compression.
- **Scalable**: TDengine provides out-of-box scalability and high-availability through its native distributed design. Nodes can be added through simple configuration to achieve greater data processing power. In addition, this feature is open source. - Simplified Solution: Through built-in caching, stream processing and data subscription features, TDengine provides a simplified solution for time-series data processing. It reduces system design complexity and operation costs significantly.
- **SQL Support**: TDengine uses SQL as the query language, thereby reducing learning and migration costs, while adding SQL extensions to handle time-series data better, and supporting convenient and flexible schemaless data ingestion. - Cloud Native: Through native distributed design, sharding and partitioning, separation of compute and storage, RAFT, support for kubernetes deployment and full observability, TDengine is a cloud native Time-Series Database and can be deployed on public, private or hybrid clouds.
- **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. - Ease of Use: For administrators, TDengine significantly reduces the effort to deploy and maintain. For developers, it provides a simple interface, simplified solution and seamless integrations for third party tools. For data users, it gives easy data access.
- **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. - Easy Data Analytics: Through super tables, storage and compute separation, data partitioning by time interval, pre-computation and other means, TDengine makes it easy to explore, format, and get access to data in a highly efficient way.
- **Zero Management**: Installation and cluster setup can be done in seconds. Data partitioning and sharding are executed automatically. TDengines running status can be monitored via Grafana or other DevOps tools. - Open Source: TDengines core modules, including cluster feature, are all available under open source licenses. It has gathered 18.8k stars on GitHub, an active developer community, and over 137k running instances worldwide.
- **Zero Learning Cost**: With SQL as the query language, support for ubiquitous tools like Python, Java, C/C++, Go, Rust, Node.js connectors, there is zero learning cost.
- **Interactive Console**: TDengine provides convenient console access to the database to run ad hoc queries, maintain the database, or manage the cluster without any programming.
TDengine can be widely applied to Internet of Things (IoT), Connected Vehicles, Industrial IoT, DevOps, energy, finance and many other scenarios.
# Documentation # Documentation
For user manual, system design and architecture, engineering blogs, refer to [TDengine Documentation](https://www.taosdata.com/en/documentation/)(中文版请点击[这里](https://www.taosdata.com/cn/documentation20/)) For user manual, system design and architecture, please refer to [TDengine Documentation](https://docs.tdengine.com) ([中文版](https://docs.taosdata.com))
for details. The documentation from our website can also be downloaded locally from _documentation/tdenginedocs-en_ or _documentation/tdenginedocs-cn_.
# Building # Building
At the moment, TDengine server only supports running on Linux systems. You can choose to [install from packages](https://www.taosdata.com/en/getting-started/#Install-from-Package) or build it from the source code. This quick guide is for installation from the source only. At the moment, TDengine server supports running on Linux, Windows, and macOS systems. You can choose to [install from packages](https://www.tdengine.com/getting-started/#Install-from-Package) or build it from the source code. This quick guide is for installation from the source only.
We provide a few useful tools such as taosBenchmark (was named taosdemo) and taosdump. They were part of TDengine. By default, TDengine compiling does not include taosTools. You can use 'cmake .. -DBUILD_TOOLS=true' to make them be compiled with TDengine.
To build TDengine, use [CMake](https://cmake.org/) 3.0.2 or higher versions in the project directory. To build TDengine, use [CMake](https://cmake.org/) 3.0.2 or higher versions in the project directory.
## Install build dependencies ## Install build dependencies
### Ubuntu 16.04 and above or Debian ### Ubuntu 18.04 and above or Debian
```bash ```bash
sudo apt-get install -y gcc cmake build-essential git libssl-dev sudo apt-get install -y gcc cmake build-essential git libssl-dev
``` ```
### Ubuntu 14.04
```bash
sudo apt-get install -y gcc cmake3 build-essential git binutils-2.26
export PATH=/usr/lib/binutils-2.26/bin:$PATH
```
To compile and package the JDBC driver source code, you should have a Java jdk-8 or higher and Apache Maven 2.7 or higher installed.
To install openjdk-8:
```bash
sudo apt-get install -y openjdk-8-jdk
```
To install Apache Maven:
```bash
sudo apt-get install -y maven
```
#### Install build dependencies for taosTools #### Install build dependencies for taosTools
We provide a few useful tools such as taosBenchmark (was named taosdemo) and taosdump. They were part of TDengine. From TDengine 2.4.0.0, taosBenchmark and taosdump were not released together with TDengine.
By default, TDengine compiling does not include taosTools. You can use 'cmake .. -DBUILD_TOOLS=true' to make them be compiled with TDengine.
To build the [taosTools](https://github.com/taosdata/taos-tools) on Ubuntu/Debian, the following packages need to be installed. To build the [taosTools](https://github.com/taosdata/taos-tools) on Ubuntu/Debian, the following packages need to be installed.
```bash ```bash
sudo apt install build-essential libjansson-dev libsnappy-dev liblzma-dev libz-dev pkg-config sudo apt install build-essential libjansson-dev libsnappy-dev liblzma-dev libz-dev pkg-config
``` ```
### CentOS 7 ### CentOS 7.9
```bash ```bash
sudo yum install epel-release sudo yum install epel-release
@ -100,36 +71,12 @@ sudo yum install -y gcc gcc-c++ make cmake3 git openssl-devel
sudo ln -sf /usr/bin/cmake3 /usr/bin/cmake sudo ln -sf /usr/bin/cmake3 /usr/bin/cmake
``` ```
To install openjdk-8:
```bash
sudo yum install -y java-1.8.0-openjdk
```
To install Apache Maven:
```bash
sudo yum install -y maven
```
### CentOS 8 & Fedora ### CentOS 8 & Fedora
```bash ```bash
sudo dnf install -y gcc gcc-c++ make cmake epel-release git openssl-devel sudo dnf install -y gcc gcc-c++ make cmake epel-release git openssl-devel
``` ```
To install openjdk-8:
```bash
sudo dnf install -y java-1.8.0-openjdk
```
To install Apache Maven:
```bash
sudo dnf install -y maven
```
#### Install build dependencies for taosTools on CentOS #### Install build dependencies for taosTools on CentOS
To build the [taosTools](https://github.com/taosdata/taos-tools) on CentOS, the following packages need to be installed. To build the [taosTools](https://github.com/taosdata/taos-tools) on CentOS, the following packages need to be installed.
@ -138,11 +85,11 @@ To build the [taosTools](https://github.com/taosdata/taos-tools) on CentOS, the
sudo yum install zlib-devel xz-devel snappy-devel jansson jansson-devel pkgconfig libatomic libstdc++-static openssl-devel sudo yum install zlib-devel xz-devel snappy-devel jansson jansson-devel pkgconfig libatomic libstdc++-static openssl-devel
``` ```
Note: Since snappy lacks pkg-config support (refer to [link](https://github.com/google/snappy/pull/86)), it lead a cmake prompt libsnappy not found. But snappy will works well. Note: Since snappy lacks pkg-config support (refer to [link](https://github.com/google/snappy/pull/86)), it leads a cmake prompt libsnappy not found. But snappy still works well.
### Setup golang environment ### Setup golang environment
TDengine includes few components developed by Go language. Please refer to golang.org official documentation for golang environment setup. TDengine includes a few components like taosAdapter developed by Go language. Please refer to golang.org official documentation for golang environment setup.
Please use version 1.14+. For the user in China, we recommend using a proxy to accelerate package downloading. Please use version 1.14+. For the user in China, we recommend using a proxy to accelerate package downloading.
@ -153,7 +100,7 @@ go env -w GOPROXY=https://goproxy.cn,direct
### Setup rust environment ### Setup rust environment
TDengine includees few compoments developed by Rust language. Please refer to rust-lang.org official documentation for rust environment setup. TDengine includes a few compoments developed by Rust language. Please refer to rust-lang.org official documentation for rust environment setup.
## Get the source codes ## Get the source codes
@ -166,7 +113,7 @@ cd TDengine
The connectors for go & Grafana and some tools have been moved to separated repositories. The connectors for go & Grafana and some tools have been moved to separated repositories.
You can modify the file ~/.gitconfig to use ssh protocol instead of https for better download speed. You need to upload ssh public key to GitHub first. Please refer to GitHub official documentation for detail. You can modify the file ~/.gitconfig to use ssh protocol instead of https for better download speed. You will need to upload ssh public key to GitHub first. Please refer to GitHub official documentation for detail.
``` ```
[url "git@github.com:"] [url "git@github.com:"]
@ -192,14 +139,7 @@ cmake .. -DBUILD_TOOLS=true
make make
``` ```
Note TDengine 2.3.x.0 and later use a component named 'taosAdapter' to play http daemon role by default instead of the http daemon embedded in the early version of TDengine. The taosAdapter is programmed by go language. If you pull TDengine source code to the latest from an existing codebase, please execute 'git submodule update --init --recursive' to pull taosAdapter source code. Please install go language version 1.14 or above for compiling taosAdapter. If you meet difficulties regarding 'go mod', especially you are from China, you can use a proxy to solve the problem. Note TDengine 2.3.x.0 and later use a component named 'taosAdapter' to play http daemon role. If you pull TDengine source code to the latest from an existing codebase, please execute 'git submodule update --init --recursive' to pull taosAdapter source code, and use the following command to choose to build taosAdapter.
```
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
```
The embedded http daemon still be built from TDengine source code by default. Or you can use the following command to choose to build taosAdapter.
``` ```
cmake .. -DBUILD_HTTP=false cmake .. -DBUILD_HTTP=false
@ -212,8 +152,8 @@ apt install autoconf
cmake .. -DJEMALLOC_ENABLED=true cmake .. -DJEMALLOC_ENABLED=true
``` ```
TDengine build script can detect the host machine's architecture on X86-64, X86, arm64, arm32 and mips64 platform. TDengine build script can detect the host machine's architecture on X86-64, X86, arm64 platform.
You can also specify CPUTYPE option like aarch64 or aarch32 too if the detection result is not correct: You can also specify CPUTYPE option like aarch64 too if the detection result is not correct:
aarch64: aarch64:
@ -221,22 +161,10 @@ aarch64:
cmake .. -DCPUTYPE=aarch64 && cmake --build . cmake .. -DCPUTYPE=aarch64 && cmake --build .
``` ```
aarch32:
```bash
cmake .. -DCPUTYPE=aarch32 && cmake --build .
```
mips64:
```bash
cmake .. -DCPUTYPE=mips64 && cmake --build .
```
### On Windows platform ### On Windows platform
If you use the Visual Studio 2013, please open a command window by executing "cmd.exe". If you use the Visual Studio 2013, please open a command window by executing "cmd.exe".
Please specify "amd64" for 64 bits Windows or specify "x86" is for 32 bits Windows when you execute vcvarsall.bat. Please specify "amd64" for 64 bits Windows or specify "x86" for 32 bits Windows when you execute vcvarsall.bat.
```cmd ```cmd
mkdir debug && cd debug mkdir debug && cd debug
@ -248,7 +176,7 @@ nmake
If you use the Visual Studio 2019 or 2017: If you use the Visual Studio 2019 or 2017:
please open a command window by executing "cmd.exe". please open a command window by executing "cmd.exe".
Please specify "x64" for 64 bits Windows or specify "x86" is for 32 bits Windows when you execute vcvarsall.bat. Please specify "x64" for 64 bits Windows or specify "x86" for 32 bits Windows when you execute vcvarsall.bat.
```cmd ```cmd
mkdir debug && cd debug mkdir debug && cd debug
@ -301,19 +229,6 @@ taos
If TDengine shell connects the server successfully, welcome messages and version info are printed. Otherwise, an error message is shown. If TDengine shell connects the server successfully, welcome messages and version info are printed. Otherwise, an error message is shown.
### Install TDengine by apt-get
If you use Debian or Ubuntu system, you can use 'apt-get' command to install TDengine from official repository. Please use following commands to setup:
```
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-cache policy tdengine
sudo apt-get install tdengine
```
## On Windows platform ## On Windows platform
After building successfully, TDengine can be installed by: After building successfully, TDengine can be installed by:
@ -330,24 +245,6 @@ After building successfully, TDengine can be installed by:
sudo make install sudo make install
``` ```
To start the service after installation, config `.plist` file first, in a terminal, use:
```bash
sudo cp ../packaging/macOS/com.taosdata.tdengine.plist /Library/LaunchDaemons
```
To start the service, in a terminal, use:
```bash
sudo launchctl load /Library/LaunchDaemons/com.taosdata.tdengine.plist
```
To stop the service, in a terminal, use:
```bash
sudo launchctl unload /Library/LaunchDaemons/com.taosdata.tdengine.plist
```
## Quick Run ## Quick Run
If you don't want to run TDengine as a service, you can run it in current shell. For example, to quickly start a TDengine server after building, run the command below in terminal: (We take Linux as an example, command on Windows will be `taosd.exe`) If you don't want to run TDengine as a service, you can run it in current shell. For example, to quickly start a TDengine server after building, run the command below in terminal: (We take Linux as an example, command on Windows will be `taosd.exe`)
@ -388,36 +285,20 @@ Query OK, 2 row(s) in set (0.001700s)
TDengine provides abundant developing tools for users to develop on TDengine. Follow the links below to find your desired connectors and relevant documentation. TDengine provides abundant developing tools for users to develop on TDengine. Follow the links below to find your desired connectors and relevant documentation.
- [Java](https://www.taosdata.com/en/documentation/connector/java) - [Java](https://docs.taosdata.com/reference/connector/java/)
- [C/C++](https://www.taosdata.com/en/documentation/connector#c-cpp) - [C/C++](https://docs.taosdata.com/reference/connector/cpp/)
- [Python](https://www.taosdata.com/en/documentation/connector#python) - [Python](https://docs.taosdata.com/reference/connector/python/)
- [Go](https://www.taosdata.com/en/documentation/connector#go) - [Go](https://docs.taosdata.com/reference/connector/go/)
- [RESTful API](https://www.taosdata.com/en/documentation/connector#restful) - [Node.js](https://docs.taosdata.com/reference/connector/node/)
- [Node.js](https://www.taosdata.com/en/documentation/connector#nodejs) - [Rust](https://docs.taosdata.com/reference/connector/rust/)
- [Rust](https://www.taosdata.com/en/documentation/connector/rust) - [C#](https://docs.taosdata.com/reference/connector/csharp/)
- [RESTful API](https://docs.taosdata.com/reference/rest-api/)
## Third Party Connectors
The TDengine community has also kindly built some of their own connectors! Follow the links below to find the source code for them.
- [Rust Bindings](https://github.com/songtianyi/tdengine-rust-bindings/tree/master/examples)
- [.Net Core Connector](https://github.com/maikebing/Maikebing.EntityFrameworkCore.Taos)
- [Lua Connector](https://github.com/taosdata/TDengine/tree/develop/tests/examples/lua)
# How to run the test cases and how to add a new test case # How to run the test cases and how to add a new test case
TDengine's test framework and all test cases are fully open source. TDengine's test framework and all test cases are fully open source.
Please refer to [this document](https://github.com/taosdata/TDengine/blob/develop/tests/How-To-Run-Test-And-How-To-Add-New-Test-Case.md) for how to run test and develop new test case. Please refer to [this document](https://github.com/taosdata/TDengine/blob/develop/tests/How-To-Run-Test-And-How-To-Add-New-Test-Case.md) for how to run test and develop new test case.
# TDengine Roadmap
- Support event-driven stream computing
- Support user defined functions
- Support MQTT connection
- Support OPC connection
- Support Hadoop, Spark connections
- Support Tableau and other BI tools
# Contribute to TDengine # Contribute to TDengine
Please follow the [contribution guidelines](CONTRIBUTING.md) to contribute to the project. Please follow the [contribution guidelines](CONTRIBUTING.md) to contribute to the project.

0
build.sh Normal file → Executable file
View File

View File

@ -1,4 +1,8 @@
IF (TD_LINUX) IF (EXISTS /var/lib/taos/dnode/dnodeCfg.json)
INSTALL(CODE "MESSAGE(\"The default data directory /var/lib/taos contains old data of tdengine 2.x, please clear it before installing!\")")
ELSEIF (EXISTS C:/TDengine/data/dnode/dnodeCfg.json)
INSTALL(CODE "MESSAGE(\"The default data directory C:/TDengine/data contains old data of tdengine 2.x, please clear it before installing!\")")
ELSEIF (TD_LINUX)
SET(TD_MAKE_INSTALL_SH "${TD_SOURCE_DIR}/packaging/tools/make_install.sh") SET(TD_MAKE_INSTALL_SH "${TD_SOURCE_DIR}/packaging/tools/make_install.sh")
INSTALL(CODE "MESSAGE(\"make install script: ${TD_MAKE_INSTALL_SH}\")") INSTALL(CODE "MESSAGE(\"make install script: ${TD_MAKE_INSTALL_SH}\")")
INSTALL(CODE "execute_process(COMMAND bash ${TD_MAKE_INSTALL_SH} ${TD_SOURCE_DIR} ${PROJECT_BINARY_DIR} Linux ${TD_VER_NUMBER})") INSTALL(CODE "execute_process(COMMAND bash ${TD_MAKE_INSTALL_SH} ${TD_SOURCE_DIR} ${PROJECT_BINARY_DIR} Linux ${TD_VER_NUMBER})")
@ -22,6 +26,9 @@ ELSEIF (TD_WINDOWS)
INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/taos.exe DESTINATION .) INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/taos.exe DESTINATION .)
INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/taosd.exe DESTINATION .) INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/taosd.exe DESTINATION .)
INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/udfd.exe DESTINATION .) INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/udfd.exe DESTINATION .)
IF (BUILD_TOOLS)
INSTALL(FILES ${EXECUTABLE_OUTPUT_PATH}/taosBenchmark.exe DESTINATION .)
ENDIF ()
IF (TD_MVN_INSTALLED) IF (TD_MVN_INSTALLED)
INSTALL(FILES ${LIBRARY_OUTPUT_PATH}/taos-jdbcdriver-2.0.38-dist.jar DESTINATION connector/jdbc) INSTALL(FILES ${LIBRARY_OUTPUT_PATH}/taos-jdbcdriver-2.0.38-dist.jar DESTINATION connector/jdbc)

View File

@ -97,13 +97,13 @@ IF ("${CPUTYPE}" STREQUAL "")
ELSE () ELSE ()
# if generate ARM version: # if generate ARM version:
# cmake -DCPUTYPE=aarch32 .. or cmake -DCPUTYPE=aarch64 # cmake -DCPUTYPE=aarch32 .. or cmake -DCPUTYPE=aarch64
IF (${CPUTYPE} MATCHES "aarch32") IF (${CPUTYPE} MATCHES "aarch32" OR ${CPUTYPE} MATCHES "arm32")
SET(PLATFORM_ARCH_STR "arm") SET(PLATFORM_ARCH_STR "arm")
MESSAGE(STATUS "input cpuType: aarch32") MESSAGE(STATUS "input cpuType: aarch32")
ADD_DEFINITIONS("-D_TD_ARM_") ADD_DEFINITIONS("-D_TD_ARM_")
ADD_DEFINITIONS("-D_TD_ARM_32") ADD_DEFINITIONS("-D_TD_ARM_32")
SET(TD_ARM_32 TRUE) SET(TD_ARM_32 TRUE)
ELSEIF (${CPUTYPE} MATCHES "aarch64") ELSEIF (${CPUTYPE} MATCHES "aarch64" OR ${CPUTYPE} MATCHES "arm64")
SET(PLATFORM_ARCH_STR "arm64") SET(PLATFORM_ARCH_STR "arm64")
MESSAGE(STATUS "input cpuType: aarch64") MESSAGE(STATUS "input cpuType: aarch64")
ADD_DEFINITIONS("-D_TD_ARM_") ADD_DEFINITIONS("-D_TD_ARM_")

View File

@ -2,7 +2,7 @@
# taosadapter # taosadapter
ExternalProject_Add(taosadapter ExternalProject_Add(taosadapter
GIT_REPOSITORY https://github.com/taosdata/taosadapter.git GIT_REPOSITORY https://github.com/taosdata/taosadapter.git
GIT_TAG ed6a160 GIT_TAG 3d21433
SOURCE_DIR "${TD_SOURCE_DIR}/tools/taosadapter" SOURCE_DIR "${TD_SOURCE_DIR}/tools/taosadapter"
BINARY_DIR "" BINARY_DIR ""
#BUILD_IN_SOURCE TRUE #BUILD_IN_SOURCE TRUE

View File

@ -2,7 +2,7 @@
# taos-tools # taos-tools
ExternalProject_Add(taos-tools ExternalProject_Add(taos-tools
GIT_REPOSITORY https://github.com/taosdata/taos-tools.git GIT_REPOSITORY https://github.com/taosdata/taos-tools.git
GIT_TAG 3c7dafe GIT_TAG 53a0103
SOURCE_DIR "${TD_SOURCE_DIR}/tools/taos-tools" SOURCE_DIR "${TD_SOURCE_DIR}/tools/taos-tools"
BINARY_DIR "" BINARY_DIR ""
#BUILD_IN_SOURCE TRUE #BUILD_IN_SOURCE TRUE

View File

@ -1,8 +1,8 @@
# taosws-rs # taosws-rs
ExternalProject_Add(taosws-rs ExternalProject_Add(taosws-rs
GIT_REPOSITORY https://github.com/taosdata/taosws-rs.git GIT_REPOSITORY https://github.com/taosdata/taos-connector-rust.git
GIT_TAG 29424d5 GIT_TAG 7a54d21
SOURCE_DIR "${TD_SOURCE_DIR}/tools/taosws-rs" SOURCE_DIR "${TD_SOURCE_DIR}/tools/taosws-rs"
BINARY_DIR "" BINARY_DIR ""
#BUILD_IN_SOURCE TRUE #BUILD_IN_SOURCE TRUE

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.8 KiB

After

Width:  |  Height:  |  Size: 37 KiB

View File

@ -0,0 +1,103 @@
---
sidebar_label: Docker
title: 通过 Docker 快速体验 TDengine
---
:::info
如果您希望对 TDengine 贡献代码或对内部实现感兴趣,请参考我们的 [TDengine GitHub 主页](https://github.com/taosdata/TDengine) 下载源码构建和安装.
:::
本节首先介绍如何通过 Docker 快速体验 TDengine然后介绍如何在 Docker 环境下体验 TDengine 的写入和查询功能。
## 启动 TDengine
如果已经安装了 docker 只需执行下面的命令。
```shell
docker run -d -p 6030:6030 -p 6041/6041 -p 6043-6049/6043-6049 -p 6043-6049:6043-6049/udp tdengine/tdengine
```
注意TDengine 3.0 服务端仅使用 6030 TCP 端口。6041 为 taosAdapter 所使用提供 REST 服务端口。6043-6049 为 taosAdapter 提供第三方应用接入所使用端口,可根据需要选择是否打开。
确定该容器已经启动并且在正常运行
```shell
docker ps
```
进入该容器并执行 bash
```shell
docker exec -it <container name> bash
```
然后就可以执行相关的 Linux 命令操作和访问 TDengine
## 运行 TDengine CLI
进入容器,执行 taos
```
$ taos
Welcome to the TDengine shell from Linux, Client Version:3.0.0.0
Copyright (c) 2022 by TAOS Data, Inc. All rights reserved.
Server is Community Edition.
taos>
```
## 写入数据
可以使用 TDengine 的自带工具 taosBenchmark 快速体验 TDengine 的写入。
进入容器,启动 taosBenchmark
```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 和 groupIdgroupId 被设置为 1 到 10 location 被设置为 "San Francisco" 或者 "Los Angeles"等城市名称。
这条命令很快完成 1 亿条记录的插入。具体时间取决于硬件性能。
taosBenchmark 命令本身带有很多选项,配置表的数目、记录条数等等,您可以设置不同参数进行体验,请执行 `taosBenchmark --help` 详细列出。taosBenchmark 详细使用方法请参照 [taosBenchmark 参考手册](../../reference/taosbenchmark)。
## 体验查询
使用上述 taosBenchmark 插入数据后,可以在 TDengine CLI 输入查询命令,体验查询速度。。
查询超级表下记录总条数:
```sql
taos> select count(*) from test.meters;
```
查询 1 亿条记录的平均值、最大值、最小值等:
```sql
taos> select avg(current), max(voltage), min(phase) from test.meters;
```
查询 location="San Francisco" 的记录总条数:
```sql
taos> select count(*) from test.meters where location="San Francisco";
```
查询 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);
```
## 其它
更多关于在 Docker 环境下使用 TDengine 的细节,请参考 [在 Docker 下使用 TDengine](../../reference/docker)

View File

@ -0,0 +1,221 @@
---
sidebar_label: 安装包
title: 使用安装包立即开始
---
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
:::info
如果您希望对 TDengine 贡献代码或对内部实现感兴趣,请参考我们的 [TDengine GitHub 主页](https://github.com/taosdata/TDengine) 下载源码构建和安装.
:::
TDengine 开源版本提供 deb 和 rpm 格式安装包,用户可以根据自己的运行环境选择合适的安装包。其中 deb 支持 Debian/Ubuntu 及衍生系统rpm 支持 CentOS/RHEL/SUSE 及衍生系统。同时我们也为企业用户提供 tar.gz 格式安装包,也支持通过 `apt-get` 工具从线上进行安装。
## 安装
<Tabs>
<TabItem value="apt-get" label="apt-get">
可以使用 apt-get 工具从官方仓库安装。
**安装包仓库**
```bash
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 版需要安装包仓库
```bash
echo "deb [arch=amd64] http://repos.taosdata.com/tdengine-beta beta main" | sudo tee /etc/apt/sources.list.d/tdengine-beta.list
```
**使用 apt-get 命令安装**
```bash
sudo apt-get update
apt-cache policy tdengine
sudo apt-get install tdengine
```
:::tip
apt-get 方式只适用于 Debian 或 Ubuntu 系统
::::
</TabItem>
<TabItem label="Deb 安装" value="debinst">
1、从官网下载获得 deb 安装包,例如 TDengine-server-3.0.0.0-Linux-x64.deb
2、进入到 TDengine-server-3.0.0.0-Linux-x64.deb 安装包所在目录,执行如下的安装命令:
```bash
sudo dpkg -i TDengine-server-3.0.0.0-Linux-x64.deb
```
</TabItem>
<TabItem label="RPM 安装" value="rpminst">
1、从官网下载获得 rpm 安装包,例如 TDengine-server-3.0.0.0-Linux-x64.rpm
2、进入到 TDengine-server-3.0.0.0-Linux-x64.rpm 安装包所在目录,执行如下的安装命令:
```bash
sudo rpm -ivh TDengine-server-3.0.0.0-Linux-x64.rpm
```
</TabItem>
<TabItem label="tar.gz 安装" value="tarinst">
1、从官网下载获得 tar.gz 安装包,例如 TDengine-server-3.0.0.0-Linux-x64.tar.gz
2、进入到 TDengine-server-3.0.0.0-Linux-x64.tar.gz 安装包所在目录,先解压文件后,进入子目录,执行其中的 install.sh 安装脚本:
```bash
tar -zxvf TDengine-server-3.0.0.0-Linux-x64.tar.gz
```
解压后进入相应路径,执行
```bash
sudo ./install.sh
```
:::info
install.sh 安装脚本在执行过程中,会通过命令行交互界面询问一些配置信息。如果希望采取无交互安装方式,那么可以用 -e no 参数来执行 install.sh 脚本。运行 `./install.sh -h` 指令可以查看所有参数的详细说明信息。
:::
</TabItem>
</Tabs>
:::note
当安装第一个节点时,出现 Enter FQDN提示的时候不需要输入任何内容。只有当安装第二个或以后更多的节点时才需要输入已有集群中任何一个可用节点的 FQDN支持该新节点加入集群。当然也可以不输入而是在新节点启动前配置到新节点的配置文件中。
:::
## 启动
安装后,请使用 `systemctl` 命令来启动 TDengine 的服务进程。
```bash
systemctl start taosd
```
检查服务是否正常工作:
```bash
systemctl status taosd
```
如果服务进程处于活动状态,则 status 指令会显示如下的相关信息:
```
Active: active (running)
```
如果后台服务进程处于停止状态,则 status 指令会显示如下的相关信息:
```
Active: inactive (dead)
```
如果 TDengine 服务正常工作,那么您可以通过 TDengine 的命令行程序 `taos` 来访问并体验 TDengine。
systemctl 命令汇总:
- 启动服务进程:`systemctl start taosd`
- 停止服务进程:`systemctl stop taosd`
- 重启服务进程:`systemctl restart taosd`
- 查看服务状态:`systemctl status taosd`
:::info
- systemctl 命令需要 _root_ 权限来运行,如果您非 _root_ 用户,请在命令前添加 sudo 。
- `systemctl stop taosd` 指令在执行后并不会马上停止 TDengine 服务,而是会等待系统中必要的落盘工作正常完成。在数据量很大的情况下,这可能会消耗较长时间。
- 如果系统中不支持 `systemd`,也可以用手动运行 `/usr/local/taos/bin/taosd` 方式启动 TDengine 服务。
:::
## TDengine 命令行 (CLI)
为便于检查 TDengine 的状态,执行数据库 (Database) 的各种即席(Ad Hoc)查询TDengine 提供一命令行应用程序(以下简称为 TDengine CLI) taos。要进入 TDengine 命令行,您只要在安装有 TDengine 的 Linux 终端执行 `taos` 即可。
```bash
taos
```
如果连接服务成功,将会打印出欢迎消息和版本信息。如果失败,则会打印错误消息出来(请参考 [FAQ](/train-faq/faq) 来解决终端连接服务端失败的问题)。 TDengine CLI 的提示符号如下:
```cmd
taos>
```
在 TDengine CLI 中,用户可以通过 SQL 命令来创建/删除数据库、表等,并进行数据库(database)插入查询操作。在终端中运行的 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 CLI 进行检查系统运行状态、添加删除用户账号等操作。TDengine CLI 连同应用驱动也可以独立安装在 Linux 或 Windows 机器上运行,更多细节请参考 [这里](../../reference/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 和 groupIdgroupId 被设置为 1 到 10 location 被设置为 "California.SanFrancisco" 或者 "California.LosAngeles"。
这条命令很快完成 1 亿条记录的插入。具体时间取决于硬件性能,即使在一台普通的 PC 服务器往往也仅需十几秒。
taosBenchmark 命令本身带有很多选项,配置表的数目、记录条数等等,您可以设置不同参数进行体验,请执行 `taosBenchmark --help` 详细列出。taosBenchmark 详细使用方法请参照 [如何使用 taosBenchmark 对 TDengine 进行性能测试](https://www.taosdata.com/2021/10/09/3111.html)。
## 使用 TDengine CLI 体验查询速度
使用上述 taosBenchmark 插入数据后,可以在 TDengine CLI 输入查询命令,体验查询速度。
查询超级表下记录总条数:
```sql
taos> select count(*) from test.meters;
```
查询 1 亿条记录的平均值、最大值、最小值等:
```sql
taos> select avg(current), max(voltage), min(phase) from test.meters;
```
查询 location="California.SanFrancisco" 的记录总条数:
```sql
taos> select count(*) from test.meters where location="California.SanFrancisco";
```
查询 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);
```

View File

@ -1,19 +1,19 @@
`apt-get` can be used to install TDengine from official package repository. 可以使用 apt-get 工具从官方仓库安装。
**Package Repository** **安装包仓库**
``` ```
wget -qO - http://repos.taosdata.com/tdengine.key | sudo apt-key add - 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 echo "deb [arch=amd64] http://repos.taosdata.com/tdengine-stable stable main" | sudo tee /etc/apt/sources.list.d/tdengine-stable.list
``` ```
The repository required for installing beta versions can be configured as below: 如果安装 Beta 版需要安装包仓库
``` ```
echo "deb [arch=amd64] http://repos.taosdata.com/tdengine-beta beta main" | sudo tee /etc/apt/sources.list.d/tdengine-beta.list echo "deb [arch=amd64] http://repos.taosdata.com/tdengine-beta beta main" | sudo tee /etc/apt/sources.list.d/tdengine-beta.list
``` ```
**Install With apt-get** **使用 apt-get 命令安装**
``` ```
sudo apt-get update sudo apt-get update
@ -22,5 +22,5 @@ sudo apt-get install tdengine
``` ```
:::tip :::tip
`apt-get` can only be used on Debian or Ubuntu Linux. apt-get 方式只适用于 Debian 或 Ubuntu 系统
:::: ::::

View File

@ -1 +1 @@
label: Get Started label: 立即开始

View File

@ -1,17 +1,17 @@
import PkgList from "/components/PkgList"; import PkgList from "/components/PkgList";
It's very easy to install TDengine and would take you only a few minutes from downloading to finishing installation. TDengine 的安装非常简单,从下载到安装成功仅仅只要几秒钟。
For the convenience of users, from version 2.4.0.10, the standard server side installation package includes `taos`, `taosd`, `taosAdapter`, `taosBenchmark` and sample code. If only the `taosd` server and C/C++ connector are required, you can also choose to download the lite package. 为方便使用,从 2.4.0.10 开始,标准的服务端安装包包含了 taos、taosd、taosAdapter、taosdump、taosBenchmark、TDinsight 安装脚本和示例代码;如果您只需要用到服务端程序和客户端连接的 C/C++ 语言支持,也可以仅下载 lite 版本的安装包。
Three kinds of packages are provided, tar.gz, rpm and deb. Especially the tar.gz package is provided for the convenience of enterprise customers on different kinds of operating systems, it includes `taosdump` and TDinsight installation script which are normally only provided in taos-tools rpm and deb packages. 在安装包格式上,我们提供 tar.gz, rpm 和 deb 格式,为企业客户提供 tar.gz 格式安装包以方便在特定操作系统上使用。需要注意的是rpm 和 deb 包不含 taosdump、taosBenchmark 和 TDinsight 安装脚本,这些工具需要通过安装 taosTool 包获得。
Between two major release versions, some beta versions may be delivered for users to try some new features. 发布版本包括稳定版和 Beta 版Beta 版含有更多新功能。正式上线或测试建议安装稳定版。您可以根据需要选择下载:
<PkgList type={0}/> <PkgList type={0}/>
For the details please refer to [Install and Uninstall](/operation/pkg-install)。 具体的安装方法,请参见[安装包的安装和卸载](/operation/pkg-install)。
To see the details of versions, please refer to [Download List](https://tdengine.com/all-downloads) and [Release Notes](https://github.com/taosdata/TDengine/releases).
下载其他组件、最新 Beta 版及之前版本的安装包,请点击[这里](https://www.taosdata.com/all-downloads)
查看 Release Notes, 请点击[这里](https://github.com/taosdata/TDengine/releases)

View File

@ -1,171 +1,15 @@
--- ---
title: Get Started title: 立即开始
description: 'Install TDengine from Docker image, apt-get or package, and run TDengine CLI and taosBenchmark to experience the features' description: '快速设置 TDengine 环境并体验其高效写入和查询'
--- ---
import Tabs from "@theme/Tabs"; TDengine 完整的软件包包括服务端taosd、用于与第三方系统对接并提供 RESTful 接口的 taosAdapter、应用驱动taosc、命令行程序 (CLItaos) 和一些工具软件。TDengine 除了提供多种语言的连接器之外,还通过 [taosAdapter](/reference/taosadapter) 提供 [RESTful 接口](/reference/rest-api)。
import TabItem from "@theme/TabItem";
import PkgInstall from "./\_pkg_install.mdx";
import AptGetInstall from "./\_apt_get_install.mdx";
## Quick Install 本章主要介绍如何利用 Docker 或者安装包快速设置 TDengine 环境并体验其高效写入和查询。
The full package of TDengine includes the server(taosd), taosAdapter for connecting with third-party systems and providing a RESTful interface, client driver(taosc), command-line program(CLI, taos) and some tools. For the current version, the server taosd and taosAdapter can only be installed and run on Linux systems. In the future taosd and taosAdapter will also be supported on Windows, macOS and other systems. The client driver taosc and TDengine CLI can be installed and run on Windows or Linux. In addition to connectors for multiple languages, TDengine also provides a [RESTful interface](/reference/rest-api) through [taosAdapter](/reference/taosadapter). Prior to version 2.4.0.0, taosAdapter did not exist and the RESTful interface was provided by the built-in HTTP service of taosd. ```mdx-code-block
import DocCardList from '@theme/DocCardList';
import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
TDengine supports X64/ARM64/MIPS64/Alpha64 hardware platforms, and will support ARM32, RISC-V and other CPU architectures in the future. <DocCardList items={useCurrentSidebarCategory().items}/>
```
<Tabs defaultValue="apt-get">
<TabItem value="docker" label="Docker">
If docker is already installed on your computer, execute the following command:
```shell
docker run -d -p 6030-6049:6030-6049 -p 6030-6049:6030-6049/udp tdengine/tdengine
```
Make sure the container is running
```shell
docker ps
```
Enter into container and execute bash
```shell
docker exec -it <container name> bash
```
Then you can execute the Linux commands and access TDengine.
For detailed steps, please visit [Experience TDengine via Docker](/train-faq/docker)。
:::info
Starting from 2.4.0.10besides taosdTDengine docker image includes: taostaosAdaptertaosdumptaosBenchmarkTDinsight, scripts and sample code. Once the TDengine container is startedit will start both taosAdapter and taosd automatically to support RESTful interface.
:::
</TabItem>
<TabItem value="apt-get" label="apt-get">
<AptGetInstall />
</TabItem>
<TabItem value="pkg" label="Package">
<PkgInstall />
</TabItem>
<TabItem value="src" label="Source Code">
If you like to check the source code, build the package by yourself or contribute to the project, please check [TDengine GitHub Repository](https://github.com/taosdata/TDengine)
</TabItem>
</Tabs>
## Quick Launch
After installation, you can launch the TDengine service by the 'systemctl' command to start 'taosd'.
```bash
systemctl start taosd
```
Check if taosd is running
```bash
systemctl status taosd
```
If everything is fine, you can run TDengine command-line interface `taos` to access TDengine and test it out yourself.
:::info
- systemctl requires _root_ privilegesif you are not _root_ please add sudo before the command.
- To get feedback and keep improving the product, TDengine is collecting some basic usage information, but you can turn it off by setting telemetryReporting to 0 in configuration file taos.cfg.
- TDengine uses FQDN (usually hostnameas the ID for a node. To make the system work, you need to configure the FQDN for the server running taosd, and configure the DNS service or hosts file on the the machine where the application or TDengine CLI runs to ensure that the FQDN can be resolved.
- `systemctl stop taosd` won't stop the server right away, it will wait until all the data in memory are flushed to disk. It may takes time depending on the cache size.
TDengine supports the installation on system which runs [`systemd`](https://en.wikipedia.org/wiki/Systemd) for process managementuse `which systemctl` to check if the system has `systemd` installed:
```bash
which systemctl
```
If the system does not have `systemd`you can start TDengine manually by executing `/usr/local/taos/bin/taosd`
:::note
## Command Line Interface
To manage the TDengine running instanceor execute ad-hoc queries, TDengine provides a Command Line Interface (hereinafter referred to as TDengine CLI) taos. To enter into the interactive CLIexecute `taos` on a Linux terminal where TDengine is installed.
```bash
taos
```
If it connects to the TDengine server successfully, it will print out the version and welcome message. If it fails, it will print out the error message, please check [FAQ](/train-faq/faq) for trouble shooting connection issue. TDengine CLI's prompt is
```cmd
taos>
```
Inside TDengine CLIyou can execute SQL commands to create/drop database/table, and run queries. The SQL command must be ended with a semicolon. For example:
```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)
```
Besides executing SQL commands, system administrators can check running status, add/drop user accounts and manage the running instances. TDengine CLI with client driver can be installed and run on either Linux or Windows machines. For more details on CLI, please [check here](../reference/taos-shell/).
## Experience the blazing fast speed
After TDengine server is runningexecute `taosBenchmark` (previously named taosdemo) from a Linux terminal
```bash
taosBenchmark
```
This command will create a super table "meters" under database "test". Under "meters", 10000 tables are created with names from "d0" to "d9999". Each table has 10000 rows and each row has four columns (ts, current, voltage, phase). Time stamp is starting from "2017-07-14 10:40:00 000" to "2017-07-14 10:40:09 999". Each table has tags "location" and "groupId". groupId is set 1 to 10 randomly, and location is set to "California.SanFrancisco" or "California.SanDiego".
This command will insert 100 million rows into the database quickly. Time to insert depends on the hardware configuration, it only takes a dozen seconds for a regular PC server.
taosBenchmark provides command-line options and a configuration file to customize the scenarios, like number of tables, number of rows per table, number of columns and more. Please execute `taosBenchmark --help` to list them. For details on running taosBenchmark, please check [reference for taosBenchmark](/reference/taosbenchmark)
## Experience query speed
After using taosBenchmark to insert a number of rows data, you can execute queries from TDengine CLI to experience the lightning fast query speed.
query the total number of rows under super table "meters"
```sql
taos> select count(*) from test.meters;
```
query the average, maximum, minimum of 100 million rows:
```sql
taos> select avg(current), max(voltage), min(phase) from test.meters;
```
query the total number of rows with location="California.SanFrancisco":
```sql
taos> select count(*) from test.meters where location="California.SanFrancisco";
```
query the average, maximum, minimum of all rows with groupId=10:
```sql
taos> select avg(current), max(voltage), min(phase) from test.meters where groupId=10;
```
query the average, maximum, minimum for table d10 in 10 seconds time interval
```sql
taos> select avg(current), max(voltage), min(phase) from test.d10 interval(10s);
```

View File

@ -55,9 +55,6 @@ For more details please refer to [InfluxDB Line Protocol](https://docs.influxdat
<TabItem label="Go" value="go"> <TabItem label="Go" value="go">
<GoLine /> <GoLine />
</TabItem> </TabItem>
<TabItem label="Rust" value="rust">
<RustLine />
</TabItem>
<TabItem label="Node.js" value="nodejs"> <TabItem label="Node.js" value="nodejs">
<NodeLine /> <NodeLine />
</TabItem> </TabItem>

View File

@ -46,9 +46,6 @@ Please refer to [OpenTSDB Telnet API](http://opentsdb.net/docs/build/html/api_te
<TabItem label="Go" value="go"> <TabItem label="Go" value="go">
<GoTelnet /> <GoTelnet />
</TabItem> </TabItem>
<TabItem label="Rust" value="rust">
<RustTelnet />
</TabItem>
<TabItem label="Node.js" value="nodejs"> <TabItem label="Node.js" value="nodejs">
<NodeTelnet /> <NodeTelnet />
</TabItem> </TabItem>

View File

@ -63,9 +63,6 @@ Please refer to [OpenTSDB HTTP API](http://opentsdb.net/docs/build/html/api_http
<TabItem label="Go" value="go"> <TabItem label="Go" value="go">
<GoJson /> <GoJson />
</TabItem> </TabItem>
<TabItem label="Rust" value="rust">
<RustJson />
</TabItem>
<TabItem label="Node.js" value="nodejs"> <TabItem label="Node.js" value="nodejs">
<NodeJson /> <NodeJson />
</TabItem> </TabItem>

View File

@ -1,3 +1,2 @@
```rust ```rust
{{#include docs/examples/rust/schemalessexample/examples/influxdb_line_example.rs}}
``` ```

View File

@ -1,3 +1,2 @@
```rust ```rust
{{#include docs/examples/rust/schemalessexample/examples/opentsdb_json_example.rs}}
``` ```

View File

@ -1,3 +1,2 @@
```rust ```rust
{{#include docs/examples/rust/schemalessexample/examples/opentsdb_telnet_example.rs}}
``` ```

View File

@ -17,7 +17,6 @@ Currently, TDengine's native interface connectors can support platforms such as
| **X86 64bit** | **Win32** | ● | ● | ● | ● | ○ | ○ | ● | | **X86 64bit** | **Win32** | ● | ● | ● | ● | ○ | ○ | ● |
| **X86 32bit** | **Win32** | ○ | ○ | ○ | ○ | ○ | ○ | ● | | **X86 32bit** | **Win32** | ○ | ○ | ○ | ○ | ○ | ○ | ● |
| **ARM64** | **Linux** | ● | ● | ● | ● | ○ | ○ | ● | | **ARM64** | **Linux** | ● | ● | ● | ● | ○ | ○ | ● |
| **ARM32** | **Linux** | ● | ● | ● | ● | ○ | ○ | ● |
| **MIPS** | **Linux** | ○ | ○ | ○ | ○ | ○ | ○ | ○ | | **MIPS** | **Linux** | ○ | ○ | ○ | ○ | ○ | ○ | ○ |
Where ● means the official test verification passed, ○ means the unofficial test verification passed, -- means no assurance. Where ● means the official test verification passed, ○ means the unofficial test verification passed, -- means no assurance.

View File

@ -10,16 +10,14 @@ import TabItem from '@theme/TabItem';
import Preparation from "./_preparation.mdx" import Preparation from "./_preparation.mdx"
import RustInsert from "../../07-develop/03-insert-data/_rust_sql.mdx" import RustInsert from "../../07-develop/03-insert-data/_rust_sql.mdx"
import RustInfluxLine from "../../07-develop/03-insert-data/_rust_line.mdx" import RustBind from "../../07-develop/03-insert-data/_rust_stmt.mdx"
import RustOpenTSDBTelnet from "../../07-develop/03-insert-data/_rust_opts_telnet.mdx"
import RustOpenTSDBJson from "../../07-develop/03-insert-data/_rust_opts_json.mdx"
import RustQuery from "../../07-develop/04-query-data/_rust.mdx" import RustQuery from "../../07-develop/04-query-data/_rust.mdx"
`libtaos` is the official Rust language connector for TDengine. Rust developers can develop applications to access the TDengine instance data. [`taos`][taos] is the official Rust language connector for TDengine. Rust developers can develop applications to access the TDengine instance data.
`libtaos` provides two ways to establish connections. One is the **Native Connection**, which connects to TDengine instances via the TDengine client driver (taosc). The other is **REST connection**, which connects to TDengine instances via taosAdapter's REST interface. Rust connector provides two ways to establish connections. One is the **Native Connection**, which connects to TDengine instances via the TDengine client driver (taosc). The other is **Websocket connection**, which connects to TDengine instances via taosAdapter service.
The source code for `libtaos` is hosted on [GitHub](https://github.com/taosdata/libtaos-rs). The source code is hosted on [taosdata/taos-connector-rust](https://github.com/taosdata/taos-connector-rust).
## Supported platforms ## Supported platforms
@ -30,119 +28,195 @@ REST connections are supported on all platforms that can run Rust.
Please refer to [version support list](/reference/connector#version-support). Please refer to [version support list](/reference/connector#version-support).
The Rust Connector is still under rapid development and is not guaranteed to be backward compatible before 1.0. We recommend using TDengine version 2.4 or higher to avoid known issues. The Rust Connector is still under rapid development and is not guaranteed to be backward compatible before 1.0. We recommend using TDengine version 3.0 or higher to avoid known issues.
## Installation ## Installation
### Pre-installation ### Pre-installation
* Install the Rust development toolchain * Install the Rust development toolchain
* If using the native connection, please install the TDengine client driver. Please refer to [install client driver](/reference/connector#install-client-driver) * If using the native connection, please install the TDengine client driver. Please refer to [install client driver](/reference/connector#install-client-driver)
### Adding libtaos dependencies ### Add dependencies
Add the [libtaos][libtaos] dependency to the [Rust](https://rust-lang.org) project as follows, depending on the connection method selected. Add the dependency to the [Rust](https://rust-lang.org) project as follows, depending on the connection method selected.
<Tabs defaultValue="native"> <Tabs defaultValue="default">
<TabItem value="native" label="native connection"> <TabItem value="default" label="Both">
Add [libtaos][libtaos] to the `Cargo.toml` file. Add [taos] to the `Cargo.toml` file.
```toml ```toml
[dependencies] [dependencies]
# use default feature # use default feature
libtaos = "*" taos = "*"
``` ```
</TabItem> </TabItem>
<TabItem value="rest" label="REST connection"> <TabItem value="native" label="Native only">
Add [libtaos][libtaos] to the `Cargo.toml` file and enable the `rest` feature. Add [taos] to the `Cargo.toml` file.
```toml ```toml
[dependencies] [dependencies]
# use rest feature taos = { version = "*", default-features = false, features = ["native"] }
libtaos = { version = "*", features = ["rest"]} ```
</TabItem>
<TabItem value="rest" label="Websocket only">
Add [taos] to the `Cargo.toml` file and enable the `ws` feature.
```toml
[dependencies]
taos = { version = "*", default-features = false, features = ["ws"] }
``` ```
</TabItem> </TabItem>
</Tabs> </Tabs>
### Using connection pools
Please enable the `r2d2` feature in `Cargo.toml`.
```toml
[dependencies]
# with taosc
libtaos = { version = "*", features = ["r2d2"] }
# or rest
libtaos = { version = "*", features = ["rest", "r2d2"] }
```
## Create a connection ## Create a connection
The [TaosCfgBuilder] provides the user with an API in the form of a constructor for the subsequent creation of connections or use of connection pools. In rust connector, we use a DSN connection string as a connection builder. For example,
```rust ```rust
let cfg: TaosCfg = TaosCfgBuilder::default() let builder = TaosBuilder::from_dsn("taos://")?;
.ip("127.0.0.1")
.user("root")
.pass("taosdata")
.db("log") // do not set if not require a default database.
.port(6030u16)
.build()
.expect("TaosCfg builder error");
}
``` ```
You can now use this object to create the connection. You can now use connection client to create the connection.
```rust ```rust
let conn = cfg.connect()? ; let conn = builder.build()?;
``` ```
The connection object can create more than one. The connection object can create more than one.
```rust ```rust
let conn = cfg.connect()? ; let conn1 = builder.build()?;
let conn2 = cfg.connect()? ; let conn2 = builder.build()?;
``` ```
You can use connection pools in applications. DSN is short for **D**ata **S**ource **N**ame string - [a data structure used to describe a connection to a data source](https://en.wikipedia.org/wiki/Data_source_name).
```rust A common DSN is basically constructed as this:
let pool = r2d2::Pool::builder()
.max_size(10000) // max connections
.build(cfg)? ;
// ... ```text
// Use pool to get connection <driver>[+<protocol>]://[[<username>:<password>@]<host>:<port>][/<database>][?<p1>=<v1>[&<p2>=<v2>]]
let conn = pool.get()? ; |------|------------|---|-----------|-----------|------|------|------------|-----------------------|
|driver| protocol | | username | password | host | port | database | params |
``` ```
After that, you can perform the following operations on the database. - **Driver**: the main entrypoint to a processer. **Required**. In Rust connector, the supported driver names are listed here:
- **taos**: the legacy TDengine connection data source.
- **tmq**: subscription data source from TDengine.
- **http/ws**: use websocket protocol via `ws://` scheme.
- **https/wss**: use websocket protocol via `wss://` scheme.
- **Protocol**: the additional information appended to driver, which can be be used to support different kind of data sources. By default, leave it empty for native driver(only under feature "native"), and `ws/wss` for websocket driver (only under feature "ws"). **Optional**.
- **Username**: as its definition, is the username to the connection. **Optional**.
- **Password**: the password of the username. **Optional**.
- **Host**: address host to the datasource. **Optional**.
- **Port**: address port to the datasource. **Optional**.
- **Database**: database name or collection name in the datasource. **Optional**.
- **Params**: a key-value map for any other informations to the datasource. **Optional**.
Here is a simple DSN connection string example:
```text
taos+ws://localhost:6041/test
```
which means connect `localhost` with port `6041` via `ws` protocol, and make `test` as the default database.
So that you can use DSN to specify connection protocol at runtime:
```rust ```rust
async fn demo() -> Result<(), Error> { use taos::*; // use it like a `prelude` mod, we need some traits at next.
// get connection ...
// create database // use native protocol.
conn.exec("create database if not exists demo").await? let builder = TaosBuilder::from_dsn("taos://localhost:6030")?;
// change database context let conn1 = builder.build();
conn.exec("use demo").await?
// create table // use websocket protocol.
conn.exec("create table if not exists tb1 (ts timestamp, v int)").await? let conn2 = TaosBuilder::from_dsn("taos+ws://localhost:6041")?;
// insert ```
conn.exec("insert into tb1 values(now, 1)").await?
// query After connected, you can perform the following operations on the database.
let rows = conn.query("select * from tb1").await?
for row in rows.rows { ```rust
println!("{}", row.into_iter().join(",")); async fn demo(taos: &Taos, db: &str) -> Result<(), Error> {
// prepare database
taos.exec_many([
format!("DROP DATABASE IF EXISTS `{db}`"),
format!("CREATE DATABASE `{db}`"),
format!("USE `{db}`"),
])
.await?;
let inserted = taos.exec_many([
// create super table
"CREATE TABLE `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) \
TAGS (`groupid` INT, `location` BINARY(16))",
// create child table
"CREATE TABLE `d0` USING `meters` TAGS(0, 'Los Angles')",
// insert into child table
"INSERT INTO `d0` values(now - 10s, 10, 116, 0.32)",
// insert with NULL values
"INSERT INTO `d0` values(now - 8s, NULL, NULL, NULL)",
// insert and automatically create table with tags if not exists
"INSERT INTO `d1` USING `meters` TAGS(1, 'San Francisco') values(now - 9s, 10.1, 119, 0.33)",
// insert many records in a single sql
"INSERT INTO `d1` values (now-8s, 10, 120, 0.33) (now - 6s, 10, 119, 0.34) (now - 4s, 11.2, 118, 0.322)",
]).await?;
assert_eq!(inserted, 6);
let mut result = taos.query("select * from `meters`").await?;
for field in result.fields() {
println!("got field: {}", field.name());
} }
let values = result.
} }
``` ```
Rust connector provides two kinds of ways to fetch data:
```rust
// Query option 1, use rows stream.
let mut rows = result.rows();
while let Some(row) = rows.try_next().await? {
for (name, value) in row {
println!("got value of {}: {}", name, value);
}
}
// Query options 2, use deserialization with serde.
#[derive(Debug, serde::Deserialize)]
#[allow(dead_code)]
struct Record {
// deserialize timestamp to chrono::DateTime<Local>
ts: DateTime<Local>,
// float to f32
current: Option<f32>,
// int to i32
voltage: Option<i32>,
phase: Option<f32>,
groupid: i32,
// binary/varchar to String
location: String,
}
let records: Vec<Record> = taos
.query("select * from `meters`")
.await?
.deserialize()
.try_collect()
.await?;
dbg!(records);
Ok(())
```
## Usage examples ## Usage examples
### Write data ### Write data
@ -151,122 +225,138 @@ async fn demo() -> Result<(), Error> {
<RustInsert /> <RustInsert />
#### InfluxDB line protocol write #### Stmt bind
<RustInfluxLine /> <RustBind />
#### OpenTSDB Telnet line protocol write
<RustOpenTSDBTelnet />
#### OpenTSDB JSON line protocol write
<RustOpenTSDBJson />
### Query data ### Query data
<RustQuery /> <RustQuery />|
### More sample programs
| Program Path | Program Description |
| -------------- | ----------------------------------------------------------------------------- |
| [demo.rs] | Basic API Usage Examples |
| [bailongma-rs] | Using TDengine as the Prometheus remote storage API adapter for the storage backend, using the r2d2 connection pool |
## API Reference ## API Reference
### Connection constructor API ### Connector builder
The [Builder Pattern](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html) constructor pattern is Rust's solution for handling complex data types or optional configuration types. The [libtaos] implementation uses the connection constructor [TaosCfgBuilder] as the entry point for the TDengine Rust connector. The [TaosCfgBuilder] provides optional configuration of servers, ports, databases, usernames, passwords, etc. Use DSN to directly construct a TaosBuilder object.
Using the `default()` method, you can construct a [TaosCfg] with default parameters for subsequent connections to the database or establishing connection pools.
```rust ```rust
let cfg = TaosCfgBuilder::default().build()? ; let builder = TaosBuilder::from_dsn("")? ;
``` ```
Using the constructor pattern, the user can set on-demand. Use `builder` to create many connections:
```rust ```rust
let cfg = TaosCfgBuilder::default() let conn: Taos = cfg.build();
.ip("127.0.0.1")
.user("root")
.pass("taosdata")
.db("log")
.port(6030u16)
.build()? ;
``` ```
Create TDengine connection using [TaosCfg] object. ### Connection pool
In complex applications, we recommend enabling connection pools. Connection pool for [taos] is implemented using [r2d2] by enabling "r2d2" feature.
Basically, a connection pool with default parameters can be generated as:
```rust ```rust
let conn: Taos = cfg.connect(); let pool = TaosBuilder::from_dsn(dsn)?.pool()?;
``` ```
### Connection pooling You can set the connection pool parameters using the `PoolBuilder`.
In complex applications, we recommend enabling connection pools. Connection pool for [libtaos] is implemented using [r2d2].
As follows, a connection pool with default parameters can be generated.
```rust ```rust
let pool = r2d2::Pool::new(cfg)? ; let dsn = "taos://localhost:6030";
let opts = PoolBuilder::new()
.max_size(5000) // max connections
.max_lifetime(Some(Duration::from_secs(60 * 60))) // lifetime of each connection
.min_idle(Some(1000)) // minimal idle connections
.connection_timeout(Duration::from_secs(2));
let pool = TaosBuilder::from_dsn(dsn)?.with_pool_builder(opts)?;
``` ```
You can set the same connection pool parameters using the connection pool's constructor. In the application code, use `pool.get()?` to get a connection object [Taos].
```rust
use std::time::Duration;
let pool = r2d2::Pool::builder()
.max_size(5000) // max connections
.max_lifetime(Some(Duration::from_minutes(100))) // lifetime of each connection
.min_idle(Some(1000)) // minimal idle connections
.connection_timeout(Duration::from_minutes(2))
.build(cfg);
```
In the application code, use `pool.get()? ` to get a connection object [Taos].
```rust ```rust
let taos = pool.get()? ; let taos = pool.get()? ;
``` ```
The [Taos] structure is the connection manager in [libtaos] and provides two main APIs. ### Connection methods
1. `exec`: Execute some non-query SQL statements, such as `CREATE`, `ALTER`, `INSERT`, etc. The [Taos] connection struct provides several APIs for convenient use.
1. `exec`: Execute some non-query SQL statements, such as `CREATE`, `ALTER`, `INSERT` etc. and return affected rows (only meaningful to `INSERT`).
```rust ```rust
taos.exec().await? let affected_rows = taos.exec("INSERT INTO tb1 VALUES(now, NULL)").await?;
``` ```
2. `query`: Execute the query statement and return the [TaosQueryData] object. 2. `exec_many`: You can execute many SQL statements in order with `exec_many` method.
```rust ```rust
let q = taos.query("select * from log.logs").await? taos.exec_many([
"CREATE DATABASE test",
"USE test",
"CREATE TABLE `tb1` (`ts` TIMESTAMP, `val` INT)",
]).await?;
``` ```
The [TaosQueryData] object stores the query result data and basic information about the returned columns (column name, type, length). 3. `query`: Execute the query statement and return the [ResultSet] object.
Column information is stored using [ColumnMeta].
```rust ```rust
let cols = &q.column_meta; let mut q = taos.query("select * from log.logs").await?
```
The [ResultSet] object stores the query result data and basic information about the returned columns (column name, type, length).
Get filed information with `fields` method.
```rust
let cols = q.fields();
for col in cols { for col in cols {
println!("name: {}, type: {:?} , bytes: {}", col.name, col.type_, col.bytes); println!("name: {}, type: {:?} , bytes: {}", col.name(), col.ty(), col.bytes());
} }
``` ```
It fetches data line by line. Users could fetch data by rows.
```rust ```rust
for (i, row) in q.rows.iter().enumerate() { let mut rows = result.rows();
for (j, cell) in row.iter().enumerate() { let mut nrows = 0;
println!("cell({}, {}) data: {}", i, j, cell); while let Some(row) = rows.try_next().await? {
for (col, (name, value)) in row.enumerate() {
println!(
"[{}] got value in col {} (named `{:>8}`): {}",
nrows, col, name, value
);
} }
nrows += 1;
} }
``` ```
Or use it with [serde](https://serde.rs) deserialization.
```rust
#[derive(Debug, Deserialize)]
struct Record {
// deserialize timestamp to chrono::DateTime<Local>
ts: DateTime<Local>,
// float to f32
current: Option<f32>,
// int to i32
voltage: Option<i32>,
phase: Option<f32>,
groupid: i32,
// binary/varchar to String
location: String,
}
let records: Vec<Record> = taos
.query("select * from `meters`")
.await?
.deserialize()
.try_collect()
.await?;
```
Note that Rust asynchronous functions and an asynchronous runtime are required. Note that Rust asynchronous functions and an asynchronous runtime are required.
[Taos] provides a few Rust methods that encapsulate SQL to reduce the frequency of `format!` code blocks. [Taos] provides a few Rust methods that encapsulate SQL to reduce the frequency of `format!` code blocks.
@ -275,110 +365,152 @@ Note that Rust asynchronous functions and an asynchronous runtime are required.
- `.create_database(database: &str)`: Executes the `CREATE DATABASE` statement. - `.create_database(database: &str)`: Executes the `CREATE DATABASE` statement.
- `.use_database(database: &str)`: Executes the `USE` statement. - `.use_database(database: &str)`: Executes the `USE` statement.
In addition, this structure is also the entry point for [Parameter Binding](#Parameter Binding Interface) and [Line Protocol Interface](#Line Protocol Interface). Please refer to the specific API descriptions for usage. ### Bind API
### Bind Interface Similar to the C interface, Rust provides the bind interface's wrapping. First, create a bind object [Stmt] for a SQL command with the [Taos] object.
Similar to the C interface, Rust provides the bind interface's wrapping. First, create a bind object [Stmt] for a SQL command from the [Taos] object.
```rust ```rust
let mut stmt: Stmt = taos.stmt("insert into ? values(? ,?)") ? ; let mut stmt = Stmt::init(&taos).await?;
stmt.prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)")?;
``` ```
The bind object provides a set of interfaces for implementing parameter binding. The bind object provides a set of interfaces for implementing parameter binding.
##### `.set_tbname(tbname: impl ToCString)` #### `.set_tbname(name)`
To bind table names. To bind table names.
##### `.set_tbname_tags(tbname: impl ToCString, tags: impl IntoParams)`
Bind sub-table table names and tag values when the SQL statement uses a super table.
```rust ```rust
let mut stmt = taos.stmt("insert into ? using stb0 tags(?) values(? ,?)") ? ; let mut stmt = taos.stmt("insert into ? values(? ,?)")?;
// tags can be created with any supported type, here is an example using JSON stmt.set_tbname("d0")?;
let v = Field::Json(serde_json::from_str("{\"tag1\":\"one, two, three, four, five, six, seven, eight, nine, ten\"}").unwrap());
stmt.set_tbname_tags("tb0", [&tag])? ;
``` ```
##### `.bind(params: impl IntoParams)` #### `.set_tags(&[tag])`
Bind value types. Use the [Field] structure to construct the desired type and bind. Bind tag values when the SQL statement uses a super table.
```rust ```rust
let ts = Field::Timestamp(Timestamp::now()); let mut stmt = taos.stmt("insert into ? using stb0 tags(?) values(? ,?)")?;
let value = Field::Float(0.0); stmt.set_tbname("d0")?;
stmt.bind(vec![ts, value].iter())? ; stmt.set_tags(&[Value::VarChar("涛思".to_string())])?;
``` ```
##### `.execute()` #### `.bind(&[column])`
Execute SQL.[Stmt] objects can be reused, re-binded, and executed after execution. Bind value types. Use the [ColumnView] structure to construct the desired type and bind.
```rust ```rust
stmt.execute()? ; let params = vec![
ColumnView::from_millis_timestamp(vec![164000000000]),
ColumnView::from_bools(vec![true]),
ColumnView::from_tiny_ints(vec![i8::MAX]),
ColumnView::from_small_ints(vec![i16::MAX]),
ColumnView::from_ints(vec![i32::MAX]),
ColumnView::from_big_ints(vec![i64::MAX]),
ColumnView::from_unsigned_tiny_ints(vec![u8::MAX]),
ColumnView::from_unsigned_small_ints(vec![u16::MAX]),
ColumnView::from_unsigned_ints(vec![u32::MAX]),
ColumnView::from_unsigned_big_ints(vec![u64::MAX]),
ColumnView::from_floats(vec![f32::MAX]),
ColumnView::from_doubles(vec![f64::MAX]),
ColumnView::from_varchar(vec!["ABC"]),
ColumnView::from_nchar(vec!["涛思数据"]),
];
let rows = stmt.bind(&params)?.add_batch()?.execute()?;
```
#### `.execute()`
Execute to insert all bind records. [Stmt] objects can be reused, re-bind, and executed after execution. Remember to call `add_batch` before `execute`.
```rust
stmt.add_batch()?.execute()?;
// next bind cycle. // next bind cycle.
// stmt.set_tbname()? ; // stmt.set_tbname()? ;
//stmt.bind()? ; //stmt.bind()? ;
//stmt.execute()? ; //stmt.add_batch().execute()? ;
``` ```
### Line protocol interface A runnable example for bind can be found [here](https://github.com/taosdata/taos-connector-rust/blob/main/examples/bind.rs).
The line protocol interface supports multiple modes and different precision and requires the introduction of constants in the schemaless module to set. ### Subscription API
Users can subscribe a [TOPIC](../../../taos-sql/tmq/) with TMQ(the TDengine Message Queue) API.
Start from a TMQ builder:
```rust ```rust
use libtaos::*; let tmq = TmqBuilder::from_dsn("taos://localhost:6030/?group.id=test")?;
use libtaos::schemaless::*;
``` ```
- InfluxDB line protocol Build a consumer:
```rust ```rust
let lines = [ let mut consumer = tmq.build()?;
"st,t1=abc,t2=def,t3=anything c1=3i64,c3=L\"pass\",c2=false 1626006833639000000" ```
"st,t1=abc,t2=def,t3=anything c1=3i64,c3=L\"abc\",c4=4f64 1626006833639000000"
];
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANOSECONDS)? ;
```
- OpenTSDB Telnet Protocol Subscribe a topic:
```rust ```rust
let lines = ["sys.if.bytes.out 1479496100 1.3E3 host=web01 interface=eth0"]; consumer.subscribe(["tmq_meters"]).await?;
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_SECONDS)? ; ```
```
- OpenTSDB JSON protocol Consume messages, and commit the offset for each message.
```rust ```rust
let lines = [r#" {
{ let mut stream = consumer.stream();
"metric": "st",
"timestamp": 1626006833, while let Some((offset, message)) = stream.try_next().await? {
"value": 10, // get information from offset
"tags": {
"t1": true, // the topic
"t2": false, let topic = offset.topic();
"t3": 10, // the vgroup id, like partition id in kafka.
"t4": "123_abc_.! @#$%^&*:;,. /? |+-=()[]{}<>" let vgroup_id = offset.vgroup_id();
println!("* in vgroup id {vgroup_id} of topic {topic}\n");
if let Some(data) = message.into_data() {
while let Some(block) = data.fetch_raw_block().await? {
// one block for one table, get table name if needed
let name = block.table_name();
let records: Vec<Record> = block.deserialize().try_collect()?;
println!(
"** table: {}, got {} records: {:#?}\n",
name.unwrap(),
records.len(),
records
);
} }
}"#]; }
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_SECONDS)? ; consumer.commit(offset).await?;
``` }
}
```
Please move to the Rust documentation hosting page for other related structure API usage instructions: <https://docs.rs/libtaos>. Unsubscribe:
[libtaos]: https://github.com/taosdata/libtaos-rs ```rust
[tdengine]: https://github.com/taosdata/TDengine consumer.unsubscribe().await;
[bailongma-rs]: https://github.com/taosdata/bailongma-rs ```
In TMQ DSN, you must choose to subscribe with a group id. Also, there's several options could be set:
- `group.id`: **Required**, a group id is any visible string you set.
- `client.id`: a optional client description string.
- `auto.offset.reset`: choose to subscribe from *earliest* or *latest*, default is *none* which means 'earliest'.
- `enable.auto.commit`: automatically commit with specified time interval. By default - in the recommended way _ you must use `commit` to ensure that you've consumed the messages correctly, otherwise, consumers will received repeated messages when re-subscribe.
- `auto.commit.interval.ms`: the auto commit interval in milliseconds.
Check the whole subscription example at [GitHub](https://github.com/taosdata/taos-connector-rust/blob/main/examples/subscribe.rs).
Please move to the Rust documentation hosting page for other related structure API usage instructions: <https://docs.rs/taos>.
[TDengine]: https://github.com/taosdata/TDengine
[r2d2]: https://crates.io/crates/r2d2 [r2d2]: https://crates.io/crates/r2d2
[demo.rs]: https://github.com/taosdata/libtaos-rs/blob/main/examples/demo.rs [Taos]: https://docs.rs/taos/latest/taos/struct.Taos.html
[TaosCfgBuilder]: https://docs.rs/libtaos/latest/libtaos/struct.TaosCfgBuilder.html [ResultSet]: https://docs.rs/taos/latest/taos/struct.ResultSet.html
[TaosCfg]: https://docs.rs/libtaos/latest/libtaos/struct.TaosCfg.html [Value]: https://docs.rs/taos/latest/taos/enum.Value.html
[Taos]: https://docs.rs/libtaos/latest/libtaos/struct.Taos.html [Stmt]: https://docs.rs/taos/latest/taos/stmt/struct.Stmt.html
[TaosQueryData]: https://docs.rs/libtaos/latest/libtaos/field/struct.TaosQueryData.html [taos]: https://crates.io/crates/taos
[Field]: https://docs.rs/libtaos/latest/libtaos/field/enum.Field.html
[Stmt]: https://docs.rs/libtaos/latest/libtaos/stmt/struct.Stmt.html

View File

@ -47,27 +47,28 @@ If the displayed content is followed by `...` you can use this command to change
You can change the behavior of TDengine CLI by specifying command-line parameters. The following parameters are commonly used. You can change the behavior of TDengine CLI by specifying command-line parameters. The following parameters are commonly used.
- -h, --host=HOST: FQDN of the server where the TDengine server is to be connected. Default is to connect to the local service - -h HOST: FQDN of the server where the TDengine server is to be connected. Default is to connect to the local service
- -P, --port=PORT: Specify the port number to be used by the server. Default is `6030` - -P PORT: Specify the port number to be used by the server. Default is `6030`
- -u, --user=USER: the user name to use when connecting. Default is `root` - -u USER: the user name to use when connecting. Default is `root`
- -p, --password=PASSWORD: the password to use when connecting to the server. Default is `taosdata` - -p PASSWORD: the password to use when connecting to the server. Default is `taosdata`
- -?, --help: print out all command-line arguments - -?, --help: print out all command-line arguments
And many more parameters. And many more parameters.
- -c, --config-dir: Specify the directory where configuration file exists. The default is `/etc/taos`, and the default name of the configuration file in this directory is `taos.cfg` - -a AUTHSTR: The auth string to use when connecting to the server
- -C, --dump-config: Print the configuration parameters of `taos.cfg` in the default directory or specified by -c - -A: Generate auth string from password
- -d, --database=DATABASE: Specify the database to use when connecting to the server - -c CONFIGDIR: Specify the directory where configuration file exists. The default is `/etc/taos`, and the default name of the configuration file in this directory is `taos.cfg`
- -D, --directory=DIRECTORY: Import the SQL script file in the specified path - -C: Print the configuration parameters of `taos.cfg` in the default directory or specified by -c
- -f, --file=FILE: Execute the SQL script file in non-interactive mode - -d DATABASE: Specify the database to use when connecting to the server
- -k, --check=CHECK: Specify the table to be checked - -f FILE: Execute the SQL script file in non-interactive mode
- -l, --pktlen=PKTLEN: Test package size to be used for network testing - -k: Check the service status, 0: unavailable1: network ok2: service ok3: service degraded4: exiting
- -n, --netrole=NETROLE: test scope for network connection test, default is `startup`. The value can be `client`, `server`, `rpc`, `startup`, `sync`, `speed`, or `fqdn`. - -l PKTLEN: Test package length to be used for network testing
- -r, --raw-time: output the timestamp format as unsigned 64-bits integer (uint64_t in C language) - -n NETROLE: test scope for network connection test, default is `client`. The value can be `client`, `server`
- -s, --commands=COMMAND: execute SQL commands in non-interactive mode - -N PKTNUM: Test package numbers to be used for network testing
- -S, --pkttype=PKTTYPE: Specify the packet type used for network testing. The default is TCP, can be specified as either TCP or UDP when `speed` is specified to `netrole` parameter - -r: output the timestamp format as unsigned 64-bits integer (uint64_t in C language)
- -T, --thread=THREADNUM: The number of threads to import data in multi-threaded mode - -s COMMAND: execute SQL commands in non-interactive mode
- -s, --commands: Run TDengine CLI commands without entering the terminal - -t: Check the details of the service statusstatus same as -k
- -w DISPLAYWIDTH: 客户端列显示宽度
- -z, --timezone=TIMEZONE: Specify time zone. Default is the value of current configuration file - -z, --timezone=TIMEZONE: Specify time zone. Default is the value of current configuration file
- -V, --version: Print out the current version number - -V, --version: Print out the current version number

View File

@ -5,12 +5,11 @@ description: "List of platforms supported by TDengine server, client, and connec
## List of supported platforms for TDengine server ## List of supported platforms for TDengine server
| | **CentOS 7/8** | **Ubuntu 16/18/20** | **Other Linux** | | | **Windows 10/11** | **CentOS 7.9/8** | **Ubuntu 18/20** | **Other Linux** | **UOS** | **Kylin** | **Ningsi V60/V80** | **HUAWEI EulerOS** |
| ------------ | -------------- | ------------------- | --------------- | | ------------------ | ----------------- | ---------------- | ---------------- | --------------- | ------- | --------- | ------------------ | ------------------ |
| X64 | ● | ● | | | X64 | ● | ● | ● | | ● | ● | ● | |
| MIPS64 | | | ● | | Raspberry Pi ARM64 | | | | ● | | | | |
| ARM64 | | ○ | ○ | | HUAWEI cloud ARM64 | | | | | | | | ● |
| Alpha64 | | | ○ |
Note: ● means officially tested and verified, ○ means unofficially tested and verified. Note: ● means officially tested and verified, ○ means unofficially tested and verified.
@ -20,15 +19,15 @@ TDengine's connector can support a wide range of platforms, including X64/X86/AR
The comparison matrix is as follows. The comparison matrix is as follows.
| **CPU** | **X64 64bit** | | | **X86 32bit** | **ARM64** | **ARM32** | **MIPS** | **Alpha** | | **CPU** | **X64 64bit** | | | **X86 32bit** | **ARM64** | **MIPS** | **Alpha** |
| ----------- | ------------- | --------- | --------- | ------------- | --------- | --------- | --------- | --------- | | ----------- | ------------- | --------- | --------- | ------------- | --------- | --------- | --------- |
| **OS** | **Linux** | **Win64** | **Win32** | **Win32** | **Linux** | **Linux** | **Linux** | **Linux** | | **OS** | **Linux** | **Win64** | **Win32** | **Win32** | **Linux** | **Linux** | **Linux** |
| **C/C++** | ● | ● | ● | ○ | ● | ● | ● | ● | | **C/C++** | ● | ● | ● | ○ | ● | ● | ● |
| **JDBC** | ● | ● | ● | ○ | ● | ● | ● | ● | | **JDBC** | ● | ● | ● | ○ | ● | ● | ● |
| **Python** | ● | ● | ● | ○ | ● | ● | ● | -- | | **Python** | ● | ● | ● | ○ | ● | ● | -- |
| **Go** | ● | ● | ● | ○ | ● | ● | ○ | -- | | **Go** | ● | ● | ● | ○ | ● | ○ | -- |
| **NodeJs** | ● | ● | ○ | ○ | ● | ● | ○ | -- | | **NodeJs** | ● | ● | ○ | ○ | ● | ○ | -- |
| **C#** | ● | ● | ○ | ○ | ○ | ○ | ○ | -- | | **C#** | ● | ● | ○ | ○ | ○ | ○ | -- |
| **RESTful** | ● | ● | ● | ● | ● | ● | ● | ● | | **RESTful** | ● | ● | ● | ● | ● | ● | ● |
Note: ● means the official test is verified, ○ means the unofficial test is verified, -- means not verified. Note: ● means the official test is verified, ○ means the unofficial test is verified, -- means not verified.

View File

@ -25,7 +25,6 @@ All executable files of TDengine are in the _/usr/local/taos/bin_ directory by d
- _taosBenchmark_: TDengine testing tool - _taosBenchmark_: TDengine testing tool
- _remove.sh_: script to uninstall TDengine, please execute it carefully, link to the **rmtaos** command in the /usr/bin directory. Will remove the TDengine installation directory `/usr/local/taos`, but will keep `/etc/taos`, `/var/lib/taos`, `/var/log/taos` - _remove.sh_: script to uninstall TDengine, please execute it carefully, link to the **rmtaos** command in the /usr/bin directory. Will remove the TDengine installation directory `/usr/local/taos`, but will keep `/etc/taos`, `/var/lib/taos`, `/var/log/taos`
- _taosadapter_: server-side executable that provides RESTful services and accepts writing requests from a variety of other softwares - _taosadapter_: server-side executable that provides RESTful services and accepts writing requests from a variety of other softwares
- _tarbitrator_: provides arbitration for two-node cluster deployments
- _TDinsight.sh_: script to download TDinsight and install it - _TDinsight.sh_: script to download TDinsight and install it
- _set_core.sh_: script for setting up the system to generate core dump files for easy debugging - _set_core.sh_: script for setting up the system to generate core dump files for easy debugging
- _taosd-dump-cfg.gdb_: script to facilitate debugging of taosd's gdb execution. - _taosd-dump-cfg.gdb_: script to facilitate debugging of taosd's gdb execution.

View File

@ -3,7 +3,7 @@ title: Schemaless Writing
description: "The Schemaless write method eliminates the need to create super tables/sub tables in advance and automatically creates the storage structure corresponding to the data, as it is written to the interface." description: "The Schemaless write method eliminates the need to create super tables/sub tables in advance and automatically creates the storage structure corresponding to the data, as it is written to the interface."
--- ---
In IoT applications, data is collected for many purposes such as intelligent control, business analysis, device monitoring and so on. Due to changes in business or functional requirements or changes in device hardware, the application logic and even the data collected may change. To provide the flexibility needed in such cases and in a rapidly changing IoT landscape, TDengine starting from version 2.2.0.0, provides a series of interfaces for the schemaless writing method. These interfaces eliminate the need to create super tables and subtables in advance by automatically creating the storage structure corresponding to the data as the data is written to the interface. When necessary, schemaless writing will automatically add the required columns to ensure that the data written by the user is stored correctly. In IoT applications, data is collected for many purposes such as intelligent control, business analysis, device monitoring and so on. Due to changes in business or functional requirements or changes in device hardware, the application logic and even the data collected may change. To provide the flexibility needed in such cases and in a rapidly changing IoT landscape, TDengine provides a series of interfaces for the schemaless writing method. These interfaces eliminate the need to create super tables and subtables in advance by automatically creating the storage structure corresponding to the data as the data is written to the interface. When necessary, schemaless writing will automatically add the required columns to ensure that the data written by the user is stored correctly.
The schemaless writing method creates super tables and their corresponding subtables. These are completely indistinguishable from the super tables and subtables created directly via SQL. You can write data directly to them via SQL statements. Note that the names of tables created by schemaless writing are based on fixed mapping rules for tag values, so they are not explicitly ideographic and they lack readability. The schemaless writing method creates super tables and their corresponding subtables. These are completely indistinguishable from the super tables and subtables created directly via SQL. You can write data directly to them via SQL statements. Note that the names of tables created by schemaless writing are based on fixed mapping rules for tag values, so they are not explicitly ideographic and they lack readability.
@ -39,10 +39,10 @@ In the schemaless writing data line protocol, each data item in the field_set ne
| -------- | -------- | ------------ | -------------- | | -------- | -------- | ------------ | -------------- |
| 1 | none or f64 | double | 8 | | 1 | none or f64 | double | 8 |
| 2 | f32 | float | 4 | | 2 | f32 | float | 4 |
| 3 | i8 | TinyInt | 1 | | 3 | i8/u8 | TinyInt/UTinyInt | 1 |
| 4 | i16 | SmallInt | 2 | | 4 | i16/u16 | SmallInt/USmallInt | 2 |
| 5 | i32 | Int | 4 | | 5 | i32/u32 | Int/UInt | 4 |
| 6 | i64 or i | Bigint | 8 | | 6 | i64/i/u64/u | Bigint/Bigint/UBigint/UBigint | 8 |
- `t`, `T`, `true`, `True`, `TRUE`, `f`, `F`, `false`, and `False` will be handled directly as BOOL types. - `t`, `T`, `true`, `True`, `TRUE`, `f`, `F`, `false`, and `False` will be handled directly as BOOL types.
@ -72,11 +72,11 @@ If the subtable obtained by the parse line protocol does not exist, Schemaless c
4. If the specified tag or regular column in the data row does not exist, the corresponding tag or regular column is added to the super table (only incremental). 4. If the specified tag or regular column in the data row does not exist, the corresponding tag or regular column is added to the super table (only incremental).
5. If there are some tag columns or regular columns in the super table that are not specified to take values in a data row, then the values of these columns are set to NULL. 5. If there are some tag columns or regular columns in the super table that are not specified to take values in a data row, then the values of these columns are set to NULL.
6. For BINARY or NCHAR columns, if the length of the value provided in a data row exceeds the column type limit, the maximum length of characters allowed to be stored in the column is automatically increased (only incremented and not decremented) to ensure complete preservation of the data. 6. For BINARY or NCHAR columns, if the length of the value provided in a data row exceeds the column type limit, the maximum length of characters allowed to be stored in the column is automatically increased (only incremented and not decremented) to ensure complete preservation of the data.
7. If the specified data subtable already exists, and the specified tag column takes a value different from the saved value this time, the value in the latest data row overwrites the old tag column take value. 7. Errors encountered throughout the processing will interrupt the writing process and return an error code.
8. Errors encountered throughout the processing will interrupt the writing process and return an error code. 8. In order to improve the efficiency of writing, it is assumed by default that the order of the fields in the same Super is the same (the first data contains all fields, and the following data is in this order). If the order is different, the parameter smlDataFormat needs to be configured to be false. Otherwise, the data is written in the same order, and the data in the library will be abnormal.
:::tip :::tip
All processing logic of schemaless will still follow TDengine's underlying restrictions on data structures, such as the total length of each row of data cannot exceed 48k bytes. See [TAOS SQL Boundary Limits](/taos-sql/limit) for specific constraints in this area. All processing logic of schemaless will still follow TDengine's underlying restrictions on data structures, such as the total length of each row of data cannot exceed 16k bytes. See [TAOS SQL Boundary Limits](/taos-sql/limit) for specific constraints in this area.
::: :::
## Time resolution recognition ## Time resolution recognition

View File

@ -1,2 +1,2 @@
[workspace] [workspace]
members = ["restexample", "nativeexample", "schemalessexample"] members = ["restexample", "nativeexample"]

View File

@ -5,6 +5,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
libtaos = { version = "0.4.3" } anyhow = "1"
tokio = { version = "*", features = ["rt", "macros", "rt-multi-thread"] } chrono = "0.4"
bstr = { version = "*" } serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["rt", "macros", "rt-multi-thread"] }
taos = { version = "0.*" }

View File

@ -1,19 +1,9 @@
use libtaos::*; use taos::*;
fn taos_connect() -> Result<Taos, Error> { #[tokio::main]
TaosCfgBuilder::default() async fn main() -> Result<(), Error> {
.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)] #[allow(unused_variables)]
let taos = taos_connect().unwrap(); let taos = TaosBuilder::from_dsn("taos://")?.build()?;
println!("Connected") println!("Connected");
Ok(())
} }

View File

@ -1,38 +1,40 @@
use bstr::BString; use taos::*;
use libtaos::*;
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Error> { async fn main() -> anyhow::Result<()> {
let taos = TaosCfg::default().connect().expect("fail to connect"); let taos = TaosBuilder::from_dsn("taos://")?.build()?;
taos.create_database("power").await?; taos.create_database("power").await?;
taos.use_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?; taos.exec("CREATE STABLE IF NOT EXISTS 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(?, ?, ?, ?)")?;
let mut stmt = Stmt::init(&taos)?;
stmt.prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)")?;
// bind table name and tags // bind table name and tags
stmt.set_tbname_tags( stmt.set_tbname_tags(
"d1001", "d1001",
[ &[Value::VarChar("San Fransico".into()), Value::Int(2)],
Field::Binary(BString::from("California.SanFrancisco")),
Field::Int(2),
],
)?; )?;
// bind values. // bind values.
let values = vec![ let values = vec![
Field::Timestamp(Timestamp::new(1648432611249, TimestampPrecision::Milli)), ColumnView::from_millis_timestamp(vec![1648432611249]),
Field::Float(10.3), ColumnView::from_floats(vec![10.3]),
Field::Int(219), ColumnView::from_ints(vec![219]),
Field::Float(0.31), ColumnView::from_floats(vec![0.31]),
]; ];
stmt.bind(&values)?; stmt.bind(&values)?;
// bind one more row // bind one more row
let values2 = vec![ let values2 = vec![
Field::Timestamp(Timestamp::new(1648432611749, TimestampPrecision::Milli)), ColumnView::from_millis_timestamp(vec![1648432611749]),
Field::Float(12.6), ColumnView::from_floats(vec![12.6]),
Field::Int(218), ColumnView::from_ints(vec![218]),
Field::Float(0.33), ColumnView::from_floats(vec![0.33]),
]; ];
stmt.bind(&values2)?; stmt.bind(&values2)?;
// execute
stmt.execute()?; stmt.add_batch()?;
// execute.
let rows = stmt.execute()?;
assert_eq!(rows, 2);
Ok(()) Ok(())
} }

View File

@ -1,3 +1,101 @@
fn main() { use std::time::Duration;
} use chrono::{DateTime, Local};
use taos::*;
// Query options 2, use deserialization with serde.
#[derive(Debug, serde::Deserialize)]
#[allow(dead_code)]
struct Record {
// deserialize timestamp to chrono::DateTime<Local>
ts: DateTime<Local>,
// float to f32
current: Option<f32>,
// int to i32
voltage: Option<i32>,
phase: Option<f32>,
}
async fn prepare(taos: Taos) -> anyhow::Result<()> {
let inserted = taos.exec_many([
// create child table
"CREATE TABLE `d0` USING `meters` TAGS(0, 'Los Angles')",
// insert into child table
"INSERT INTO `d0` values(now - 10s, 10, 116, 0.32)",
// insert with NULL values
"INSERT INTO `d0` values(now - 8s, NULL, NULL, NULL)",
// insert and automatically create table with tags if not exists
"INSERT INTO `d1` USING `meters` TAGS(1, 'San Francisco') values(now - 9s, 10.1, 119, 0.33)",
// insert many records in a single sql
"INSERT INTO `d1` values (now-8s, 10, 120, 0.33) (now - 6s, 10, 119, 0.34) (now - 4s, 11.2, 118, 0.322)",
]).await?;
assert_eq!(inserted, 6);
Ok(())
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let dsn = "taos://localhost:6030";
let builder = TaosBuilder::from_dsn(dsn)?;
let taos = builder.build()?;
let db = "tmq";
// prepare database
taos.exec_many([
format!("DROP TOPIC IF EXISTS tmq_meters"),
format!("DROP DATABASE IF EXISTS `{db}`"),
format!("CREATE DATABASE `{db}`"),
format!("USE `{db}`"),
// create super table
format!("CREATE TABLE `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"),
// create topic for subscription
format!("CREATE TOPIC tmq_meters with META AS DATABASE {db}")
])
.await?;
let task = tokio::spawn(prepare(taos));
tokio::time::sleep(Duration::from_secs(1)).await;
// subscribe
let tmq = TmqBuilder::from_dsn("taos://localhost:6030/?group.id=test")?;
let mut consumer = tmq.build()?;
consumer.subscribe(["tmq_meters"]).await?;
{
let mut stream = consumer.stream();
while let Some((offset, message)) = stream.try_next().await? {
// get information from offset
// the topic
let topic = offset.topic();
// the vgroup id, like partition id in kafka.
let vgroup_id = offset.vgroup_id();
println!("* in vgroup id {vgroup_id} of topic {topic}\n");
if let Some(data) = message.into_data() {
while let Some(block) = data.fetch_raw_block().await? {
// one block for one table, get table name if needed
let name = block.table_name();
let records: Vec<Record> = block.deserialize().try_collect()?;
println!(
"** table: {}, got {} records: {:#?}\n",
name.unwrap(),
records.len(),
records
);
}
}
consumer.commit(offset).await?;
}
}
consumer.unsubscribe().await;
task.await??;
Ok(())
}

View File

@ -4,5 +4,9 @@ version = "0.1.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
libtaos = { version = "0.4.3", features = ["rest"] } anyhow = "1"
tokio = { version = "*", features = ["rt", "macros", "rt-multi-thread"] } chrono = "0.4"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["rt", "macros", "rt-multi-thread"] }
taos = { version = "0.*" }

View File

@ -1,20 +1,9 @@
use libtaos::*; use taos::*;
fn taos_connect() -> Result<Taos, Error> {
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()
}
#[tokio::main] #[tokio::main]
async fn main() { async fn main() -> Result<(), Error> {
#[allow(unused_variables)] #[allow(unused_variables)]
let taos = taos_connect().expect("connect error"); let taos = TaosBuilder::from_dsn("taos://")?.build()?;
println!("Connected") println!("Connected");
Ok(())
} }

View File

@ -1,18 +1,29 @@
use libtaos::*; use taos::*;
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Error> { async fn main() -> anyhow::Result<()> {
let taos = TaosCfg::default().connect().expect("fail to connect"); let dsn = "ws://";
taos.create_database("power").await?; let taos = TaosBuilder::from_dsn(dsn)?.build()?;
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(California.SanFrancisco, 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(California.SanFrancisco, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) taos.exec_many([
power.d1003 USING power.meters TAGS(California.LosAngeles, 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) "DROP DATABASE IF EXISTS power",
power.d1004 USING power.meters TAGS(California.LosAngeles, 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)"; "CREATE DATABASE power",
let result = taos.query(sql).await?; "USE power",
println!("{:?}", result); "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"
]).await?;
let inserted = taos.exec("INSERT INTO
power.d1001 USING power.meters TAGS('San Francisco', 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('San Francisco', 3)
VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)
power.d1003 USING power.meters TAGS('Los Angeles', 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('Los Angeles', 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)").await?;
assert_eq!(inserted, 8);
Ok(()) Ok(())
} }
// output:
// TaosQueryData { column_meta: [ColumnMeta { name: "affected_rows", type_: Int, bytes: 4 }], rows: [[Int(8)]] }

View File

@ -1,39 +1,25 @@
use libtaos::*; use taos::sync::*;
fn taos_connect() -> Result<Taos, Error> { fn main() -> anyhow::Result<()> {
TaosCfgBuilder::default() let taos = TaosBuilder::from_dsn("ws:///power")?.build()?;
.ip("localhost") let mut result = taos.query("SELECT ts, current FROM meters LIMIT 2")?;
.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 // print column names
let meta: Vec<ColumnMeta> = result.column_meta; let meta = result.fields();
for column in meta { println!("{}", meta.iter().map(|field| field.name()).join("\t"));
print!("{}\t", column.name)
}
println!();
// print rows // print rows
let rows: Vec<Vec<Field>> = result.rows; let rows = result.rows();
for row in rows { for row in rows {
for field in row { let row = row?;
print!("{}\t", field); for (_name, value) in row {
print!("{}\t", value);
} }
println!(); println!();
} }
Ok(()) Ok(())
} }
// output: // output(suppose you are in +8 timezone):
// ts current // ts current
// 2022-03-28 09:56:51.249 10.3 // 2018-10-03T14:38:05+08:00 10.3
// 2022-03-28 09:56:51.749 12.6 // 2018-10-03T14:38:15+08:00 12.6

View File

@ -1,7 +0,0 @@
[package]
name = "schemalessexample"
version = "0.1.0"
edition = "2021"
[dependencies]
libtaos = { version = "0.4.3" }

View File

@ -1,22 +0,0 @@
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=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249",
"meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250",
"meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249",
"meters,location=California.LosAngeles,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

View File

@ -1,25 +0,0 @@
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": "California.SanFrancisco", "groupid": 2}},
{"metric": "meters.voltage", "timestamp": 1648432611249, "value": 219, "tags": {"location": "California.LosAngeles", "groupid": 1}},
{"metric": "meters.current", "timestamp": 1648432611250, "value": 12.6, "tags": {"location": "California.SanFrancisco", "groupid": 2}},
{"metric": "meters.voltage", "timestamp": 1648432611250, "value": 221, "tags": {"location": "California.LosAngeles", "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

View File

@ -1,28 +0,0 @@
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=California.SanFrancisco groupid=2",
"meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2",
"meters.current 1648432611249 10.8 location=California.LosAngeles groupid=3",
"meters.current 1648432611250 11.3 location=California.LosAngeles groupid=3",
"meters.voltage 1648432611249 219 location=California.SanFrancisco groupid=2",
"meters.voltage 1648432611250 218 location=California.SanFrancisco groupid=2",
"meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3",
"meters.voltage 1648432611250 217 location=California.LosAngeles 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

View File

@ -1,3 +0,0 @@
fn main() {
println!("Hello, world!");
}

View File

@ -4,13 +4,13 @@ sidebar_label: 文档首页
slug: / slug: /
--- ---
TDengine是一款开源、[高性能](https://www.taosdata.com/fast)、云原生的时序数据库(Time-Series Database, TSDB), 它专为物联网、工业互联网、金融等场景优化设计。同时它还带有内建的缓存、流式计算、数据订阅等系统功能,能大幅减少系统设计的复杂度,降低研发和运营成本,是一极简的时序数据处理平台。本文档是 TDengine 用户手册,主要是介绍 TDengine 的基本概念、安装、使用、功能、开发接口、运营维护、TDengine 内核设计等等,它主要是面向架构师、开发者与系统管理员的。 TDengine是一款[开源](https://www.taosdata.com/tdengine/open_source_time-series_database)、[高性能](https://www.taosdata.com/fast)、[云原生](https://www.taosdata.com/tdengine/cloud_native_time-series_database)的时序数据库(Time-Series Database, TSDB), 它专为物联网、工业互联网、金融等场景优化设计。同时它还带有内建的缓存、流式计算、数据订阅等系统功能,能大幅减少系统设计的复杂度,降低研发和运营成本,是一极简的时序数据处理平台。本文档是 TDengine 用户手册,主要是介绍 TDengine 的基本概念、安装、使用、功能、开发接口、运营维护、TDengine 内核设计等等,它主要是面向架构师、开发者与系统管理员的。
TDengine 充分利用了时序数据的特点提出了“一个数据采集点一张表”与“超级表”的概念设计了创新的存储引擎让数据的写入、查询和存储效率都得到极大的提升。为正确理解并使用TDengine, 无论如何,请您仔细阅读[基本概念](./concept)一章。 TDengine 充分利用了时序数据的特点提出了“一个数据采集点一张表”与“超级表”的概念设计了创新的存储引擎让数据的写入、查询和存储效率都得到极大的提升。为正确理解并使用TDengine, 无论如何,请您仔细阅读[基本概念](./concept)一章。
如果你是开发者,请一定仔细阅读[开发指南](./develop)一章,该部分对数据库连接、建模、插入数据、查询、流式计算、缓存、数据订阅、用户自定义函数等功能都做了详细介绍,并配有各种编程语言的示例代码。大部分情况下,你只要把示例代码拷贝粘贴,针对自己的应用稍作改动,就能跑起来。 如果你是开发者,请一定仔细阅读[开发指南](./develop)一章,该部分对数据库连接、建模、插入数据、查询、流式计算、缓存、数据订阅、用户自定义函数等功能都做了详细介绍,并配有各种编程语言的示例代码。大部分情况下,你只要把示例代码拷贝粘贴,针对自己的应用稍作改动,就能跑起来。
我们已经生活在大数据的时代,纵向扩展已经无法满足日益增长的业务需求,任何系统都必须具有水平扩展的能力,集群成为大数据以及 database 系统的不可缺失功能。TDengine 团队不仅实现了集群功能,而且将这一重要核心功能开源。怎么部署、管理和维护 TDengine 集群,请参考[集群管理](./cluster)一章。 我们已经生活在大数据的时代,纵向扩展已经无法满足日益增长的业务需求,任何系统都必须具有水平扩展的能力,集群成为大数据以及 database 系统的不可缺失功能。TDengine 团队不仅实现了集群功能,而且将这一重要核心功能开源。怎么部署、管理和维护 TDengine 集群,请参考[部署集群](./deployment)一章。
TDengine 采用 SQL 作为其查询语言,大大降低学习成本、降低迁移成本,但同时针对时序数据场景,又做了一些扩展,以支持插值、降采样、时间加权平均等操作。[SQL 手册](./taos-sql)一章详细描述了 SQL 语法、详细列出了各种支持的命令和函数。 TDengine 采用 SQL 作为其查询语言,大大降低学习成本、降低迁移成本,但同时针对时序数据场景,又做了一些扩展,以支持插值、降采样、时间加权平均等操作。[SQL 手册](./taos-sql)一章详细描述了 SQL 语法、详细列出了各种支持的命令和函数。

View File

@ -3,7 +3,7 @@ title: 产品简介
toc_max_heading_level: 2 toc_max_heading_level: 2
--- ---
TDengine 是一款开源、高性能、云原生的时序数据库 (Time-Series Database, TSDB)。TDengine 能被广泛运用于物联网、工业互联网、车联网、IT 运维、金融等领域。除核心的时序数据库功能外TDengine 还提供[缓存](/develop/cache/)、[数据订阅](/develop/subscribe)、[流式计算](/develop/continuous-query)等功能,是一极简的时序数据处理平台,最大程度的减小系统设计的复杂度,降低研发和运营成本。 TDengine 是一款[开源](https://www.taosdata.com/tdengine/open_source_time-series_database)[高性能](https://www.taosdata.com/tdengine/fast)[云原生](https://www.taosdata.com/tdengine/cloud_native_time-series_database)的时序数据库 (Time-Series Database, TSDB)。TDengine 能被广泛运用于物联网、工业互联网、车联网、IT 运维、金融等领域。除核心的时序数据库功能外TDengine 还提供[缓存](../develop/cache/)、[数据订阅](../develop/tmq)、[流式计算](../develop/stream)等功能,是一极简的时序数据处理平台,最大程度的减小系统设计的复杂度,降低研发和运营成本。
本章节介绍TDengine的主要功能、竞争优势、适用场景、与其他数据库的对比测试等等让大家对TDengine有个整体的了解。 本章节介绍TDengine的主要功能、竞争优势、适用场景、与其他数据库的对比测试等等让大家对TDengine有个整体的了解。
@ -11,21 +11,22 @@ TDengine 是一款开源、高性能、云原生的时序数据库 (Time-Series
TDengine的主要功能如下 TDengine的主要功能如下
1. 高速数据写入,除 [SQL 写入](/develop/insert-data/sql-writing)外,还支持 [Schemaless 写入](/reference/schemaless/),支持 [InfluxDB LINE 协议](/develop/insert-data/influxdb-line)[OpenTSDB Telnet](/develop/insert-data/opentsdb-telnet), [OpenTSDB JSON ](/develop/insert-data/opentsdb-json)等协议写入; 1. 高速数据写入,除 [SQL 写入](../develop/insert-data/sql-writing)外,还支持 [Schemaless 写入](../reference/schemaless/),支持 [InfluxDB LINE 协议](../develop/insert-data/influxdb-line)[OpenTSDB Telnet](../develop/insert-data/opentsdb-telnet), [OpenTSDB JSON ](../develop/insert-data/opentsdb-json)等协议写入;
2. 第三方数据采集工具 [Telegraf](/third-party/telegraf)[Prometheus](/third-party/prometheus)[StatsD](/third-party/statsd)[collectd](/third-party/collectd)[icinga2](/third-party/icinga2), [TCollector](/third-party/tcollector), [EMQ](/third-party/emq-broker), [HiveMQ](/third-party/hive-mq-broker) 等都可以进行配置后,不用任何代码,即可将数据写入; 2. 第三方数据采集工具 [Telegraf](../third-party/telegraf)[Prometheus](../third-party/prometheus)[StatsD](../third-party/statsd)[collectd](../third-party/collectd)[icinga2](../third-party/icinga2), [TCollector](../third-party/tcollector), [EMQ](../third-party/emq-broker), [HiveMQ](../third-party/hive-mq-broker) 等都可以进行配置后,不用任何代码,即可将数据写入;
3. 支持[各种查询](/develop/query-data),包括聚合查询、嵌套查询、降采样查询、插值等 3. 支持[各种查询](../develop/query-data),包括聚合查询、嵌套查询、降采样查询、插值等
4. 支持[用户自定义函数](/develop/udf) 4. 支持[用户自定义函数](../develop/udf)
5. 支持[缓存](/develop/cache),将每张表的最后一条记录缓存起来,这样无需 Redis 5. 支持[缓存](../develop/cache),将每张表的最后一条记录缓存起来,这样无需 Redis
6. 支持[流式计算](/develop/continuous-query)(Stream Processing) 6. 支持[流式计算](../develop/stream)(Stream Processing)
7. 支持[数据订阅](/develop/subscribe),而且可以指定过滤条件 7. 支持[数据订阅](../develop/tmq),而且可以指定过滤条件
8. 支持[集群](/cluster/),可以通过多节点进行水平扩展,并通过多副本实现高可靠 8. 支持[集群](../deployment/),可以通过多节点进行水平扩展,并通过多副本实现高可靠
9. 提供[命令行程序](/reference/taos-shell),便于管理集群,检查系统状态,做即席查询 9. 提供[命令行程序](../reference/taos-shell),便于管理集群,检查系统状态,做即席查询
10. 提供多种数据的[导入](/operation/import)、[导出](/operation/export) 10. 提供多种数据的[导入](../operation/import)、[导出](../operation/export)
11. 支持对[TDengine 集群本身的监控](/operation/monitor) 11. 支持对[TDengine 集群本身的监控](../operation/monitor)
12. 提供 [C/C++](/reference/connector/cpp), [Java](/reference/connector/java), [Python](/reference/connector/python), [Go](/reference/connector/go), [Rust](/reference/connector/rust), [Node.js](/reference/connector/node) 等多种编程语言的[连接器](/reference/connector/) 12. 提供 [C/C++](../reference/connector/cpp), [Java](../reference/connector/java), [Python](../reference/connector/python), [Go](../reference/connector/go), [Rust](../reference/connector/rust), [Node.js](../reference/connector/node) 等多种编程语言的[连接器](../reference/connector/)
13. 支持 [REST 接口](/reference/rest-api/) 13. 支持 [REST 接口](../reference/rest-api/)
14. 支持与[ Grafana 无缝集成](/third-party/grafana) 14. 支持与[ Grafana 无缝集成](../third-party/grafana)
15. 支持与 Google Data Studio 无缝集成 15. 支持与 Google Data Studio 无缝集成
16. 支持 [Kubernetes 部署](../deployment/k8s)
更多细小的功能,请阅读整个文档。 更多细小的功能,请阅读整个文档。
@ -33,17 +34,17 @@ TDengine的主要功能如下
由于 TDengine 充分利用了[时序数据特点](https://www.taosdata.com/blog/2019/07/09/105.html)比如结构化、无需事务、很少删除或更新、写多读少等等设计了全新的针对时序数据的存储引擎和计算引擎因此与其他时序数据库相比TDengine 有以下特点: 由于 TDengine 充分利用了[时序数据特点](https://www.taosdata.com/blog/2019/07/09/105.html)比如结构化、无需事务、很少删除或更新、写多读少等等设计了全新的针对时序数据的存储引擎和计算引擎因此与其他时序数据库相比TDengine 有以下特点:
- **高性能**通过创新的存储引擎设计无论是数据写入还是查询TDengine 的性能比通用数据库快 10 倍以上也远超其他时序数据库存储空间不及通用数据库的1/10。 - **[高性能](https://www.taosdata.com/tdengine/fast)**通过创新的存储引擎设计无论是数据写入还是查询TDengine 的性能比通用数据库快 10 倍以上也远超其他时序数据库存储空间不及通用数据库的1/10。
- **云原生**通过原生分布式的设计充分利用云平台的优势TDengine 提供了水平扩展能力具备弹性、韧性和可观测性支持k8s部署可运行在公有云、私有云和混合云上。 - **[云原生](https://www.taosdata.com/tdengine/cloud_native_time-series_database)**通过原生分布式的设计充分利用云平台的优势TDengine 提供了水平扩展能力具备弹性、韧性和可观测性支持k8s部署可运行在公有云、私有云和混合云上。
- **极简时序数据平台**TDengine 内建消息队列、缓存、流式计算等功能,应用无需再集成 Kafka/Redis/HBase/Spark 等软件,大幅降低系统的复杂度,降低应用开发和运营成本。 - **[极简时序数据平台](https://www.taosdata.com/tdengine/simplified_solution_for_time-series_data_processing)**TDengine 内建消息队列、缓存、流式计算等功能,应用无需再集成 Kafka/Redis/HBase/Spark 等软件,大幅降低系统的复杂度,降低应用开发和运营成本。
- **分析能力**:支持 SQL同时为时序数据特有的分析提供SQL扩展。通过超级表、存储计算分离、分区分片、预计算、自定义函数等技术TDengine 具备强大的分析能力。 - **[分析能力](https://www.taosdata.com/tdengine/easy_data_analytics)**:支持 SQL同时为时序数据特有的分析提供SQL扩展。通过超级表、存储计算分离、分区分片、预计算、自定义函数等技术TDengine 具备强大的分析能力。
- **简单易用**无任何依赖安装、集群几秒搞定提供REST以及各种语言连接器与众多第三方工具无缝集成提供命令行程序便于管理和即席查询提供各种运维工具。 - **[简单易用](https://www.taosdata.com/tdengine/ease_of_use)**无任何依赖安装、集群几秒搞定提供REST以及各种语言连接器与众多第三方工具无缝集成提供命令行程序便于管理和即席查询提供各种运维工具。
- **核心开源**TDengine 的核心代码包括集群功能全部开源截止到2022年8月1日全球超过 135.9k 个运行实例GitHub Star 18.7kFork 4.4k,社区活跃。 - **[核心开源](https://www.taosdata.com/tdengine/open_source_time-series_database)**TDengine 的核心代码包括集群功能全部开源截止到2022年8月1日全球超过 135.9k 个运行实例GitHub Star 18.7kFork 4.4k,社区活跃。
采用 TDengine可将典型的物联网、车联网、工业互联网大数据平台的总拥有成本大幅降低。表现在几个方面 采用 TDengine可将典型的物联网、车联网、工业互联网大数据平台的总拥有成本大幅降低。表现在几个方面

View File

@ -2,6 +2,9 @@
sidebar_label: Docker sidebar_label: Docker
title: 通过 Docker 快速体验 TDengine title: 通过 Docker 快速体验 TDengine
--- ---
:::info
如果您希望为 TDengine 贡献代码或对内部技术实现感兴趣,请参考[TDengine GitHub 主页](https://github.com/taosdata/TDengine) 下载源码构建和安装.
:::
本节首先介绍如何通过 Docker 快速体验 TDengine然后介绍如何在 Docker 环境下体验 TDengine 的写入和查询功能。 本节首先介绍如何通过 Docker 快速体验 TDengine然后介绍如何在 Docker 环境下体验 TDengine 的写入和查询功能。
@ -10,9 +13,11 @@ title: 通过 Docker 快速体验 TDengine
如果已经安装了 docker 只需执行下面的命令。 如果已经安装了 docker 只需执行下面的命令。
```shell ```shell
docker run -d -p 6030-6049:6030-6049 -p 6030-6049:6030-6049/udp tdengine/tdengine docker run -d -p 6030:6030 -p 6041/6041 -p 6043-6049/6043-6049 -p 6043-6049:6043-6049/udp tdengine/tdengine
``` ```
注意TDengine 3.0 服务端仅使用 6030 TCP 端口。6041 为 taosAdapter 所使用提供 REST 服务端口。6043-6049 为 taosAdapter 提供第三方应用接入所使用端口,可根据需要选择是否打开。
确定该容器已经启动并且在正常运行 确定该容器已经启动并且在正常运行
```shell ```shell
@ -27,77 +32,24 @@ docker exec -it <container name> bash
然后就可以执行相关的 Linux 命令操作和访问 TDengine 然后就可以执行相关的 Linux 命令操作和访问 TDengine
:::info 注: Docker 工具自身的下载和使用请参考 [Docker 官网文档](https://docs.docker.com/get-docker/)。
Docker 工具自身的下载请参考 [Docker 官网文档](https://docs.docker.com/get-docker/)。
安装完毕后可以在命令行终端查看 Docker 版本。如果版本号正常输出,则说明 Docker 环境已经安装成功。
```bash
$ docker -v
Docker version 20.10.3, build 48d30b5
```
:::
## 运行 TDengine CLI ## 运行 TDengine CLI
有两种方式在 Docker 环境下使用 TDengine CLI (taos) 访问 TDengine. 进入容器,执行 taos
- 进入容器后,执行 taos
- 在宿主机使用容器映射到主机的端口进行访问 `taos -h <hostname> -P <port>`
``` ```
$ taos $ taos
Welcome to the TDengine shell from Linux, Client Version:3.0.0.0
Copyright (c) 2022 by TAOS Data, Inc. All rights reserved.
Server is Community Edition.
taos> taos>
``` ```
## 访问 REST 接口
taosAdapter 是 TDengine 中提供 REST 服务的组件。下面这条命令会在容器中同时启动 `taosd``taosadapter` 两个服务组件。默认 Docker 镜像同时启动 TDengine 后台服务 taosd 和 taosAdatper。
可以在宿主机使用 curl 通过 RESTful 端口访问 Docker 容器内的 TDengine server。
```
curl -L -u root:taosdata -d "show databases" 127.0.0.1:6041/rest/sql
```
输出示例如下:
```
{"code":0,"column_meta":[["name","VARCHAR",64],["create_time","TIMESTAMP",8],["vgroups","SMALLINT",2],["ntables","BIGINT",8],["replica","TINYINT",1],["strict","VARCHAR",4],["duration","VARCHAR",10],["keep","VARCHAR",32],["buffer","INT",4],["pagesize","INT",4],["pages","INT",4],["minrows","INT",4],["maxrows","INT",4],["wal","TINYINT",1],["fsync","INT",4],["comp","TINYINT",1],["cacheModel","VARCHAR",11],["precision","VARCHAR",2],["single_stable","BOOL",1],["status","VARCHAR",10],["retention","VARCHAR",60]],"data":[["information_schema",null,null,14,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"ready"],["performance_schema",null,null,3,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"ready"]],"rows":2}
```
这条命令,通过 REST API 访问 TDengine server这时连接的是从容器映射到主机的 6041 端口。
TDengine REST API 详情请参考[官方文档](/reference/rest-api/)。
## 单独启动 REST 服务
如果想只启动 `taosadapter`
```bash
docker run -d --network=host --name tdengine-taosa -e TAOS_FIRST_EP=tdengine-taosd tdengine/tdengine:3.0.0.0 taosadapter
```
只启动 `taosd`
```bash
docker run -d --network=host --name tdengine-taosd -e TAOS_DISABLE_ADAPTER=true tdengine/tdengine:3.0.0.0
```
注意以上为容器使用 host 方式网络配置进行单独部署 taosAdapter 的命令行参数。其他网络访问方式请设置 hostname、 DNS 等必要的网络配置。
## 写入数据 ## 写入数据
可以使用 TDengine 的自带工具 taosBenchmark 快速体验 TDengine 的写入。 可以使用 TDengine 的自带工具 taosBenchmark 快速体验 TDengine 的写入。
假定启动容器时已经将容器的6030端口映射到了宿主机的6030端口则可以直接在宿主机命令行启动 taosBenchmark也可以进入容器后执行 进入容器,启动 taosBenchmark
```bash ```bash
$ taosBenchmark $ taosBenchmark
@ -112,7 +64,7 @@ docker run -d --network=host --name tdengine-taosd -e TAOS_DISABLE_ADAPTER=true
## 体验查询 ## 体验查询
使用上述 taosBenchmark 插入数据后,可以在 TDengine CLI 输入查询命令,体验查询速度。可以直接在宿主机上也可以进入容器后运行 使用上述 taosBenchmark 插入数据后,可以在 TDengine CLI 输入查询命令,体验查询速度。。
查询超级表下记录总条数: 查询超级表下记录总条数:
@ -143,3 +95,7 @@ taos> select avg(current), max(voltage), min(phase) from test.meters where group
```sql ```sql
taos> select avg(current), max(voltage), min(phase) from test.d10 interval(10s); taos> select avg(current), max(voltage), min(phase) from test.d10 interval(10s);
``` ```
## 其它
更多关于在 Docker 环境下使用 TDengine 的细节,请参考 [在 Docker 下使用 TDengine](../../reference/docker)

View File

@ -11,7 +11,7 @@ import TabItem from "@theme/TabItem";
::: :::
TDengine 开源版本提供 deb 和 rpm 格式安装包,用户可以根据自己的运行环境选择合适的安装包。其中 deb 支持 Debian/Ubuntu 及衍生系统rpm 支持 CentOS/RHEL/SUSE 及衍生系统。同时我们也为企业用户提供 tar.gz 格式安装包也支持通过 `apt-get` 工具从线上进行安装。 在 Linux 系统上,TDengine 开源版本提供 deb 和 rpm 格式安装包,用户可以根据自己的运行环境选择合适的安装包。其中 deb 支持 Debian/Ubuntu 及衍生系统rpm 支持 CentOS/RHEL/SUSE 及衍生系统。同时我们也为企业用户提供 tar.gz 格式安装包也支持通过 `apt-get` 工具从线上进行安装。TDengine 也提供 Windows x64 平台的安装包。
## 安装 ## 安装
@ -21,20 +21,20 @@ TDengine 开源版本提供 deb 和 rpm 格式安装包,用户可以根据自
**安装包仓库** **安装包仓库**
``` ```bash
wget -qO - http://repos.taosdata.com/tdengine.key | sudo apt-key add - 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 echo "deb [arch=amd64] http://repos.taosdata.com/tdengine-stable stable main" | sudo tee /etc/apt/sources.list.d/tdengine-stable.list
``` ```
如果安装 Beta 版需要安装包仓库 如果安装 Beta 版需要安装包仓库
``` ```bash
echo "deb [arch=amd64] http://repos.taosdata.com/tdengine-beta beta main" | sudo tee /etc/apt/sources.list.d/tdengine-beta.list echo "deb [arch=amd64] http://repos.taosdata.com/tdengine-beta beta main" | sudo tee /etc/apt/sources.list.d/tdengine-beta.list
``` ```
**使用 apt-get 命令安装** **使用 apt-get 命令安装**
``` ```bash
sudo apt-get update sudo apt-get update
apt-cache policy tdengine apt-cache policy tdengine
sudo apt-get install tdengine sudo apt-get install tdengine
@ -46,122 +46,39 @@ apt-get 方式只适用于 Debian 或 Ubuntu 系统
</TabItem> </TabItem>
<TabItem label="Deb 安装" value="debinst"> <TabItem label="Deb 安装" value="debinst">
1、从官网下载获得 deb 安装包,例如 TDengine-server-3.0.0.10002-Linux-x64.deb 1. 从官网下载获得 deb 安装包,例如 TDengine-server-3.0.0.0-Linux-x64.deb
2、进入到 TDengine-server-3.0.0.10002-Linux-x64.deb 安装包所在目录,执行如下的安装命令: 2. 进入到 TDengine-server-3.0.0.0-Linux-x64.deb 安装包所在目录,执行如下的安装命令:
```
$ sudo dpkg -i TDengine-server-3.0.0.10002-Linux-x64.deb
Selecting previously unselected package tdengine.
(Reading database ... 119653 files and directories currently installed.)
Preparing to unpack TDengine-server-3.0.0.10002-Linux-x64.deb ...
Unpacking tdengine (3.0.0.10002) ...
Setting up tdengine (3.0.0.10002) ...
Start to install TDengine...
System hostname is: v3cluster-0002
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 v3cluster-0002 to login into TDengine server
TDengine is installed successfully!
```bash
sudo dpkg -i TDengine-server-3.0.0.0-Linux-x64.deb
``` ```
</TabItem> </TabItem>
<TabItem label="RPM 安装" value="rpminst"> <TabItem label="RPM 安装" value="rpminst">
1、从官网下载获得 rpm 安装包,例如 TDengine-server-3.0.0.10002-Linux-x64.rpm 1. 从官网下载获得 rpm 安装包,例如 TDengine-server-3.0.0.0-Linux-x64.rpm
2、进入到 TDengine-server-3.0.0.10002-Linux-x64.rpm 安装包所在目录,执行如下的安装命令: 2. 进入到 TDengine-server-3.0.0.0-Linux-x64.rpm 安装包所在目录,执行如下的安装命令:
```
$ sudo rpm -ivh TDengine-server-3.0.0.10002-Linux-x64.rpm
Preparing... ################################# [100%]
Stop taosd service success!
Updating / installing...
1:tdengine-3.0.0.10002-3 ################################# [100%]
Start to install TDengine...
System hostname is: chenhaoran01
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 chenhaoran01 to login into TDengine server
TDengine is installed successfully!
```bash
sudo rpm -ivh TDengine-server-3.0.0.0-Linux-x64.rpm
``` ```
</TabItem> </TabItem>
<TabItem label="tar.gz 安装" value="tarinst"> <TabItem label="tar.gz 安装" value="tarinst">
1从官网下载获得 tar.gz 安装包,例如 TDengine-server-3.0.0.10002-Linux-x64.tar.gz 1. 从官网下载获得 tar.gz 安装包,例如 TDengine-server-3.0.0.0-Linux-x64.tar.gz
2、进入到 TDengine-server-3.0.0.10002-Linux-x64.tar.gz 安装包所在目录,先解压文件后,进入子目录,执行其中的 install.sh 安装脚本: 2. 进入到 TDengine-server-3.0.0.0-Linux-x64.tar.gz 安装包所在目录,先解压文件后,进入子目录,执行其中的 install.sh 安装脚本:
```bash
tar -zxvf TDengine-server-3.0.0.0-Linux-x64.tar.gz
``` ```
$ tar -zxvf TDengine-server-3.0.0.10002-Linux-x64.tar.gz
TDengine-server-3.0.0.10002/
TDengine-server-3.0.0.10002/driver/
TDengine-server-3.0.0.10002/driver/libtaos.so.3.0.0.10002
TDengine-server-3.0.0.10002/driver/vercomp.txt
TDengine-server-3.0.0.10002/release_note
TDengine-server-3.0.0.10002/taos.tar.gz
TDengine-server-3.0.0.10002/install.sh
...
$ ll 解压后进入相应路径,执行
total 56832
drwxr-xr-x 3 root root 4096 Aug 8 10:29 ./
drwxrwxrwx 6 root root 4096 Aug 5 16:45 ../
drwxr-xr-x 4 root root 4096 Aug 4 18:03 TDengine-server-3.0.0.10002/
-rwxr-xr-x 1 root root 58183066 Aug 8 10:28 TDengine-server-3.0.0.10002-Linux-x64.tar.gz*
$ cd TDengine-server-3.0.0.10002/ ```bash
sudo ./install.sh
$ ll
total 51612
drwxr-xr-x 4 root root 4096 Aug 4 18:03 ./
drwxr-xr-x 3 root root 4096 Aug 8 10:29 ../
drwxr-xr-x 2 root root 4096 Aug 4 18:03 driver/
drwxr-xr-x 11 root root 4096 Aug 4 18:03 examples/
-rwxr-xr-x 1 root root 30980 Aug 4 18:03 install.sh*
-rw-r--r-- 1 root root 6724 Aug 4 18:03 release_note
-rw-r--r-- 1 root root 52793079 Aug 4 18:03 taos.tar.gz
$ sudo ./install.sh
Start to install TDengine...
Created symlink /etc/systemd/system/multi-user.target.wants/taosd.service → /etc/systemd/system/taosd.service.
System hostname is: v3cluster-0002
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:
To configure TDengine : edit /etc/taos/taos.cfg
To configure taosadapter (if has) : edit /etc/taos/taosadapter.toml
To start TDengine : sudo systemctl start taosd
To access TDengine : taos -h v3cluster-0002 to login into TDengine server
TDengine is installed successfully!
``` ```
:::info :::info
@ -169,6 +86,13 @@ install.sh 安装脚本在执行过程中,会通过命令行交互界面询问
::: :::
</TabItem>
<TabItem label="Windows 安装" value="windows">
1. 从官网下载获得 exe 安装程序,例如 TDengine-server-3.0.0.0-Windows-x64.exe
2. 运行 TDengine-server-3.0.0.0-Windows-x64.exe 来安装 TDengine。
</TabItem> </TabItem>
</Tabs> </Tabs>
@ -179,6 +103,9 @@ install.sh 安装脚本在执行过程中,会通过命令行交互界面询问
## 启动 ## 启动
<Tabs>
<TabItem label="Linux 系统" value="linux">
安装后,请使用 `systemctl` 命令来启动 TDengine 的服务进程。 安装后,请使用 `systemctl` 命令来启动 TDengine 的服务进程。
```bash ```bash
@ -223,9 +150,18 @@ systemctl 命令汇总:
::: :::
</TabItem>
<TabItem label="Windows 系统" value="windows">
安装后,在 C:\TDengine 目录下,运行 taosd.exe 来启动 TDengine 服务进程。
</TabItem>
</Tabs>
## TDengine 命令行 (CLI) ## TDengine 命令行 (CLI)
为便于检查 TDengine 的状态,执行数据库 (Database) 的各种即席(Ad Hoc)查询TDengine 提供一命令行应用程序(以下简称为 TDengine CLI) taos。要进入 TDengine 命令行,您只要在安装有 TDengine 的 Linux 终端执行 `taos` 即可。 为便于检查 TDengine 的状态,执行数据库 (Database) 的各种即席(Ad Hoc)查询TDengine 提供一命令行应用程序(以下简称为 TDengine CLI) taos。要进入 TDengine 命令行,您只要在安装有 TDengine 的 Linux 终端执行 `taos` 即可,也可以在安装有 TDengine 的 Windows 终端的 C:\TDengine 目录下,运行 taos.exe 来启动 TDengine 命令行
```bash ```bash
taos taos

View File

@ -54,9 +54,6 @@ meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0
<TabItem label="Go" value="go"> <TabItem label="Go" value="go">
<GoLine /> <GoLine />
</TabItem> </TabItem>
<TabItem label="Rust" value="rust">
<RustLine />
</TabItem>
<TabItem label="Node.js" value="nodejs"> <TabItem label="Node.js" value="nodejs">
<NodeLine /> <NodeLine />
</TabItem> </TabItem>

View File

@ -46,9 +46,6 @@ meters.current 1648432611250 11.3 location=California.LosAngeles groupid=3
<TabItem label="Go" value="go"> <TabItem label="Go" value="go">
<GoTelnet /> <GoTelnet />
</TabItem> </TabItem>
<TabItem label="Rust" value="rust">
<RustTelnet />
</TabItem>
<TabItem label="Node.js" value="nodejs"> <TabItem label="Node.js" value="nodejs">
<NodeTelnet /> <NodeTelnet />
</TabItem> </TabItem>

View File

@ -63,9 +63,6 @@ OpenTSDB JSON 格式协议采用一个 JSON 字符串表示一行或多行数据
<TabItem label="Go" value="go"> <TabItem label="Go" value="go">
<GoJson /> <GoJson />
</TabItem> </TabItem>
<TabItem label="Rust" value="rust">
<RustJson />
</TabItem>
<TabItem label="Node.js" value="nodejs"> <TabItem label="Node.js" value="nodejs">
<NodeJson /> <NodeJson />
</TabItem> </TabItem>

View File

@ -1,3 +1,2 @@
```rust ```rust
{{#include docs/examples/rust/schemalessexample/examples/influxdb_line_example.rs}}
``` ```

View File

@ -1,3 +1,2 @@
```rust ```rust
{{#include docs/examples/rust/schemalessexample/examples/opentsdb_json_example.rs}}
``` ```

View File

@ -1,3 +1,2 @@
```rust ```rust
{{#include docs/examples/rust/schemalessexample/examples/opentsdb_telnet_example.rs}}
``` ```

View File

@ -1,84 +1,128 @@
--- ---
sidebar_label: 连续查询 sidebar_label: 流式计算
description: "连续查询是一个按照预设频率自动执行的查询功能,提供按照时间窗口的聚合查询能力,是一种简化的时间驱动流式计算。" description: "TDengine 流式计算将数据的写入、预处理、复杂分析、实时计算、报警触发等功能融为一体,是一个能够降低用户部署成本、存储成本和运维成本的计算引擎。"
title: "连续查询Continuous Query" title: 流式计算
--- ---
连续查询是 TDengine 定期自动执行的查询采用滑动窗口的方式进行计算是一种简化的时间驱动的流式计算。针对库中的表或超级表TDengine 可提供定期自动执行的连续查询,用户可让 TDengine 推送查询的结果,也可以将结果再写回到 TDengine 中。每次执行的查询是一个时间窗口时间窗口随着时间流动向前滑动。在定义连续查询的时候需要指定时间窗口time window, 参数 interval大小和每次前向增量时间forward sliding times, 参数 sliding 在时序数据的处理中,经常要对原始数据进行清洗、预处理,再使用时序数据库进行长久的储存。用户通常需要在时序数据库之外再搭建 Kafka、Flink、Spark 等流计算处理引擎,增加了用户的开发成本和维护成本。
使用 TDengine 3.0 的流式计算引擎能够最大限度的减少对这些额外中间件的依赖,真正将数据的写入、预处理、长期存储、复杂分析、实时计算、实时报警触发等功能融为一体,并且,所有这些任务只需要使用 SQL 完成,极大降低了用户的学习成本、使用成本。
TDengine 的连续查询采用时间驱动模式,可以直接使用 TAOS SQL 进行定义不需要额外的操作。使用连续查询可以方便快捷地按照时间窗口生成结果从而对原始采集数据进行降采样down sampling。用户通过 TAOS SQL 定义连续查询以后TDengine 自动在最后的一个完整的时间周期末端拉起查询,并将计算获得的结果推送给用户或者写回 TDengine。
## 流式计算的创建
TDengine 提供的连续查询与普通流计算中的时间窗口计算具有以下区别:
```sql
- 不同于流计算的实时反馈计算结果,连续查询只在时间窗口关闭以后才开始计算。例如时间周期是 1 天,那么当天的结果只会在 23:59:59 以后才会生成。 CREATE STREAM [IF NOT EXISTS] stream_name [stream_options] INTO stb_name AS subquery
- 如果有历史记录写入到已经计算完成的时间区间,连续查询并不会重新进行计算,也不会重新将结果推送给用户。对于写回 TDengine 的模式,也不会更新已经存在的计算结果。 stream_options: {
- 使用连续查询推送结果的模式,服务端并不缓存客户端计算状态,也不提供 Exactly-Once 的语义保证。如果用户的应用端崩溃再次拉起的连续查询将只会从再次拉起的时间开始重新计算最近的一个完整的时间窗口。如果使用写回模式TDengine 可确保数据写回的有效性和连续性。 TRIGGER [AT_ONCE | WINDOW_CLOSE | MAX_DELAY time]
WATERMARK time
## 连续查询语法 IGNORE EXPIRED
}
```sql ```
[CREATE TABLE AS] SELECT select_expr [, select_expr ...]
FROM {tb_name_list} 详细的语法规则参考 [流式计算](../../taos-sql/stream)
[WHERE where_condition]
[INTERVAL(interval_val [, interval_offset]) [SLIDING sliding_val]] ## 示例一
``` 企业电表的数据经常都是成百上千亿条的,那么想要将这些分散、凌乱的数据清洗或转换都需要比较长的时间,很难做到高效性和实时性,以下例子中,通过流计算可以将过去 12 小时电表电压大于 220V 的数据清洗掉,然后以小时为窗口整合并计算出每个窗口中电流的最大值,并将结果输出到指定的数据表中。
INTERVAL: 连续查询作用的时间窗口 ### 创建 DB 和原始数据表
SLIDING: 连续查询的时间窗口向前滑动的时间间隔 首先准备数据,完成建库、建一张超级表和多张子表操作
## 使用连续查询 ```sql
drop database if exists stream_db;
下面以智能电表场景为例介绍连续查询的具体使用方法。假设我们通过下列 SQL 语句创建了超级表和子表: create database stream_db;
```sql create stable stream_db.meters (ts timestamp, current float, voltage int) TAGS (location varchar(64), groupId int);
create table meters (ts timestamp, current float, voltage int, phase float) tags (location binary(64), groupId int);
create table D1001 using meters tags ("California.SanFrancisco", 2); create table stream_db.d1001 using stream_db.meters tags("beijing", 1);
create table D1002 using meters tags ("California.LosAngeles", 2); create table stream_db.d1002 using stream_db.meters tags("guangzhou", 2);
... create table stream_db.d1003 using stream_db.meters tags("shanghai", 3);
``` ```
可以通过下面这条 SQL 语句以一分钟为时间窗口、30 秒为前向增量统计这些电表的平均电压。 ### 创建流
```sql ```sql
select avg(voltage) from meters interval(1m) sliding(30s); create stream stream1 into stream_db.stream1_output_stb as select _wstart as start, _wend as end, max(current) as max_current from stream_db.meters where voltage <= 220 and ts > now - 12h interval (1h);
``` ```
每次执行这条语句,都会重新计算所有数据。 如果需要每隔 30 秒执行一次来增量计算最近一分钟的数据,可以把上面的语句改进成下面的样子,每次使用不同的 `startTime` 并定期执行: ### 写入数据
```sql
```sql insert into stream_db.d1001 values(now-14h, 10.3, 210);
select avg(voltage) from meters where ts > {startTime} interval(1m) sliding(30s); insert into stream_db.d1001 values(now-13h, 13.5, 216);
``` insert into stream_db.d1001 values(now-12h, 12.5, 219);
insert into stream_db.d1002 values(now-11h, 14.7, 221);
这样做没有问题,但 TDengine 提供了更简单的方法,只要在最初的查询语句前面加上 `create table {tableName} as` 就可以了,例如: insert into stream_db.d1002 values(now-10h, 10.5, 218);
insert into stream_db.d1002 values(now-9h, 11.2, 220);
```sql insert into stream_db.d1003 values(now-8h, 11.5, 217);
create table avg_vol as select avg(voltage) from meters interval(1m) sliding(30s); insert into stream_db.d1003 values(now-7h, 12.3, 227);
``` insert into stream_db.d1003 values(now-6h, 12.3, 215);
```
会自动创建一个名为 `avg_vol` 的新表,然后每隔 30 秒TDengine 会增量执行 `as` 后面的 SQL 语句,并将查询结果写入这个表中,用户程序后续只要从 `avg_vol` 中查询数据即可。例如:
### 查询以观查结果
```sql ```sql
taos> select * from avg_vol; taos> select * from stream_db.stream1_output_stb;
ts | avg_voltage_ | start | end | max_current | group_id |
=================================================== ===================================================================================================
2020-07-29 13:37:30.000 | 222.0000000 | 2022-08-09 14:00:00.000 | 2022-08-09 15:00:00.000 | 10.50000 | 0 |
2020-07-29 13:38:00.000 | 221.3500000 | 2022-08-09 15:00:00.000 | 2022-08-09 16:00:00.000 | 11.20000 | 0 |
2020-07-29 13:38:30.000 | 220.1700000 | 2022-08-09 16:00:00.000 | 2022-08-09 17:00:00.000 | 11.50000 | 0 |
2020-07-29 13:39:00.000 | 223.0800000 | 2022-08-09 18:00:00.000 | 2022-08-09 19:00:00.000 | 12.30000 | 0 |
``` Query OK, 4 rows in database (0.012033s)
```
需要注意,查询时间窗口的最小值是 10 毫秒,没有时间窗口范围的上限。
## 示例二
此外TDengine 还支持用户指定连续查询的起止时间。如果不输入开始时间,连续查询将从第一条原始数据所在的时间窗口开始;如果没有输入结束时间,连续查询将永久运行;如果用户指定了结束时间,连续查询在系统时间达到指定的时间以后停止运行。比如使用下面的 SQL 创建的连续查询将运行一小时,之后会自动停止。 某运营商平台要采集机房所有服务器的系统资源指标,包含 cpu、内存、网络延迟等采集后需要对数据进行四舍五入运算将地域和服务器名以下划线拼接然后将结果按时间排序并以服务器名分组输出到新的数据表中。
```sql ### 创建 DB 和原始数据表
create table avg_vol as select avg(voltage) from meters where ts > now and ts <= now + 1h interval(1m) sliding(30s); 首先准备数据,完成建库、建一张超级表和多张子表操作
```
```sql
需要说明的是,上面例子中的 `now` 是指创建连续查询的时间而不是查询执行的时间否则查询就无法自动停止了。另外为了尽量避免原始数据延迟写入导致的问题TDengine 中连续查询的计算有一定的延迟。也就是说一个时间窗口过去后TDengine 并不会立即计算这个窗口的数据,所以要稍等一会(一般不会超过 1 分钟)才能查到计算结果。 drop database if exists stream_db;
create database stream_db;
## 管理连续查询
create stable stream_db.idc (ts timestamp, cpu float, mem float, latency float) TAGS (location varchar(64), groupId int);
用户可在控制台中通过 `show streams` 命令来查看系统中全部运行的连续查询,并可以通过 `kill stream` 命令杀掉对应的连续查询。后续版本会提供更细粒度和便捷的连续查询管理命令。
create table stream_db.server01 using stream_db.idc tags("beijing", 1);
create table stream_db.server02 using stream_db.idc tags("shanghai", 2);
create table stream_db.server03 using stream_db.idc tags("beijing", 2);
create table stream_db.server04 using stream_db.idc tags("tianjin", 3);
create table stream_db.server05 using stream_db.idc tags("shanghai", 1);
```
### 创建流
```sql
create stream stream2 into stream_db.stream2_output_stb as select ts, concat_ws("_", location, tbname) as server_location, round(cpu) as cpu, round(mem) as mem, round(latency) as latency from stream_db.idc partition by tbname order by ts;
```
### 写入数据
```sql
insert into stream_db.server01 values(now-14h, 50.9, 654.8, 23.11);
insert into stream_db.server01 values(now-13h, 13.5, 221.2, 11.22);
insert into stream_db.server02 values(now-12h, 154.7, 218.3, 22.33);
insert into stream_db.server02 values(now-11h, 120.5, 111.5, 5.55);
insert into stream_db.server03 values(now-10h, 101.5, 125.6, 5.99);
insert into stream_db.server03 values(now-9h, 12.3, 165.6, 6.02);
insert into stream_db.server04 values(now-8h, 160.9, 120.7, 43.51);
insert into stream_db.server04 values(now-7h, 240.9, 520.7, 54.55);
insert into stream_db.server05 values(now-6h, 190.9, 320.7, 55.43);
insert into stream_db.server05 values(now-5h, 110.9, 600.7, 35.54);
```
### 查询以观查结果
```sql
taos> select ts, server_location, cpu, mem, latency from stream_db.stream2_output_stb;
ts | server_location | cpu | mem | latency |
================================================================================================================================
2022-08-09 21:24:56.785 | beijing_server01 | 51.00000 | 655.00000 | 23.00000 |
2022-08-09 22:24:56.795 | beijing_server01 | 14.00000 | 221.00000 | 11.00000 |
2022-08-09 23:24:56.806 | shanghai_server02 | 155.00000 | 218.00000 | 22.00000 |
2022-08-10 00:24:56.815 | shanghai_server02 | 121.00000 | 112.00000 | 6.00000 |
2022-08-10 01:24:56.826 | beijing_server03 | 102.00000 | 126.00000 | 6.00000 |
2022-08-10 02:24:56.838 | beijing_server03 | 12.00000 | 166.00000 | 6.00000 |
2022-08-10 03:24:56.846 | tianjin_server04 | 161.00000 | 121.00000 | 44.00000 |
2022-08-10 04:24:56.853 | tianjin_server04 | 241.00000 | 521.00000 | 55.00000 |
2022-08-10 05:24:56.866 | shanghai_server05 | 191.00000 | 321.00000 | 55.00000 |
2022-08-10 06:24:57.301 | shanghai_server05 | 111.00000 | 601.00000 | 36.00000 |
Query OK, 10 rows in database (0.022950s)
```

View File

@ -4,14 +4,18 @@ title: UDF用户定义函数
description: "支持用户编码的聚合函数和标量函数,在查询中嵌入并使用用户定义函数,拓展查询的能力和功能。" description: "支持用户编码的聚合函数和标量函数,在查询中嵌入并使用用户定义函数,拓展查询的能力和功能。"
--- ---
在有些应用场景中,应用逻辑需要的查询无法直接使用系统内置的函数来表示。利用 UDF 功能TDengine 可以插入用户编写的处理代码并在查询中使用它们,就能够很方便地解决特殊应用场景中的使用需求。 UDF 通常以数据表中的一列数据做为输入,同时支持以嵌套子查询的结果作为输入。 在有些应用场景中,应用逻辑需要的查询无法直接使用系统内置的函数来表示。利用 UDF(User Defined Function) 功能TDengine 可以插入用户编写的处理代码并在查询中使用它们,就能够很方便地解决特殊应用场景中的使用需求。 UDF 通常以数据表中的一列数据做为输入,同时支持以嵌套子查询的结果作为输入。
从 2.2.0.0 版本开始,TDengine 支持通过 C/C++ 语言进行 UDF 定义。接下来结合示例讲解 UDF 的使用方法。 TDengine 支持通过 C/C++ 语言进行 UDF 定义。接下来结合示例讲解 UDF 的使用方法。
用户可以通过 UDF 实现两类函数: 标量函数和聚合函数。标量函数对每行数据返回一个值,如求绝对值 abs正弦函数 sin字符串拼接函数 concat 等。聚合函数对多行数据进行返回一个值,如求平均数 avg最大值 max 等。实现udf时需要实现规定的接口函数。接口函数的名称是 udf 名称,或者是 udf 名称和特定后缀_start, _finish, _init, _destroy)的连接。scalarfnaggfn, udf需要替换成udf函数名。 用户可以通过 UDF 实现两类函数:标量函数和聚合函数。标量函数对每行数据输出一个值,如求绝对值 abs正弦函数 sin字符串拼接函数 concat 等。聚合函数对多行数据进行输出一个值,如求平均数 avg最大值 max 等。
- 标量函数需要实现标量接口函数 scalarfn
实现 UDF 时,需要实现规定的接口函数
- 标量函数需要实现标量接口函数 scalarfn 。
- 聚合函数需要实现聚合接口函数 aggfn_start aggfn aggfn_finish。 - 聚合函数需要实现聚合接口函数 aggfn_start aggfn aggfn_finish。
- 无论标量函数还是聚合函数,如果需要初始化,实现 udf_init如果需要清理工作实现udf_destory。 - 如果需要初始化,实现 udf_init如果需要清理工作实现udf_destroy。
接口函数的名称是 UDF 名称,或者是 UDF 名称和特定后缀_start, _finish, _init, _destroy)的连接。列表中的scalarfnaggfn, udf需要替换成udf函数名。
## 实现标量函数 ## 实现标量函数
标量函数实现模板如下 标量函数实现模板如下
@ -98,19 +102,21 @@ aggfn为函数名的占位符需要修改为自己的函数名如l2norm。
## 接口函数定义 ## 接口函数定义
接口函数的名称是 udf 名称,或者是 udf 名称和特定后缀_start, _finish, _init, _destroy)的连接。scalarfnaggfn, udf需要替换成udf函数名。 接口函数的名称是 udf 名称,或者是 udf 名称和特定后缀_start, _finish, _init, _destroy)的连接。以下描述中函数名称中的 scalarfnaggfn, udf 需要替换成udf函数名。
接口函数返回值表示是否成功如果错误返回错误代码。错误见taoserror.h 接口函数返回值表示是否成功。如果返回值是 TSDB_CODE_SUCCESS表示操作成功否则返回的是错误代码。错误代码定义在 taoserror.h和 taos.h 中的API共享错误码的定义。例如 TSDB_CODE_UDF_INVALID_INPUT 表示输入无效输入。TSDB_CODE_OUT_OF_MEMORY 表示内存不足。
接口函数参数类型见数据结构定义。
### 标量接口函数 ### 标量接口函数
`int32_t scalarfn(SUdfDataBlock* inputDataBlock, SUdfColumn *resultColumn)` `int32_t scalarfn(SUdfDataBlock* inputDataBlock, SUdfColumn *resultColumn)`
其中 udf 是函数名的占位符,以上述模板实现的函数对行数据块进行标量计算。 其中 scalarFn 是函数名的占位符。这个函数对数据块进行标量计算通过设置resultColumn结构体中的变量设置值
- 其中各参数的具体含义是: 参数的具体含义是:
- inputDataBlock: 输入的数据块 - inputDataBlock: 输入的数据块
- resultColumn: 输出列 - resultColumn: 输出列。输出列
### 聚合接口函数 ### 聚合接口函数
@ -119,22 +125,22 @@ aggfn为函数名的占位符需要修改为自己的函数名如l2norm。
`int32_t aggfn(SUdfDataBlock* inputBlock, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf)` `int32_t aggfn(SUdfDataBlock* inputBlock, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf)`
`int32_t aggfn_finish(SUdfInterBuf* interBuf, SUdfInterBuf *result)` `int32_t aggfn_finish(SUdfInterBuf* interBuf, SUdfInterBuf *result)`
其中 aggfn 是函数名的占位符。其中各参数的具体含义是:
其中 aggfn 是函数名的占位符。首先调用aggfn_start生成结果buffer然后相关的数据会被分为多个行数据块对每个数据块调用 aggfn 用数据块更新中间结果,最后再调用 aggfn_finish 从中间结果产生最终结果,最终结果只能含 0 或 1 条结果数据。
参数的具体含义是:
- interBuf中间结果 buffer。 - interBuf中间结果 buffer。
- inputBlock输入的数据块。 - inputBlock输入的数据块。
- newInterBuf新的中间结果buffer。 - newInterBuf新的中间结果buffer。
- result最终结果。 - result最终结果。
其计算过程为首先调用aggfn_start生成结果buffer然后相关的数据会被分为多个行数据块对每个行数据块调用 aggfn 用数据块更新中间结果,最后再调用 aggfn_finish 从中间结果产生最终结果,最终结果只能含 0 或 1 条结果数据。
### UDF 初始化和销毁 ### UDF 初始化和销毁
`int32_t udf_init()` `int32_t udf_init()`
`int32_t udf_destroy()` `int32_t udf_destroy()`
其中 udf 是函数名的占位符,可以替换成自己的函数名。udf_init 完成初始化工作。 udf_destroy 完成清理工作。如果没有初始化工作无需定义udf_init函数。如果没有清理工作无需定义udf_destroy函数。 其中 udf 是函数名的占位符。udf_init 完成初始化工作。 udf_destroy 完成清理工作。如果没有初始化工作无需定义udf_init函数。如果没有清理工作无需定义udf_destroy函数。
## UDF 数据结构 ## UDF 数据结构
@ -188,10 +194,10 @@ typedef struct SUdfInterBuf {
数据结构说明如下: 数据结构说明如下:
- SUdfDataBlock 数据块包含行数 numOfRows 和列数 numCols。udfCols[i] (0 <= i <= numCols-1)表示每一列数据类型为SUdfColumn*。 - SUdfDataBlock 数据块包含行数 numOfRows 和列数 numCols。udfCols[i] (0 <= i <= numCols-1)表示每一列数据类型为SUdfColumn*。
- SUdfColumn 包含列的数据类型定义 colMeta 和列的数据colData。 - SUdfColumn 包含列的数据类型定义 colMeta 和列的数据 colData。
- SUdfColumnMeta 成员定义同 taos.h 数据类型定义。 - SUdfColumnMeta 成员定义同 taos.h 数据类型定义。
- SUdfColumnData 数据可以变长varLenCol定义变长数据fixLenCol定义定长数据。 - SUdfColumnData 数据可以变长varLenCol 定义变长数据fixLenCol 定义定长数据。
- SUdfInterBuf 定义中间结构buffer以及buffer中结果个数 numOfResult - SUdfInterBuf 定义中间结构 buffer以及 buffer 中结果个数 numOfResult
为了更好的操作以上数据结构,提供了一些便利函数,定义在 taosudf.h。 为了更好的操作以上数据结构,提供了一些便利函数,定义在 taosudf.h。
@ -207,70 +213,8 @@ gcc -g -O0 -fPIC -shared add_one.c -o add_one.so
这样就准备好了动态链接库 add_one.so 文件,可以供后文创建 UDF 时使用了。为了保证可靠的系统运行,编译器 GCC 推荐使用 7.5 及以上版本。 这样就准备好了动态链接库 add_one.so 文件,可以供后文创建 UDF 时使用了。为了保证可靠的系统运行,编译器 GCC 推荐使用 7.5 及以上版本。
## 在系统中管理和使用 UDF ## 管理和使用UDF
编译好的UDF还需要将其加入到系统才能被正常的SQL调用。关于如何管理和使用UDF参见[UDF使用说明](../12-taos-sql/26-udf.md)
### 创建 UDF
用户可以通过 SQL 指令在系统中加载客户端所在主机上的 UDF 函数库(不能通过 RESTful 接口或 HTTP 管理界面来进行这一过程)。一旦创建成功,则当前 TDengine 集群的所有用户都可以在 SQL 指令中使用这些函数。UDF 存储在系统的 MNode 节点上,因此即使重启 TDengine 系统,已经创建的 UDF 也仍然可用。
在创建 UDF 时,需要区分标量函数和聚合函数。如果创建时声明了错误的函数类别,则可能导致通过 SQL 指令调用函数时出错。此外,用户需要保证输入数据类型与 UDF 程序匹配UDF 输出数据类型与 OUTPUTTYPE 匹配。
- 创建标量函数
```sql
CREATE FUNCTION function_name AS library_path OUTPUTTYPE output_type;
```
- function_name标量函数未来在 SQL 中被调用时的函数名,必须与函数实现中 udf 的实际名称一致;
- library_path包含 UDF 函数实现的动态链接库的库文件绝对路径(指的是库文件在当前客户端所在主机上的保存路径,通常是指向一个 .so 文件),这个路径需要用英文单引号或英文双引号括起来;
- output_type此函数计算结果的数据类型名称
例如,如下语句可以把 libbitand.so 创建为系统中可用的 UDF
```sql
CREATE FUNCTION bit_and AS "/home/taos/udf_example/libbitand.so" OUTPUTTYPE INT;
```
- 创建聚合函数:
```sql
CREATE AGGREGATE FUNCTION function_name AS library_path OUTPUTTYPE output_type [ BUFSIZE buffer_size ];
```
- function_name聚合函数未来在 SQL 中被调用时的函数名,必须与函数实现中 udfNormalFunc 的实际名称一致;
- library_path包含 UDF 函数实现的动态链接库的库文件绝对路径(指的是库文件在当前客户端所在主机上的保存路径,通常是指向一个 .so 文件),这个路径需要用英文单引号或英文双引号括起来;
- output_type此函数计算结果的数据类型与上文中 udfNormalFunc 的 itype 参数不同,这里不是使用数字表示法,而是直接写类型名称即可;
- buffer_size中间计算结果的缓冲区大小单位是字节。如果不使用可以不设置。
例如,如下语句可以把 libl2norm.so 创建为系统中可用的 UDF
```sql
CREATE AGGREGATE FUNCTION l2norm AS "/home/taos/udf_example/libl2norm.so" OUTPUTTYPE DOUBLE bufsize 8;
```
### 管理 UDF
- 删除指定名称的用户定义函数:
```
DROP FUNCTION function_name;
```
- function_name此参数的含义与 CREATE 指令中的 function_name 参数一致,也即要删除的函数的名字,例如
```sql
DROP FUNCTION bit_and;
```
- 显示系统中当前可用的所有 UDF
```sql
SHOW FUNCTIONS;
```
### 调用 UDF
在 SQL 指令中,可以直接以在系统中创建 UDF 时赋予的函数名来调用用户定义函数。例如:
```sql
SELECT X(c1,c2) FROM table/stable;
```
表示对名为 c1, c2 的数据列调用名为 X 的用户定义函数。SQL 指令中用户定义函数可以配合 WHERE 等查询特性来使用。
## 示例代码 ## 示例代码

View File

@ -73,11 +73,6 @@ serverPort 6030
按照《立即开始》里的步骤,启动第一个数据节点,例如 h1.taosdata.com然后执行 taos启动 taos shell从 shell 里执行命令“SHOW DNODES”如下所示 按照《立即开始》里的步骤,启动第一个数据节点,例如 h1.taosdata.com然后执行 taos启动 taos shell从 shell 里执行命令“SHOW DNODES”如下所示
``` ```
Welcome to the TDengine shell from Linux, Client Version:3.0.0.0
Copyright (c) 2022 by TAOS Data, Inc. All rights reserved.
Server is Enterprise trial Edition, ver:3.0.0.0 and will never expire.
taos> show dnodes; taos> show dnodes;
id | endpoint | vnodes | support_vnodes | status | create_time | note | id | endpoint | vnodes | support_vnodes | status | create_time | note |
============================================================================================================================================ ============================================================================================================================================

View File

@ -3,27 +3,20 @@ sidebar_label: Kubernetes
title: 在 Kubernetes 上部署 TDengine 集群 title: 在 Kubernetes 上部署 TDengine 集群
--- ---
## 配置 ConfigMap 作为面向云原生架构设计的时序数据库TDengine 支持 Kubernetes 部署。这里介绍如何使用 YAML 文件一步一步从头创建一个 TDengine 集群,并重点介绍 Kubernetes 环境下 TDengine 的常用操作。
为 TDengine 创建 `taoscfg.yaml`,此文件中的配置将作为环境变量传入 TDengine 镜像,更新此配置将导致所有 TDengine POD 重启。 ## 前置条件
```yaml 要使用 Kubernetes 部署管理 TDengine 集群,需要做好如下准备工作。
---
apiVersion: v1
kind: ConfigMap
metadata:
name: taoscfg
labels:
app: tdengine
data:
CLUSTER: "1"
TAOS_KEEP: "3650"
TAOS_DEBUG_FLAG: "135"
```
## 配置服务 * 本文和下一章使用 minikube、kubectl 和 helm 等工具进行安装部署,请提前安装好相应软件
* Kubernetes 已经安装部署并能正常访问使用或更新必要的容器仓库或其他服务
创建一个 service 配置文件:`taosd-service.yaml`,服务名称 `metadata.name` (此处为 "taosd") 将在下一步中使用到。添加 TDengine 所用到的所有端口: 以下配置文件也可以从 [GitHub 仓库](https://github.com/taosdata/TDengine-Operator/tree/3.0/src/tdengine) 下载。
## 配置 Service 服务
创建一个 Service 配置文件:`taosd-service.yaml`,服务名称 `metadata.name` (此处为 "taosd") 将在下一步中使用到。添加 TDengine 所用到的端口:
```yaml ```yaml
--- ---
@ -38,52 +31,17 @@ spec:
- name: tcp6030 - name: tcp6030
protocol: "TCP" protocol: "TCP"
port: 6030 port: 6030
- name: tcp6035
protocol: "TCP"
port: 6035
- name: tcp6041 - name: tcp6041
protocol: "TCP" protocol: "TCP"
port: 6041 port: 6041
- name: udp6030
protocol: "UDP"
port: 6030
- name: udp6031
protocol: "UDP"
port: 6031
- name: udp6032
protocol: "UDP"
port: 6032
- name: udp6033
protocol: "UDP"
port: 6033
- name: udp6034
protocol: "UDP"
port: 6034
- name: udp6035
protocol: "UDP"
port: 6035
- name: udp6036
protocol: "UDP"
port: 6036
- name: udp6037
protocol: "UDP"
port: 6037
- name: udp6038
protocol: "UDP"
port: 6038
- name: udp6039
protocol: "UDP"
port: 6039
- name: udp6040
protocol: "UDP"
port: 6040
selector: selector:
app: "tdengine" app: "tdengine"
``` ```
## 有状态服务 StatefulSet ## 有状态服务 StatefulSet
根据 Kubernetes 对各类部署的说明,我们将使用 StatefulSet 作为 TDengine 的服务类型,创建文件 `tdengine.yaml` 根据 Kubernetes 对各类部署的说明,我们将使用 StatefulSet 作为 TDengine 的服务类型。
创建文件 `tdengine.yaml`,其中 replicas 定义集群节点的数量为 3。节点时区为中国Asia/Shanghai每个节点分配 10G 标准standard存储。你也可以根据实际情况进行相应修改。
```yaml ```yaml
--- ---
@ -95,7 +53,7 @@ metadata:
app: "tdengine" app: "tdengine"
spec: spec:
serviceName: "taosd" serviceName: "taosd"
replicas: 2 replicas: 3
updateStrategy: updateStrategy:
type: RollingUpdate type: RollingUpdate
selector: selector:
@ -109,54 +67,15 @@ spec:
spec: spec:
containers: containers:
- name: "tdengine" - name: "tdengine"
image: "zitsen/taosd:develop" image: "tdengine/tdengine:3.0.0.0"
imagePullPolicy: "Always" imagePullPolicy: "IfNotPresent"
envFrom:
- configMapRef:
name: taoscfg
ports: ports:
- name: tcp6030 - name: tcp6030
protocol: "TCP" protocol: "TCP"
containerPort: 6030 containerPort: 6030
- name: tcp6035
protocol: "TCP"
containerPort: 6035
- name: tcp6041 - name: tcp6041
protocol: "TCP" protocol: "TCP"
containerPort: 6041 containerPort: 6041
- name: udp6030
protocol: "UDP"
containerPort: 6030
- name: udp6031
protocol: "UDP"
containerPort: 6031
- name: udp6032
protocol: "UDP"
containerPort: 6032
- name: udp6033
protocol: "UDP"
containerPort: 6033
- name: udp6034
protocol: "UDP"
containerPort: 6034
- name: udp6035
protocol: "UDP"
containerPort: 6035
- name: udp6036
protocol: "UDP"
containerPort: 6036
- name: udp6037
protocol: "UDP"
containerPort: 6037
- name: udp6038
protocol: "UDP"
containerPort: 6038
- name: udp6039
protocol: "UDP"
containerPort: 6039
- name: udp6040
protocol: "UDP"
containerPort: 6040
env: env:
# POD_NAME for FQDN config # POD_NAME for FQDN config
- name: POD_NAME - name: POD_NAME
@ -190,14 +109,13 @@ spec:
readinessProbe: readinessProbe:
exec: exec:
command: command:
- taos - taos-check
- -s
- "show mnodes"
initialDelaySeconds: 5 initialDelaySeconds: 5
timeoutSeconds: 5000 timeoutSeconds: 5000
livenessProbe: livenessProbe:
tcpSocket: exec:
port: 6030 command:
- taos-check
initialDelaySeconds: 15 initialDelaySeconds: 15
periodSeconds: 20 periodSeconds: 20
volumeClaimTemplates: volumeClaimTemplates:
@ -206,44 +124,74 @@ spec:
spec: spec:
accessModes: accessModes:
- "ReadWriteOnce" - "ReadWriteOnce"
storageClassName: "csi-rbd-sc" storageClassName: "standard"
resources: resources:
requests: requests:
storage: "10Gi" storage: "10Gi"
``` ```
## 启动集群 ## 使用 kubectl 命令部署 TDengine 集群
将前述三个文件添加到 Kubernetes 集群中: 顺序执行以下命令。
```bash ```bash
kubectl apply -f taoscfg.yaml
kubectl apply -f taosd-service.yaml kubectl apply -f taosd-service.yaml
kubectl apply -f tdengine.yaml kubectl apply -f tdengine.yaml
``` ```
上面的配置将生成一个两节点的 TDengine 集群dnode 是自动配置的,可以使用 `show dnodes` 命令查看当前集群的节点: 上面的配置将生成一个三节点的 TDengine 集群dnode 为自动配置,可以使用 show dnodes 命令查看当前集群的节点:
```bash ```bash
kubectl exec -i -t tdengine-0 -- taos -s "show dnodes" kubectl exec -i -t tdengine-0 -- taos -s "show dnodes"
kubectl exec -i -t tdengine-1 -- taos -s "show dnodes" kubectl exec -i -t tdengine-1 -- taos -s "show dnodes"
kubectl exec -i -t tdengine-2 -- taos -s "show dnodes"
``` ```
输出如下: 输出如下:
``` ```
Welcome to the TDengine shell from Linux, Client Version:2.1.1.0
Copyright (c) 2020 by TAOS Data, Inc. All rights reserved.
taos> show dnodes taos> show dnodes
id | end_point | vnodes | cores | status | role | create_time | offline reason | id | endpoint | vnodes | support_vnodes | status | create_time | note |
====================================================================================================================================== ============================================================================================================================================
1 | tdengine-0.taosd.default.sv... | 1 | 40 | ready | any | 2021-06-01 17:13:24.181 | | 1 | tdengine-0.taosd.default.sv... | 0 | 256 | ready | 2022-08-10 13:14:57.285 | |
2 | tdengine-1.taosd.default.sv... | 0 | 40 | ready | any | 2021-06-01 17:14:09.257 | | 2 | tdengine-1.taosd.default.sv... | 0 | 256 | ready | 2022-08-10 13:15:11.302 | |
Query OK, 2 row(s) in set (0.000997s) 3 | tdengine-2.taosd.default.sv... | 0 | 256 | ready | 2022-08-10 13:15:23.290 | |
Query OK, 3 rows in database (0.003655s)
```
## 使能端口转发
利用 kubectl 端口转发功能可以使应用可以访问 Kubernetes 环境运行的 TDengine 集群。
```
kubectl port-forward tdengine-0 6041:6041 &
```
使用 curl 命令验证 TDengine REST API 使用的 6041 接口。
```
$ curl -u root:taosdata -d "show databases" 127.0.0.1:6041/rest/sql
Handling connection for 6041
{"code":0,"column_meta":[["name","VARCHAR",64],["create_time","TIMESTAMP",8],["vgroups","SMALLINT",2],["ntables","BIGINT",8],["replica","TINYINT",1],["strict","VARCHAR",4],["duration","VARCHAR",10],["keep","VARCHAR",32],["buffer","INT",4],["pagesize","INT",4],["pages","INT",4],["minrows","INT",4],["maxrows","INT",4],["comp","TINYINT",1],["precision","VARCHAR",2],["status","VARCHAR",10],["retention","VARCHAR",60],["single_stable","BOOL",1],["cachemodel","VARCHAR",11],["cachesize","INT",4],["wal_level","TINYINT",1],["wal_fsync_period","INT",4],["wal_retention_period","INT",4],["wal_retention_size","BIGINT",8],["wal_roll_period","INT",4],["wal_segment_size","BIGINT",8]],"data":[["information_schema",null,null,16,null,null,null,null,null,null,null,null,null,null,null,"ready",null,null,null,null,null,null,null,null,null,null],["performance_schema",null,null,10,null,null,null,null,null,null,null,null,null,null,null,"ready",null,null,null,null,null,null,null,null,null,null]],"rows":2}
```
## 使用 dashboard 进行图形化管理
minikube 提供 dashboard 命令支持图形化管理界面。
```
$ minikube dashboard
* Verifying dashboard health ...
* Launching proxy ...
* Verifying proxy health ...
* Opening http://127.0.0.1:46617/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/ in your default browser...
http://127.0.0.1:46617/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/
```
对于某些公有云环境minikube 绑定在 127.0.0.1 IP 地址上无法通过远程访问,需要使用 kubectl proxy 命令将端口映射到 0.0.0.0 IP 地址上,再通过浏览器访问虚拟机公网 IP 和端口以及相同的 dashboard URL 路径即可远程访问 dashboard。
```
$ kubectl proxy --accept-hosts='^.*$' --address='0.0.0.0'
``` ```
## 集群扩容 ## 集群扩容
@ -252,14 +200,12 @@ TDengine 集群支持自动扩容:
```bash ```bash
kubectl scale statefulsets tdengine --replicas=4 kubectl scale statefulsets tdengine --replicas=4
``` ```
上面命令行中参数 `--replica=4` 表示要将 TDengine 集群扩容到 4 个节点,执行后首先检查 POD 的状态: 上面命令行中参数 `--replica=4` 表示要将 TDengine 集群扩容到 4 个节点,执行后首先检查 POD 的状态:
```bash ```bash
kubectl get pods -l app=tdengine kubectl get pods -l app=tdengine
``` ```
输出如下: 输出如下:
@ -270,102 +216,101 @@ tdengine-0 1/1 Running 0 161m
tdengine-1 1/1 Running 0 161m tdengine-1 1/1 Running 0 161m
tdengine-2 1/1 Running 0 32m tdengine-2 1/1 Running 0 32m
tdengine-3 1/1 Running 0 32m tdengine-3 1/1 Running 0 32m
``` ```
此时 POD 的状态仍然是 RunningTDengine 集群中的 dnode 状态要等 POD 状态为 `ready` 之后才能看到: 此时 POD 的状态仍然是 RunningTDengine 集群中的 dnode 状态要等 POD 状态为 `ready` 之后才能看到:
```bash ```bash
kubectl exec -i -t tdengine-0 -- taos -s "show dnodes" kubectl exec -i -t tdengine-3 -- taos -s "show dnodes"
``` ```
扩容后的四节点 TDengine 集群的 dnode 列表: 扩容后的四节点 TDengine 集群的 dnode 列表:
``` ```
Welcome to the TDengine shell from Linux, Client Version:2.1.1.0
Copyright (c) 2020 by TAOS Data, Inc. All rights reserved.
taos> show dnodes taos> show dnodes
id | end_point | vnodes | cores | status | role | create_time | offline reason | id | endpoint | vnodes | support_vnodes | status | create_time | note |
====================================================================================================================================== ============================================================================================================================================
1 | tdengine-0.taosd.default.sv... | 0 | 40 | ready | any | 2021-06-01 11:58:12.915 | | 1 | tdengine-0.taosd.default.sv... | 0 | 256 | ready | 2022-08-10 13:14:57.285 | |
2 | tdengine-1.taosd.default.sv... | 0 | 40 | ready | any | 2021-06-01 11:58:33.127 | | 2 | tdengine-1.taosd.default.sv... | 0 | 256 | ready | 2022-08-10 13:15:11.302 | |
3 | tdengine-2.taosd.default.sv... | 0 | 40 | ready | any | 2021-06-01 14:07:27.078 | | 3 | tdengine-2.taosd.default.sv... | 0 | 256 | ready | 2022-08-10 13:15:23.290 | |
4 | tdengine-3.taosd.default.sv... | 1 | 40 | ready | any | 2021-06-01 14:07:48.362 | | 4 | tdengine-3.taosd.default.sv... | 0 | 256 | ready | 2022-08-10 13:33:16.039 | |
Query OK, 4 row(s) in set (0.001293s) Query OK, 4 rows in database (0.008377s)
``` ```
## 集群缩容 ## 集群缩容
TDengine 的缩容并没有自动化,我们尝试将一个三节点集群缩容到两节点 由于 TDengine 集群在扩缩容时会对数据进行节点间迁移,使用 kubectl 命令进行缩容需要首先使用 "drop dnodes" 命令,节点删除完成后再进行 Kubernetes 集群缩容
首先,确认一个三节点 TDengine 集群正常工作,在 TDengine CLI 中查看 dnode 的状态: 注意:由于 Kubernetes Statefulset 中 Pod 的只能按创建顺序逆序移除,所以 TDengine drop dnode 也需要按照创建顺序逆序移除,否则会导致 Pod 处于错误状态。
```
$ kubectl exec -i -t tdengine-0 -- taos -s "drop dnode 4"
```
```bash ```bash
$ kubectl exec -it tdengine-0 -- taos -s "show dnodes"
taos> show dnodes taos> show dnodes
id | end_point | vnodes | cores | status | role | create_time | offline reason | id | endpoint | vnodes | support_vnodes | status | create_time | note |
====================================================================================================================================== ============================================================================================================================================
1 | tdengine-0.taosd.default.sv... | 1 | 40 | ready | any | 2021-06-01 16:27:24.852 | | 1 | tdengine-0.taosd.default.sv... | 0 | 256 | ready | 2022-08-10 13:14:57.285 | |
2 | tdengine-1.taosd.default.sv... | 0 | 40 | ready | any | 2021-06-01 16:27:53.339 | | 2 | tdengine-1.taosd.default.sv... | 0 | 256 | ready | 2022-08-10 13:15:11.302 | |
3 | tdengine-2.taosd.default.sv... | 0 | 40 | ready | any | 2021-06-01 16:28:49.787 | | 3 | tdengine-2.taosd.default.sv... | 0 | 256 | ready | 2022-08-10 13:15:23.290 | |
Query OK, 3 row(s) in set (0.001101s) Query OK, 3 rows in database (0.004861s)
``` ```
想要安全的缩容,首先需要将节点从 dnode 列表中移除,也即从集群中移除: 确认移除成功后(使用 kubectl exec -i -t tdengine-0 -- taos -s "show dnodes" 查看和确认 dnode 列表),使用 kubectl 命令移除 POD
```
kubectl scale statefulsets tdengine --replicas=3
```
最后一个 POD 将会被删除。使用命令 kubectl get pods -l app=tdengine 查看POD状态
```
$ kubectl get pods -l app=tdengine
NAME READY STATUS RESTARTS AGE
tdengine-0 1/1 Running 0 4m7s
tdengine-1 1/1 Running 0 3m55s
tdengine-2 1/1 Running 0 2m28s
```
POD删除后需要手动删除PVC否则下次扩容时会继续使用以前的数据导致无法正常加入集群。
```bash ```bash
kubectl exec -i -t tdengine-0 -- taos -s "drop dnode 'tdengine-2.taosd.default.svc.cluster.local:6030'" $ kubectl delete pvc taosdata-tdengine-3
```
通过 `show dondes` 命令确认移除成功后,移除相应的 POD
```bash
kubectl scale statefulsets tdengine --replicas=2
```
最后一个 POD 会被删除,使用 `kubectl get pods -l app=tdengine` 查看集群状态:
```
NAME READY STATUS RESTARTS AGE
tdengine-0 1/1 Running 0 3h40m
tdengine-1 1/1 Running 0 3h40m
```
POD 删除后,需要手动删除 PVC否则下次扩容时会继续使用以前的数据导致无法正常加入集群。
```bash
kubectl delete pvc taosdata-tdengine-2
``` ```
此时的集群状态是安全的,需要时还可以再次进行扩容: 此时的集群状态是安全的,需要时还可以再次进行扩容:
```bash ```bash
kubectl scale statefulsets tdengine --replicas=3 $ kubectl scale statefulsets tdengine --replicas=4
statefulset.apps/tdengine scaled
it@k8s-2:~/TDengine-Operator/src/tdengine$ kubectl get pods -l app=tdengine
NAME READY STATUS RESTARTS AGE
tdengine-0 1/1 Running 0 35m
tdengine-1 1/1 Running 0 34m
tdengine-2 1/1 Running 0 12m
tdengine-3 0/1 ContainerCreating 0 4s
it@k8s-2:~/TDengine-Operator/src/tdengine$ kubectl get pods -l app=tdengine
NAME READY STATUS RESTARTS AGE
tdengine-0 1/1 Running 0 35m
tdengine-1 1/1 Running 0 34m
tdengine-2 1/1 Running 0 12m
tdengine-3 0/1 Running 0 7s
it@k8s-2:~/TDengine-Operator/src/tdengine$ kubectl exec -it tdengine-0 -- taos -s "show dnodes"
```
`show dnodes` 输出如下:
```
taos> show dnodes taos> show dnodes
id | end_point | vnodes | cores | status | role | create_time | offline reason | id | endpoint | vnodes | support_vnodes | status | create_time | offline reason |
====================================================================================================================================== ======================================================================================================================================
1 | tdengine-0.taosd.default.sv... | 1 | 40 | ready | any | 2021-06-01 16:27:24.852 | | 1 | tdengine-0.taosd.default.sv... | 0 | 4 | ready | 2022-07-25 17:38:49.012 | |
2 | tdengine-1.taosd.default.sv... | 0 | 40 | ready | any | 2021-06-01 16:27:53.339 | | 2 | tdengine-1.taosd.default.sv... | 1 | 4 | ready | 2022-07-25 17:39:01.517 | |
4 | tdengine-2.taosd.default.sv... | 0 | 40 | ready | any | 2021-06-01 16:40:49.177 | | 5 | tdengine-2.taosd.default.sv... | 0 | 4 | ready | 2022-07-25 18:01:36.479 | |
6 | tdengine-3.taosd.default.sv... | 0 | 4 | ready | 2022-07-25 18:13:54.411 | |
Query OK, 4 row(s) in set (0.001348s)
``` ```
## 删除集群 ## 清理 TDengine 集群
完整移除 TDengine 集群,需要分别清理 statefulset、svc、configmap、pvc。 完整移除 TDengine 集群,需要分别清理 statefulset、svc、configmap、pvc。
@ -381,26 +326,21 @@ kubectl delete configmap taoscfg
### 错误一 ### 错误一
扩容到四节点之后缩容到两节点,删除的 POD 会进入 offline 状态: 未进行 "drop dnode" 直接进行缩容,由于 TDengine 尚未删除节点,缩容 pod 导致 TDengine 集群中部分节点处于 offline 状态。
``` ```
Welcome to the TDengine shell from Linux, Client Version:2.1.1.0 $ kubectl exec -it tdengine-0 -- taos -s "show dnodes"
Copyright (c) 2020 by TAOS Data, Inc. All rights reserved.
taos> show dnodes taos> show dnodes
id | end_point | vnodes | cores | status | role | create_time | offline reason | id | endpoint | vnodes | support_vnodes | status | create_time | offline reason |
====================================================================================================================================== ======================================================================================================================================
1 | tdengine-0.taosd.default.sv... | 0 | 40 | ready | any | 2021-06-01 11:58:12.915 | | 1 | tdengine-0.taosd.default.sv... | 0 | 4 | ready | 2022-07-25 17:38:49.012 | |
2 | tdengine-1.taosd.default.sv... | 0 | 40 | ready | any | 2021-06-01 11:58:33.127 | | 2 | tdengine-1.taosd.default.sv... | 1 | 4 | ready | 2022-07-25 17:39:01.517 | |
3 | tdengine-2.taosd.default.sv... | 0 | 40 | offline | any | 2021-06-01 14:07:27.078 | status msg timeout | 5 | tdengine-2.taosd.default.sv... | 0 | 4 | offline | 2022-07-25 18:01:36.479 | status msg timeout |
4 | tdengine-3.taosd.default.sv... | 1 | 40 | offline | any | 2021-06-01 14:07:48.362 | status msg timeout | 6 | tdengine-3.taosd.default.sv... | 0 | 4 | offline | 2022-07-25 18:13:54.411 | status msg timeout |
Query OK, 4 row(s) in set (0.001236s) Query OK, 4 row(s) in set (0.001323s)
``` ```
`drop dnode` 的行为按不会按照预期进行,且下次集群重启后,所有的 dnode 节点将无法启动 dropping 状态无法退出。
### 错误二 ### 错误二
TDengine 集群会持有 replica 参数,如果缩容后的节点数小于这个值,集群将无法使用: TDengine 集群会持有 replica 参数,如果缩容后的节点数小于这个值,集群将无法使用:

View File

@ -22,7 +22,7 @@ Helm 会使用 kubectl 和 kubeconfig 的配置来操作 Kubernetes可以参
TDengine Chart 尚未发布到 Helm 仓库,当前可以从 GitHub 直接下载: TDengine Chart 尚未发布到 Helm 仓库,当前可以从 GitHub 直接下载:
```bash ```bash
wget https://github.com/taosdata/TDengine-Operator/raw/main/helm/tdengine-0.3.0.tgz wget https://github.com/taosdata/TDengine-Operator/raw/3.0/helm/tdengine-3.0.0.tgz
``` ```
@ -38,7 +38,7 @@ kubectl get storageclass
之后,使用 helm 命令安装: 之后,使用 helm 命令安装:
```bash ```bash
helm install tdengine tdengine-0.3.0.tgz \ helm install tdengine tdengine-3.0.0.tgz \
--set storage.className=<your storage class name> --set storage.className=<your storage class name>
``` ```
@ -46,7 +46,7 @@ helm install tdengine tdengine-0.3.0.tgz \
在 minikube 环境下,可以设置一个较小的容量避免超出磁盘可用空间: 在 minikube 环境下,可以设置一个较小的容量避免超出磁盘可用空间:
```bash ```bash
helm install tdengine tdengine-0.3.0.tgz \ helm install tdengine tdengine-3.0.0.tgz \
--set storage.className=standard \ --set storage.className=standard \
--set storage.dataSize=2Gi \ --set storage.dataSize=2Gi \
--set storage.logSize=10Mi --set storage.logSize=10Mi
@ -83,14 +83,14 @@ TDengine 支持 `values.yaml` 自定义。
通过 helm show values 可以获取 TDengine Chart 支持的全部 values 列表: 通过 helm show values 可以获取 TDengine Chart 支持的全部 values 列表:
```bash ```bash
helm show values tdengine-0.3.0.tgz helm show values tdengine-3.0.0.tgz
``` ```
你可以将结果保存为 values.yaml之后可以修改其中的各项参数如 replica 数量存储类名称容量大小TDengine 配置等,然后使用如下命令安装 TDengine 集群: 你可以将结果保存为 values.yaml之后可以修改其中的各项参数如 replica 数量存储类名称容量大小TDengine 配置等,然后使用如下命令安装 TDengine 集群:
```bash ```bash
helm install tdengine tdengine-0.3.0.tgz -f values.yaml helm install tdengine tdengine-3.0.0.tgz -f values.yaml
``` ```
@ -107,37 +107,17 @@ image:
prefix: tdengine/tdengine prefix: tdengine/tdengine
#pullPolicy: Always #pullPolicy: Always
# Overrides the image tag whose default is the chart appVersion. # Overrides the image tag whose default is the chart appVersion.
#tag: "2.4.0.5" # tag: "3.0.0.0"
service: service:
# ClusterIP is the default service type, use NodeIP only if you know what you are doing. # ClusterIP is the default service type, use NodeIP only if you know what you are doing.
type: ClusterIP type: ClusterIP
ports: ports:
# TCP range required # TCP range required
tcp: tcp: [6030, 6041, 6042, 6043, 6044, 6046, 6047, 6048, 6049, 6060]
[ # UDP range
6030, udp: [6044, 6045]
6031,
6032,
6033,
6034,
6035,
6036,
6037,
6038,
6039,
6040,
6041,
6042,
6043,
6044,
6045,
6060,
]
# UDP range 6030-6039
udp: [6030, 6031, 6032, 6033, 6034, 6035, 6036, 6037, 6038, 6039]
arbitrator: true
# Set timezone here, not in taoscfg # Set timezone here, not in taoscfg
timezone: "Asia/Shanghai" timezone: "Asia/Shanghai"
@ -182,11 +162,14 @@ clusterDomainSuffix: ""
# #
# Btw, keep quotes "" around the value like below, even the value will be number or not. # Btw, keep quotes "" around the value like below, even the value will be number or not.
taoscfg: taoscfg:
# Starts as cluster or not, must be 0 or 1.
# 0: all pods will start as a seperate TDengine server
# 1: pods will start as TDengine server cluster. [default]
CLUSTER: "1"
# number of replications, for cluster only # number of replications, for cluster only
TAOS_REPLICA: "1" TAOS_REPLICA: "1"
# number of management nodes in the system
TAOS_NUM_OF_MNODES: "1"
# number of days per DB file # number of days per DB file
# TAOS_DAYS: "10" # TAOS_DAYS: "10"
@ -422,7 +405,7 @@ kubectl --namespace default exec $POD_NAME -- taos -s 'drop dnode "<you dnode in
``` ```
## 删除集群 ## 清理集群
Helm 管理下,清理操作也变得简单: Helm 管理下,清理操作也变得简单:

View File

@ -112,9 +112,9 @@ alter_database_options:
alter_database_option: { alter_database_option: {
CACHEMODEL {'none' | 'last_row' | 'last_value' | 'both'} CACHEMODEL {'none' | 'last_row' | 'last_value' | 'both'}
| CACHESIZE value | CACHESIZE value
| FSYNC value | WAL_LEVEL value
| WAL_FSYNC_PERIOD value
| KEEP value | KEEP value
| WAL value
} }
``` ```

View File

@ -140,10 +140,6 @@ taos> SELECT ts, ts AS primary_key_ts FROM d1001;
但是针对`first(*)`、`last(*)`、`last_row(*)`不支持针对单列的重命名。 但是针对`first(*)`、`last(*)`、`last_row(*)`不支持针对单列的重命名。
### 隐式结果列
`Select_exprs`可以是表所属列的列名,也可以是基于列的函数表达式或计算式,数量的上限 256 个。当用户使用了`interval`或`group by tags`的子句以后,在最后返回结果中会强制返回时间戳列(第一列)和 group by 子句中的标签列。后续的版本中可以支持关闭 group by 子句中隐式列的输出,列输出完全由 select 子句控制。
### 伪列 ### 伪列
**TBNAME** **TBNAME**
@ -152,7 +148,13 @@ taos> SELECT ts, ts AS primary_key_ts FROM d1001;
获取一个超级表所有的子表名及相关的标签信息: 获取一个超级表所有的子表名及相关的标签信息:
```mysql ```mysql
SELECT TBNAME, location FROM meters; SELECT DISTINCT TBNAME, location FROM meters;
```
建议用户使用 INFORMATION_SCHEMA 下的 INS_TAGS 系统表来查询超级表的子表标签信息,例如获取超级表 meters 所有的子表名和标签值:
```mysql
SELECT table_name, tag_name, tag_type, tag_value FROM information_schema.ins_tags WHERE stable_name='meters';
``` ```
统计超级表下辖子表数量: 统计超级表下辖子表数量:

View File

@ -89,10 +89,6 @@ T = 最新事件时间 - watermark
无论在哪种模式下watermark 都应该被妥善设置,来得到正确结果(直接丢弃模式)或避免频繁触发重算带来的性能开销(重新计算模式)。 无论在哪种模式下watermark 都应该被妥善设置,来得到正确结果(直接丢弃模式)或避免频繁触发重算带来的性能开销(重新计算模式)。
## 流式计算的数据填充策略
TODO
## 流式计算与会话窗口session window ## 流式计算与会话窗口session window
```sql ```sql
@ -105,14 +101,6 @@ window_clause: {
其中SESSION 是会话窗口tol_val 是时间间隔的最大范围。在 tol_val 时间间隔范围内的数据都属于同一个窗口,如果连续的两条数据的时间超过 tol_val则自动开启下一个窗口。 其中SESSION 是会话窗口tol_val 是时间间隔的最大范围。在 tol_val 时间间隔范围内的数据都属于同一个窗口,如果连续的两条数据的时间超过 tol_val则自动开启下一个窗口。
## 流式计算的监控与流任务分布查询
TODO
## 流式计算的内存控制与存算分离
TODO
## 流式计算的暂停与恢复 ## 流式计算的暂停与恢复
```sql ```sql

View File

@ -1,6 +1,6 @@
--- ---
sidebar_label: 元数据 sidebar_label: 元数据
title: 元数据库 title: 存储数据的 Information_Schema 数据库
--- ---
TDengine 内置了一个名为 `INFORMATION_SCHEMA` 的数据库,提供对数据库元数据、数据库系统信息和状态的访问,例如数据库或表的名称,当前执行的 SQL 语句等。该数据库存储有关 TDengine 维护的所有其他数据库的信息。它包含多个只读表。实际上,这些表都是视图,而不是基表,因此没有与它们关联的文件。所以对这些表只能查询,不能进行 INSERT 等写入操作。`INFORMATION_SCHEMA` 数据库旨在以一种更一致的方式来提供对 TDengine 支持的各种 SHOW 语句(如 SHOW TABLES、SHOW DATABASES所提供的信息的访问。与 SHOW 语句相比,使用 SELECT ... FROM INFORMATION_SCHEMA.tablename 具有以下优点: TDengine 内置了一个名为 `INFORMATION_SCHEMA` 的数据库,提供对数据库元数据、数据库系统信息和状态的访问,例如数据库或表的名称,当前执行的 SQL 语句等。该数据库存储有关 TDengine 维护的所有其他数据库的信息。它包含多个只读表。实际上,这些表都是视图,而不是基表,因此没有与它们关联的文件。所以对这些表只能查询,不能进行 INSERT 等写入操作。`INFORMATION_SCHEMA` 数据库旨在以一种更一致的方式来提供对 TDengine 支持的各种 SHOW 语句(如 SHOW TABLES、SHOW DATABASES所提供的信息的访问。与 SHOW 语句相比,使用 SELECT ... FROM INFORMATION_SCHEMA.tablename 具有以下优点:

View File

@ -0,0 +1,129 @@
---
sidebar_label: 统计数据
title: 存储统计数据的 Performance_Schema 数据库
---
TDengine 3.0 版本开始提供一个内置数据库 `performance_schema`,其中存储了与性能有关的统计数据。本节详细介绍其中的表和表结构。
## PERF_APP
提供接入集群的应用(客户端)的相关信息。也可以使用 SHOW APPS 来查询这些信息。
| # | **列名** | **数据类型** | **说明** |
| --- | :----------: | ------------ | ------------------------------- |
| 1 | app_id | UBIGINT | 客户端 ID |
| 2 | ip | BINARY(16) | 客户端地址 |
| 3 | pid | INT | 客户端进程 号 |
| 4 | name | BINARY(24) | 客户端名称 |
| 5 | start_time | TIMESTAMP | 客户端启动时间 |
| 6 | insert_req | UBIGINT | insert 请求次数 |
| 7 | insert_row | UBIGINT | insert 插入行数 |
| 8 | insert_time | UBIGINT | insert 请求的处理时间,单位微秒 |
| 9 | insert_bytes | UBIGINT | insert 请求消息字节数 |
| 10 | fetch_bytes | UBIGINT | 查询结果字节数 |
| 11 | query_time | UBIGINT | 查询请求处理时间 |
| 12 | slow_query | UBIGINT | 慢查询(处理时间 >= 3 秒)个数 |
| 13 | total_req | UBIGINT | 总请求数 |
| 14 | current_req | UBIGINT | 当前正在处理的请求个数 |
| 15 | last_access | TIMESTAMP | 最后更新时间 |
## PERF_CONNECTIONS
数据库的连接的相关信息。也可以使用 SHOW CONNECTIONS 来查询这些信息。
| # | **列名** | **数据类型** | **说明** |
| --- | :---------: | ------------ | -------------------------------------------------- |
| 1 | conn_id | INT | 连接 ID |
| 2 | user | BINARY(24) | 用户名 |
| 3 | app | BINARY(24) | 客户端名称 |
| 4 | pid | UINT | 发起此连接的客户端在自己所在服务器或主机上的进程号 |
| 5 | end_point | BINARY(128) | 客户端地址 |
| 6 | login_time | TIMESTAMP | 登录时间 |
| 7 | last_access | TIMESTAMP | 最后更新时间 |
## PERF_QUERIES
提供当前正在执行的 SQL 语句的信息。也可以使用 SHOW QUERIES 来查询这些信息。
| # | **列名** | **数据类型** | **说明** |
| --- | :----------: | ------------ | ---------------------------- |
| 1 | kill_id | UBIGINT | 用来停止查询的 ID |
| 2 | query_id | INT | 查询 ID |
| 3 | conn_id | UINT | 连接 ID |
| 4 | app | BINARY(24) | app 名称 |
| 5 | pid | INT | app 在自己所在主机上的进程号 |
| 6 | user | BINARY(24) | 用户名 |
| 7 | end_point | BINARY(16) | 客户端地址 |
| 8 | create_time | TIMESTAMP | 创建时间 |
| 9 | exec_usec | BIGINT | 已执行时间 |
| 10 | stable_query | BOOL | 是否是超级表查询 |
| 11 | sub_num | INT | 子查询数量 |
| 12 | sub_status | BINARY(1000) | 子查询状态 |
| 13 | sql | BINARY(1024) | SQL 语句 |
## PERF_TOPICS
| # | **列名** | **数据类型** | **说明** |
| --- | :---------: | ------------ | ------------------------------ |
| 1 | topic_name | BINARY(192) | topic 名称 |
| 2 | db_name | BINARY(64) | topic 相关的 DB |
| 3 | create_time | TIMESTAMP | topic 的 创建时间 |
| 4 | sql | BINARY(1024) | 创建该 topic 时所用的 SQL 语句 |
## PERF_CONSUMERS
| # | **列名** | **数据类型** | **说明** |
| --- | :------------: | ------------ | ----------------------------------------------------------- |
| 1 | consumer_id | BIGINT | 消费者的唯一 ID |
| 2 | consumer_group | BINARY(192) | 消费者组 |
| 3 | client_id | BINARY(192) | 用户自定义字符串,通过创建 consumer 时指定 client_id 来展示 |
| 4 | status | BINARY(20) | 消费者当前状态 |
| 5 | topics | BINARY(204) | 被订阅的 topic。若订阅多个 topic则展示为多行 |
| 6 | up_time | TIMESTAMP | 第一次连接 taosd 的时间 |
| 7 | subscribe_time | TIMESTAMP | 上一次发起订阅的时间 |
| 8 | rebalance_time | TIMESTAMP | 上一次触发 rebalance 的时间 |
## PERF_SUBSCRIPTIONS
| # | **列名** | **数据类型** | **说明** |
| --- | :------------: | ------------ | ------------------------ |
| 1 | topic_name | BINARY(204) | 被订阅的 topic |
| 2 | consumer_group | BINARY(193) | 订阅者的消费者组 |
| 3 | vgroup_id | INT | 消费者被分配的 vgroup id |
| 4 | consumer_id | BIGINT | 消费者的唯一 id |
## PERF_TRANS
| # | **列名** | **数据类型** | **说明** |
| --- | :--------------: | ------------ | -------------------------------------------------------------- |
| 1 | id | INT | 正在进行的事务的编号 |
| 2 | create_time | TIMESTAMP | 事务的创建时间 |
| 3 | stage | BINARY(12) | 事务的当前阶段,通常为 redoAction、undoAction、commit 三个阶段 |
| 4 | db1 | BINARY(64) | 与此事务存在冲突的数据库一的名称 |
| 5 | db2 | BINARY(64) | 与此事务存在冲突的数据库二的名称 |
| 6 | failed_times | INT | 事务执行失败的总次数 |
| 7 | last_exec_time | TIMESTAMP | 事务上次执行的时间 |
| 8 | last_action_info | BINARY(511) | 事务上次执行失败的明细信息 |
## PERF_SMAS
| # | **列名** | **数据类型** | **说明** |
| --- | :---------: | ------------ | ------------------------------------------- |
| 1 | sma_name | BINARY(192) | 时间维度的预计算 (time-range-wise sma) 名称 |
| 2 | create_time | TIMESTAMP | sma 创建时间 |
| 3 | stable_name | BINARY(192) | sma 所属的超级表名称 |
| 4 | vgroup_id | INT | sma 专属的 vgroup 名称 |
## PERF_STREAMS
| # | **列名** | **数据类型** | **说明** |
| --- | :----------: | ------------ | --------------------------------------- |
| 1 | stream_name | BINARY(64) | 流计算名称 |
| 2 | create_time | TIMESTAMP | 创建时间 |
| 3 | sql | BINARY(1024) | 创建流计算时提供的 SQL 语句 |
| 4 | status | BIANRY(20) | 流当前状态 |
| 5 | source_db | BINARY(64) | 源数据库 |
| 6 | target_db | BIANRY(64) | 目的数据库 |
| 7 | target_table | BINARY(192) | 流计算写入的目标表 |
| 8 | watermark | BIGINT | watermark详见 SQL 手册流式计算 |
| 9 | trigger | INT | 计算结果推送模式,详见 SQL 手册流式计算 |

View File

@ -8,7 +8,7 @@ title: 权限管理
## 创建用户 ## 创建用户
```sql ```sql
CREATE USER use_name PASS password; CREATE USER use_name PASS 'password';
``` ```
创建用户。 创建用户。
@ -91,4 +91,4 @@ priv_level : {
``` ```
收回对用户的授权。 收回对用户的授权。

View File

@ -4,34 +4,65 @@ title: 用户自定义函数
--- ---
除了 TDengine 的内置函数以外用户还可以编写自己的函数逻辑并加入TDengine系统中。 除了 TDengine 的内置函数以外用户还可以编写自己的函数逻辑并加入TDengine系统中。
## 创建 UDF
## 创建函数 用户可以通过 SQL 指令在系统中加载客户端所在主机上的 UDF 函数库(不能通过 RESTful 接口或 HTTP 管理界面来进行这一过程)。一旦创建成功,则当前 TDengine 集群的所有用户都可以在 SQL 指令中使用这些函数。UDF 存储在系统的 MNode 节点上,因此即使重启 TDengine 系统,已经创建的 UDF 也仍然可用。
在创建 UDF 时,需要区分标量函数和聚合函数。如果创建时声明了错误的函数类别,则可能导致通过 SQL 指令调用函数时出错。此外,用户需要保证输入数据类型与 UDF 程序匹配UDF 输出数据类型与 OUTPUTTYPE 匹配。
- 创建标量函数
```sql ```sql
CREATE [AGGREGATE] FUNCTION func_name AS library_path OUTPUTTYPE type_name [BUFSIZE buffer_size] CREATE FUNCTION function_name AS library_path OUTPUTTYPE output_type;
``` ```
语法说明: - function_name标量函数未来在 SQL 中被调用时的函数名,必须与函数实现中 udf 的实际名称一致;
- library_path包含 UDF 函数实现的动态链接库的库文件绝对路径(指的是库文件在当前客户端所在主机上的保存路径,通常是指向一个 .so 文件),这个路径需要用英文单引号或英文双引号括起来;
- output_type此函数计算结果的数据类型名称
AGGREGATE标识此函数是标量函数还是聚集函数。 例如,如下语句可以把 libbitand.so 创建为系统中可用的 UDF
func_name函数名必须与函数实现中 udf 的实际名称一致。
library_path包含UDF函数实现的动态链接库的绝对路径是在客户端侧主机上的绝对路径。
type_name标识此函数的返回类型。
buffer_size中间结果的缓冲区大小单位是字节。不设置则默认为0。
```sql
CREATE FUNCTION bit_and AS "/home/taos/udf_example/libbitand.so" OUTPUTTYPE INT;
```
- 创建聚合函数:
```sql
CREATE AGGREGATE FUNCTION function_name AS library_path OUTPUTTYPE output_type [ BUFSIZE buffer_size ];
```
- function_name聚合函数未来在 SQL 中被调用时的函数名,必须与函数实现中 udfNormalFunc 的实际名称一致;
- library_path包含 UDF 函数实现的动态链接库的库文件绝对路径(指的是库文件在当前客户端所在主机上的保存路径,通常是指向一个 .so 文件),这个路径需要用英文单引号或英文双引号括起来;
- output_type此函数计算结果的数据类型与上文中 udfNormalFunc 的 itype 参数不同,这里不是使用数字表示法,而是直接写类型名称即可;
- buffer_size中间计算结果的缓冲区大小单位是字节。如果不使用可以不设置。
例如,如下语句可以把 libl2norm.so 创建为系统中可用的 UDF
```sql
CREATE AGGREGATE FUNCTION l2norm AS "/home/taos/udf_example/libl2norm.so" OUTPUTTYPE DOUBLE bufsize 8;
```
关于如何开发自定义函数,请参考 [UDF使用说明](../../develop/udf)。 关于如何开发自定义函数,请参考 [UDF使用说明](../../develop/udf)。
## 删除自定义函数 ## 管理 UDF
- 删除指定名称的用户定义函数:
``` ```
DROP FUNCTION function_name; DROP FUNCTION function_name;
``` ```
- function_name此参数的含义与 CREATE 指令中的 function_name 参数一致,也即要删除的函数的名字,例如 - function_name此参数的含义与 CREATE 指令中的 function_name 参数一致也即要删除的函数的名字例如bit_and, l2norm
## 显示 UDF
```sql ```sql
SHOW FUNCTION; DROP FUNCTION bit_and;
``` ```
- 显示系统中当前可用的所有 UDF
```sql
SHOW FUNCTIONS;
```
## 调用 UDF
在 SQL 指令中,可以直接以在系统中创建 UDF 时赋予的函数名来调用用户定义函数。例如:
```sql
SELECT X(c1,c2) FROM table/stable;
```
表示对名为 c1, c2 的数据列调用名为 X 的用户定义函数。SQL 指令中用户定义函数可以配合 WHERE 等查询特性来使用。

View File

@ -5,11 +5,12 @@ description: "TAOS SQL 支持的语法规则、主要查询功能、支持的 SQ
本文档说明 TAOS SQL 支持的语法规则、主要查询功能、支持的 SQL 查询函数,以及常用技巧等内容。阅读本文档需要读者具有基本的 SQL 语言的基础。 本文档说明 TAOS SQL 支持的语法规则、主要查询功能、支持的 SQL 查询函数,以及常用技巧等内容。阅读本文档需要读者具有基本的 SQL 语言的基础。
TAOS SQL 是用户对 TDengine 进行数据写入和查询的主要工具。TAOS SQL 为了便于用户快速上手,在一定程度上提供与标准 SQL 类似的风格和模式。严格意义上TAOS SQL 并不是也不试图提供标准的 SQL 语法。此外,由于 TDengine 针对的时序性结构化数据不提供删除功能,因此在 TAO SQL 中不提供数据删除的相关功能 TAOS SQL 是用户对 TDengine 进行数据写入和查询的主要工具。TAOS SQL 提供标准的 SQL 语法并针对时序数据和业务的特点优化和新增了许多语法和功能。TAOS SQL 语句的最大长度为 1M。TAOS SQL 不支持关键字的缩写,例如 DELETE 不能缩写为 DEL
本章节 SQL 语法遵循如下约定: 本章节 SQL 语法遵循如下约定:
- <\> 里的内容是用户需要输入的但不要输入 <\> 本身 - 用大写字母表示关键字,但 SQL 本身并不区分关键字和标识符的大小写
- 用小写字母表示需要用户输入的内容
- \[ \] 表示内容为可选项,但不能输入 [] 本身 - \[ \] 表示内容为可选项,但不能输入 [] 本身
- | 表示多选一,选择其中一个即可,但不能输入 | 本身 - | 表示多选一,选择其中一个即可,但不能输入 | 本身
- … 表示前面的项可重复多个 - … 表示前面的项可重复多个

View File

@ -10,14 +10,13 @@ TDengine 提供了丰富的应用程序开发接口,为了便于用户快速
目前 TDengine 的原生接口连接器可支持的平台包括X64/X86/ARM64/ARM32/MIPS/Alpha 等硬件平台,以及 Linux/Win64/Win32 等开发环境。对照矩阵如下: 目前 TDengine 的原生接口连接器可支持的平台包括X64/X86/ARM64/ARM32/MIPS/Alpha 等硬件平台,以及 Linux/Win64/Win32 等开发环境。对照矩阵如下:
| **CPU** | **OS** | **JDBC** | **Python** | **Go** | **Node.js** | **C#** | **Rust** | C/C++ | | **CPU** | **OS** | **Java** | **Python** | **Go** | **Node.js** | **C#** | **Rust** | C/C++ |
| -------------- | --------- | -------- | ---------- | ------ | ----------- | ------ | -------- | ----- | | -------------- | --------- | -------- | ---------- | ------ | ----------- | ------ | -------- | ----- |
| **X86 64bit** | **Linux** | ● | ● | ● | ● | ● | ● | ● | | **X86 64bit** | **Linux** | ● | ● | ● | ● | ● | ● | ● |
| **X86 64bit** | **Win64** | ● | ● | ● | ● | ● | ● | ● | | **X86 64bit** | **Win64** | ● | ● | ● | ● | ● | ● | ● |
| **X86 64bit** | **Win32** | ● | ● | ● | ● | ○ | ○ | ● | | **X86 64bit** | **Win32** | ● | ● | ● | ● | ○ | ○ | ● |
| **X86 32bit** | **Win32** | ○ | ○ | ○ | ○ | ○ | ○ | ● | | **X86 32bit** | **Win32** | ○ | ○ | ○ | ○ | ○ | ○ | ● |
| **ARM64** | **Linux** | ● | ● | ● | ● | ○ | ○ | ● | | **ARM64** | **Linux** | ● | ● | ● | ● | ○ | ○ | ● |
| **ARM32** | **Linux** | ● | ● | ● | ● | ○ | ○ | ● |
| **MIPS 龙芯** | **Linux** | ○ | ○ | ○ | ○ | ○ | ○ | ○ | | **MIPS 龙芯** | **Linux** | ○ | ○ | ○ | ○ | ○ | ○ | ○ |
| **Alpha 申威** | **Linux** | ○ | ○ | -- | -- | -- | -- | ○ | | **Alpha 申威** | **Linux** | ○ | ○ | -- | -- | -- | -- | ○ |
| **X86 海光** | **Linux** | ○ | ○ | ○ | -- | -- | -- | ○ | | **X86 海光** | **Linux** | ○ | ○ | ○ | -- | -- | -- | ○ |
@ -32,6 +31,7 @@ TDengine 版本更新往往会增加新的功能特性,列表中的连接器
| **TDengine 版本** | **Java** | **Python** | **Go** | **C#** | **Node.js** | **Rust** | | **TDengine 版本** | **Java** | **Python** | **Go** | **C#** | **Node.js** | **Rust** |
| --------------------- | -------- | ---------- | ------------ | ------------- | --------------- | -------- | | --------------------- | -------- | ---------- | ------------ | ------------- | --------------- | -------- |
| **3.0.0.0 及以上** | 3.0.0 | 当前版本 | 3.0 分支 | 3.0.0 | 3.0.0 | 当前版本 |
| **2.4.0.14 及以上** | 2.0.38 | 当前版本 | develop 分支 | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | 当前版本 | | **2.4.0.14 及以上** | 2.0.38 | 当前版本 | develop 分支 | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | 当前版本 |
| **2.4.0.6 及以上** | 2.0.37 | 当前版本 | develop 分支 | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | 当前版本 | | **2.4.0.6 及以上** | 2.0.37 | 当前版本 | develop 分支 | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | 当前版本 |
| **2.4.0.4 - 2.4.0.5** | 2.0.37 | 当前版本 | develop 分支 | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | 当前版本 | | **2.4.0.4 - 2.4.0.5** | 2.0.37 | 当前版本 | develop 分支 | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | 当前版本 |
@ -48,9 +48,8 @@ TDengine 版本更新往往会增加新的功能特性,列表中的连接器
| -------------- | -------- | ---------- | ------ | ------ | ----------- | -------- | | -------------- | -------- | ---------- | ------ | ------ | ----------- | -------- |
| **连接管理** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | | **连接管理** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **普通查询** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | | **普通查询** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **连续查询** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **参数绑定** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | | **参数绑定** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **订阅功能** | 支持 | 支持 | 支持 | 支持 | 支持 | 暂不支持 | | ** TMQ ** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **Schemaless** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | | **Schemaless** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **DataFrame** | 不支持 | 支持 | 不支持 | 不支持 | 不支持 | 不支持 | | **DataFrame** | 不支持 | 支持 | 不支持 | 不支持 | 不支持 | 不支持 |
@ -58,17 +57,17 @@ TDengine 版本更新往往会增加新的功能特性,列表中的连接器
由于不同编程语言数据库框架规范不同,并不意味着所有 C/C++ 接口都需要对应封装支持。 由于不同编程语言数据库框架规范不同,并不意味着所有 C/C++ 接口都需要对应封装支持。
::: :::
### 使用 REST 接口 ### 使用 http (REST 或 WebSocket) 接口
| **功能特性** | **Java** | **Python** | **Go** | **C#(暂不支持)** | **Node.js** | **Rust** | | **功能特性** | **Java** | **Python** | **Go** | **C#(暂不支持)** | **Node.js** | **Rust** |
| ------------------------------ | -------- | ---------- | -------- | ------------------ | ----------- | -------- | | ------------------------------ | -------- | ---------- | -------- | ------------------ | ----------- | -------- |
| **连接管理** | 支持 | 支持 | 支持 | N/A | 支持 | 支持 | | **连接管理** | 支持 | 支持 | 支持 | N/A | 支持 | 支持 |
| **普通查询** | 支持 | 支持 | 支持 | N/A | 支持 | 支持 | | **普通查询** | 支持 | 支持 | 支持 | N/A | 支持 | 支持 |
| **连续查询** | 支持 | 支持 | 支持 | N/A | 支持 | 支持 | | **连续查询** | 支持 | 支持 | 支持 | N/A | 支持 | 支持 |
| **参数绑定** | 不支持 | 不支持 | 不支持 | N/A | 不支持 | 支持 | | **参数绑定** | 不支持 | 不支持 | 不支持 | N/A | 不支持 | 支持 |
| **订阅功能** | 不支持 | 不支持 | 不支持 | N/A | 不支持 | 不支持 | | ** TMQ ** | 不支持 | 暂不支持 | 暂不支持 | N/A | 不支持 | 支持 |
| **Schemaless** | 暂不支持 | 暂不支持 | 暂不支持 | N/A | 不支持 | 暂不支持 | | **Schemaless** | 暂不支持 | 暂不支持 | 暂不支持 | N/A | 不支持 | 暂不支持 |
| **批量拉取(基于 WebSocket** | 支持 | 暂不支持 | 暂不支持 | N/A | 不支持 | 暂不支持 | | **批量拉取(基于 WebSocket** | 支持 | 支持 | 暂不支持 | N/A | 不支持 | 支持 |
| **DataFrame** | 不支持 | 支持 | 不支持 | N/A | 不支持 | 不支持 | | **DataFrame** | 不支持 | 支持 | 不支持 | N/A | 不支持 | 不支持 |
:::warning :::warning

View File

@ -2,10 +2,6 @@
```text ```text
$ taos $ taos
Welcome to the TDengine shell from Linux, Client Version:3.0.0.0
Copyright (c) 2022 by TAOS Data, Inc. All rights reserved.
Server is Community Edition.
taos> show databases; taos> show databases;
name | create_time | vgroups | ntables | replica | strict | duration | keep | buffer | pagesize | pages | minrows | maxrows | comp | precision | status | retention | single_stable | cachemodel | cachesize | wal_level | wal_fsync_period | wal_retention_period | wal_retention_size | wal_roll_period | wal_seg_size | name | create_time | vgroups | ntables | replica | strict | duration | keep | buffer | pagesize | pages | minrows | maxrows | comp | precision | status | retention | single_stable | cachemodel | cachesize | wal_level | wal_fsync_period | wal_retention_period | wal_retention_size | wal_roll_period | wal_seg_size |

View File

@ -1,11 +1,6 @@
在 cmd 下进入到 C:\TDengine 目录下直接执行 `taos.exe`,连接到 TDengine 服务,进入到 TDengine CLI 界面,示例如下: 在 cmd 下进入到 C:\TDengine 目录下直接执行 `taos.exe`,连接到 TDengine 服务,进入到 TDengine CLI 界面,示例如下:
```text ```text
Welcome to the TDengine shell from Windows, Client Version:3.0.0.0
Copyright (c) 2022 by TAOS Data, Inc. All rights reserved.
Server is Community Edition.
taos> show databases; taos> show databases;
name | create_time | vgroups | ntables | replica | strict | duration | keep | buffer | pagesize | pages | minrows | maxrows | comp | precision | status | retention | single_stable | cachemodel | cachesize | wal_level | wal_fsync_period | wal_retention_period | wal_retention_size | wal_roll_period | wal_seg_size | name | create_time | vgroups | ntables | replica | strict | duration | keep | buffer | pagesize | pages | minrows | maxrows | comp | precision | status | retention | single_stable | cachemodel | cachesize | wal_level | wal_fsync_period | wal_retention_period | wal_retention_size | wal_roll_period | wal_seg_size |
========================================================================================================================================================================================================================================================================================================================================================================================================================================================================= =========================================================================================================================================================================================================================================================================================================================================================================================================================================================================

View File

@ -279,7 +279,7 @@ TDengine 的异步 API 均采用非阻塞调用模式。应用程序可以用多
2. 调用 `taos_stmt_prepare()` 解析 INSERT 语句; 2. 调用 `taos_stmt_prepare()` 解析 INSERT 语句;
3. 如果 INSERT 语句中预留了表名但没有预留 TAGS那么调用 `taos_stmt_set_tbname()` 来设置表名; 3. 如果 INSERT 语句中预留了表名但没有预留 TAGS那么调用 `taos_stmt_set_tbname()` 来设置表名;
4. 如果 INSERT 语句中既预留了表名又预留了 TAGS例如 INSERT 语句采取的是自动建表的方式),那么调用 `taos_stmt_set_tbname_tags()` 来设置表名和 TAGS 的值; 4. 如果 INSERT 语句中既预留了表名又预留了 TAGS例如 INSERT 语句采取的是自动建表的方式),那么调用 `taos_stmt_set_tbname_tags()` 来设置表名和 TAGS 的值;
5. 调用 `taos_stmt_bind_param_batch()` 以多的方式设置 VALUES 的值,或者调用 `taos_stmt_bind_param()` 以单行的方式设置 VALUES 的值; 5. 调用 `taos_stmt_bind_param_batch()` 以多的方式设置 VALUES 的值,或者调用 `taos_stmt_bind_param()` 以单行的方式设置 VALUES 的值;
6. 调用 `taos_stmt_add_batch()` 把当前绑定的参数加入批处理; 6. 调用 `taos_stmt_add_batch()` 把当前绑定的参数加入批处理;
7. 可以重复第 3 6 步,为批处理加入更多的数据行; 7. 可以重复第 3 6 步,为批处理加入更多的数据行;
8. 调用 `taos_stmt_execute()` 执行已经准备好的批处理指令; 8. 调用 `taos_stmt_execute()` 执行已经准备好的批处理指令;

View File

@ -9,7 +9,7 @@ description: TDengine Java 连接器基于标准 JDBC API 实现, 并提供原
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem'; import TabItem from '@theme/TabItem';
`taos-jdbcdriver` 是 TDengine 的官方 Java 语言连接器Java 开发人员可以通过它开发存取 TDengine 数据库的应用软件。`taos-jdbcdriver` 实现了 JDBC driver 标准的接口,并提供两种形式的连接器。一种是通过 TDengine 客户端驱动程序taosc原生连接 TDengine 实例支持数据写入、查询、订阅、schemaless 接口和参数绑定接口等功能,一种是通过 taosAdapter 提供的 REST 接口连接 TDengine 实例2.4.0.0 及更高版本)。REST 连接实现的功能集合和原生连接有少量不同。 `taos-jdbcdriver` 是 TDengine 的官方 Java 语言连接器Java 开发人员可以通过它开发存取 TDengine 数据库的应用软件。`taos-jdbcdriver` 实现了 JDBC driver 标准的接口,并提供两种形式的连接器。一种是通过 TDengine 客户端驱动程序taosc原生连接 TDengine 实例支持数据写入、查询、订阅、schemaless 接口和参数绑定接口等功能,一种是通过 taosAdapter 提供的 REST 接口连接 TDengine 实例。REST 连接实现的功能集合和原生连接有少量不同。
![TDengine Database Connector Java](tdengine-jdbc-connector.webp) ![TDengine Database Connector Java](tdengine-jdbc-connector.webp)
@ -41,19 +41,19 @@ REST 连接支持所有能运行 Java 的平台。
TDengine 目前支持时间戳、数字、字符、布尔类型,与 Java 对应类型转换如下: TDengine 目前支持时间戳、数字、字符、布尔类型,与 Java 对应类型转换如下:
| TDengine DataType | JDBCType driver 版本 < 2.0.24 | JDBCType driver 版本 >= 2.0.24 | | TDengine DataType | JDBCType |
| ----------------- | --------------------------------- | ---------------------------------- | | ----------------- | ---------------------------------- |
| TIMESTAMP | java.lang.Long | java.sql.Timestamp | | TIMESTAMP | java.sql.Timestamp |
| INT | java.lang.Integer | java.lang.Integer | | INT | java.lang.Integer |
| BIGINT | java.lang.Long | java.lang.Long | | BIGINT | java.lang.Long |
| FLOAT | java.lang.Float | java.lang.Float | | FLOAT | java.lang.Float |
| DOUBLE | java.lang.Double | java.lang.Double | | DOUBLE | java.lang.Double |
| SMALLINT | java.lang.Short | java.lang.Short | | SMALLINT | java.lang.Short |
| TINYINT | java.lang.Byte | java.lang.Byte | | TINYINT | java.lang.Byte |
| BOOL | java.lang.Boolean | java.lang.Boolean | | BOOL | java.lang.Boolean |
| BINARY | java.lang.String | byte array | | BINARY | byte array |
| NCHAR | java.lang.String | java.lang.String | | NCHAR | java.lang.String |
| JSON | - | java.lang.String | | JSON | java.lang.String |
**注意**JSON 类型仅在 tag 中支持。 **注意**JSON 类型仅在 tag 中支持。
@ -198,7 +198,7 @@ url 中的配置参数如下:
- user登录 TDengine 用户名,默认值 'root'。 - user登录 TDengine 用户名,默认值 'root'。
- password用户登录密码默认值 'taosdata'。 - password用户登录密码默认值 'taosdata'。
- batchfetch: true在执行查询时批量拉取结果集false逐行拉取结果集。默认值为false。逐行拉取结果集使用 HTTP 方式进行数据传输。从 taos-jdbcdriver-2.0.38 和 TDengine 2.4.0.12 版本开始JDBC REST 连接增加批量拉取数据功能。taos-jdbcdriver 与 TDengine 之间通过 WebSocket 连接进行数据传输。相较于 HTTPWebSocket 可以使 JDBC REST 连接支持大数据量查询,并提升查询性能。 - batchfetch: true在执行查询时批量拉取结果集false逐行拉取结果集。默认值为false。逐行拉取结果集使用 HTTP 方式进行数据传输。从 taos-jdbcdriver-2.0.38 开始JDBC REST 连接增加批量拉取数据功能。taos-jdbcdriver 与 TDengine 之间通过 WebSocket 连接进行数据传输。相较于 HTTPWebSocket 可以使 JDBC REST 连接支持大数据量查询,并提升查询性能。
- charset: 当开启批量拉取数据时,指定解析字符串数据的字符集。 - charset: 当开启批量拉取数据时,指定解析字符串数据的字符集。
- batchErrorIgnoretrue在执行 Statement 的 executeBatch 时,如果中间有一条 SQL 执行失败,继续执行下面的 SQL 了。false不再执行失败 SQL 后的任何语句。默认值为false。 - batchErrorIgnoretrue在执行 Statement 的 executeBatch 时,如果中间有一条 SQL 执行失败,继续执行下面的 SQL 了。false不再执行失败 SQL 后的任何语句。默认值为false。
- httpConnectTimeout: 连接超时时间,单位 ms 默认值为 5000。 - httpConnectTimeout: 连接超时时间,单位 ms 默认值为 5000。
@ -216,7 +216,7 @@ url 中的配置参数如下:
INSERT INTO test.t1 USING test.weather (ts, temperature) TAGS('California.SanFrancisco') VALUES(now, 24.6); INSERT INTO test.t1 USING test.weather (ts, temperature) TAGS('California.SanFrancisco') VALUES(now, 24.6);
``` ```
- 从 taos-jdbcdriver-2.0.36 和 TDengine 2.2.0.0 版本开始,如果在 url 中指定了 dbname那么JDBC REST 连接会默认使用/rest/sql/dbname 作为 restful 请求的 url在 SQL 中不需要指定 dbname。例如url 为 jdbc:TAOS-RS://127.0.0.1:6041/test那么可以执行 sqlinsert into t1 using weather(ts, temperature) tags('California.SanFrancisco') values(now, 24.6); - 从 taos-jdbcdriver-2.0.36 开始,如果在 url 中指定了 dbname那么JDBC REST 连接会默认使用/rest/sql/dbname 作为 restful 请求的 url在 SQL 中不需要指定 dbname。例如url 为 jdbc:TAOS-RS://127.0.0.1:6041/test那么可以执行 sqlinsert into t1 using weather(ts, temperature) tags('California.SanFrancisco') values(now, 24.6);
::: :::
@ -358,11 +358,11 @@ JDBC 连接器可能报错的错误码包括 3 种JDBC driver 本身的报错
具体的错误码请参考: 具体的错误码请参考:
- [TDengine Java Connector](https://github.com/taosdata/taos-connector-jdbc/blob/main/src/main/java/com/taosdata/jdbc/TSDBErrorNumbers.java) - [TDengine Java Connector](https://github.com/taosdata/taos-connector-jdbc/blob/main/src/main/java/com/taosdata/jdbc/TSDBErrorNumbers.java)
- [TDengine_ERROR_CODE](https://github.com/taosdata/TDengine/blob/develop/src/inc/taoserror.h) <!-- - [TDengine_ERROR_CODE](../error-code) -->
### 通过参数绑定写入数据 ### 通过参数绑定写入数据
从 2.1.2.0 版本开始,TDengine 的 JDBC 原生连接实现大幅改进了参数绑定方式对数据写入INSERT场景的支持。采用这种方式写入数据时能避免 SQL 语法解析的资源消耗,从而在很多情况下显著提升写入性能。 TDengine 的 JDBC 原生连接实现大幅改进了参数绑定方式对数据写入INSERT场景的支持。采用这种方式写入数据时能避免 SQL 语法解析的资源消耗,从而在很多情况下显著提升写入性能。
**注意** **注意**
@ -630,7 +630,7 @@ public void setNString(int columnIndex, ArrayList<String> list, int size) throws
### 无模式写入 ### 无模式写入
从 2.2.0.0 版本开始TDengine 增加了对无模式写入功能。无模式写入兼容 InfluxDB 的 行协议Line Protocol、OpenTSDB 的 telnet 行协议和 OpenTSDB 的 JSON 格式协议。详情请参见[无模式写入](/reference/schemaless/)。 TDengine 支持无模式写入功能。无模式写入兼容 InfluxDB 的 行协议Line Protocol、OpenTSDB 的 telnet 行协议和 OpenTSDB 的 JSON 格式协议。详情请参见[无模式写入](../../schemaless)。
**注意** **注意**
@ -670,55 +670,127 @@ public class SchemalessInsertTest {
TDengine Java 连接器支持订阅功能,应用 API 如下: TDengine Java 连接器支持订阅功能,应用 API 如下:
#### 创建订阅 #### 创建 Topic
```java ```java
TSDBSubscribe sub = ((TSDBConnection)conn).subscribe("topic", "select * from meters", false); Connection connection = DriverManager.getConnection(url, properties);
Statement statement = connection.createStatement();
statement.executeUpdate("create topic if not exists topic_speed as select ts, speed from speed_table");
``` ```
`subscribe` 方法的三个参数含义如下: `subscribe` 方法的三个参数含义如下:
- topic订阅的主题即名称此参数是订阅的唯一标识 - topic_speed订阅的主题即名称此参数是订阅的唯一标识。
- sql订阅的查询语句此语句只能是 `select` 语句,只应查询原始数据,只能按时间正序查询数据 - sql订阅的查询语句此语句只能是 `select` 语句,只应查询原始数据,只能按时间正序查询数据。
- restart如果订阅已经存在是重新开始还是继续之前的订阅
如上面的例子将使用 SQL 语句 `select * from meters` 创建一个名为 `topic` 的订阅,如果这个订阅已经存在,将继续之前的查询进度,而不是从头开始消费所有的数据。 如上面的例子将使用 SQL 语句 `select ts, speed from speed_table` 创建一个名为 `topic_speed` 的订阅。
#### 创建 Consumer
```java
Properties config = new Properties();
config.setProperty("enable.auto.commit", "true");
config.setProperty("group.id", "group1");
config.setProperty("value.deserializer", "com.taosdata.jdbc.tmq.ConsumerTest.ResultDeserializer");
TaosConsumer consumer = new TaosConsumer<>(config);
```
- enable.auto.commit: 是否允许自动提交。
- group.id: consumer: 所在的 group。
- value.deserializer: 结果集反序列化方法,可以继承 `com.taosdata.jdbc.tmq.ReferenceDeserializer`,并指定结果集 bean实现反序列化。也可以继承 `com.taosdata.jdbc.tmq.Deserializer`,根据 SQL 的 resultSet 自定义反序列化方式。
- 其他参数请参考:[Consumer 参数列表](../../../develop/tmq#创建-consumer-以及consumer-group)
#### 订阅消费数据 #### 订阅消费数据
```java ```java
int total = 0;
while(true) { while(true) {
TSDBResultSet rs = sub.consume(); ConsumerRecords<ResultBean> records = consumer.poll(Duration.ofMillis(100));
int count = 0; for (ResultBean record : records) {
while(rs.next()) { process(record);
count++; }
}
total += count;
System.out.printf("%d rows consumed, total %d\n", count, total);
Thread.sleep(1000);
} }
``` ```
`consume` 方法返回一个结果集,其中包含从上次 `consume` 到目前为止的所有新数据。请务必按需选择合理的调用 `consume` 的频率(如例子中的 `Thread.sleep(1000)`),否则会给服务端造成不必要的压力。 `poll` 方法返回一个结果集,其中包含从上次 `poll` 到目前为止的所有新数据。请务必按需选择合理的调用 `poll` 的频率(如例子中的 `Duration.ofMillis(100)`),否则会给服务端造成不必要的压力。
#### 关闭订阅 #### 关闭订阅
```java ```java
sub.close(true); consumer.close()
``` ```
`close` 方法关闭一个订阅。如果其参数为 `true` 表示保留订阅进度信息,后续可以创建同名订阅继续消费数据;如为 `false` 则不保留订阅进度。 ### 使用示例如下:
### 关闭资源
```java ```java
resultSet.close(); public abstract class ConsumerLoop {
stmt.close(); private final TaosConsumer<ResultBean> consumer;
conn.close(); private final List<String> topics;
``` private final AtomicBoolean shutdown;
private final CountDownLatch shutdownLatch;
> `注意务必要将 connection 进行关闭`,否则会出现连接泄露。 public ConsumerLoop() throws SQLException {
Properties config = new Properties();
config.setProperty("msg.with.table.name", "true");
config.setProperty("enable.auto.commit", "true");
config.setProperty("group.id", "group1");
config.setProperty("value.deserializer", "com.taosdata.jdbc.tmq.ConsumerTest.ResultDeserializer");
this.consumer = new TaosConsumer<>(config);
this.topics = Collections.singletonList("topic_speed");
this.shutdown = new AtomicBoolean(false);
this.shutdownLatch = new CountDownLatch(1);
}
public abstract void process(ResultBean result);
public void pollData() throws SQLException {
try {
consumer.subscribe(topics);
while (!shutdown.get()) {
ConsumerRecords<ResultBean> records = consumer.poll(Duration.ofMillis(100));
for (ResultBean record : records) {
process(record);
}
}
} finally {
consumer.close();
shutdownLatch.countDown();
}
}
public void shutdown() throws InterruptedException {
shutdown.set(true);
shutdownLatch.await();
}
static class ResultDeserializer extends ReferenceDeserializer<ResultBean> {
}
static class ResultBean {
private Timestamp ts;
private int speed;
public Timestamp getTs() {
return ts;
}
public void setTs(Timestamp ts) {
this.ts = ts;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
}
}
```
### 与连接池使用 ### 与连接池使用
@ -787,20 +859,6 @@ public static void main(String[] args) throws Exception {
> 更多 druid 使用问题请查看[官方说明](https://github.com/alibaba/druid)。 > 更多 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)
```
### 更多示例程序 ### 更多示例程序
示例程序源码位于 `TDengine/examples/JDBC` 下: 示例程序源码位于 `TDengine/examples/JDBC` 下:
@ -811,7 +869,7 @@ Query OK, 1 row(s) in set (0.000141s)
- SpringJdbcTemplateSpring JdbcTemplate 中使用 taos-jdbcdriver。 - SpringJdbcTemplateSpring JdbcTemplate 中使用 taos-jdbcdriver。
- mybatisplus-demoSpringboot + Mybatis 中使用 taos-jdbcdriver。 - mybatisplus-demoSpringboot + Mybatis 中使用 taos-jdbcdriver。
请参考:[JDBC example](https://github.com/taosdata/TDengine/tree/develop/examples/JDBC) 请参考:[JDBC example](https://github.com/taosdata/TDengine/tree/3.0/examples/JDBC)
## 最近更新记录 ## 最近更新记录
@ -842,7 +900,7 @@ Query OK, 1 row(s) in set (0.000141s)
**解决方法**:重新安装 64 位 JDK。 **解决方法**:重新安装 64 位 JDK。
4. 其它问题请参考 [FAQ](/train-faq/faq) 4. 其它问题请参考 [FAQ](../../../train-faq/faq)
## API 参考 ## API 参考

View File

@ -306,8 +306,7 @@ TaosCursor 类使用原生连接进行写入、查询操作。在客户端多线
| [bind_row.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/bind-row.py) | 参数绑定,一次绑定一行 | | [bind_row.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/bind-row.py) | 参数绑定,一次绑定一行 |
| [insert_lines.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/insert-lines.py) | InfluxDB 行协议写入 | | [insert_lines.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/insert-lines.py) | InfluxDB 行协议写入 |
| [json_tag.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/json-tag.py) | 使用 JSON 类型的标签 | | [json_tag.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/json-tag.py) | 使用 JSON 类型的标签 |
| [subscribe-async.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/subscribe-async.py) | 异步订阅 | | [tmq.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/tmq.py) | tmq 订阅 |
| [subscribe-sync.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/subscribe-sync.py) | 同步订阅 |
## 其它说明 ## 其它说明
@ -326,23 +325,15 @@ TaosCursor 类使用原生连接进行写入、查询操作。在客户端多线
1. https://stackoverflow.com/questions/10611328/parsing-datetime-strings-containing-nanoseconds 1. https://stackoverflow.com/questions/10611328/parsing-datetime-strings-containing-nanoseconds
2. https://www.python.org/dev/peps/pep-0564/ 2. https://www.python.org/dev/peps/pep-0564/
## 常见问题
欢迎[提问或报告问题](https://github.com/taosdata/taos-connector-python/issues)。
## 重要更新 ## 重要更新
| 连接器版本 | 重要更新 | 发布日期 |
| ---------- | --------------------------------------------------------------------------------- | ---------- |
| 2.3.1 | 1. support TDengine REST API <br/> 2. remove support for Python version below 3.6 | 2022-04-28 |
| 2.2.5 | support timezone option when connect | 2022-04-13 |
| 2.2.2 | support sqlalchemy dialect plugin | 2022-03-28 |
[**Release Notes**](https://github.com/taosdata/taos-connector-python/releases) [**Release Notes**](https://github.com/taosdata/taos-connector-python/releases)
## API 参考 ## API 参考
- [taos](https://docs.taosdata.com/api/taospy/taos/) - [taos](https://docs.taosdata.com/api/taospy/taos/)
- [taosrest](https://docs.taosdata.com/api/taospy/taosrest) - [taosrest](https://docs.taosdata.com/api/taospy/taosrest)
## 常见问题
欢迎[提问或报告问题](https://github.com/taosdata/taos-connector-python/issues)。

View File

@ -10,141 +10,214 @@ import TabItem from '@theme/TabItem';
import Preparition from "./_preparition.mdx" import Preparition from "./_preparition.mdx"
import RustInsert from "../../07-develop/03-insert-data/_rust_sql.mdx" import RustInsert from "../../07-develop/03-insert-data/_rust_sql.mdx"
import RustInfluxLine from "../../07-develop/03-insert-data/_rust_line.mdx" import RustBind from "../../07-develop/03-insert-data/_rust_stmt.mdx"
import RustOpenTSDBTelnet from "../../07-develop/03-insert-data/_rust_opts_telnet.mdx"
import RustOpenTSDBJson from "../../07-develop/03-insert-data/_rust_opts_json.mdx"
import RustQuery from "../../07-develop/04-query-data/_rust.mdx" import RustQuery from "../../07-develop/04-query-data/_rust.mdx"
[![Crates.io](https://img.shields.io/crates/v/libtaos)](https://crates.io/crates/libtaos) ![Crates.io](https://img.shields.io/crates/d/libtaos) [![docs.rs](https://img.shields.io/docsrs/libtaos)](https://docs.rs/libtaos) [![Crates.io](https://img.shields.io/crates/v/taos)](https://crates.io/crates/taos) ![Crates.io](https://img.shields.io/crates/d/taos) [![docs.rs](https://img.shields.io/docsrs/taos)](https://docs.rs/taos)
`libtaos` 是 TDengine 的官方 Rust 语言连接器。Rust 开发人员可以通过它开发存取 TDengine 数据库的应用软件。 `taos` 是 TDengine 的官方 Rust 语言连接器。Rust 开发人员可以通过它开发存取 TDengine 数据库的应用软件。
`libtaos` 提供两种建立连接的方式。一种是**原生连接**,它通过 TDengine 客户端驱动程序taosc连接 TDengine 运行实例。另外一种是 **REST 连接**,它通过 taosAdapter 的 REST 接口连接 TDengine 运行实例。你可以通过不同的 “特性(即 Cargo 关键字 features” 来指定使用哪种连接器。REST 连接支持任何平台,但原生连接支持所有 TDengine 客户端能运行的平台。 `taos` 提供两种建立连接的方式。一种是**原生连接**,它通过 TDengine 客户端驱动程序taosc连接 TDengine 运行实例。另外一种是 **Websocket 连接**,它通过 taosAdapter 的 Websocket 接口连接 TDengine 运行实例。你可以通过不同的 “特性(即 Cargo 关键字 `features`)” 来指定使用哪种连接器默认同时支持。Websocket 连接支持任何平台,原生连接支持所有 TDengine 客户端能运行的平台。
`libtaos` 的源码托管在 [GitHub](https://github.com/taosdata/libtaos-rs)。 该 Rust 连接器的源码托管在 [GitHub](https://github.com/taosdata/taos-connector-rust)。
## 支持的平台 ## 支持的平台
原生连接支持的平台和 TDengine 客户端驱动支持的平台一致。 原生连接支持的平台和 TDengine 客户端驱动支持的平台一致。
REST 连接支持所有能运行 Rust 的平台。 Websocket 连接支持所有能运行 Rust 的平台。
## 版本支持 ## 版本支持
请参考[版本支持列表](/reference/connector#版本支持) 请参考[版本支持列表](/reference/connector#版本支持)
Rust 连接器仍然在快速开发中1.0 之前无法保证其向后兼容。建议使用 2.4 版本以上的 TDengine以避免已知问题。 Rust 连接器仍然在快速开发中1.0 之前无法保证其向后兼容。建议使用 3.0 版本以上的 TDengine以避免已知问题。
## 安装 ## 安装
### 安装前准备 ### 安装前准备
* 安装 Rust 开发工具链 * 安装 Rust 开发工具链
* 如果使用原生连接,请安装 TDengine 客户端驱动,具体步骤请参考[安装客户端驱动](/reference/connector#安装客户端驱动) * 如果使用原生连接,请安装 TDengine 客户端驱动,具体步骤请参考[安装客户端驱动](/reference/connector#安装客户端驱动)
### 添加 libtaos 依赖 ### 添加 taos 依赖
根据选择的连接方式,按照如下说明在 [Rust](https://rust-lang.org) 项目中添加 [libtaos][libtaos] 依赖: 根据选择的连接方式,按照如下说明在 [Rust](https://rust-lang.org) 项目中添加 [taos][taos] 依赖:
<Tabs defaultValue="native"> <Tabs defaultValue="default">
<TabItem value="native" label="原生连接"> <TabItem value="default" label="同时支持">
在 `Cargo.toml` 文件中添加 [libtaos][libtaos] 在 `Cargo.toml` 文件中添加 [taos][taos]
```toml ```toml
[dependencies] [dependencies]
# use default feature # use default feature
libtaos = "*" taos = "*"
``` ```
</TabItem> </TabItem>
<TabItem value="rest" label="REST 连接">
在 `Cargo.toml` 文件中添加 [libtaos][libtaos],并启用 `rest` 特性。 <TabItem value="native" label="仅原生连接">
在 `Cargo.toml` 文件中添加 [taos][taos],并启用 `native` 特性:
```toml ```toml
[dependencies] [dependencies]
# use rest feature taos = { version = "*", default-features = false, features = ["native"] }
libtaos = { version = "*", features = ["rest"]} ```
</TabItem>
<TabItem value="rest" label="仅 Websocket">
在 `Cargo.toml` 文件中添加 [taos][taos],并启用 `ws` 特性。
```toml
[dependencies]
taos = { version = "*", default-features = false, features = ["ws"] }
``` ```
</TabItem> </TabItem>
</Tabs> </Tabs>
### 使用连接池
请在 `Cargo.toml` 中启用 `r2d2` 特性。
```toml
[dependencies]
# with taosc
libtaos = { version = "*", features = ["r2d2"] }
# or rest
libtaos = { version = "*", features = ["rest", "r2d2"] }
```
## 建立连接 ## 建立连接
[TaosCfgBuilder] 为使用者提供构造器形式的 API以便于后续创建连接或使用连接池 [TaosBuilder] 通过 DSN 连接描述字符串创建一个连接构造器。
```rust ```rust
let cfg: TaosCfg = TaosCfgBuilder::default() let builder = TaosBuilder::from_dsn("taos://")?;
.ip("127.0.0.1")
.user("root")
.pass("taosdata")
.db("log") // do not set if not require a default database.
.port(6030u16)
.build()
.expect("TaosCfg builder error");
}
``` ```
现在您可以使用该对象创建连接: 现在您可以使用该对象创建连接:
```rust ```rust
let conn = cfg.connect()?; let conn = builder.build()?;
``` ```
连接对象可以创建多个: 连接对象可以创建多个:
```rust ```rust
let conn = cfg.connect()?; let conn1 = builder.build()?;
let conn2 = cfg.connect()?; let conn2 = builder.build()?;
``` ```
可以在应用中使用连接池 DSN 描述字符串基本结构如下
```rust ```text
let pool = r2d2::Pool::builder() <driver>[+<protocol>]://[[<username>:<password>@]<host>:<port>][/<database>][?<p1>=<v1>[&<p2>=<v2>]]
.max_size(10000) // max connections |------|------------|---|-----------|-----------|------|------|------------|-----------------------|
.build(cfg)?; |driver| protocol | | username | password | host | port | database | params |
// ...
// Use pool to get connection
let conn = pool.get()?;
``` ```
之后您可以对数据库进行相关操作: 各部分意义见下表:
- **driver**: 必须指定驱动名以便连接器选择何种方式创建连接,支持如下驱动名:
- **taos**: 表名使用 TDengine 连接器驱动。
- **tmq**: 使用 TMQ 订阅数据。
- **http/ws**: 使用 Websocket 创建连接。
- **https/wss**: 在 Websocket 连接方式下显示启用 SSL/TLS 连接。
- **protocol**: 显示指定以何种方式建立连接,例如:`taos+ws://localhost:6041` 指定以 Websocket 方式建立连接。
- **username/password**: 用于创建连接的用户名及密码。
- **host/port**: 指定创建连接的服务器及端口,当不指定服务器地址及端口时(`taos://`),原生连接默认为 `localhost:6030`Websocket 连接默认为 `localhost:6041` 。
- **database**: 指定默认连接的数据库名。
- **params**:其他可选参数。
一个完整的 DSN 描述字符串示例如下:
```text
taos+ws://localhost:6041/test
```
表示使用 Websocket`ws`)方式通过 `6041` 端口连接服务器 `localhost`,并指定默认数据库为 `test`。
这使得用户可以通过 DSN 指定连接方式:
```rust ```rust
async fn demo() -> Result<(), Error> { use taos::*;
// get connection ...
// create database // use native protocol.
conn.exec("create database if not exists demo").await?; let builder = TaosBuilder::from_dsn("taos://localhost:6030")?;
// change database context let conn1 = builder.build();
conn.exec("use demo").await?;
// create table // use websocket protocol.
conn.exec("create table if not exists tb1 (ts timestamp, v int)").await?; let conn2 = TaosBuilder::from_dsn("taos+ws://localhost:6041")?;
// insert ```
conn.exec("insert into tb1 values(now, 1)").await?;
// query 建立连接后,您可以进行相关数据库操作:
let rows = conn.query("select * from tb1").await?;
for row in rows.rows { ```rust
println!("{}", row.into_iter().join(",")); async fn demo(taos: &Taos, db: &str) -> Result<(), Error> {
// prepare database
taos.exec_many([
format!("DROP DATABASE IF EXISTS `{db}`"),
format!("CREATE DATABASE `{db}`"),
format!("USE `{db}`"),
])
.await?;
let inserted = taos.exec_many([
// create super table
"CREATE TABLE `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) \
TAGS (`groupid` INT, `location` BINARY(16))",
// create child table
"CREATE TABLE `d0` USING `meters` TAGS(0, 'Los Angles')",
// insert into child table
"INSERT INTO `d0` values(now - 10s, 10, 116, 0.32)",
// insert with NULL values
"INSERT INTO `d0` values(now - 8s, NULL, NULL, NULL)",
// insert and automatically create table with tags if not exists
"INSERT INTO `d1` USING `meters` TAGS(1, 'San Francisco') values(now - 9s, 10.1, 119, 0.33)",
// insert many records in a single sql
"INSERT INTO `d1` values (now-8s, 10, 120, 0.33) (now - 6s, 10, 119, 0.34) (now - 4s, 11.2, 118, 0.322)",
]).await?;
assert_eq!(inserted, 6);
let mut result = taos.query("select * from `meters`").await?;
for field in result.fields() {
println!("got field: {}", field.name());
} }
let values = result.
} }
``` ```
查询数据可以通过两种方式:使用内建类型或 [serde](https://serde.rs) 序列化框架。
```rust
// Query option 1, use rows stream.
let mut rows = result.rows();
while let Some(row) = rows.try_next().await? {
for (name, value) in row {
println!("got value of {}: {}", name, value);
}
}
// Query options 2, use deserialization with serde.
#[derive(Debug, serde::Deserialize)]
#[allow(dead_code)]
struct Record {
// deserialize timestamp to chrono::DateTime<Local>
ts: DateTime<Local>,
// float to f32
current: Option<f32>,
// int to i32
voltage: Option<i32>,
phase: Option<f32>,
groupid: i32,
// binary/varchar to String
location: String,
}
let records: Vec<Record> = taos
.query("select * from `meters`")
.await?
.deserialize()
.try_collect()
.await?;
dbg!(records);
Ok(())
```
## 使用示例 ## 使用示例
### 写入数据 ### 写入数据
@ -153,79 +226,52 @@ async fn demo() -> Result<(), Error> {
<RustInsert /> <RustInsert />
#### InfluxDB 行协议写入 #### STMT 写入
<RustInfluxLine /> <RustBind />
#### OpenTSDB Telnet 行协议写入
<RustOpenTSDBTelnet />
#### OpenTSDB JSON 行协议写入
<RustOpenTSDBJson />
### 查询数据 ### 查询数据
<RustQuery /> <RustQuery />
### 更多示例程序
| 程序路径 | 程序说明 |
| -------------- | ----------------------------------------------------------------------------- |
| [demo.rs] | 基本API 使用示例 |
| [bailongma-rs] | 使用 TDengine 作为存储后端的 Prometheus 远程存储 API 适配器,使用 r2d2 连接池 |
## API 参考 ## API 参考
### 连接构造器 API ### 连接构造器
[Builder Pattern](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html) 构造器模式是 Rust 处理复杂数据类型或可选配置类型的解决方案。[libtaos] 实现中,使用连接构造器 [TaosCfgBuilder] 作为 TDengine Rust 连接器的入口。[TaosCfgBuilder] 提供对服务器、端口、数据库、用户名和密码等的可选配置。 通过 DSN 来构建一个连接器构造器。
使用 `default()` 方法可以构建一个默认参数的 [TaosCfg],用于后续连接数据库或建立连接池。
```rust ```rust
let cfg = TaosCfgBuilder::default().build()?; let cfg = TaosBuilder::default().build()?;
``` ```
使用构造器模式,用户可按需设置 使用 `builder` 对象创建多个连接
```rust ```rust
let cfg = TaosCfgBuilder::default() let conn: Taos = cfg.build();
.ip("127.0.0.1")
.user("root")
.pass("taosdata")
.db("log")
.port(6030u16)
.build()?;
```
使用 [TaosCfg] 对象创建 TDengine 连接:
```rust
let conn: Taos = cfg.connect();
``` ```
### 连接池 ### 连接池
在复杂应用中,建议启用连接池。[libtaos] 的连接池使用 [r2d2] 实现。 在复杂应用中,建议启用连接池。[taos] 的连接池使用 [r2d2] 实现。
如下,可以生成一个默认参数的连接池。 如下,可以生成一个默认参数的连接池。
```rust ```rust
let pool = r2d2::Pool::new(cfg)?; let pool = TaosBuilder::from_dsn(dsn)?.pool()?;
``` ```
同样可以使用连接池的构造器,对连接池参数进行设置: 同样可以使用连接池的构造器,对连接池参数进行设置:
```rust ```rust
use std::time::Duration; let dsn = "taos://localhost:6030";
let pool = r2d2::Pool::builder()
.max_size(5000) // max connections let opts = PoolBuilder::new()
.max_lifetime(Some(Duration::from_minutes(100))) // lifetime of each connection .max_size(5000) // max connections
.min_idle(Some(1000)) // minimal idle connections .max_lifetime(Some(Duration::from_secs(60 * 60))) // lifetime of each connection
.connection_timeout(Duration::from_minutes(2)) .min_idle(Some(1000)) // minimal idle connections
.build(cfg); .connection_timeout(Duration::from_secs(2));
let pool = TaosBuilder::from_dsn(dsn)?.with_pool_builder(opts)?;
``` ```
在应用代码中,使用 `pool.get()?` 来获取一个连接对象 [Taos]。 在应用代码中,使用 `pool.get()?` 来获取一个连接对象 [Taos]。
@ -236,44 +282,85 @@ let taos = pool.get()?;
### 连接 ### 连接
[Taos] 结构体是 [libtaos] 中的连接管理者,主要提供了两个 API [Taos][struct.Taos] 对象提供了多个数据库操作的 API
1. `exec`: 执行某个非查询类 SQL 语句,例如 `CREATE``ALTER``INSERT` 等。 1. `exec`: 执行某个非查询类 SQL 语句,例如 `CREATE``ALTER``INSERT` 等。
```rust ```rust
taos.exec().await?; let affected_rows = taos.exec("INSERT INTO tb1 VALUES(now, NULL)").await?;
``` ```
2. `query`:执行查询语句,返回 [TaosQueryData] 对象 2. `exec_many`: 同时(顺序)执行多个 SQL 语句
```rust ```rust
let q = taos.query("select * from log.logs").await?; taos.exec_many([
"CREATE DATABASE test",
"USE test",
"CREATE TABLE `tb1` (`ts` TIMESTAMP, `val` INT)",
]).await?;
``` ```
[TaosQueryData] 对象存储了查询结果数据和返回的列的基本信息(列名,类型,长度): 3. `query`:执行查询语句,返回 [ResultSet] 对象。
列信息使用 [ColumnMeta] 存储:
```rust ```rust
let cols = &q.column_meta; let mut q = taos.query("select * from log.logs").await?;
```
[ResultSet] 对象存储了查询结果数据和返回的列的基本信息(列名,类型,长度):
列信息使用 [.fields()] 方法获取:
```rust
let cols = q.fields();
for col in cols { for col in cols {
println!("name: {}, type: {:?}, bytes: {}", col.name, col.type_, col.bytes); println!("name: {}, type: {:?} , bytes: {}", col.name(), col.ty(), col.bytes());
} }
``` ```
逐行获取数据: 逐行获取数据:
```rust ```rust
for (i, row) in q.rows.iter().enumerate() { let mut rows = result.rows();
for (j, cell) in row.iter().enumerate() { let mut nrows = 0;
println!("cell({}, {}) data: {}", i, j, cell); while let Some(row) = rows.try_next().await? {
for (col, (name, value)) in row.enumerate() {
println!(
"[{}] got value in col {} (named `{:>8}`): {}",
nrows, col, name, value
);
} }
nrows += 1;
} }
``` ```
或使用 [serde](https://serde.rs) 序列化框架。
```rust
#[derive(Debug, Deserialize)]
struct Record {
// deserialize timestamp to chrono::DateTime<Local>
ts: DateTime<Local>,
// float to f32
current: Option<f32>,
// int to i32
voltage: Option<i32>,
phase: Option<f32>,
groupid: i32,
// binary/varchar to String
location: String,
}
let records: Vec<Record> = taos
.query("select * from `meters`")
.await?
.deserialize()
.try_collect()
.await?;
```
需要注意的是,需要使用 Rust 异步函数和异步运行时。 需要注意的是,需要使用 Rust 异步函数和异步运行时。
[Taos] 提供部分 SQL 的 Rust 方法化以减少 `format!` 代码块的频率: [Taos][struct.Taos] 提供部分 SQL 的 Rust 方法化以减少 `format!` 代码块的频率:
- `.describe(table: &str)`: 执行 `DESCRIBE` 并返回一个 Rust 数据结构。 - `.describe(table: &str)`: 执行 `DESCRIBE` 并返回一个 Rust 数据结构。
- `.create_database(database: &str)`: 执行 `CREATE DATABASE` 语句。 - `.create_database(database: &str)`: 执行 `CREATE DATABASE` 语句。
@ -283,42 +370,61 @@ let taos = pool.get()?;
### 参数绑定接口 ### 参数绑定接口
与 C 接口类似Rust 提供参数绑定接口。首先,通过 [Taos] 对象创建一个 SQL 语句的参数绑定对象 [Stmt] 与 C 接口类似Rust 提供参数绑定接口。首先,通过 [Taos][struct.Taos] 对象创建一个 SQL 语句的参数绑定对象 [Stmt]
```rust ```rust
let mut stmt: Stmt = taos.stmt("insert into ? values(?,?)")?; let mut stmt = Stmt::init(&taos).await?;
stmt.prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)")?;
``` ```
参数绑定对象提供了一组接口用于实现参数绑定: 参数绑定对象提供了一组接口用于实现参数绑定:
##### `.set_tbname(tbname: impl ToCString)` #### `.set_tbname(name)`
用于绑定表名。 用于绑定表名。
##### `.set_tbname_tags(tbname: impl ToCString, tags: impl IntoParams)` ```rust
let mut stmt = taos.stmt("insert into ? values(? ,?)")?;
stmt.set_tbname("d0")?;
```
#### `.set_tags(&[tag])`
当 SQL 语句使用超级表时,用于绑定子表表名和标签值: 当 SQL 语句使用超级表时,用于绑定子表表名和标签值:
```rust ```rust
let mut stmt = taos.stmt("insert into ? using stb0 tags(?) values(?,?)")?; let mut stmt = taos.stmt("insert into ? using stb0 tags(?) values(? ,?)")?;
// tags can be created with any supported type, here is an example using JSON stmt.set_tbname("d0")?;
let v = Field::Json(serde_json::from_str("{\"tag1\":\"一二三四五六七八九十\"}").unwrap()); stmt.set_tags(&[Value::VarChar("涛思".to_string())])?;
stmt.set_tbname_tags("tb0", [&tag])?;
``` ```
##### `.bind(params: impl IntoParams)` #### `.bind(&[column])`
用于绑定值类型。使用 [Field] 结构体构建需要的类型并绑定: 用于绑定值类型。使用 [ColumnView] 结构体构建需要的类型并绑定:
```rust ```rust
let ts = Field::Timestamp(Timestamp::now()); let params = vec![
let value = Field::Float(0.0); ColumnView::from_millis_timestamp(vec![164000000000]),
stmt.bind(vec![ts, value].iter())?; ColumnView::from_bools(vec![true]),
ColumnView::from_tiny_ints(vec![i8::MAX]),
ColumnView::from_small_ints(vec![i16::MAX]),
ColumnView::from_ints(vec![i32::MAX]),
ColumnView::from_big_ints(vec![i64::MAX]),
ColumnView::from_unsigned_tiny_ints(vec![u8::MAX]),
ColumnView::from_unsigned_small_ints(vec![u16::MAX]),
ColumnView::from_unsigned_ints(vec![u32::MAX]),
ColumnView::from_unsigned_big_ints(vec![u64::MAX]),
ColumnView::from_floats(vec![f32::MAX]),
ColumnView::from_doubles(vec![f64::MAX]),
ColumnView::from_varchar(vec!["ABC"]),
ColumnView::from_nchar(vec!["涛思数据"]),
];
let rows = stmt.bind(&params)?.add_batch()?.execute()?;
``` ```
##### `.execute()` #### `.execute()`
执行 SQL。[Stmt] 对象可以复用,在执行后可以重新绑定并执行。 执行 SQL。[Stmt] 对象可以复用,在执行后可以重新绑定并执行。执行前请确保所有数据已通过 `.add_batch` 加入到执行队列中。
```rust ```rust
stmt.execute()?; stmt.execute()?;
@ -329,60 +435,84 @@ stmt.execute()?;
//stmt.execute()?; //stmt.execute()?;
``` ```
### 行协议接口 一个可运行的示例请见 [GitHub 上的示例](https://github.com/taosdata/taos-connector-rust/blob/main/examples/bind.rs)。
行协议接口支持多种模式和不同精度,需要引入 schemaless 模块中的常量以进行设置: ### 订阅
TDengine 通过消息队列 [TMQ](../../../taos-sql/tmq/) 启动一个订阅。
从 DSN 开始,构建一个 TMQ 连接器。
```rust ```rust
use libtaos::*; let tmq = TmqBuilder::from_dsn("taos://localhost:6030/?group.id=test")?;
use libtaos::schemaless::*;
``` ```
- InfluxDB 行协议 创建消费者:
```rust ```rust
let lines = [ let mut consumer = tmq.build()?;
"st,t1=abc,t2=def,t3=anything c1=3i64,c3=L\"pass\",c2=false 1626006833639000000" ```
"st,t1=abc,t2=def,t3=anything c1=3i64,c3=L\"abc\",c4=4f64 1626006833639000000"
];
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANOSECONDS)?;
```
- OpenTSDB Telnet 协议 消费者可订阅一个或多个 `TOPIC`。
```rust ```rust
let lines = ["sys.if.bytes.out 1479496100 1.3E3 host=web01 interface=eth0"]; consumer.subscribe(["tmq_meters"]).await?;
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_SECONDS)?; ```
```
- OpenTSDB JSON 协议 TMQ 消息队列是一个 [futures::Stream](https://docs.rs/futures/latest/futures/stream/index.html) 类型,可以使用相应 API 对每个消息进行消费,并通过 `.commit` 进行已消费标记。
```rust ```rust
let lines = [r#" {
{ let mut stream = consumer.stream();
"metric": "st",
"timestamp": 1626006833, while let Some((offset, message)) = stream.try_next().await? {
"value": 10, // get information from offset
"tags": {
"t1": true, // the topic
"t2": false, let topic = offset.topic();
"t3": 10, // the vgroup id, like partition id in kafka.
"t4": "123_abc_.!@#$%^&*:;,./?|+-=()[]{}<>" let vgroup_id = offset.vgroup_id();
println!("* in vgroup id {vgroup_id} of topic {topic}\n");
if let Some(data) = message.into_data() {
while let Some(block) = data.fetch_raw_block().await? {
// one block for one table, get table name if needed
let name = block.table_name();
let records: Vec<Record> = block.deserialize().try_collect()?;
println!(
"** table: {}, got {} records: {:#?}\n",
name.unwrap(),
records.len(),
records
);
} }
}"#]; }
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_SECONDS)?; consumer.commit(offset).await?;
``` }
}
```
其他相关结构体 API 使用说明请移步 Rust 文档托管网页:<https://docs.rs/libtaos>。 停止订阅:
[libtaos]: https://github.com/taosdata/libtaos-rs ```rust
[tdengine]: https://github.com/taosdata/TDengine consumer.unsubscribe().await;
[bailongma-rs]: https://github.com/taosdata/bailongma-rs ```
对于 TMQ DSN, 有以下配置项可以进行设置,需要注意的是,`group.id` 是必须的。
- `group.id`: 同一个消费者组,将以至少消费一次的方式进行消息负载均衡。
- `client.id`: 可选的订阅客户端识别项。
- `auto.offset.reset`: 可选初始化订阅起点, *earliest* 为从头开始订阅, *latest* 为仅从最新数据开始订阅,默认为从头订阅。注意,此选项在同一个 `group.id` 中仅生效一次。
- `enable.auto.commit`: 当设置为 `true` 时,将启用自动标记模式,当对数据一致性不敏感时,可以启用此方式。
- `auto.commit.interval.ms`: 自动标记的时间间隔。
完整订阅示例参见 [GitHub 示例文件](https://github.com/taosdata/taos-connector-rust/blob/main/examples/subscribe.rs).
其他相关结构体 API 使用说明请移步 Rust 文档托管网页:<https://docs.rs/taos>。
[taos]: https://github.com/taosdata/rust-connector-taos
[r2d2]: https://crates.io/crates/r2d2 [r2d2]: https://crates.io/crates/r2d2
[demo.rs]: https://github.com/taosdata/libtaos-rs/blob/main/examples/demo.rs [TaosBuilder]: https://docs.rs/taos/latest/taos/struct.TaosBuilder.html
[TaosCfgBuilder]: https://docs.rs/libtaos/latest/libtaos/struct.TaosCfgBuilder.html [TaosCfg]: https://docs.rs/taos/latest/taos/struct.TaosCfg.html
[TaosCfg]: https://docs.rs/libtaos/latest/libtaos/struct.TaosCfg.html [struct.Taos]: https://docs.rs/taos/latest/taos/struct.Taos.html
[Taos]: https://docs.rs/libtaos/latest/libtaos/struct.Taos.html [Stmt]: https://docs.rs/taos/latest/taos/struct.Stmt.html
[TaosQueryData]: https://docs.rs/libtaos/latest/libtaos/field/struct.TaosQueryData.html
[Field]: https://docs.rs/libtaos/latest/libtaos/field/enum.Field.html
[Stmt]: https://docs.rs/libtaos/latest/libtaos/stmt/struct.Stmt.html

View File

@ -48,29 +48,30 @@ taos> SET MAX_BINARY_DISPLAY_WIDTH <nn>;
您可通过配置命令行参数来改变 TDengine CLI 的行为。以下为常用的几个命令行参数: 您可通过配置命令行参数来改变 TDengine CLI 的行为。以下为常用的几个命令行参数:
- -h, --host=HOST: 要连接的 TDengine 服务端所在服务器的 FQDN, 默认为连接本地服务 - -h HOST: 要连接的 TDengine 服务端所在服务器的 FQDN, 默认为连接本地服务
- -P, --port=PORT: 指定服务端所用端口号 - -P PORT: 指定服务端所用端口号
- -u, --user=USER: 连接时使用的用户名 - -u USER: 连接时使用的用户名
- -p, --password=PASSWORD: 连接服务端时使用的密码 - -p PASSWORD: 连接服务端时使用的密码
- -?, --help: 打印出所有命令行参数 - -?, --help: 打印出所有命令行参数
还有更多其他参数: 还有更多其他参数:
- -c, --config-dir: 指定配置文件目录Linux 环境下默认为 `/etc/taos`,该目录下的配置文件默认名称为 `taos.cfg` - -a AUTHSTR: 连接服务端的授权信息
- -C, --dump-config: 打印 -c 指定的目录中 `taos.cfg` 的配置参数 - -A: 通过用户名和密码计算授权信息
- -d, --database=DATABASE: 指定连接到服务端时使用的数据库 - -c CONFIGDIR: 指定配置文件目录Linux 环境下默认为 `/etc/taos`,该目录下的配置文件默认名称为 `taos.cfg`
- -D, --directory=DIRECTORY: 导入指定路径中的 SQL 脚本文件 - -C: 打印 -c 指定的目录中 `taos.cfg` 的配置参数
- -f, --file=FILE: 以非交互模式执行 SQL 脚本文件。文件中一个 SQL 语句只能占一行 - -d DATABASE: 指定连接到服务端时使用的数据库
- -k, --check=CHECK: 指定要检查的表 - -f FILE: 以非交互模式执行 SQL 脚本文件。文件中一个 SQL 语句只能占一行
- -l, --pktlen=PKTLEN: 网络测试时使用的测试包大小 - -k: 测试服务端运行状态0: unavailable1: network ok2: service ok3: service degraded4: exiting
- -n, --netrole=NETROLE: 网络连接测试时的测试范围,默认为 `startup`, 可选值为 `client`、`server`、`rpc`、`startup`、`sync`、`speed` 和 `fqdn` 之一 - -l PKTLEN: 网络测试时使用的测试包大小
- -r, --raw-time: 将时间输出出无符号 64 位整数类型(即 C 语音中 uint64_t) - -n NETROLE: 网络连接测试时的测试范围,默认为 `client`, 可选值为 `client`、`server`
- -s, --commands=COMMAND: 以非交互模式执行的 SQL 命令 - -N PKTNUM: 网络测试时使用的测试包数量
- -S, --pkttype=PKTTYPE: 指定网络测试所用的包类型,默认为 TCP。只有 netrole 为 `speed` 时既可以指定为 TCP 也可以指定为 UDP - -r: 将时间输出出无符号 64 位整数类型(即 C 语音中 uint64_t)
- -T, --thread=THREADNUM: 以多线程模式导入数据时的线程数 - -s COMMAND: 以非交互模式执行的 SQL 命令
- -s, --commands: 在不进入终端的情况下运行 TDengine 命令 - -t: 测试服务端启动状态,状态同-k
- -z, --timezone=TIMEZONE: 指定时区,默认为本地时区 - -w DISPLAYWIDTH: 客户端列显示宽度
- -V, --version: 打印出当前版本号 - -z TIMEZONE: 指定时区,默认为本地时区
- -V: 打印出当前版本号
示例: 示例:

View File

@ -5,18 +5,11 @@ description: "TDengine 服务端、客户端和连接器支持的平台列表"
## TDengine 服务端支持的平台列表 ## TDengine 服务端支持的平台列表
| | **CentOS 7/8** | **Ubuntu 16/18/20** | **Other Linux** | **统信 UOS** | **银河/中标麒麟** | **凝思 V60/V80** | **华为 EulerOS** | | | **Windows 10/11** | **CentOS 7.9/8** | **Ubuntu 18/20** | **Other Linux** | **统信 UOS** | **银河/中标麒麟** | **凝思 V60/V80** | **华为 EulerOS** |
| ------------ | -------------- | ------------------- | --------------- | ------------ | ----------------- | ---------------- | ---------------- | | ------------ | ----------------- | ---------------- | ---------------- | --------------- | ------------ | ----------------- | ---------------- | ---------------- |
| X64 | ● | ● | | ○ | ● | ● | ● | | X64 | ● | ● | ● | | ● | ● | ● | |
| 龙芯 MIPS64 | | | ● | | | | | | 树莓派 ARM64 | | | | ● | | | | |
| 鲲鹏 ARM64 | | ○ | ○ | | ● | | | | 华为云 ARM64 | | | | | | | | ● |
| 申威 Alpha64 | | | ○ | ● | | | |
| 飞腾 ARM64 | | ○ 优麒麟 | | | | | |
| 海光 X64 | ● | ● | ● | ○ | ● | ● | |
| 瑞芯微 ARM64 | | | ○ | | | | |
| 全志 ARM64 | | | ○ | | | | |
| 炬力 ARM64 | | | ○ | | | | |
| 华为云 ARM64 | | | | | | | ● |
注: ● 表示经过官方测试验证, ○ 表示非官方测试验证。 注: ● 表示经过官方测试验证, ○ 表示非官方测试验证。
@ -26,15 +19,15 @@ description: "TDengine 服务端、客户端和连接器支持的平台列表"
对照矩阵如下: 对照矩阵如下:
| **CPU** | **X64 64bit** | | | **X86 32bit** | **ARM64** | **ARM32** | **MIPS 龙芯** | **Alpha 申威** | **X64 海光** | | **CPU** | **X64 64bit** | | | **X86 32bit** | **ARM64** | **MIPS 龙芯** | **Alpha 申威** | **X64 海光** |
| ----------- | ------------- | --------- | --------- | ------------- | --------- | --------- | ------------- | -------------- | ------------ | | ----------- | ------------- | --------- | --------- | ------------- | --------- | ------------- | -------------- | ------------ |
| **OS** | **Linux** | **Win64** | **Win32** | **Win32** | **Linux** | **Linux** | **Linux** | **Linux** | **Linux** | | **OS** | **Linux** | **Win64** | **Win32** | **Win32** | **Linux** | **Linux** | **Linux** | **Linux** |
| **C/C++** | ● | ● | ● | ○ | ● | ● | ● | ● | ● | | **C/C++** | ● | ● | ● | ○ | ● | ● | ● | ● |
| **JDBC** | ● | ● | ● | ○ | ● | ● | ● | ● | ● | | **JDBC** | ● | ● | ● | ○ | ● | ● | ● | ● |
| **Python** | ● | ● | ● | ○ | ● | ● | ● | -- | ● | | **Python** | ● | ● | ● | ○ | ● | ● | -- | ● |
| **Go** | ● | ● | ● | ○ | ● | ● | ○ | -- | -- | | **Go** | ● | ● | ● | ○ | ● | ○ | -- | -- |
| **NodeJs** | ● | ● | ○ | ○ | ● | ● | ○ | -- | -- | | **NodeJs** | ● | ● | ○ | ○ | ● | ○ | -- | -- |
| **C#** | ● | ● | ○ | ○ | ○ | ○ | ○ | -- | -- | | **C#** | ● | ● | ○ | ○ | ○ | ○ | -- | -- |
| **RESTful** | ● | ● | ● | ● | ● | ● | ● | ● | ● | | **RESTful** | ● | ● | ● | ● | ● | ● | ● | ● |
注:● 表示官方测试验证通过,○ 表示非官方测试验证通过,-- 表示未经验证。 注:● 表示官方测试验证通过,○ 表示非官方测试验证通过,-- 表示未经验证。

View File

@ -24,9 +24,6 @@ curl -u root:taosdata -d "show databases" localhost:6041/rest/sql
```shell ```shell
$ docker exec -it tdengine taos $ 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; taos> show databases;
name | created_time | ntables | vgroups | replica | quorum | days | keep | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | cachelast | precision | update | status | name | created_time | ntables | vgroups | replica | quorum | days | keep | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | cachelast | precision | update | status |
==================================================================================================================================================================================================================================================================================== ====================================================================================================================================================================================================================================================================================
@ -47,9 +44,6 @@ docker run -d --name tdengine --network host tdengine/tdengine
```shell ```shell
$ taos $ 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; taos> show dnodes;
id | end_point | vnodes | cores | status | role | create_time | offline reason | id | end_point | vnodes | cores | status | role | create_time | offline reason |
====================================================================================================================================== ======================================================================================================================================
@ -353,9 +347,6 @@ password: taosdata
```shell ```shell
$ docker-compose exec td-1 taos -s "show dnodes" $ 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 taos> show dnodes
id | end_point | vnodes | cores | status | role | create_time | offline reason | id | end_point | vnodes | cores | status | role | create_time | offline reason |
====================================================================================================================================== ======================================================================================================================================

View File

@ -25,7 +25,6 @@ TDengine 的所有可执行文件默认存放在 _/usr/local/taos/bin_ 目录下
- _taosBenchmark_TDengine 测试工具 - _taosBenchmark_TDengine 测试工具
- _remove.sh_:卸载 TDengine 的脚本,请谨慎执行,链接到/usr/bin 目录下的**rmtaos**命令。会删除 TDengine 的安装目录/usr/local/taos但会保留/etc/taos、/var/lib/taos、/var/log/taos - _remove.sh_:卸载 TDengine 的脚本,请谨慎执行,链接到/usr/bin 目录下的**rmtaos**命令。会删除 TDengine 的安装目录/usr/local/taos但会保留/etc/taos、/var/lib/taos、/var/log/taos
- _taosadapter_: 提供 RESTful 服务和接受其他多种软件写入请求的服务端可执行文件 - _taosadapter_: 提供 RESTful 服务和接受其他多种软件写入请求的服务端可执行文件
- _tarbitrator_: 提供双节点集群部署的仲裁功能
- _TDinsight.sh_:用于下载 TDinsight 并安装的脚本 - _TDinsight.sh_:用于下载 TDinsight 并安装的脚本
- _set_core.sh_用于方便调试设置系统生成 core dump 文件的脚本 - _set_core.sh_用于方便调试设置系统生成 core dump 文件的脚本
- _taosd-dump-cfg.gdb_:用于方便调试 taosd 的 gdb 执行脚本。 - _taosd-dump-cfg.gdb_:用于方便调试 taosd 的 gdb 执行脚本。

View File

@ -3,8 +3,7 @@ title: Schemaless 写入
description: 'Schemaless 写入方式,可以免于预先创建超级表/子表的步骤,随着数据写入接口能够自动创建与数据对应的存储结构' description: 'Schemaless 写入方式,可以免于预先创建超级表/子表的步骤,随着数据写入接口能够自动创建与数据对应的存储结构'
--- ---
在物联网应用中常会采集比较多的数据项用于实现智能控制、业务分析、设备监控等。由于应用逻辑的版本升级或者设备自身的硬件调整等原因数据采集项就有可能比较频繁地出现变动。为了在这种情况下方便地完成数据记录工作TDengine 在物联网应用中常会采集比较多的数据项用于实现智能控制、业务分析、设备监控等。由于应用逻辑的版本升级或者设备自身的硬件调整等原因数据采集项就有可能比较频繁地出现变动。为了在这种情况下方便地完成数据记录工作TDengine提供调用 Schemaless 写入方式,可以免于预先创建超级表/子表的步骤随着数据写入接口能够自动创建与数据对应的存储结构。并且在必要时Schemaless
从 2.2.0.0 版本开始,提供调用 Schemaless 写入方式,可以免于预先创建超级表/子表的步骤随着数据写入接口能够自动创建与数据对应的存储结构。并且在必要时Schemaless
将自动增加必要的数据列,保证用户写入的数据可以被正确存储。 将自动增加必要的数据列,保证用户写入的数据可以被正确存储。
无模式写入方式建立的超级表及其对应的子表与通过 SQL 直接建立的超级表和子表完全没有区别你也可以通过SQL 语句直接向其中写入数据。需要注意的是,通过无模式写入方式建立的表,其表名是基于标签值按照固定的映射规则生成,所以无法明确地进行表意,缺乏可读性。 无模式写入方式建立的超级表及其对应的子表与通过 SQL 直接建立的超级表和子表完全没有区别你也可以通过SQL 语句直接向其中写入数据。需要注意的是,通过无模式写入方式建立的表,其表名是基于标签值按照固定的映射规则生成,所以无法明确地进行表意,缺乏可读性。
@ -41,10 +40,10 @@ tag_set 中的所有的数据自动转化为 nchar 数据类型,并不需要
| -------- | -------- | ------------ | -------------- | | -------- | -------- | ------------ | -------------- |
| 1 | 无或 f64 | double | 8 | | 1 | 无或 f64 | double | 8 |
| 2 | f32 | float | 4 | | 2 | f32 | float | 4 |
| 3 | i8 | TinyInt | 1 | | 3 | i8/u8 | TinyInt/UTinyInt | 1 |
| 4 | i16 | SmallInt | 2 | | 4 | i16/u16 | SmallInt/USmallInt | 2 |
| 5 | i32 | Int | 4 | | 5 | i32/u32 | Int/UInt | 4 |
| 6 | i64 或 i | Bigint | 8 | | 6 | i64/i/u64/u | BigInt/BigInt/UBigInt/UBigInt | 8 |
- t, T, true, True, TRUE, f, F, false, False 将直接作为 BOOL 型来处理。 - t, T, true, True, TRUE, f, F, false, False 将直接作为 BOOL 型来处理。
@ -69,20 +68,21 @@ st,t1=3,t2=4,t3=t3 c1=3i64,c3="passit",c2=false,c4=4f64 1626006833639000000
``` ```
需要注意的是,这里的 tag_key1, tag_key2 并不是用户输入的标签的原始顺序而是使用了标签名称按照字符串升序排列后的结果。所以tag_key1 并不是在行协议中输入的第一个标签。 需要注意的是,这里的 tag_key1, tag_key2 并不是用户输入的标签的原始顺序而是使用了标签名称按照字符串升序排列后的结果。所以tag_key1 并不是在行协议中输入的第一个标签。
排列完成以后计算该字符串的 MD5 散列值 "md5_val"。然后将计算的结果与字符串组合生成表名“t_md5_val”。其中的 “t\*” 是固定的前缀,每个通过该映射关系自动生成的表都具有该前缀。 排列完成以后计算该字符串的 MD5 散列值 "md5_val"。然后将计算的结果与字符串组合生成表名“t_md5_val”。其中的 “t_” 是固定的前缀,每个通过该映射关系自动生成的表都具有该前缀。
为了让用户可以指定生成的表名可以通过配置smlChildTableName来指定比如 配置smlChildTableName=tname 插入数据为st,tname=cpu1,t1=4 c1=3 1626006833639000000 则创建的表名为cpu1注意如果多行数据tname相同但是后面的tag_set不同则使用第一次自动建表时指定的tag_set其他的会忽略
2. 如果解析行协议获得的超级表不存在,则会创建这个超级表。 2. 如果解析行协议获得的超级表不存在,则会创建这个超级表(不建议手动创建超级表,不然插入数据可能异常)
3. 如果解析行协议获得子表不存在,则 Schemaless 会按照步骤 1 或 2 确定的子表名来创建子表。 3. 如果解析行协议获得子表不存在,则 Schemaless 会按照步骤 1 或 2 确定的子表名来创建子表。
4. 如果数据行中指定的标签列或普通列不存在,则在超级表中增加对应的标签列或普通列(只增不减)。 4. 如果数据行中指定的标签列或普通列不存在,则在超级表中增加对应的标签列或普通列(只增不减)。
5. 如果超级表中存在一些标签列或普通列未在一个数据行中被指定取值,那么这些列的值在这一行中会被置为 5. 如果超级表中存在一些标签列或普通列未在一个数据行中被指定取值,那么这些列的值在这一行中会被置为
NULL。 NULL。
6. 对 BINARY 或 NCHAR 列,如果数据行中所提供值的长度超出了列类型的限制,自动增加该列允许存储的字符长度上限(只增不减),以保证数据的完整保存。 6. 对 BINARY 或 NCHAR 列,如果数据行中所提供值的长度超出了列类型的限制,自动增加该列允许存储的字符长度上限(只增不减),以保证数据的完整保存。
7. 如果指定的数据子表已经存在,而且本次指定的标签列取值跟已保存的值不一样,那么最新的数据行中的值会覆盖旧的标签列取值 7. 整个处理过程中遇到的错误会中断写入过程,并返回错误代码
8. 整个处理过程中遇到的错误会中断写入过程,并返回错误代码 8. 为了提高写入的效率默认假设同一个超级表中field_set的顺序是一样的第一条数据包含所有的field后面的数据按照这个顺序如果顺序不一样需要配置参数smlDataFormat为false否则数据写入按照相同顺序写入库中数据会异常
:::tip :::tip
无模式所有的处理逻辑,仍会遵循 TDengine 对数据结构的底层限制,例如每行数据的总长度不能超过 无模式所有的处理逻辑,仍会遵循 TDengine 对数据结构的底层限制,例如每行数据的总长度不能超过
48KB。这方面的具体限制约束请参见 [TAOS SQL 边界限制](/taos-sql/limit) 16KB。这方面的具体限制约束请参见 [TAOS SQL 边界限制](/taos-sql/limit)
::: :::

View File

@ -84,6 +84,9 @@ $ rmtaos
TDengine is removed successfully! TDengine is removed successfully!
``` ```
</TabItem>
<TabItem label="Windows 卸载" value="windows">
在 C:\TDengine 目录下,通过运行 unins000.exe 卸载程序来卸载 TDengine。
</TabItem> </TabItem>
</Tabs> </Tabs>

View File

@ -39,9 +39,6 @@ $ echo "foo:1|c" | nc -u -w0 127.0.0.1 8125
使用 TDengine CLI 验证从 StatsD 向 TDengine 写入数据并能够正确读出: 使用 TDengine CLI 验证从 StatsD 向 TDengine 写入数据并能够正确读出:
``` ```
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; taos> show databases;
name | created_time | ntables | vgroups | replica | quorum | days | keep | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | cachelast | precision | update | status | name | created_time | ntables | vgroups | replica | quorum | days | keep | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | cachelast | precision | update | status |
==================================================================================================================================================================================================================================================================================== ====================================================================================================================================================================================================================================================================================

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.8 KiB

After

Width:  |  Height:  |  Size: 37 KiB

View File

@ -21,17 +21,17 @@
#include "taos.h" #include "taos.h"
static int running = 1; static int running = 1;
static char dbName[64] = "tmqdb"; static char dbName[64] = "tmqdb";
static char stbName[64] = "stb"; static char stbName[64] = "stb";
static char topicName[64] = "topicname"; static char topicName[64] = "topicname";
static int32_t msg_process(TAOS_RES* msg) { static int32_t msg_process(TAOS_RES* msg) {
char buf[1024]; char buf[1024];
int32_t rows = 0; int32_t rows = 0;
const char* topicName = tmq_get_topic_name(msg); const char* topicName = tmq_get_topic_name(msg);
const char* dbName = tmq_get_db_name(msg); const char* dbName = tmq_get_db_name(msg);
int32_t vgroupId = tmq_get_vgroup_id(msg); int32_t vgroupId = tmq_get_vgroup_id(msg);
printf("topic: %s\n", topicName); printf("topic: %s\n", topicName);
printf("db: %s\n", dbName); printf("db: %s\n", dbName);
@ -41,14 +41,14 @@ static int32_t msg_process(TAOS_RES* msg) {
TAOS_ROW row = taos_fetch_row(msg); TAOS_ROW row = taos_fetch_row(msg);
if (row == NULL) break; if (row == NULL) break;
TAOS_FIELD* fields = taos_fetch_fields(msg); TAOS_FIELD* fields = taos_fetch_fields(msg);
int32_t numOfFields = taos_field_count(msg); int32_t numOfFields = taos_field_count(msg);
int32_t* length = taos_fetch_lengths(msg); int32_t* length = taos_fetch_lengths(msg);
int32_t precision = taos_result_precision(msg); int32_t precision = taos_result_precision(msg);
const char* tbName = tmq_get_table_name(msg); const char* tbName = tmq_get_table_name(msg);
rows++; rows++;
taos_print_row(buf, row, fields, numOfFields); taos_print_row(buf, row, fields, numOfFields);
printf("row content from %s: %s\n", (tbName != NULL ? tbName : "null table"), buf); printf("row content from %s: %s\n", (tbName != NULL ? tbName : "table null"), buf);
} }
return rows; return rows;
@ -80,7 +80,8 @@ static int32_t init_env() {
// create super table // create super table
printf("create super table\n"); printf("create super table\n");
pRes = taos_query(pConn, "create table tmqdb.stb (ts timestamp, c1 int, c2 float, c3 varchar(16)) tags(t1 int, t3 varchar(16))"); pRes = taos_query(
pConn, "create table tmqdb.stb (ts timestamp, c1 int, c2 float, c3 varchar(16)) tags(t1 int, t3 varchar(16))");
if (taos_errno(pRes) != 0) { if (taos_errno(pRes) != 0) {
printf("failed to create super table stb, reason:%s\n", taos_errstr(pRes)); printf("failed to create super table stb, reason:%s\n", taos_errstr(pRes));
return -1; return -1;
@ -166,7 +167,6 @@ int32_t create_topic() {
} }
taos_free_result(pRes); taos_free_result(pRes);
// pRes = taos_query(pConn, "create topic topic_ctb_column with meta as database abc1");
pRes = taos_query(pConn, "create topic topicname as select ts, c1, c2, c3 from tmqdb.stb where c1 > 1"); pRes = taos_query(pConn, "create topic topicname as select ts, c1, c2, c3 from tmqdb.stb where c1 > 1");
if (taos_errno(pRes) != 0) { if (taos_errno(pRes) != 0) {
printf("failed to create topic topicname, reason:%s\n", taos_errstr(pRes)); printf("failed to create topic topicname, reason:%s\n", taos_errstr(pRes));
@ -184,26 +184,28 @@ void tmq_commit_cb_print(tmq_t* tmq, int32_t code, void* param) {
tmq_t* build_consumer() { tmq_t* build_consumer() {
tmq_conf_res_t code; tmq_conf_res_t code;
tmq_conf_t* conf = tmq_conf_new(); tmq_conf_t* conf = tmq_conf_new();
code = tmq_conf_set(conf, "enable.auto.commit", "true"); code = tmq_conf_set(conf, "enable.auto.commit", "true");
if (TMQ_CONF_OK != code) return NULL; if (TMQ_CONF_OK != code) return NULL;
code = tmq_conf_set(conf, "auto.commit.interval.ms", "1000"); code = tmq_conf_set(conf, "auto.commit.interval.ms", "1000");
if (TMQ_CONF_OK != code) return NULL; if (TMQ_CONF_OK != code) return NULL;
code = tmq_conf_set(conf, "group.id", "cgrpName"); code = tmq_conf_set(conf, "group.id", "cgrpName");
if (TMQ_CONF_OK != code) return NULL; if (TMQ_CONF_OK != code) return NULL;
code = tmq_conf_set(conf, "client.id", "user defined name");
if (TMQ_CONF_OK != code) return NULL;
code = tmq_conf_set(conf, "td.connect.user", "root"); code = tmq_conf_set(conf, "td.connect.user", "root");
if (TMQ_CONF_OK != code) return NULL; if (TMQ_CONF_OK != code) return NULL;
code = tmq_conf_set(conf, "td.connect.pass", "taosdata"); code = tmq_conf_set(conf, "td.connect.pass", "taosdata");
if (TMQ_CONF_OK != code) return NULL; if (TMQ_CONF_OK != code) return NULL;
code = tmq_conf_set(conf, "auto.offset.reset", "earliest"); code = tmq_conf_set(conf, "auto.offset.reset", "earliest");
if (TMQ_CONF_OK != code) return NULL; if (TMQ_CONF_OK != code) return NULL;
code = tmq_conf_set(conf, "experimental.snapshot.enable", "true"); code = tmq_conf_set(conf, "experimental.snapshot.enable", "true");
if (TMQ_CONF_OK != code) return NULL; if (TMQ_CONF_OK != code) return NULL;
code = tmq_conf_set(conf, "msg.with.table.name", "true"); code = tmq_conf_set(conf, "msg.with.table.name", "true");
if (TMQ_CONF_OK != code) return NULL; if (TMQ_CONF_OK != code) return NULL;
tmq_conf_set_auto_commit_cb(conf, tmq_commit_cb_print, NULL); tmq_conf_set_auto_commit_cb(conf, tmq_commit_cb_print, NULL);
tmq_t* tmq = tmq_consumer_new(conf, NULL, 0); tmq_t* tmq = tmq_consumer_new(conf, NULL, 0);
tmq_conf_destroy(conf); tmq_conf_destroy(conf);
return tmq; return tmq;
@ -211,7 +213,7 @@ tmq_t* build_consumer() {
tmq_list_t* build_topic_list() { tmq_list_t* build_topic_list() {
tmq_list_t* topicList = tmq_list_new(); tmq_list_t* topicList = tmq_list_new();
int32_t code = tmq_list_append(topicList, "topicname"); int32_t code = tmq_list_append(topicList, "topicname");
if (code) { if (code) {
return NULL; return NULL;
} }
@ -228,18 +230,18 @@ void basic_consume_loop(tmq_t* tmq, tmq_list_t* topicList) {
int32_t totalRows = 0; int32_t totalRows = 0;
int32_t msgCnt = 0; int32_t msgCnt = 0;
int32_t consumeDelay = 5000; int32_t timeout = 5000;
while (running) { while (running) {
TAOS_RES* tmqmsg = tmq_consumer_poll(tmq, consumeDelay); TAOS_RES* tmqmsg = tmq_consumer_poll(tmq, timeout);
if (tmqmsg) { if (tmqmsg) {
msgCnt++; msgCnt++;
totalRows += msg_process(tmqmsg); totalRows += msg_process(tmqmsg);
taos_free_result(tmqmsg); taos_free_result(tmqmsg);
} else { /*} else {*/
break; /*break;*/
} }
} }
fprintf(stderr, "%d msg consumed, include %d rows\n", msgCnt, totalRows); fprintf(stderr, "%d msg consumed, include %d rows\n", msgCnt, totalRows);
} }
@ -256,32 +258,30 @@ int main(int argc, char* argv[]) {
tmq_t* tmq = build_consumer(); tmq_t* tmq = build_consumer();
if (NULL == tmq) { if (NULL == tmq) {
fprintf(stderr, "%% build_consumer() fail!\n"); fprintf(stderr, "%% build_consumer() fail!\n");
return -1; return -1;
} }
tmq_list_t* topic_list = build_topic_list(); tmq_list_t* topic_list = build_topic_list();
if (NULL == topic_list) { if (NULL == topic_list) {
return -1; return -1;
} }
basic_consume_loop(tmq, topic_list); basic_consume_loop(tmq, topic_list);
code = tmq_unsubscribe(tmq); code = tmq_unsubscribe(tmq);
if (code) { if (code) {
fprintf(stderr, "%% Failed to unsubscribe: %s\n", tmq_err2str(code)); fprintf(stderr, "%% Failed to unsubscribe: %s\n", tmq_err2str(code));
} } else {
else {
fprintf(stderr, "%% unsubscribe\n"); fprintf(stderr, "%% unsubscribe\n");
} }
code = tmq_consumer_close(tmq); code = tmq_consumer_close(tmq);
if (code) { if (code) {
fprintf(stderr, "%% Failed to close consumer: %s\n", tmq_err2str(code)); fprintf(stderr, "%% Failed to close consumer: %s\n", tmq_err2str(code));
} } else {
else {
fprintf(stderr, "%% Consumer closed\n"); fprintf(stderr, "%% Consumer closed\n");
} }
return 0; return 0;
} }

View File

@ -196,15 +196,6 @@ DLL_EXPORT void taos_fetch_rows_a(TAOS_RES *res, __taos_async_fn_t fp, vo
DLL_EXPORT void taos_fetch_raw_block_a(TAOS_RES *res, __taos_async_fn_t fp, void *param); DLL_EXPORT void taos_fetch_raw_block_a(TAOS_RES *res, __taos_async_fn_t fp, void *param);
DLL_EXPORT const void *taos_get_raw_block(TAOS_RES *res); DLL_EXPORT const void *taos_get_raw_block(TAOS_RES *res);
// Shuduo: temporary enable for app build
#if 1
typedef void (*__taos_sub_fn_t)(TAOS_SUB *tsub, TAOS_RES *res, void *param, int code);
DLL_EXPORT TAOS_SUB *taos_subscribe(TAOS *taos, int restart, const char *topic, const char *sql, __taos_sub_fn_t fp,
void *param, int interval);
DLL_EXPORT TAOS_RES *taos_consume(TAOS_SUB *tsub);
DLL_EXPORT void taos_unsubscribe(TAOS_SUB *tsub, int keepProgress);
#endif
DLL_EXPORT int taos_load_table_info(TAOS *taos, const char *tableNameList); DLL_EXPORT int taos_load_table_info(TAOS *taos, const char *tableNameList);
DLL_EXPORT TAOS_RES *taos_schemaless_insert(TAOS *taos, char *lines[], int numLines, int protocol, int precision); DLL_EXPORT TAOS_RES *taos_schemaless_insert(TAOS *taos, char *lines[], int numLines, int protocol, int precision);
@ -281,10 +272,6 @@ DLL_EXPORT const char *tmq_get_table_name(TAOS_RES *res);
/* ------------------------------ TMQ END -------------------------------- */ /* ------------------------------ TMQ END -------------------------------- */
#if 1 // Shuduo: temporary enable for app build
typedef void (*TAOS_SUBSCRIBE_CALLBACK)(TAOS_SUB *tsub, TAOS_RES *res, void *param, int code);
#endif
typedef enum { typedef enum {
TSDB_SRV_STATUS_UNAVAILABLE = 0, TSDB_SRV_STATUS_UNAVAILABLE = 0,
TSDB_SRV_STATUS_NETWORK_OK = 1, TSDB_SRV_STATUS_NETWORK_OK = 1,

View File

@ -103,12 +103,12 @@ typedef struct SDataBlockInfo {
int16_t hasVarCol; int16_t hasVarCol;
uint32_t capacity; uint32_t capacity;
// TODO: optimize and remove following // TODO: optimize and remove following
int64_t version; // used for stream, and need serialization int64_t version; // used for stream, and need serialization
int64_t ts; // used for stream, and need serialization int64_t ts; // used for stream, and need serialization
int32_t childId; // used for stream, do not serialize int32_t childId; // used for stream, do not serialize
EStreamType type; // used for stream, do not serialize EStreamType type; // used for stream, do not serialize
STimeWindow calWin; // used for stream, do not serialize STimeWindow calWin; // used for stream, do not serialize
TSKEY watermark;// used for stream TSKEY watermark; // used for stream
} SDataBlockInfo; } SDataBlockInfo;
typedef struct SSDataBlock { typedef struct SSDataBlock {
@ -268,6 +268,15 @@ typedef struct SSortExecInfo {
int32_t readBytes; // read io bytes int32_t readBytes; // read io bytes
} SSortExecInfo; } SSortExecInfo;
// stream special block column
#define START_TS_COLUMN_INDEX 0
#define END_TS_COLUMN_INDEX 1
#define UID_COLUMN_INDEX 2
#define GROUPID_COLUMN_INDEX 3
#define CALCULATE_START_TS_COLUMN_INDEX 4
#define CALCULATE_END_TS_COLUMN_INDEX 5
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View File

@ -249,6 +249,7 @@ char* dumpBlockData(SSDataBlock* pDataBlock, const char* flag, char** dumpBuf);
int32_t buildSubmitReqFromDataBlock(SSubmitReq** pReq, const SSDataBlock* pDataBlocks, STSchema* pTSchema, int32_t vgId, int32_t buildSubmitReqFromDataBlock(SSubmitReq** pReq, const SSDataBlock* pDataBlocks, STSchema* pTSchema, int32_t vgId,
tb_uid_t suid); tb_uid_t suid);
char* buildCtbNameByGroupId(const char* stbName, uint64_t groupId); char* buildCtbNameByGroupId(const char* stbName, uint64_t groupId);
static FORCE_INLINE int32_t blockGetEncodeSize(const SSDataBlock* pBlock) { static FORCE_INLINE int32_t blockGetEncodeSize(const SSDataBlock* pBlock) {

View File

@ -200,8 +200,6 @@ struct STag {
#if 1 //================================================================================================================================================ #if 1 //================================================================================================================================================
// Imported since 3.0 and use bitmap to demonstrate None/Null/Norm, while use Null/Norm below 3.0 without of bitmap. // Imported since 3.0 and use bitmap to demonstrate None/Null/Norm, while use Null/Norm below 3.0 without of bitmap.
#define TD_SUPPORT_BITMAP #define TD_SUPPORT_BITMAP
#define TD_SUPPORT_READ2
#define TD_SUPPORT_BACK2 // suppport back compatibility of 2.0
#define TASSERT(x) ASSERT(x) #define TASSERT(x) ASSERT(x)

View File

@ -1369,8 +1369,8 @@ typedef struct {
int32_t numOfCols; int32_t numOfCols;
int64_t skey; int64_t skey;
int64_t ekey; int64_t ekey;
int64_t version; // for stream int64_t version; // for stream
TSKEY watermark;// for stream TSKEY watermark; // for stream
char data[]; char data[];
} SRetrieveTableRsp; } SRetrieveTableRsp;
@ -3080,6 +3080,22 @@ typedef struct SDeleteRes {
int32_t tEncodeDeleteRes(SEncoder* pCoder, const SDeleteRes* pRes); int32_t tEncodeDeleteRes(SEncoder* pCoder, const SDeleteRes* pRes);
int32_t tDecodeDeleteRes(SDecoder* pCoder, SDeleteRes* pRes); int32_t tDecodeDeleteRes(SDecoder* pCoder, SDeleteRes* pRes);
typedef struct {
int64_t uid;
int64_t ts;
} SSingleDeleteReq;
int32_t tEncodeSSingleDeleteReq(SEncoder* pCoder, const SSingleDeleteReq* pReq);
int32_t tDecodeSSingleDeleteReq(SDecoder* pCoder, SSingleDeleteReq* pReq);
typedef struct {
int64_t suid;
SArray* deleteReqs; // SArray<SSingleDeleteReq>
} SBatchDeleteReq;
int32_t tEncodeSBatchDeleteReq(SEncoder* pCoder, const SBatchDeleteReq* pReq);
int32_t tDecodeSBatchDeleteReq(SDecoder* pCoder, SBatchDeleteReq* pReq);
typedef struct { typedef struct {
int32_t msgIdx; int32_t msgIdx;
int32_t msgType; int32_t msgType;

View File

@ -202,6 +202,7 @@ enum {
TD_DEF_MSG_TYPE(TDMT_VND_SUBMIT_RSMA, "vnode-submit-rsma", SSubmitReq, SSubmitRsp) TD_DEF_MSG_TYPE(TDMT_VND_SUBMIT_RSMA, "vnode-submit-rsma", SSubmitReq, SSubmitRsp)
TD_DEF_MSG_TYPE(TDMT_VND_FETCH_RSMA, "vnode-fetch-rsma", SRSmaFetchMsg, NULL) TD_DEF_MSG_TYPE(TDMT_VND_FETCH_RSMA, "vnode-fetch-rsma", SRSmaFetchMsg, NULL)
TD_DEF_MSG_TYPE(TDMT_VND_DELETE, "delete-data", SVDeleteReq, SVDeleteRsp) TD_DEF_MSG_TYPE(TDMT_VND_DELETE, "delete-data", SVDeleteReq, SVDeleteRsp)
TD_DEF_MSG_TYPE(TDMT_VND_BATCH_DEL, "batch-delete", SBatchDeleteReq, NULL)
TD_DEF_MSG_TYPE(TDMT_VND_ALTER_CONFIG, "alter-config", NULL, NULL) TD_DEF_MSG_TYPE(TDMT_VND_ALTER_CONFIG, "alter-config", NULL, NULL)
TD_DEF_MSG_TYPE(TDMT_VND_ALTER_REPLICA, "alter-replica", NULL, NULL) TD_DEF_MSG_TYPE(TDMT_VND_ALTER_REPLICA, "alter-replica", NULL, NULL)
TD_DEF_MSG_TYPE(TDMT_VND_ALTER_CONFIRM, "alter-confirm", NULL, NULL) TD_DEF_MSG_TYPE(TDMT_VND_ALTER_CONFIRM, "alter-confirm", NULL, NULL)

View File

@ -319,21 +319,17 @@ typedef struct {
col_id_t kvIdx; // [0, nKvCols) col_id_t kvIdx; // [0, nKvCols)
} STSRowIter; } STSRowIter;
void tdSTSRowIterReset(STSRowIter *pIter, STSRow *pRow); void tdSTSRowIterInit(STSRowIter *pIter, STSchema *pSchema);
void tdSTSRowIterInit(STSRowIter *pIter, STSchema *pSchema); void tdSTSRowIterReset(STSRowIter *pIter, STSRow *pRow);
bool tdSTSRowIterFetch(STSRowIter *pIter, col_id_t colId, col_type_t colType, SCellVal *pVal);
bool tdSTSRowIterNext(STSRowIter *pIter, SCellVal *pVal);
int32_t tdSTSRowNew(SArray *pArray, STSchema *pTSchema, STSRow **ppRow); int32_t tdSTSRowNew(SArray *pArray, STSchema *pTSchema, STSRow **ppRow);
bool tdSTSRowGetVal(STSRowIter *pIter, col_id_t colId, col_type_t colType, SCellVal *pVal); bool tdSTSRowGetVal(STSRowIter *pIter, col_id_t colId, col_type_t colType, SCellVal *pVal);
bool tdGetTpRowDataOfCol(STSRowIter *pIter, col_type_t colType, int32_t offset, SCellVal *pVal);
bool tdGetKvRowValOfColEx(STSRowIter *pIter, col_id_t colId, col_type_t colType, col_id_t *nIdx, SCellVal *pVal);
bool tdSTSRowIterNext(STSRowIter *pIter, col_id_t colId, col_type_t colType, SCellVal *pVal);
bool tdSTpRowGetVal(STSRow *pRow, col_id_t colId, col_type_t colType, int32_t flen, uint32_t offset, col_id_t colIdx,
SCellVal *pVal);
bool tdSKvRowGetVal(STSRow *pRow, col_id_t colId, col_id_t colIdx, SCellVal *pVal);
void tdSCellValPrint(SCellVal *pVal, int8_t colType);
void tdSRowPrint(STSRow *row, STSchema *pSchema, const char *tag); void tdSRowPrint(STSRow *row, STSchema *pSchema, const char *tag);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /*_TD_COMMON_ROW_H_*/ #endif /*_TD_COMMON_ROW_H_*/

View File

@ -154,7 +154,7 @@
#define TK_ACCOUNTS 136 #define TK_ACCOUNTS 136
#define TK_APPS 137 #define TK_APPS 137
#define TK_CONNECTIONS 138 #define TK_CONNECTIONS 138
#define TK_LICENCE 139 #define TK_LICENCES 139
#define TK_GRANTS 140 #define TK_GRANTS 140
#define TK_QUERIES 141 #define TK_QUERIES 141
#define TK_SCORES 142 #define TK_SCORES 142
@ -266,12 +266,60 @@
#define TK_OFFSET 248 #define TK_OFFSET 248
#define TK_ASC 249 #define TK_ASC 249
#define TK_NULLS 250 #define TK_NULLS 250
#define TK_ID 251 #define TK_ABORT 251
#define TK_NK_BITNOT 252 #define TK_AFTER 252
#define TK_VALUES 253 #define TK_ATTACH 253
#define TK_IMPORT 254 #define TK_BEFORE 254
#define TK_NK_SEMI 255 #define TK_BEGIN 255
#define TK_FILE 256 #define TK_BITAND 256
#define TK_BITNOT 257
#define TK_BITOR 258
#define TK_BLOCKS 259
#define TK_CHANGE 260
#define TK_COMMA 261
#define TK_COMPACT 262
#define TK_CONCAT 263
#define TK_CONFLICT 264
#define TK_COPY 265
#define TK_DEFERRED 266
#define TK_DELIMITERS 267
#define TK_DETACH 268
#define TK_DIVIDE 269
#define TK_DOT 270
#define TK_EACH 271
#define TK_END 272
#define TK_FAIL 273
#define TK_FILE 274
#define TK_FOR 275
#define TK_GLOB 276
#define TK_ID 277
#define TK_IMMEDIATE 278
#define TK_IMPORT 279
#define TK_INITIALLY 280
#define TK_INSTEAD 281
#define TK_ISNULL 282
#define TK_KEY 283
#define TK_NK_BITNOT 284
#define TK_NK_SEMI 285
#define TK_NOTNULL 286
#define TK_OF 287
#define TK_PLUS 288
#define TK_PRIVILEGE 289
#define TK_RAISE 290
#define TK_REPLACE 291
#define TK_RESTRICT 292
#define TK_ROW 293
#define TK_SEMI 294
#define TK_STAR 295
#define TK_STATEMENT 296
#define TK_STRING 297
#define TK_TIMES 298
#define TK_UPDATE 299
#define TK_VALUES 300
#define TK_VARIABLE 301
#define TK_VIEW 302
#define TK_VNODES 303
#define TK_WAL 304
#define TK_NK_SPACE 300 #define TK_NK_SPACE 300
#define TK_NK_COMMENT 301 #define TK_NK_COMMENT 301

View File

@ -54,10 +54,6 @@ typedef struct SFuncExecFuncs {
FExecCombine combine; FExecCombine combine;
} SFuncExecFuncs; } SFuncExecFuncs;
typedef struct SFileBlockInfo {
int32_t numBlocksOfStep;
} SFileBlockInfo;
#define MAX_INTERVAL_TIME_WINDOW 1000000 // maximum allowed time windows in final results #define MAX_INTERVAL_TIME_WINDOW 1000000 // maximum allowed time windows in final results
#define TOP_BOTTOM_QUERY_LIMIT 100 #define TOP_BOTTOM_QUERY_LIMIT 100
@ -171,8 +167,6 @@ typedef struct tExprNode {
}; };
} tExprNode; } tExprNode;
void tExprTreeDestroy(tExprNode *pNode, void (*fp)(void *));
struct SScalarParam { struct SScalarParam {
bool colAlloced; bool colAlloced;
SColumnInfoData *columnData; SColumnInfoData *columnData;
@ -182,14 +176,10 @@ struct SScalarParam {
int32_t numOfRows; int32_t numOfRows;
}; };
int32_t getResultDataInfo(int32_t dataType, int32_t dataBytes, int32_t functionId, int32_t param, SResultDataInfo* pInfo, int16_t extLength, void cleanupResultRowEntry(struct SResultRowEntryInfo* pCell);
bool isSuperTable);
void resetResultRowEntryResult(SqlFunctionCtx* pCtx, int32_t num);
void cleanupResultRowEntry(struct SResultRowEntryInfo* pCell);
int32_t getNumOfResult(SqlFunctionCtx* pCtx, int32_t num, SSDataBlock* pResBlock); int32_t getNumOfResult(SqlFunctionCtx* pCtx, int32_t num, SSDataBlock* pResBlock);
bool isRowEntryCompleted(struct SResultRowEntryInfo* pEntry); bool isRowEntryCompleted(struct SResultRowEntryInfo* pEntry);
bool isRowEntryInitialized(struct SResultRowEntryInfo* pEntry); bool isRowEntryInitialized(struct SResultRowEntryInfo* pEntry);
typedef struct SPoint { typedef struct SPoint {
int64_t key; int64_t key;

View File

@ -199,6 +199,7 @@ bool fmIsUserDefinedFunc(int32_t funcId);
bool fmIsDistExecFunc(int32_t funcId); bool fmIsDistExecFunc(int32_t funcId);
bool fmIsForbidFillFunc(int32_t funcId); bool fmIsForbidFillFunc(int32_t funcId);
bool fmIsForbidStreamFunc(int32_t funcId); bool fmIsForbidStreamFunc(int32_t funcId);
bool fmIsForbidSuperTableFunc(int32_t funcId);
bool fmIsIntervalInterpoFunc(int32_t funcId); bool fmIsIntervalInterpoFunc(int32_t funcId);
bool fmIsInterpFunc(int32_t funcId); bool fmIsInterpFunc(int32_t funcId);
bool fmIsLastRowFunc(int32_t funcId); bool fmIsLastRowFunc(int32_t funcId);

View File

@ -172,27 +172,24 @@ typedef enum ENodeType {
QUERY_NODE_SHOW_TABLES_STMT, QUERY_NODE_SHOW_TABLES_STMT,
QUERY_NODE_SHOW_TAGS_STMT, QUERY_NODE_SHOW_TAGS_STMT,
QUERY_NODE_SHOW_USERS_STMT, QUERY_NODE_SHOW_USERS_STMT,
QUERY_NODE_SHOW_LICENCE_STMT, QUERY_NODE_SHOW_LICENCES_STMT,
QUERY_NODE_SHOW_VGROUPS_STMT, QUERY_NODE_SHOW_VGROUPS_STMT,
QUERY_NODE_SHOW_TOPICS_STMT, QUERY_NODE_SHOW_TOPICS_STMT,
QUERY_NODE_SHOW_CONSUMERS_STMT, QUERY_NODE_SHOW_CONSUMERS_STMT,
QUERY_NODE_SHOW_SUBSCRIBES_STMT,
QUERY_NODE_SHOW_SMAS_STMT,
QUERY_NODE_SHOW_CONFIGS_STMT,
QUERY_NODE_SHOW_CONNECTIONS_STMT, QUERY_NODE_SHOW_CONNECTIONS_STMT,
QUERY_NODE_SHOW_QUERIES_STMT, QUERY_NODE_SHOW_QUERIES_STMT,
QUERY_NODE_SHOW_VNODES_STMT,
QUERY_NODE_SHOW_APPS_STMT, QUERY_NODE_SHOW_APPS_STMT,
QUERY_NODE_SHOW_SCORES_STMT,
QUERY_NODE_SHOW_VARIABLES_STMT, QUERY_NODE_SHOW_VARIABLES_STMT,
QUERY_NODE_SHOW_LOCAL_VARIABLES_STMT,
QUERY_NODE_SHOW_DNODE_VARIABLES_STMT, QUERY_NODE_SHOW_DNODE_VARIABLES_STMT,
QUERY_NODE_SHOW_TRANSACTIONS_STMT,
QUERY_NODE_SHOW_SUBSCRIPTIONS_STMT,
QUERY_NODE_SHOW_CREATE_DATABASE_STMT, QUERY_NODE_SHOW_CREATE_DATABASE_STMT,
QUERY_NODE_SHOW_CREATE_TABLE_STMT, QUERY_NODE_SHOW_CREATE_TABLE_STMT,
QUERY_NODE_SHOW_CREATE_STABLE_STMT, QUERY_NODE_SHOW_CREATE_STABLE_STMT,
QUERY_NODE_SHOW_TRANSACTIONS_STMT,
QUERY_NODE_SHOW_TABLE_DISTRIBUTED_STMT, QUERY_NODE_SHOW_TABLE_DISTRIBUTED_STMT,
QUERY_NODE_SHOW_SUBSCRIPTIONS_STMT, QUERY_NODE_SHOW_LOCAL_VARIABLES_STMT,
QUERY_NODE_SHOW_VNODES_STMT,
QUERY_NODE_SHOW_SCORES_STMT,
QUERY_NODE_KILL_CONNECTION_STMT, QUERY_NODE_KILL_CONNECTION_STMT,
QUERY_NODE_KILL_QUERY_STMT, QUERY_NODE_KILL_QUERY_STMT,
QUERY_NODE_KILL_TRANSACTION_STMT, QUERY_NODE_KILL_TRANSACTION_STMT,

View File

@ -269,6 +269,7 @@ typedef struct SSelectStmt {
bool hasInterpFunc; bool hasInterpFunc;
bool hasLastRowFunc; bool hasLastRowFunc;
bool hasTimeLineFunc; bool hasTimeLineFunc;
bool hasUdaf;
bool onlyHasKeepOrderFunc; bool onlyHasKeepOrderFunc;
bool groupSort; bool groupSort;
} SSelectStmt; } SSelectStmt;

View File

@ -34,6 +34,8 @@ typedef struct SStreamTask SStreamTask;
enum { enum {
STREAM_STATUS__NORMAL = 0, STREAM_STATUS__NORMAL = 0,
STREAM_STATUS__STOP,
STREAM_STATUS__FAILED,
STREAM_STATUS__RECOVER, STREAM_STATUS__RECOVER,
}; };
@ -42,8 +44,8 @@ enum {
TASK_STATUS__DROPPING, TASK_STATUS__DROPPING,
TASK_STATUS__FAIL, TASK_STATUS__FAIL,
TASK_STATUS__STOP, TASK_STATUS__STOP,
TASK_STATUS__PREPARE_RECOVER, TASK_STATUS__RECOVER_DOWNSTREAM,
TASK_STATUS__RECOVERING, TASK_STATUS__RECOVER_SELF,
}; };
enum { enum {
@ -118,7 +120,7 @@ typedef struct {
int64_t sourceVer; int64_t sourceVer;
int64_t reqId; int64_t reqId;
SArray* blocks; // SArray<SSDataBlock*> SArray* blocks; // SArray<SSDataBlock>
} SStreamDataBlock; } SStreamDataBlock;
typedef struct { typedef struct {
@ -154,7 +156,10 @@ static FORCE_INLINE void streamQueueProcessFail(SStreamQueue* queue) {
atomic_store_8(&queue->status, STREAM_QUEUE__FAILED); atomic_store_8(&queue->status, STREAM_QUEUE__FAILED);
} }
static FORCE_INLINE void* streamQueueCurItem(SStreamQueue* queue) { return queue->qItem; } static FORCE_INLINE void* streamQueueCurItem(SStreamQueue* queue) {
//
return queue->qItem;
}
static FORCE_INLINE void* streamQueueNextItem(SStreamQueue* queue) { static FORCE_INLINE void* streamQueueNextItem(SStreamQueue* queue) {
int8_t dequeueFlag = atomic_exchange_8(&queue->status, STREAM_QUEUE__PROCESSING); int8_t dequeueFlag = atomic_exchange_8(&queue->status, STREAM_QUEUE__PROCESSING);
@ -226,14 +231,12 @@ typedef struct {
int32_t nodeId; int32_t nodeId;
int32_t childId; int32_t childId;
int32_t taskId; int32_t taskId;
// int64_t checkpointVer; SEpSet epSet;
// int64_t processedVer;
SEpSet epSet;
} SStreamChildEpInfo; } SStreamChildEpInfo;
typedef struct { typedef struct {
int32_t nodeId; int32_t srcNodeId;
int32_t childId; int32_t srcChildId;
int64_t stateSaveVer; int64_t stateSaveVer;
int64_t stateProcessedVer; int64_t stateProcessedVer;
} SStreamCheckpointInfo; } SStreamCheckpointInfo;
@ -372,15 +375,6 @@ static FORCE_INLINE int32_t streamTaskOutput(SStreamTask* pTask, SStreamDataBloc
return 0; return 0;
} }
typedef struct {
int32_t reserved;
} SStreamTaskDeployRsp;
typedef struct {
// SMsgHead head;
SStreamTask* task;
} SStreamTaskDeployReq;
typedef struct { typedef struct {
SMsgHead head; SMsgHead head;
int64_t streamId; int64_t streamId;
@ -394,9 +388,6 @@ typedef struct {
int32_t upstreamTaskId; int32_t upstreamTaskId;
int32_t upstreamChildId; int32_t upstreamChildId;
int32_t upstreamNodeId; int32_t upstreamNodeId;
#if 0
int64_t sourceVer;
#endif
int32_t blockNum; int32_t blockNum;
SArray* dataLen; // SArray<int32_t> SArray* dataLen; // SArray<int32_t>
SArray* data; // SArray<SRetrieveTableRsp*> SArray* data; // SArray<SRetrieveTableRsp*>
@ -426,6 +417,7 @@ typedef struct {
int32_t rspToTaskId; int32_t rspToTaskId;
} SStreamRetrieveRsp; } SStreamRetrieveRsp;
#if 0
typedef struct { typedef struct {
int64_t streamId; int64_t streamId;
int32_t taskId; int32_t taskId;
@ -462,13 +454,36 @@ int32_t tDecodeSMStreamTaskRecoverReq(SDecoder* pDecoder, SMStreamTaskRecoverReq
int32_t tEncodeSMStreamTaskRecoverRsp(SEncoder* pEncoder, const SMStreamTaskRecoverRsp* pRsp); int32_t tEncodeSMStreamTaskRecoverRsp(SEncoder* pEncoder, const SMStreamTaskRecoverRsp* pRsp);
int32_t tDecodeSMStreamTaskRecoverRsp(SDecoder* pDecoder, SMStreamTaskRecoverRsp* pRsp); int32_t tDecodeSMStreamTaskRecoverRsp(SDecoder* pDecoder, SMStreamTaskRecoverRsp* pRsp);
typedef struct { int32_t streamProcessRecoverReq(SStreamTask* pTask, SStreamTaskRecoverReq* pReq, SRpcMsg* pMsg);
int64_t streamId; int32_t streamProcessRecoverRsp(SStreamTask* pTask, SStreamTaskRecoverRsp* pRsp);
} SPStreamTaskRecoverReq; #endif
typedef struct { typedef struct {
int8_t reserved; int64_t streamId;
} SPStreamTaskRecoverRsp; int32_t downstreamTaskId;
int32_t taskId;
} SStreamRecoverDownstreamReq;
typedef struct {
int64_t streamId;
int32_t downstreamTaskId;
int32_t taskId;
SArray* checkpointVer; // SArray<SStreamCheckpointInfo>
} SStreamRecoverDownstreamRsp;
int32_t tEncodeSStreamTaskRecoverReq(SEncoder* pEncoder, const SStreamRecoverDownstreamReq* pReq);
int32_t tDecodeSStreamTaskRecoverReq(SDecoder* pDecoder, SStreamRecoverDownstreamReq* pReq);
int32_t tEncodeSStreamTaskRecoverRsp(SEncoder* pEncoder, const SStreamRecoverDownstreamRsp* pRsp);
int32_t tDecodeSStreamTaskRecoverRsp(SDecoder* pDecoder, SStreamRecoverDownstreamRsp* pRsp);
typedef struct {
int64_t streamId;
int32_t taskId;
int32_t waitingRspCnt;
int32_t totReq;
SArray* info; // SArray<SArray<SStreamCheckpointInfo>*>
} SStreamRecoverStatus;
int32_t tDecodeStreamDispatchReq(SDecoder* pDecoder, SStreamDispatchReq* pReq); int32_t tDecodeStreamDispatchReq(SDecoder* pDecoder, SStreamDispatchReq* pReq);
int32_t tDecodeStreamRetrieveReq(SDecoder* pDecoder, SStreamRetrieveReq* pReq); int32_t tDecodeStreamRetrieveReq(SDecoder* pDecoder, SStreamRetrieveReq* pReq);
@ -479,8 +494,6 @@ int32_t streamSetupTrigger(SStreamTask* pTask);
int32_t streamProcessRunReq(SStreamTask* pTask); int32_t streamProcessRunReq(SStreamTask* pTask);
int32_t streamProcessDispatchReq(SStreamTask* pTask, SStreamDispatchReq* pReq, SRpcMsg* pMsg, bool exec); int32_t streamProcessDispatchReq(SStreamTask* pTask, SStreamDispatchReq* pReq, SRpcMsg* pMsg, bool exec);
int32_t streamProcessDispatchRsp(SStreamTask* pTask, SStreamDispatchRsp* pRsp); int32_t streamProcessDispatchRsp(SStreamTask* pTask, SStreamDispatchRsp* pRsp);
int32_t streamProcessRecoverReq(SStreamTask* pTask, SStreamTaskRecoverReq* pReq, SRpcMsg* pMsg);
int32_t streamProcessRecoverRsp(SStreamTask* pTask, SStreamTaskRecoverRsp* pRsp);
int32_t streamProcessRetrieveReq(SStreamTask* pTask, SStreamRetrieveReq* pReq, SRpcMsg* pMsg); int32_t streamProcessRetrieveReq(SStreamTask* pTask, SStreamRetrieveReq* pReq, SRpcMsg* pMsg);
int32_t streamProcessRetrieveRsp(SStreamTask* pTask, SStreamRetrieveRsp* pRsp); int32_t streamProcessRetrieveRsp(SStreamTask* pTask, SStreamRetrieveRsp* pRsp);
@ -496,7 +509,7 @@ typedef struct SStreamMeta {
TTB* pTaskDb; TTB* pTaskDb;
TTB* pStateDb; TTB* pStateDb;
SHashObj* pTasks; SHashObj* pTasks;
SHashObj* pRecoveringState; SHashObj* pRecoverStatus;
void* ahandle; void* ahandle;
TXN txn; TXN txn;
FTaskExpand* expandFunc; FTaskExpand* expandFunc;

View File

@ -47,6 +47,8 @@ bool updateInfoIgnore(SUpdateInfo *pInfo, STimeWindow* pWin, uint64_t groupId, u
void updateInfoDestroy(SUpdateInfo *pInfo); void updateInfoDestroy(SUpdateInfo *pInfo);
void updateInfoAddCloseWindowSBF(SUpdateInfo *pInfo); void updateInfoAddCloseWindowSBF(SUpdateInfo *pInfo);
void updateInfoDestoryColseWinSBF(SUpdateInfo *pInfo); void updateInfoDestoryColseWinSBF(SUpdateInfo *pInfo);
int32_t updateInfoSerialize(void *buf, int32_t bufLen, const SUpdateInfo *pInfo);
int32_t updateInfoDeserialize(void *buf, int32_t bufLen, SUpdateInfo *pInfo);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -129,6 +129,9 @@ typedef struct SSyncFSM {
void (*FpReConfigCb)(struct SSyncFSM* pFsm, const SRpcMsg* pMsg, SReConfigCbMeta cbMeta); void (*FpReConfigCb)(struct SSyncFSM* pFsm, const SRpcMsg* pMsg, SReConfigCbMeta cbMeta);
void (*FpLeaderTransferCb)(struct SSyncFSM* pFsm, const SRpcMsg* pMsg, SFsmCbMeta cbMeta); void (*FpLeaderTransferCb)(struct SSyncFSM* pFsm, const SRpcMsg* pMsg, SFsmCbMeta cbMeta);
void (*FpBecomeLeaderCb)(struct SSyncFSM* pFsm);
void (*FpBecomeFollowerCb)(struct SSyncFSM* pFsm);
int32_t (*FpGetSnapshot)(struct SSyncFSM* pFsm, SSnapshot* pSnapshot, void* pReaderParam, void** ppReader); int32_t (*FpGetSnapshot)(struct SSyncFSM* pFsm, SSnapshot* pSnapshot, void* pReaderParam, void** ppReader);
int32_t (*FpGetSnapshotInfo)(struct SSyncFSM* pFsm, SSnapshot* pSnapshot); int32_t (*FpGetSnapshotInfo)(struct SSyncFSM* pFsm, SSnapshot* pSnapshot);

View File

@ -47,8 +47,6 @@ typedef struct SRpcHandleInfo {
int8_t persistHandle; // persist handle or not int8_t persistHandle; // persist handle or not
int8_t hasEpSet; int8_t hasEpSet;
STraceId traceId;
// app info // app info
void *ahandle; // app handle set by client void *ahandle; // app handle set by client
void *wrapper; // wrapper handle void *wrapper; // wrapper handle
@ -58,7 +56,8 @@ typedef struct SRpcHandleInfo {
void *rsp; void *rsp;
int32_t rspLen; int32_t rspLen;
// conn info STraceId traceId;
SRpcConnInfo conn; SRpcConnInfo conn;
} SRpcHandleInfo; } SRpcHandleInfo;

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