05-go.mdx 16.2 KB
Newer Older
1 2
---
title: TDengine Go Connector
D
danielclow 已提交
3 4 5
sidebar_label: Go
description: This document describes the TDengine Go connector.
toc_max_heading_level: 4
6 7 8 9 10 11 12 13 14 15 16
---

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

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
`driver-go` is the official Go language connector for TDengine. It implements the [database/sql](https://golang.org/pkg/database/sql/) package, the generic Go language interface to SQL databases. Go developers can use it to develop applications that access TDengine cluster data.
18

19
`driver-go` provides two ways to establish connections. One is **native connection**, which connects to TDengine instances natively through the TDengine client driver (taosc), supporting data writing, querying, subscriptions, schemaless writing, and bind interface. The other is the **REST connection**, which connects to TDengine instances via the REST interface provided by taosAdapter. The set of features implemented by the REST connection differs slightly from those implemented by the native connection.
20 21 22 23 24

This article describes how to install `driver-go` and connect to TDengine clusters and perform basic operations such as data query and data writing through `driver-go`.

The source code of `driver-go` is hosted on [GitHub](https://github.com/taosdata/driver-go).

D
danielclow 已提交
25
## Supported platforms
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

Native connections are supported on the same platforms as the TDengine client driver.
REST connections are supported on all platforms that can run Go.

## Version support

Please refer to [version support list](/reference/connector#version-support)

## Supported features

### Native connections

A "native connection" is established by the connector directly to the TDengine instance via the TDengine client driver (taosc). The supported functional features are:

* Normal queries
* Continuous queries
* Subscriptions
D
danielclow 已提交
43 44
* Schemaless interface
* Parameter binding interface
45 46 47 48 49

### REST connection

A "REST connection" is a connection between the application and the TDengine instance via the REST API provided by the taosAdapter component. The following features are supported:

D
danielclow 已提交
50
* Normal queries
51 52
* Continuous queries

D
danielclow 已提交
53
## Installation Steps
54

D
danielclow 已提交
55
### Pre-installation preparation
56

D
danielclow 已提交
57
* Install Go development environment (Go 1.14 and above, GCC 4.8.5 and above)
B
Bo Ding 已提交
58
- If you use the native connector, please install the TDengine client driver. Please refer to [Install Client Driver](/reference/connector/#install-client-driver) for specific steps
59 60 61

Configure the environment variables and check the command.

D
danielclow 已提交
62 63
* ```go env```
* ```gcc -v```
64 65 66

### Use go get to install

D
danielclow 已提交
67
`go get -u github.com/taosdata/driver-go/v3@latest`
68 69 70 71 72

### Manage with go mod

1. Initialize the project with the `go mod` command.

B
Bo Ding 已提交
73
  ```text
74
  go mod init taos-demo
D
danielclow 已提交
75
  ```
76 77 78 79 80 81

2. Introduce taosSql

  ```go
  import (
    "database/sql"
D
danielclow 已提交
82
    _ "github.com/taosdata/driver-go/v3/taosSql"
83 84 85 86 87 88 89
  )
  ```

3. Update the dependency packages with `go mod tidy`.

  ```text
  go mod tidy
D
danielclow 已提交
90
  ```
91 92 93 94 95 96 97 98

4. Run the program with `go run taos-demo` or compile the binary with the `go build` command.

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

D
danielclow 已提交
99
## Establishing a connection
100 101 102 103 104 105

### Data source name (DSN)

Data source names have a standard format, e.g. [PEAR DB](http://pear.php.net/manual/en/package.database.db.intro-dsn.php), but no type prefix (square brackets indicate optionally):

``` text
D
danielclow 已提交
106
[username[:password]@][protocol[(address)]]/[dbname][?param1=value1&...&paramN=valueN]
107 108 109 110 111 112 113 114 115
```

DSN in full form.

```text
username:password@protocol(address)/dbname?param=value
```
### Connecting via connector

116
<Tabs defaultValue="rest">
117 118 119 120 121 122
<TabItem value="native" label="native connection">

_taosSql_ implements Go's `database/sql/driver` interface via cgo. You can use the [`database/sql`](https://golang.org/pkg/database/sql/) interface by simply introducing the driver.

Use `taosSql` as `driverName` and use a correct [DSN](#DSN) as `dataSourceName`, DSN supports the following parameters.

123
* cfg specifies the `taos.cfg` directory
124

D
danielclow 已提交
125
For example:
126 127 128 129 130 131 132 133

```go
package main

import (
    "database/sql"
    "fmt"

D
danielclow 已提交
134
    _ "github.com/taosdata/driver-go/v3/taosSql"
135 136 137 138 139
)

func main() {
    var taosUri = "root:taosdata@tcp(localhost:6030)/"
    taos, err := sql.Open("taosSql", taosUri)
D
danielclow 已提交
140
    if err != nil {
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        fmt.Println("failed to connect TDengine, err:", err)
        return
    }
}
```

</TabItem>
<TabItem value="rest" label="REST connection">

_taosRestful_ implements Go's `database/sql/driver` interface via `http client`. You can use the [`database/sql`](https://golang.org/pkg/database/sql/) interface by simply introducing the driver.

Use `taosRestful` as `driverName` and use a correct [DSN](#DSN) as `dataSourceName` with the following parameters supported by the DSN.

* `disableCompression` whether to accept compressed data, default is true do not accept compressed data, set to false if transferring data using gzip compression.
* `readBufferSize` The default size of the buffer for reading data is 4K (4096), which can be adjusted upwards when the query result has a lot of data.

D
danielclow 已提交
157
For example:
158 159 160 161 162 163 164 165

```go
package main

import (
    "database/sql"
    "fmt"

D
danielclow 已提交
166
    _ "github.com/taosdata/driver-go/v3/taosRestful"
167 168 169 170 171
)

func main() {
    var taosUri = "root:taosdata@http(localhost:6041)/"
    taos, err := sql.Open("taosRestful", taosUri)
D
danielclow 已提交
172
    if err != nil {
173 174 175 176 177 178
        fmt.Println("failed to connect TDengine, err:", err)
        return
    }
}
```
</TabItem>
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 208 209
<TabItem value="WebSocket" label="WebSocket connection">

_taosRestful_ implements Go's `database/sql/driver` interface via `http client`. You can use the [`database/sql`](https://golang.org/pkg/database/sql/) interface by simply introducing the driver (driver-go minimum version 3.0.2).

Use `taosWS` as `driverName` and use a correct [DSN](#DSN) as `dataSourceName` with the following parameters supported by the DSN.

* `writeTimeout` The timeout to send data via WebSocket.
* `readTimeout` The timeout to receive response data via WebSocket.

For example:

```go
package main

import (
    "database/sql"
    "fmt"

    _ "github.com/taosdata/driver-go/v3/taosWS"
)

func main() {
    var taosUri = "root:taosdata@ws(localhost:6041)/"
    taos, err := sql.Open("taosWS", taosUri)
    if err != nil {
        fmt.Println("failed to connect TDengine, err:", err)
        return
    }
}
```
</TabItem>
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
</Tabs>

## Usage examples

### Write data

#### SQL Write

<GoInsert />

#### InfluxDB line protocol write

<GoInfluxLine />

#### OpenTSDB Telnet line protocol write

<GoOpenTSDBTelnet />

#### OpenTSDB JSON line protocol write

<GoOpenTSDBJson />

### Query data

<GoQuery />

### More sample programs

D
danielclow 已提交
238 239
* [sample program](https://github.com/taosdata/driver-go/tree/3.0/examples)

240 241 242 243 244

## Usage limitations

Since the REST interface is stateless, the `use db` syntax will not work. You need to put the db name into the SQL command, e.g. `create table if not exists tb1 (ts timestamp, a int)` to `create table if not exists test.tb1 (ts timestamp, a int)` otherwise it will report the error `[0x217] Database not specified or available`.

D
danielclow 已提交
245
You can also put the db name in the DSN by changing `root:taosdata@http(localhost:6041)/` to `root:taosdata@http(localhost:6041)/test`. Executing the `create database` statement when the specified db does not exist will not report an error while executing other queries or writing against that db will report an error.
246 247 248 249 250 251 252 253 254 255 256

The complete example is as follows.

```go
package main

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

D
danielclow 已提交
257
    _ "github.com/taosdata/driver-go/v3/taosRestful"
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
)

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

## Frequently Asked Questions

D
danielclow 已提交
299
1. bind interface in database/sql crashes
300 301 302

  REST does not support parameter binding related interface. It is recommended to use `db.Exec` and `db.Query`.

D
danielclow 已提交
303
2. error `[0x217] Database not specified or available` after executing other statements with `use db` statement
304 305 306

  The execution of SQL command in the REST interface is not contextual, so using `use db` statement will not work, see the usage restrictions section above.

D
danielclow 已提交
307
3. use `taosSql` without error but use `taosRestful` with error `[0x217] Database not specified or available`
308 309 310

  Because the REST interface is stateless, using the `use db` statement will not take effect. See the usage restrictions section above.

D
danielclow 已提交
311
4. `readBufferSize` parameter has no significant effect after being increased
312

313
  Increasing `readBufferSize` will reduce the number of `syscall` calls when fetching results. If the query result is smaller, modifying this parameter will not improve performance significantly. If you increase the parameter value too much, the bottleneck will be parsing JSON data. If you need to optimize the query speed, you must adjust the value based on the actual situation to achieve the best query performance.
314

D
danielclow 已提交
315
5. `disableCompression` parameter is set to `false` when the query efficiency is reduced
316 317 318

  When set `disableCompression` parameter to `false`, the query result will be compressed by `gzip` and then transmitted, so you have to decompress the data by `gzip` after getting it.

D
danielclow 已提交
319
6. `go get` command can't get the package, or timeout to get the package
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

  Set Go proxy `go env -w GOPROXY=https://goproxy.cn,direct`.

## Common APIs

### database/sql API

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

  Use This API to open a DB, returning an object of type \*DB.

:::info
This API is created successfully without checking permissions, but only when you execute a Query or Exec, and check if user/password/host/port is legal.
:::

D
danielclow 已提交
335
* `func (db *DB) Exec(query string, args ...interface{}) (Result, error)`
336 337 338

  `sql.Open` built-in method to execute non-query related SQL.

D
danielclow 已提交
339
* `func (db *DB) Query(query string, args ...interface{}) (*Rows, error)`
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356

  `sql.Open` Built-in method to execute query statements.

### Advanced functions (af) API

The `af` package encapsulates TDengine advanced functions such as connection management, subscriptions, schemaless, parameter binding, etc.

#### Connection management

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

  This API creates a connection to taosd via cgo.

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

  Closes the connection.

357
#### Subscribe
358

359
* `func NewConsumer(conf *tmq.ConfigMap) (*Consumer, error)`
D
danielclow 已提交
360 361 362

Creates consumer group.

363 364 365 366 367 368 369
* `func (c *Consumer) Subscribe(topic string, rebalanceCb RebalanceCb) error`
Note: `rebalanceCb` is reserved for compatibility purpose

Subscribes a topic.

* `func (c *Consumer) SubscribeTopics(topics []string, rebalanceCb RebalanceCb) error`
Note: `rebalanceCb` is reserved for compatibility purpose
D
danielclow 已提交
370

371
Subscribes to topics.
D
danielclow 已提交
372

373
* `func (c *Consumer) Poll(timeoutMs int) tmq.Event`
374

D
danielclow 已提交
375
Polling information.
376

377 378
* `func (c *Consumer) Commit() ([]tmq.TopicPartition, error)`
Note: `tmq.TopicPartition` is reserved for compatibility purpose
379

D
danielclow 已提交
380
Commit information.
381

382 383 384 385 386 387 388 389 390
* `func (c *Consumer) Assignment() (partitions []tmq.TopicPartition, err error)`

Get Assignment(TDengine >= 3.0.5.0 and driver-go >= v3.5.0 are required).

* `func (c *Consumer) Seek(partition tmq.TopicPartition, ignoredTimeoutMs int) error`
Note: `ignoredTimeoutMs` is reserved for compatibility purpose

Seek offset(TDengine >= 3.0.5.0 and driver-go >= v3.5.0 are required).

D
danielclow 已提交
391 392 393 394 395 396 397
* `func (c *Consumer) Unsubscribe() error`

Unsubscribe.

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

Close consumer.
398 399 400 401 402

#### schemaless

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

403
  Write to InfluxDB line protocol.
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418

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

  Write OpenTDSB telnet protocol data.

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

  Writes OpenTSDB JSON protocol data.

#### parameter binding

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

  Parameter bound single row insert.

D
danielclow 已提交
419
* `func (conn *Connector) InsertStmt() *insertstmt.InsertStmt`
420 421 422 423 424 425 426 427 428

  Initialize the parameters.

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

  Parameter binding preprocessing SQL statement.

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

429
  Bind the table name parameter.
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454

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

  Parameter binding to set the sub table name.

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

  Parameter bind multiple rows of data.

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

  Add to a parameter-bound batch.

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

  Execute a parameter binding.

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

  Gets the number of affected rows inserted by the parameter binding.

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

  Closes the parameter binding.

455 456
### Subscribe via WebSocket

457
* `func NewConsumer(conf *tmq.ConfigMap) (*Consumer, error)`
458

459 460 461 462
Creates consumer group.

* `func (c *Consumer) Subscribe(topic string, rebalanceCb RebalanceCb) error`
Note: `rebalanceCb` is reserved for compatibility purpose
463

464
Subscribes a topic.
465

466 467
* `func (c *Consumer) SubscribeTopics(topics []string, rebalanceCb RebalanceCb) error`
Note: `rebalanceCb` is reserved for compatibility purpose
468

469
Subscribes to topics.
470

471
* `func (c *Consumer) Poll(timeoutMs int) tmq.Event`
472

473
Polling information.
474

475 476 477 478 479
* `func (c *Consumer) Commit() ([]tmq.TopicPartition, error)`
Note: `tmq.TopicPartition` is reserved for compatibility purpose

Commit information.

480 481 482 483 484 485 486 487 488
* `func (c *Consumer) Assignment() (partitions []tmq.TopicPartition, err error)`

Get Assignment(TDengine >= 3.0.5.0 and driver-go >= v3.5.0 are required).

* `func (c *Consumer) Seek(partition tmq.TopicPartition, ignoredTimeoutMs int) error`
Note: `ignoredTimeoutMs` is reserved for compatibility purpose

Seek offset(TDengine >= 3.0.5.0 and driver-go >= v3.5.0 are required).

489 490 491
* `func (c *Consumer) Unsubscribe() error`

Unsubscribe.
492 493 494

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

495
Close consumer.
496

497
For a complete example see [GitHub sample file](https://github.com/taosdata/driver-go/blob/main/examples/tmqoverws/main.go)
498

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
### parameter binding via WebSocket

* `func NewConnector(config *Config) (*Connector, error)`

  Create a connection.

* `func (c *Connector) Init() (*Stmt, error)`

  Initialize the parameters.

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

  Close the connection.

* `func (s *Stmt) Prepare(sql string) error`

  Parameter binding preprocessing SQL statement.

* `func (s *Stmt) SetTableName(name string) error`

  Bind the table name parameter.

* `func (s *Stmt) SetTags(tags *param.Param, bindType *param.ColumnType) error`

  Set tags.

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

  Parameter bind multiple rows of data.

* `func (s *Stmt) AddBatch() error`

  Add to a parameter-bound batch.

* `func (s *Stmt) Exec() error`

  Execute a parameter binding.

* `func (s *Stmt) GetAffectedRows() int`

  Gets the number of affected rows inserted by the parameter binding.

* `func (s *Stmt) Close() error`

  Closes the parameter binding.

545
For a complete example see [GitHub sample file](https://github.com/taosdata/driver-go/blob/main/examples/stmtoverws/main.go)
546

547 548
## API Reference

D
danielclow 已提交
549
Full API see [driver-go documentation](https://pkg.go.dev/github.com/taosdata/driver-go/v3)