go.mdx 11.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
---
toc_max_heading_level: 4
sidebar_position: 4
sidebar_label: Go
title: TDengine Go Connector
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

import Preparition from "./_preparition.mdx"
G
gccgdb1234 已提交
12 13 14 15 16
import GoInsert from "../07-develop/03-insert-data/_go_sql.mdx"
import GoInfluxLine from "../07-develop/03-insert-data/_go_line.mdx"
import GoOpenTSDBTelnet from "../07-develop/03-insert-data/_go_opts_telnet.mdx"
import GoOpenTSDBJson from "../07-develop/03-insert-data/_go_opts_json.mdx"
import GoQuery from "../07-develop/04-query-data/_go.mdx"
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

`driver-go`  TDengine 的官方 Go 语言连接器,实现了 Go 语言[ database/sql ](https://golang.org/pkg/database/sql/) 包的接口。Go 开发人员可以通过它开发存取 TDengine 集群数据的应用软件。

`driver-go` 提供两种建立连接的方式。一种是**原生连接**,它通过 TDengine 客户端驱动程序(taosc)原生连接 TDengine 运行实例,支持数据写入、查询、订阅、schemaless 接口和参数绑定接口等功能。另外一种是 **REST 连接**,它通过 taosAdapter 提供的 REST 接口连接 TDengine 运行实例。REST 连接实现的功能特性集合和原生连接有少量不同。

本文介绍如何安装 `driver-go`,并通过 `driver-go` 连接 TDengine 集群、进行数据查询、数据写入等基本操作。

`driver-go` 的源码托管在 [GitHub](https://github.com/taosdata/driver-go)

## 支持的平台

原生连接支持的平台和 TDengine 客户端驱动支持的平台一致。
REST 连接支持所有能运行 Go 的平台。

## 版本支持

G
gccgdb1234 已提交
33
请参考[版本支持列表](../#版本支持)
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

## 支持的功能特性

### 原生连接

“原生连接”指连接器通过 TDengine 客户端驱动(taosc)直接与 TDengine 运行实例建立的连接。支持的功能特性有:

* 普通查询
* 连续查询
* 订阅
* schemaless 接口
* 参数绑定接口

### REST 连接

"REST 连接"指连接器通过 taosAdapter 组件提供的 REST API  TDengine 运行实例建立的连接。支持的功能特性有:

* 普通查询
* 连续查询

## 安装步骤

### 安装前准备

* 安装 Go 开发环境(Go 1.14 及以上,GCC 4.8.5 及以上)
G
gccgdb1234 已提交
59
* 如果使用原生连接器,请安装 TDengine 客户端驱动,具体步骤请参考[安装客户端驱动](../#安装客户端驱动)
60 61 62 63 64 65 66 67

配置好环境变量,检查命令:

* ```go env```
* ```gcc -v```

### 使用 go get 安装

T
t_max 已提交
68
`go get -u github.com/taosdata/driver-go/v3@latest`
69 70 71 72 73 74 75 76 77 78 79 80 81 82

### 使用 go mod 管理

1. 使用 `go mod` 命令初始化项目:

  ```text
  go mod init taos-demo
  ```

2. 引入 taosSql 

  ```go
  import (
    "database/sql"
T
t_max 已提交
83
    _ "github.com/taosdata/driver-go/v3/taosSql"
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
  )
  ```

3. 使用 `go mod tidy` 更新依赖包:

  ```text
  go mod tidy
  ```

4. 使用 `go run taos-demo` 运行程序或使用 `go build` 命令编译出二进制文件。

  ```text
  go run taos-demo
  go build
  ```

## 建立连接

### 数据源名称(DSN

数据源名称具有通用格式,例如 [PEAR DB](http://pear.php.net/manual/en/package.database.db.intro-dsn.php),但没有类型前缀(方括号表示可选):

``` text
[username[:password]@][protocol[(address)]]/[dbname][?param1=value1&...&paramN=valueN]
```

完整形式的 DSN

```text
username:password@protocol(address)/dbname?param=value
```
### 使用连接器进行连接

<Tabs defaultValue="native">
<TabItem value="native" label="原生连接">

_taosSql_ 通过 cgo 实现了 Go  `database/sql/driver` 接口。只需要引入驱动就可以使用 [`database/sql`](https://golang.org/pkg/database/sql/) 的接口。

使用 `taosSql` 作为 `driverName` 并且使用一个正确的 [DSN](#DSN) 作为 `dataSourceName`DSN 支持的参数:

* configPath 指定 taos.cfg 目录

示例:

```go
package main

import (
    "database/sql"
    "fmt"

T
t_max 已提交
135
    _ "github.com/taosdata/driver-go/v3/taosSql"
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
)

func main() {
    var taosUri = "root:taosdata@tcp(localhost:6030)/"
    taos, err := sql.Open("taosSql", taosUri)
    if err != nil {
        fmt.Println("failed to connect TDengine, err:", err)
        return
    }
}
```

</TabItem>
<TabItem value="rest" label="REST 连接">

_taosRestful_ 通过 `http client` 实现了 Go  `database/sql/driver` 接口。只需要引入驱动就可以使用[`database/sql`](https://golang.org/pkg/database/sql/)的接口。

使用 `taosRestful` 作为 `driverName` 并且使用一个正确的 [DSN](#DSN) 作为 `dataSourceName`DSN 支持的参数:

* `disableCompression` 是否接受压缩数据,默认为 true 不接受压缩数据,如果传输数据使用 gzip 压缩设置为 false
* `readBufferSize` 读取数据的缓存区大小默认为 4K4096),当查询结果数据量多时可以适当调大该值。

示例:

```go
package main

import (
    "database/sql"
    "fmt"

T
t_max 已提交
167
    _ "github.com/taosdata/driver-go/v3/taosRestful"
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
)

func main() {
    var taosUri = "root:taosdata@http(localhost:6041)/"
    taos, err := sql.Open("taosRestful", taosUri)
    if err != nil {
        fmt.Println("failed to connect TDengine, err:", err)
        return
    }
}
```
</TabItem>
</Tabs>

## 使用示例

### 写入数据

#### SQL 写入

<GoInsert />

#### InfluxDB 行协议写入

<GoInfluxLine />

#### OpenTSDB Telnet 行协议写入

<GoOpenTSDBTelnet />

#### OpenTSDB JSON 行协议写入

<GoOpenTSDBJson />

### 查询数据

<GoQuery />

### 更多示例程序

T
t_max 已提交
208
* [示例程序](https://github.com/taosdata/driver-go/tree/3.0/examples)
209 210 211 212 213 214
* [视频教程](https://www.taosdata.com/blog/2020/11/11/1951.html)

## 使用限制

由于 REST 接口无状态所以 `use db` 语法不会生效,需要将 db 名称放到 SQL 语句中,如:`create table if not exists tb1 (ts timestamp, a int)`改为`create table if not exists test.tb1 (ts timestamp, a int)`否则将报错`[0x217] Database not specified or available`

T
t_max 已提交
215
也可以将 db 名称放到 DSN 中,将 `root:taosdata@http(localhost:6041)/` 改为 `root:taosdata@http(localhost:6041)/test`。当指定的 db 不存在时执行 `create database` 语句不会报错,而执行针对该 db 的其他查询或写入操作会报错。
216 217 218 219 220 221 222 223 224 225 226

完整示例如下:

```go
package main

import (
    "database/sql"
    "fmt"
    "time"

T
t_max 已提交
227
    _ "github.com/taosdata/driver-go/v3/taosRestful"
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
)

func main() {
    var taosDSN = "root:taosdata@http(localhost:6041)/test"
    taos, err := sql.Open("taosRestful", taosDSN)
    if err != nil {
        fmt.Println("failed to connect TDengine, err:", err)
        return
    }
    defer taos.Close()
    taos.Exec("create database if not exists test")
    taos.Exec("create table if not exists tb1 (ts timestamp, a int)")
    _, err = taos.Exec("insert into tb1 values(now, 0)(now+1s,1)(now+2s,2)(now+3s,3)")
    if err != nil {
        fmt.Println("failed to insert, err:", err)
        return
    }
    rows, err := taos.Query("select * from tb1")
    if err != nil {
        fmt.Println("failed to select from table, err:", err)
        return
    }

    defer rows.Close()
    for rows.Next() {
        var r struct {
            ts time.Time
            a  int
        }
        err := rows.Scan(&r.ts, &r.a)
        if err != nil {
            fmt.Println("scan error:\n", err)
            return
        }
        fmt.Println(r.ts, r.a)
    }
}
```

## 常见问题

T
t_max 已提交
269
1. database/sql  stmt(参数绑定)相关接口崩溃
270 271 272

  REST 不支持参数绑定相关接口,建议使用`db.Exec``db.Query`

T
t_max 已提交
273
2. 使用 `use db` 语句后执行其他语句报错 `[0x217] Database not specified or available`
274 275 276

   REST 接口中 SQL 语句的执行无上下文关联,使用 `use db` 语句不会生效,解决办法见上方使用限制章节。

T
t_max 已提交
277
3. 使用 taosSql 不报错使用 taosRestful 报错 `[0x217] Database not specified or available`
278 279 280

  因为 REST 接口无状态,使用 `use db` 语句不会生效,解决办法见上方使用限制章节。

T
t_max 已提交
281
4. `readBufferSize` 参数调大后无明显效果
282 283 284

  `readBufferSize` 调大后会减少获取结果时 `syscall` 的调用。如果查询结果的数据量不大,修改该参数不会带来明显提升,如果该参数修改过大,瓶颈会在解析 JSON 数据。如果需要优化查询速度,需要根据实际情况调整该值来达到查询效果最优。

T
t_max 已提交
285
5. `disableCompression` 参数设置为 `false` 时查询效率降低
286 287 288

   `disableCompression` 参数设置为 `false` 时查询结果会使用 `gzip` 压缩后传输,拿到数据后要先进行 `gzip` 解压。

T
t_max 已提交
289
6. `go get` 命令无法获取包,或者获取包超时
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328

  设置 Go 代理 `go env -w GOPROXY=https://goproxy.cn,direct`

## 常用 API

### database/sql API

* `sql.Open(DRIVER_NAME string, dataSourceName string) *DB`

   API 用来打开 DB,返回一个类型为 \*DB 的对象。

:::info
 API 成功创建的时候,并没有做权限等检查,只有在真正执行 Query 或者 Exec 的时候才能真正的去创建连接,并同时检查 user/password/host/port 是不是合法。
:::

* `func (db *DB) Exec(query string, args ...interface{}) (Result, error)`

  `sql.Open` 内置的方法,用来执行非查询相关 SQL

* `func (db *DB) Query(query string, args ...interface{}) (*Rows, error)`

  `sql.Open` 内置的方法,用来执行查询语句。

### 高级功能(afAPI

`af` 包封装了连接管理、订阅、schemaless、参数绑定等 TDengine 高级功能。

#### 连接管理

* `af.Open(host, user, pass, db string, port int) (*Connector, error)`

   API 通过 cgo 创建与 taosd 的连接。

* `func (conn *Connector) Close() error`

  关闭与 taosd 的连接。

#### 订阅

T
t_max 已提交
329 330 331 332 333 334 335
* `func NewConsumer(conf *Config) (*Consumer, error)`

创建消费者。

* `func (c *Consumer) Subscribe(topics []string) error`

订阅主题。
336

T
t_max 已提交
337
* `func (c *Consumer) Poll(timeout time.Duration) (*Result, error)`
338

T
t_max 已提交
339
轮询消息。
340

T
t_max 已提交
341
* `func (c *Consumer) Commit(ctx context.Context, message unsafe.Pointer) error`
342

T
t_max 已提交
343
提交消息。
344

T
t_max 已提交
345 346 347 348 349 350 351 352 353 354 355
* `func (c *Consumer) FreeMessage(message unsafe.Pointer)`

释放消息。

* `func (c *Consumer) Unsubscribe() error`

取消订阅。

* `func (c *Consumer) Close() error`

关闭消费者。
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414

#### schemaless

* `func (conn *Connector) InfluxDBInsertLines(lines []string, precision string) error`

  写入 influxDB 行协议。

* `func (conn *Connector) OpenTSDBInsertTelnetLines(lines []string) error`

  写入 OpenTDSB telnet 协议数据。

* `func (conn *Connector) OpenTSDBInsertJsonPayload(payload string) error`

  写入 OpenTSDB JSON 协议数据。

#### 参数绑定

* `func (conn *Connector) StmtExecute(sql string, params *param.Param) (res driver.Result, err error)`

  参数绑定单行插入。

* `func (conn *Connector) InsertStmt() *insertstmt.InsertStmt`

  初始化参数。

* `func (stmt *InsertStmt) Prepare(sql string) error`

  参数绑定预处理 SQL 语句。

* `func (stmt *InsertStmt) SetTableName(name string) error`

  参数绑定设置表名。

* `func (stmt *InsertStmt) SetSubTableName(name string) error`

  参数绑定设置子表名。

* `func (stmt *InsertStmt) BindParam(params []*param.Param, bindType *param.ColumnType) error`

  参数绑定多行数据。

* `func (stmt *InsertStmt) AddBatch() error`

  添加到参数绑定批处理。

* `func (stmt *InsertStmt) Execute() error`

  执行参数绑定。

* `func (stmt *InsertStmt) GetAffectedRows() int`

  获取参数绑定插入受影响行数。

* `func (stmt *InsertStmt) Close() error`

  结束参数绑定。

## API 参考

T
t_max 已提交
415
全部 API  [driver-go 文档](https://pkg.go.dev/github.com/taosdata/driver-go/v3)