go.mdx 12.8 KB
Newer Older
D
dingbo 已提交
1 2 3 4 5 6 7
---
toc_max_heading_level: 4
sidebar_position: 4
sidebar_label: Go
title: TDengine Go Connector
---

D
dingbo 已提交
8 9
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
D
dingbo 已提交
10

D
dingbo 已提交
11 12 13 14 15 16
import Preparation from "./_preparation.mdx";
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";
D
dingbo 已提交
17

18
`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.
D
dingbo 已提交
19

20
`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.
D
dingbo 已提交
21

22
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`.
D
dingbo 已提交
23

24
The source code of `driver-go` is hosted on [GitHub](https://github.com/taosdata/driver-go).
D
dingbo 已提交
25

26
## Supported Platforms
D
dingbo 已提交
27

28 29
Native connections are supported on the same platforms as the TDengine client driver.
REST connections are supported on all platforms that can run Go.
D
dingbo 已提交
30

31
## Version support
D
dingbo 已提交
32

33
Please refer to [version support list](/reference/connector#version-support)
D
dingbo 已提交
34

35
## Supported features
D
dingbo 已提交
36

37
### Native connections
D
dingbo 已提交
38

39
A "native connection" is established by the connector directly to the TDengine instance via the TDengine client driver (taosc). The supported functional features are:
D
dingbo 已提交
40

D
dingbo 已提交
41 42 43 44 45
- Normal queries
- Continuous queries
- Subscriptions
- schemaless interface
- parameter binding interface
D
dingbo 已提交
46

47
### REST connection
D
dingbo 已提交
48

49
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
dingbo 已提交
50

D
dingbo 已提交
51 52
- General queries
- Continuous queries
D
dingbo 已提交
53

54
## Installation steps
D
dingbo 已提交
55

56
### Pre-installation
D
dingbo 已提交
57

B
Bo Ding 已提交
58 59
- Install Go development environment (Go 1.14 and above, GCC 4.8.5 and above)
- 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
D
dingbo 已提交
60

61
Configure the environment variables and check the command.
D
dingbo 已提交
62

D
dingbo 已提交
63 64
- `go env`
- `gcc -v`
D
dingbo 已提交
65

66
### Use go get to install
D
dingbo 已提交
67

B
Bo Ding 已提交
68
```
D
dingbo 已提交
69
go get -u github.com/taosdata/driver-go/v2@latest
B
Bo Ding 已提交
70
```
D
dingbo 已提交
71

72
### Manage with go mod
D
dingbo 已提交
73

74
1. Initialize the project with the `go mod` command.
D
dingbo 已提交
75

D
dingbo 已提交
76 77 78
```text
go mod init taos-demo
```
D
dingbo 已提交
79

80
2. Introduce taosSql
D
dingbo 已提交
81

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

89
3. Update the dependency packages with `go mod tidy`.
D
dingbo 已提交
90

D
dingbo 已提交
91 92 93
```text
go mod tidy
```
D
dingbo 已提交
94

95
4. Run the program with `go run taos-demo` or compile the binary with the `go build` command.
D
dingbo 已提交
96

D
dingbo 已提交
97 98 99 100
```text
go run taos-demo
go build
```
D
dingbo 已提交
101

102
## Create a connection
D
dingbo 已提交
103

104
### Data source name (DSN)
D
dingbo 已提交
105

106
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):
D
dingbo 已提交
107

D
dingbo 已提交
108
```text
109
[username[:password]@][protocol[(address)]]/[dbname][?param1=value1&... &paramN=valueN]
D
dingbo 已提交
110 111
```

112
DSN in full form.
D
dingbo 已提交
113 114 115 116

```text
username:password@protocol(address)/dbname?param=value
```
117 118

### Connecting via connector
D
dingbo 已提交
119 120

<Tabs defaultValue="native">
121
<TabItem value="native" label="native connection">
D
dingbo 已提交
122

123
_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.
D
dingbo 已提交
124

125
Use `taosSql` as `driverName` and use a correct [DSN](#DSN) as `dataSourceName`, DSN supports the following parameters.
D
dingbo 已提交
126

D
dingbo 已提交
127
- configPath specifies the `taos.cfg` directory
D
dingbo 已提交
128

129
Example.
D
dingbo 已提交
130 131 132 133 134 135 136 137 138 139 140 141

```go
package main

import (
    "database/sql"
    "fmt"

    _ "github.com/taosdata/driver-go/v2/taosSql"
)

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

151
</TabItem>
152
<TabItem value="rest" label="REST connection">
D
dingbo 已提交
153

154
_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.
D
dingbo 已提交
155

156
Use `taosRestful` as `driverName` and use a correct [DSN](#DSN) as `dataSourceName` with the following parameters supported by the DSN.
D
dingbo 已提交
157

D
dingbo 已提交
158 159
- `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
dingbo 已提交
160

161
Example.
D
dingbo 已提交
162 163 164 165 166 167 168 169 170 171 172 173

```go
package main

import (
    "database/sql"
    "fmt"

    _ "github.com/taosdata/driver-go/v2/taosRestful"
)

func main() {
174
    var taosUri = "root:taosdata@http(localhost:6041)/"
D
dingbo 已提交
175
    taos, err := sql.Open("taosRestful", taosUri)
176
    if err ! = nil {
D
dingbo 已提交
177 178 179 180 181
        fmt.Println("failed to connect TDengine, err:", err)
        return
    }
}
```
D
dingbo 已提交
182

D
dingbo 已提交
183 184 185
</TabItem>
</Tabs>

186
## Usage examples
D
dingbo 已提交
187

188
### Write data
D
dingbo 已提交
189

190
#### SQL Write
D
dingbo 已提交
191 192 193

<GoInsert />

194
#### InfluxDB line protocol write
D
dingbo 已提交
195 196 197

<GoInfluxLine />

198
#### OpenTSDB Telnet line protocol write
D
dingbo 已提交
199 200 201

<GoOpenTSDBTelnet />

202
#### OpenTSDB JSON line protocol write
D
dingbo 已提交
203 204 205

<GoOpenTSDBJson />

206
### Query data
D
dingbo 已提交
207 208 209

<GoQuery />

210
### More sample programs
D
dingbo 已提交
211

D
dingbo 已提交
212 213
- [sample program](https://github.com/taosdata/TDengine/tree/develop/examples/go)
- [Video tutorial](https://www.taosdata.com/blog/2020/11/11/1951.html).
D
dingbo 已提交
214

215
## Usage limitations
D
dingbo 已提交
216

217
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
dingbo 已提交
218

219
You can also put the db name in the DSN by changing `root:taosdata@http(localhost:6041)/` to `root:taosdata@http(localhost:6041)/test`. This method is supported by taosAdapter since TDengine 2.4.0.5. 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.
D
dingbo 已提交
220

221
The complete example is as follows.
D
dingbo 已提交
222 223 224 225 226 227 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 269 270

```go
package main

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

    _ "github.com/taosdata/driver-go/v2/taosRestful"
)

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

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

271
## Frequently Asked Questions
D
dingbo 已提交
272

D
dingbo 已提交
273
1. bind interface in database/sql crashes
D
dingbo 已提交
274

D
dingbo 已提交
275
   REST does not support parameter binding related interface. It is recommended to use `db.Exec` and `db.Query`.
D
dingbo 已提交
276

D
dingbo 已提交
277
2. error `[0x217] Database not specified or available` after executing other statements with `use db` statement
D
dingbo 已提交
278

D
dingbo 已提交
279
   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
dingbo 已提交
280

D
dingbo 已提交
281
3. use `taosSql` without error but use `taosRestful` with error `[0x217] Database not specified or available`
D
dingbo 已提交
282

D
dingbo 已提交
283
   Because the REST interface is stateless, using the `use db` statement will not take effect. See the usage restrictions section above.
D
dingbo 已提交
284

D
dingbo 已提交
285
4. Upgrade `github.com/taosdata/driver-go/v2/taosRestful`
D
dingbo 已提交
286

D
dingbo 已提交
287
   Change the `github.com/taosdata/driver-go/v2` line in the `go.mod` file to `github.com/taosdata/driver-go/v2 develop`, then execute `go mod tidy`.
D
dingbo 已提交
288

D
dingbo 已提交
289
5. `readBufferSize` parameter has no significant effect after being increased
D
dingbo 已提交
290

D
dingbo 已提交
291
   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.
D
dingbo 已提交
292

D
dingbo 已提交
293
6. `disableCompression` parameter is set to `false` when the query efficiency is reduced
D
dingbo 已提交
294

D
dingbo 已提交
295
   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
dingbo 已提交
296

D
dingbo 已提交
297
7. `go get` command can't get the package, or timeout to get the package
D
dingbo 已提交
298

D
dingbo 已提交
299
   Set Go proxy `go env -w GOPROXY=https://goproxy.cn,direct`.
D
dingbo 已提交
300

301
## Common APIs
D
dingbo 已提交
302 303 304

### database/sql API

D
dingbo 已提交
305
- `sql.Open(DRIVER_NAME string, dataSourceName string) *DB`
D
dingbo 已提交
306

307
  Use This API to open a DB, returning an object of type \*DB.
D
dingbo 已提交
308

D
dingbo 已提交
309 310
  :::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.
B
Bo Ding 已提交
311

D
dingbo 已提交
312
  :::
D
dingbo 已提交
313

D
dingbo 已提交
314
- `func (db *DB) Exec(query string, args . .interface{}) (Result, error)`
D
dingbo 已提交
315

316
  `sql.Open` built-in method to execute non-query related SQL.
D
dingbo 已提交
317

D
dingbo 已提交
318
- `func (db *DB) Query(query string, args ... . interface{}) (*Rows, error)`
D
dingbo 已提交
319

320
  `sql.Open` Built-in method to execute query statements.
D
dingbo 已提交
321

322
### Advanced functions (af) API
D
dingbo 已提交
323

324
The `af` package encapsulates TDengine advanced functions such as connection management, subscriptions, schemaless, parameter binding, etc.
D
dingbo 已提交
325

326
#### Connection management
D
dingbo 已提交
327

D
dingbo 已提交
328
- `af.Open(host, user, pass, db string, port int) (*Connector, error)`
D
dingbo 已提交
329

330
  This API creates a connection to taosd via cgo.
D
dingbo 已提交
331

D
dingbo 已提交
332
- `func (conn *Connector) Close() error`
D
dingbo 已提交
333

334
  Closes the connection.
D
dingbo 已提交
335

336
#### Subscribe to
D
dingbo 已提交
337

D
dingbo 已提交
338
- `func (conn *Connector) Subscribe(restart bool, topic string, sql string, interval time.Duration) (Subscriber, error)`
D
dingbo 已提交
339

340
  Subscribe to data.
D
dingbo 已提交
341

D
dingbo 已提交
342
- `func (s *taosSubscriber) Consume() (driver.Rows, error)`
D
dingbo 已提交
343

344
  Consume the subscription data, returning the `Rows` structure of the `database/sql/driver` package.
D
dingbo 已提交
345

D
dingbo 已提交
346
- `func (s *taosSubscriber) Unsubscribe(keepProgress bool)`
D
dingbo 已提交
347

348
  Unsubscribe from data.
D
dingbo 已提交
349 350 351

#### schemaless

D
dingbo 已提交
352
- `func (conn *Connector) InfluxDBInsertLines(lines []string, precision string) error`
D
dingbo 已提交
353

354
  Write to influxDB line protocol.
D
dingbo 已提交
355

D
dingbo 已提交
356
- `func (conn *Connector) OpenTSDBInsertTelnetLines(lines []string) error`
D
dingbo 已提交
357

358
  Write OpenTDSB telnet protocol data.
D
dingbo 已提交
359

D
dingbo 已提交
360
- `func (conn *Connector) OpenTSDBInsertJsonPayload(payload string) error`
D
dingbo 已提交
361

362
  Writes OpenTSDB JSON protocol data.
D
dingbo 已提交
363

364
#### parameter binding
D
dingbo 已提交
365

D
dingbo 已提交
366
- `func (conn *Connector) StmtExecute(sql string, params *param.Param) (res driver.Result, err error)`
D
dingbo 已提交
367

368
  Parameter bound single row insert.
D
dingbo 已提交
369

D
dingbo 已提交
370
- `func (conn *Connector) StmtQuery(sql string, params *param.Param) (rows driver.Rows, err error)`
D
dingbo 已提交
371

372
  Parameter bound query that returns the `Rows` structure of the `database/sql/driver` package.
D
dingbo 已提交
373

D
dingbo 已提交
374
- `func (conn *Connector) InsertStmt() *insertstmt.
D
dingbo 已提交
375

376
  Initialize the parameters.
D
dingbo 已提交
377

D
dingbo 已提交
378
- `func (stmt *InsertStmt) Prepare(sql string) error`
D
dingbo 已提交
379

380
  Parameter binding preprocessing SQL statement.
D
dingbo 已提交
381

D
dingbo 已提交
382
- `func (stmt *InsertStmt) SetTableName(name string) error`
D
dingbo 已提交
383

384
  Bind the set table name parameter.
D
dingbo 已提交
385

D
dingbo 已提交
386
- `func (stmt *InsertStmt) SetSubTableName(name string) error`
D
dingbo 已提交
387

388
  Parameter binding to set the sub table name.
D
dingbo 已提交
389

D
dingbo 已提交
390
- `func (stmt *InsertStmt) BindParam(params []*param.Param, bindType *param.ColumnType) error`
D
dingbo 已提交
391

392
  Parameter bind multiple rows of data.
D
dingbo 已提交
393

D
dingbo 已提交
394
- `func (stmt *InsertStmt) AddBatch() error`
D
dingbo 已提交
395

396
  Add to a parameter-bound batch.
D
dingbo 已提交
397

D
dingbo 已提交
398
- `func (stmt *InsertStmt) Execute() error`
D
dingbo 已提交
399

400
  Execute a parameter binding.
D
dingbo 已提交
401

D
dingbo 已提交
402
- `func (stmt *InsertStmt) GetAffectedRows() int`
D
dingbo 已提交
403

404
  Gets the number of affected rows inserted by the parameter binding.
D
dingbo 已提交
405

D
dingbo 已提交
406
- `func (stmt *InsertStmt) Close() error`
D
dingbo 已提交
407

408
  Closes the parameter binding.
D
dingbo 已提交
409

410
## API Reference
D
dingbo 已提交
411

412
Full API see [driver-go documentation](https://pkg.go.dev/github.com/taosdata/driver-go/v2)