Go Client Library
driver-go is the official Go language connector for TDengine, implementing the interface of the Go language database/sql package. Go developers can use it to develop applications that access data in the TDengine cluster.
Go's native connection and REST connection are deprecated and will be discontinued on 2027-01-01, please migrate to WebSocket connection.
For detailed migration guide, please refer to: Connection Methods
Go Version Compatibility
Supports Go 1.14 and above.
Supported Platforms
- Native connections support the same platforms as the TDengine client driver.
- WebSocket connections support all platforms that can run Go.
Version History
| driver-go Version | Major Changes | TDengine Version |
|---|---|---|
| v3.8.0 | Introduce ws/unified as the unified WebSocket interface; support multi-endpoint DSN, auto reconnect, and failover; ws/stmt and ws/schemaless are marked as deprecated since this version. | - |
| v3.7.8 | WebSocket connections support both two-factor authentication and token authentication. | - |
| v3.7.7 | Fix WebSocket connection crash caused by race condition. | - |
| v3.7.6 | Fix native connection stmt2 binding empty string and empty byte array crash. | - |
| v3.7.5 | Fix native connection failures on Windows. | - |
| v3.7.4 | Support for connection-level time zone settings. | - |
| v3.7.3 | Fix crash when WebSocket connection STMT query results contain decimal data. | - |
| v3.7.2 | support BLOB type. | - |
| v3.7.1 | support IPv6 connection. | - |
| v3.7.0 | support decimal type. | 3.3.6.0 and higher |
| v3.6.0 | stmt2 native interface, DSN supports passwords containing special characters (url.QueryEscape). | 3.3.5.0 and higher |
| v3.5.8 | Fixed null pointer exception. | - |
| v3.5.7 | taosWS and taosRestful support passing request id. | - |
| v3.5.6 | Improved WebSocket query and insert performance. | 3.3.2.0 and higher |
| v3.5.5 | Restful supports skipping SSL certificate check. | - |
| v3.5.4 | Compatible with TDengine 3.3.0.0 tmq raw data. | - |
| v3.5.3 | Refactored taosWS. | - |
| v3.5.2 | WebSocket compression and optimized tmq subscription performance. | 3.2.3.0 and higher |
| v3.5.1 | Native stmt query and geometry type support. | 3.2.1.0 and higher |
| v3.5.0 | Support tmq get assignment and seek offset. | 3.0.5.0 and higher |
| v3.3.1 | Schemaless protocol insert based on WebSocket. | 3.0.4.1 and higher |
| v3.1.0 | Provided Kafka-like subscription API. | - |
| v3.0.4 | Added request id related interfaces. | 3.0.2.2 and higher |
| v3.0.3 | WebSocket-based statement insert. | - |
| v3.0.2 | WebSocket-based data query and insert. | 3.0.1.5 and higher |
| v3.0.1 | WebSocket-based message subscription. | - |
| v3.0.0 | Adapted to TDengine 3.0 query and insert. | 3.0.0.0 and higher |
Exceptions and Error Codes
If it is a TDengine error, you can obtain the error code and error message as follows.
// import "github.com/taosdata/driver-go/v3/errors"
if err != nil {
tError, is := err.(*errors.TaosError)
if is {
fmt.Println("errorCode:", int(tError.Code))
fmt.Println("errorMessage:", tError.ErrStr)
} else {
fmt.Println(err.Error())
}
}
For errors in other TDengine modules, please refer to Error Codes.
Data Type Mapping
| TDengine DataType | Go Type |
|---|---|
| TIMESTAMP | time.Time |
| TINYINT | int8 |
| SMALLINT | int16 |
| INT | int32 |
| BIGINT | int64 |
| TINYINT UNSIGNED | uint8 |
| SMALLINT UNSIGNED | uint16 |
| INT UNSIGNED | uint32 |
| BIGINT UNSIGNED | uint64 |
| FLOAT | float32 |
| DOUBLE | float64 |
| BOOL | bool |
| BINARY | string |
| NCHAR | string |
| JSON | []byte |
| GEOMETRY | []byte |
| VARBINARY | []byte |
| DECIMAL | string |
| BLOB | []byte |
Note: The JSON type is only supported in tags. The GEOMETRY type is binary data in little endian byte order, conforming to the WKB standard. For more details, please refer to Data Types For the WKB standard, please refer to Well-Known Binary (WKB).
Example Programs Summary
For the source code of the example programs, please refer to: Example Programs.
Frequently Asked Questions
-
Crashes related to stmt (parameter binding) interfaces in database/sql
REST does not support interfaces related to parameter binding, it is recommended to use
db.Execanddb.Query. -
Error
[0x217] Database not specified or availableoccurs after executing other statements following theuse dbstatementIn the REST interface, the execution of SQL statements has no context association, and the
use dbstatement will not take effect. See the usage restrictions section above for solutions. -
No error with taosSql but error
[0x217] Database not specified or availablewith taosRestfulSince the REST interface is stateless, the
use dbstatement will not take effect. See the usage restrictions section above for solutions. -
No significant effect after increasing the
readBufferSizeparameterIncreasing
readBufferSizewill reduce the number ofsyscallcalls when fetching results. If the data volume of the query results is not large, modifying this parameter will not bring significant improvement. If this parameter is increased too much, the bottleneck will be in parsing JSON data. To optimize query speed, adjust this value according to the actual situation to achieve the best query effect. -
Query efficiency decreases when
disableCompressionparameter is set tofalseWhen the
disableCompressionparameter is set tofalse, the query results will be transmitted after being compressed withgzip, and the data must be decompressed withgzipafter being received. -
go getcommand cannot fetch packages, or fetching packages times outSet the Go proxy
go env -w GOPROXY=https://goproxy.cn,direct. -
Timezone Handling for Query Results
For WebSocket and native connections, the query results use time.Unix to convert timestamps to the local timezone.
API Reference
database/sql Driver
driver-go implements the Go database/sql/driver interface, allowing direct use of the Go database/sql package. It provides two drivers: github.com/taosdata/driver-go/v3/taosSql and github.com/taosdata/driver-go/v3/taosWS corresponding to native connection and WebSocket connection.
DSN Specification
The Data Source Name has a generic format, similar to PEAR DB, but without the type prefix (brackets indicate optional):
[username[:password]@][protocol[(address)]]/[dbname][?param1=value1&...¶mN=valueN]
Full form of DSN:
username:password@protocol(address)/dbname?param=value
When the password contains special characters, it needs to be escaped using url.QueryEscape.
When using an IPv6 address (supported in v3.7.1 and above), the address needs to be enclosed in square brackets, for example:
root:taosdata@ws([::1]:6041)/testdb
WebSocket Connection
Import the driver:
import (
"database/sql"
_ "github.com/taosdata/driver-go/v3/taosWS"
)
Use taosWS as driverName and use a correct DSN as dataSourceName as follows:
var taosUri = "root:taosdata@ws(localhost:6041)/"
taos, err := sql.Open("taosWS", taosUri)
Supported DSN parameters:
enableCompressionwhether to send compressed data, default is false which means not sending compressed data, set to true if transferring data using compression.readTimeoutthe timeout for reading data, default is 5m.writeTimeoutthe timeout for writing data, default is 10s.timezonespecifies the timezone used for the connection. Both SQL parsing and query results will be converted according to this timezone. Only IANA timezone formats are supported, and special characters need to be encoded. Taking the Shanghai timezone (Asia/Shanghai) as an example:timezone=Asia%2FShanghai.tokenspecifies the token used by cloud services.bearerTokenthe token used for authentication.totpCodethe TOTP code used for two-factor authentication.autoReconnectwhether to enable automatic reconnect, default is false (supported sincev3.8.0).chanLengthmessage channel length, default is 1 (supported sincev3.8.0).reconnectIntervalMsreconnect interval in milliseconds, default is 2000 (supported sincev3.8.0).reconnectRetryCountreconnect retry count, default is 3 (supported sincev3.8.0).
Note: After reconnect succeeds, the current DB on the connection is lost. Specify DB in DSN and avoid switching DB later.
Starting from v3.8.0, multi-endpoint failover is supported:
root:taosdata@ws(node1:6041,node2:6042)/db?autoReconnect=true&reconnectRetryCount=10
Starting from v3.8.0, ws/unified is supported as the unified WebSocket interface. For stmt and schemaless writes over WebSocket, use interfaces in the ws/unified package, for example:
import "github.com/taosdata/driver-go/v3/ws/unified"
taos, err := unified.Open("root:taosdata@ws(localhost:6041,localhost:6042)/")
Native Connection, Deprecated, will be discontinued on 2027-01-01
Import the driver:
import (
"database/sql"
_ "github.com/taosdata/driver-go/v3/taosSql"
)
Use taosSql as driverName and a correct DSN as dataSourceName as follows:
var taosUri = "root:taosdata@tcp(localhost:6030)/"
taos, err := sql.Open("taosSql", taosUri)
Supported DSN parameters:
cfgspecifies the taos.cfg directory.cgoThreadspecifies the number of cgo executions at the same time, default is the number of system cores.cgoAsyncHandlerPoolSizespecifies the size of the async function handle, default is 10000.timezonespecifies the timezone used for the connection. Both SQL parsing and query results will be converted according to this timezone. Only IANA timezone formats are supported, and special characters need to be encoded. Taking the Shanghai timezone (Asia/Shanghai) as an example:timezone=Asia%2FShanghai.
Connection Features
The Go driver supports creating connections, returning objects that support the sql/driver standard Connector interface. It also provides the af package (native connection) and ws/unified (WebSocket connection), and extends interfaces such as schema-less writing.
Standard Interface
Interface for creating connections in the database/sql package
func Open(driverName, dataSourceName string) (*DB, error)- Interface Description: Connect to the database (
database/sql). - Parameter Description:
driverName: Driver name.dataSourceName: Connection parameters DSN.
- Return Value: Connection object, error information.
- Interface Description: Connect to the database (
Extended Interface
Interfaces for creating connections in the af package (native connection, package path: github.com/taosdata/driver-go/v3/af)
-
func Open(host, user, pass, db string, port int) (*Connector, error)- Interface Description: Connect to the database.
- Parameter Description:
host: Host address.user: Username.pass: Password.db: Database name.port: Port number.
- Return Value: Connection object, error information.
-
func (conn *Connector) SetTimezone(timezone string) error- Interface Description: Set connection timezone.
- Parameter Description:
timezone: Timezone string, using the IANA timezone format, for example:Asia/Shanghai.
- Return Value: error information.
Interfaces for creating WebSocket connections in the ws/unified package (WebSocket connection, supported since v3.8.0, package path: github.com/taosdata/driver-go/v3/ws/unified)
func Open(dsn string) (*Client, error)- Interface Description: Open a unified WebSocket connection using DSN.
- Parameter Description:
dsn: Connection DSN. Multi-endpoint addresses are supported.
- Return Value: Unified client object, error information.
Schema-less Writing
Interfaces for schemaless writing in the af package (native connection, package path: github.com/taosdata/driver-go/v3/af).
-
func (conn *Connector) InfluxDBInsertLines(lines []string, precision string) error- Interface Description: Schema-less writing of InfluxDB format data.
- Parameter Description:
lines: Data to write.precision: Time precision.
- Return Value: Error information.
-
func (conn *Connector) OpenTSDBInsertJsonPayload(payload string) error- Interface Description: Schema-less writing of OpenTSDB JSON format data.
- Parameter Description:
payload: Data to write.
- Return Value: Error information.
-
func (conn *Connector) OpenTSDBInsertTelnetLines(lines []string) error- Interface Description: Schema-less writing of OpenTSDB Telnet format data.
- Parameter Description:
lines: Data to write.
- Return Value: Error information.
Schemaless interface in the ws/unified package (WebSocket connection, supported since v3.8.0, package path: github.com/taosdata/driver-go/v3/ws/unified):
func (c *Client) SchemalessInsert(reqID int64, lines string, protocol int, precision string, ttl int, tableNameKey string) error- Interface Description: Recommended WebSocket schemaless write interface.
- Parameter Description:
reqID: Request ID. If set to 0, it will be auto-generated.lines: Data to be written.protocol: Supported protocols for data writing:InfluxDBLineProtocol = 1,OpenTSDBTelnetLineProtocol = 2,OpenTSDBJsonFormatProtocol = 3.precision: Time precision.ttl: Data expiration time, 0 means never expires.tableNameKey: Table-name key. Pass empty string when the protocol does not require it.
- Return Value: Error information.
Schemaless interface in the ws/schemaless package (WebSocket compatibility layer, package path: github.com/taosdata/driver-go/v3/ws/schemaless) (Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified. Use ws/unified Client.SchemalessInsert).
func (s *Schemaless) Insert(lines string, protocol int, precision string, ttl int, reqID int64) error(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Schemaless data insertion.
- Parameter Description:
lines: Data to be written.protocol: Supported protocols for data writing:InfluxDBLineProtocol = 1,OpenTSDBTelnetLineProtocol = 2,OpenTSDBJsonFormatProtocol = 3.precision: Time precision.ttl: Data expiration time, 0 means never expires.reqID: Request ID.
- Return Value: Error information.
Execute SQL
The Go driver provides interfaces compliant with database/sql standards, supporting the following features:
- Execute SQL Statements: Execute static SQL statements and return the resulting object.
- Query Execution: Can execute queries that return data sets (
SELECTstatements). - Update Execution: Can execute SQL statements that affect rows, such as
INSERT,UPDATE,DELETE, etc. - Get Results: Can obtain and traverse the result set returned after query execution.
- Get Update Count: For non-query SQL statements, can obtain the number of rows affected after execution.
- Close Resources: Release database resources.
Standard Interfaces
-
func (db *DB) Close() error- Interface Description: Close the connection.
- Return Value: Error information.
-
func (db *DB) Exec(query string, args ...any) (Result, error)- Interface Description: Execute a query without returning any rows.
- Parameter Description:
query: Command to execute.args: Command arguments.
- Return Value: Result object (only affected rows), error information.
-
func (db *DB) Query(query string, args ...any) (*Rows, error)- Interface Description: Execute a query and return the results as rows.
- Parameter Description:
query: Command to execute.args: Command arguments.
- Return Value: Rows object, error information.
-
func (db *DB) QueryRow(query string, args ...any) *Row- Interface Description: Execute a query and return a single row result.
- Parameter Description:
query: Command to execute.args: Command arguments.
- Return Value: Row object.
Extended Interfaces
-
func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (Result, error)- Interface Description: Execute a query without returning any rows.
- Parameter Description:
ctx: Context, use Value to pass request ID for link tracing, key istaos_req_idvalue is an int64 type.query: Command to execute.args: Command arguments.
- Return Value: Result object (only affected rows), error information.
-
func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)- Interface Description: Execute a query and return the results as rows.
- Parameter Description:
ctx: Context, use Value to pass request ID for link tracing, key istaos_req_idvalue is an int64 type.query: Command to execute.args: Command arguments.
- Return Value: Rows object, error information.
-
func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row- Interface Description: Executes a query and returns a single row result. Errors are deferred until the row is scanned.
- Parameter Description:
ctx: Context, uses Value to pass the request ID for link tracing, key istaos_req_idand value is an int64 type.query: Command to execute.args: Command parameters.
- Return Value: Single row result Row object.
SQL interfaces in the ws/unified package (WebSocket connection, supported since v3.8.0, package path: github.com/taosdata/driver-go/v3/ws/unified):
func (c *Client) Exec(reqID int64, sql string) (int, error)func (c *Client) Query(reqID int64, sql string) (*ResultSet, error)func (r *ResultSet) Next(dest []driver.Value) errorfunc (r *ResultSet) Close() error
Result Retrieval
The Go driver supports retrieving query result sets and corresponding metadata, providing methods to read metadata and data from the result set.
Result Set
Retrieve the query result set through the Rows object, which provides the following methods:
-
func (rs *Rows) Next() bool- Interface Description: Prepares the next row of data.
- Return Value: Whether there is another row of data.
-
func (rs *Rows) Columns() ([]string, error)- Interface Description: Returns column names.
- Return Value: Column names, error information.
-
func (rs *Rows) Scan(dest ...any) error- Interface Description: Copies the current row's column values into the values pointed to by dest.
- Parameter Description:
dest: Target values.
- Return Value: Error information.
-
func (rs *Rows) Close() error- Interface Description: Closes the rows.
- Return Value: Error information.
-
func (r *Row) Scan(dest ...any) error- Interface Description: Copies the current row's column values into the values pointed to by dest.
- Parameter Description:
dest: Target values.
- Return Value: Error information.
Retrieve the update result set through the Result object, which provides the following method:
func (dr driverResult) RowsAffected() (int64, error)- Interface Description: Returns the number of rows affected.
- Return Value: Number of rows affected, error information.
Result Set Metadata
Retrieve query result set metadata through the Rows object, providing the following methods:
-
func (rs *Rows) ColumnTypes() ([]*ColumnType, error)- Interface Description: Returns column types.
- Return Value: Column types, error information.
-
func (ci *ColumnType) Name() string- Interface Description: Returns the column name.
- Return Value: Column name.
-
func (ci *ColumnType) Length() (length int64, ok bool)- Interface Description: Returns the column length.
- Return Value: Column length, whether there is a length.
-
func (ci *ColumnType) ScanType() reflect.Type- Interface Description: Returns the Go type corresponding to the column type.
- Return Value: Column type.
-
func (ci *ColumnType) DatabaseTypeName() string- Interface Description: Returns the database name of the column type.
- Return Value: Column type name.
Parameter Binding
Prepare allows the use of precompiled SQL statements, which can improve performance and provide the ability for parameterized queries, thereby increasing security.
Standard Interface
Use the Prepare method in the Conn interface of sql/driver to prepare a statement bound to this connection, returning a Stmt object for use.
-
Prepare(query string) (Stmt, error)- Interface Description: Prepares and returns a statement bound to this connection.
- Parameter Description:
query: Statement for parameter binding.
- Return Value: Stmt object, error information.
-
func (s *Stmt) Exec(args ...any) (Result, error)- Interface Description: Executes the prepared statement with the given parameters and returns a result summarizing the effect of the statement (only column values can be bound, not table names or tags).
- Parameter Description:
args: Command parameters, Go native types are automatically converted to database types, type mismatches may lose precision, it is recommended to use the same type as the database, time types use int64 orRFC3339Nanoformatted strings.
- Return Value: Result object (only affected rows), error information.
-
func (s *Stmt) Query(args ...any) (*Rows, error)- Interface Description: Executes the prepared statement with the given arguments and returns the result rows.
- Parameter Description:
args: Command arguments, Go native types will automatically convert to database types, type mismatches may lose precision, it is recommended to use the same type as the database, time types use int64 orRFC3339Nanoformatted strings.
- Return Value: Result set Rows object, error information.
-
func (s *Stmt) Close() error- Interface Description: Closes the statement.
- Return Value: Error information.
Extended Interfaces
The af package (native connection, package path: github.com/taosdata/driver-go/v3/af) provides more interfaces for parameter binding
-
func (conn *Connector) Stmt() *Stmt- Interface Description: Returns a Stmt object bound to this connection.
- Return Value: Stmt object.
-
func (s *Stmt) Prepare(sql string) error- Interface Description: Prepares an SQL.
- Parameter Description:
sql: The statement for parameter binding.
- Return Value: Error information.
-
func (s *Stmt) NumParams() (int, error)- Interface Description: Returns the number of parameters.
- Return Value: Number of parameters, error information.
-
func (s *Stmt) SetTableNameWithTags(tableName string, tags *param.Param) error- Interface Description: Sets the table name and tags.
- Parameter Description:
tableName: Table name.tags: Tags.
- Return Value: Error information.
-
func (s *Stmt) SetTableName(tableName string) error- Interface Description: Sets the table name.
- Parameter Description:
tableName: Table name.
- Return Value: Error information.
-
func (s *Stmt) BindRow(row *param.Param) error- Interface Description: Binds a row.
- Parameter Description:
row: Row data.
- Return Value: Error information.
-
func (s *Stmt) GetAffectedRows() int- Interface Description: Gets the number of affected rows.
- Return Value: Number of affected rows.
-
func (s *Stmt) AddBatch() error- Interface Description: Adds a batch.
- Return Value: Error information.
-
func (s *Stmt) Execute() error- Interface Description: Executes the batch.
- Return Value: Error information.
-
func (s *Stmt) UseResult() (driver.Rows, error)- Interface Description: Uses the result.
- Return Value: Result set Rows object, error information.
-
func (s *Stmt) Close() error- Interface Description: Closes the statement.
- Return Value: Error information.
From version 3.6.0, the stmt2 interface for binding parameters is provided.
-
func (conn *Connector) Stmt2(reqID int64, singleTableBindOnce bool) *Stmt2- Interface Description: Returns a Stmt2 object bound to this connection.
- Parameter Description:
reqID: Request ID.singleTableBindOnce: Indicates whether a single child table is bound only once during a single execution.
- Return Value: Stmt2 object.
-
func (s *Stmt2) Prepare(sql string) error- Interface Description: Prepares an SQL.
- Parameter Description:
sql: The statement for parameter binding.
- Return Value: Error information.
-
func (s *Stmt2) Bind(params []*stmt.TaosStmt2BindData) error- Interface Description: Binds data to the prepared statement.
- Parameter Description:
params: The data to bind.
- Return Value: Error information.
-
func (s *Stmt2) Execute() error- Interface Description: Executes the batch.
- Return Value: Error information.
-
func (s *Stmt2) GetAffectedRows() int- Interface Description: Gets the number of affected rows (only valid for insert statements).
- Return Value: Number of affected rows.
-
func (s *Stmt2) UseResult() (driver.Rows, error)- Interface Description: Retrieves the result set (only valid for query statements).
- Return Value: Result set Rows object, error information.
-
func (s *Stmt2) Close() error- Interface Description: Closes the statement.
- Return Value: Error information.
Parameter-binding interfaces in the ws/unified package (WebSocket connection, supported since v3.8.0, package path: github.com/taosdata/driver-go/v3/ws/unified):
func (c *Client) InitStmt(reqID int64) (*Stmt, error)- Interface Description: Initialize a stmt2 parameter-binding handle.
- Parameter Description:
reqID: Request ID. If set to 0, it will be auto-generated.
- Return Value: Stmt object, error information.
func (s *Stmt) Prepare(reqID int64, sql string) error- Interface Description: Prepare SQL for parameter binding.
- Parameter Description:
reqID: Request ID. If set to 0, it will be auto-generated.sql: SQL statement for parameter binding.
- Return Value: Error information.
func (s *Stmt) Bind(params []*stmt.TaosStmt2BindData) error- Interface Description: Bind parameters using stmt2 bind data (recommended).
- Parameter Description:
params: Data to bind. Multiple batches are supported for insert statements, while query statements support exactly one batch.
- Return Value: Error information.
func (s *Stmt) Exec(reqID int64) (int, error)- Interface Description: Execute currently bound batches.
- Parameter Description:
reqID: Request ID. If set to 0, it will be auto-generated.
- Return Value: Affected rows, error information.
func (s *Stmt) UseResult(reqID int64) (*ResultSet, error)- Interface Description: Retrieve the result set for parameterized query execution.
- Parameter Description:
reqID: Request ID. If set to 0, it will be auto-generated.
- Return Value: ResultSet object, error information.
func (s *Stmt) Close(reqID int64) error- Interface Description: Close the parameter-binding handle.
- Parameter Description:
reqID: Request ID. If set to 0, it will be auto-generated.
- Return Value: Error information.
param-based compatibility interfaces in the ws/unified package (param.Param / param.ColumnType) should be treated as deprecated migration path. Migrate to Bind(params []*stmt.TaosStmt2BindData) with raw Go types:
func (s *Stmt) SetTableName(name string) error(Deprecated since v3.8.0; marked for removal in a future release; migrate toBind(params []*stmt.TaosStmt2BindData))func (s *Stmt) SetTags(tags *param.Param, bindType *param.ColumnType) error(Deprecated since v3.8.0; marked for removal in a future release; migrate toBind(params []*stmt.TaosStmt2BindData))func (s *Stmt) BindParam(params []*param.Param, bindType *param.ColumnType) error(Deprecated since v3.8.0; marked for removal in a future release; migrate toBind(params []*stmt.TaosStmt2BindData))func (s *Stmt) AddBatch() error(Deprecated since v3.8.0; marked for removal in a future release; migrate toBind(params []*stmt.TaosStmt2BindData))
stmt2 Bind raw type mapping:
| DBType | GoType |
|---|---|
| BOOL | bool |
| TINYINT | int8 |
| SMALLINT | int16 |
| INT | int32 |
| BIGINT | int64 |
| TINYINT UNSIGNED | uint8 |
| SMALLINT UNSIGNED | uint16 |
| INT UNSIGNED | uint32 |
| BIGINT UNSIGNED | uint64 |
| FLOAT | float32 |
| DOUBLE | float64 |
| TIMESTAMP | time.Time |
| BINARY | []byte |
| NCHAR | string/[]byte |
| VARBINARY | []byte |
| GEOMETRY | []byte |
| JSON | []byte |
| DECIMAL/DECIMAL64 | string |
| BLOB | []byte/string |
The ws/stmt package (WebSocket compatibility layer, package path: github.com/taosdata/driver-go/v3/ws/stmt) provides parameter-binding interfaces (Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified. Use ws/unified).
-
func (c *Connector) Init() (*Stmt, error)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Initialization.
- Return Value: Stmt object, error information.
-
func (s *Stmt) Prepare(sql string) error(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Prepares an SQL.
- Parameter Description:
sql: The statement for parameter binding.
- Return Value: Error information.
-
func (s *Stmt) SetTableName(name string) error(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Sets the table name.
- Parameter Description:
name: Table name.
- Return Value: Error information.
-
func (s *Stmt) SetTags(tags *param.Param, bindType *param.ColumnType) error(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set tags.
- Parameter Description:
tags: tag.bindType: Type information.
- Return Value: Error information.
-
func (s *Stmt) BindParam(params []*param.Param, bindType *param.ColumnType) error(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Bind parameters.
- Parameter Description:
params: Parameters.bindType: Type information.
- Return Value: Error information.
-
func (s *Stmt) AddBatch() error(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Add batch processing.
- Return Value: Error information.
-
func (s *Stmt) Exec() error(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Execute batch processing.
- Return Value: Error information.
-
func (s *Stmt) GetAffectedRows() int(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Get the number of affected rows.
- Return Value: Number of affected rows.
-
func (s *Stmt) UseResult() (*Rows, error)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Use result.
- Return Value: Rows object, error information.
-
func (s *Stmt) Close() error(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Close statement.
- Return Value: Error information.
Rows row results refer to the Rows interface in the sql/driver package, providing the following interfaces:
-
func (rs *Rows) Columns() []string- Interface Description: Return column names.
- Return Value: Column names.
-
func (rs *Rows) ColumnTypeDatabaseTypeName(i int) string- Interface Description: Return the database name of the column type.
- Parameter Description:
i: Column index.
- Return Value: Column type name.
-
func (rs *Rows) ColumnTypeLength(i int) (length int64, ok bool)- Interface Description: Return column length.
- Parameter Description:
i: Column index.
- Return Value: Column length, whether there is a length.
-
func (rs *Rows) ColumnTypeScanType(i int) reflect.Type- Interface Description: Return the Go type corresponding to the column type.
- Parameter Description:
i: Column index.
- Return Value: Column type.
-
func (rs *Rows) Next(dest []driver.Value) error- Interface Description: Prepare the next row of data and assign it to the target.
- Parameter Description:
dest: Target values.
- Return Value: Error information.
-
func (rs *Rows) Close() error- Interface Description: Close rows.
- Return Value: Error information.
The common/param package provides parameter-binding data structures (Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified Bind(params []*stmt.TaosStmt2BindData). Use ws/unified Bind(params []*stmt.TaosStmt2BindData) with raw Go types).
Below are the interfaces for setting parameters by offset:
-
func NewParam(size int) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Create a parameter binding data structure.
- Parameter Description:
size: Number of parameters.
- Return Value: Param object.
-
func (p *Param) SetBool(offset int, value bool)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set a boolean value.
- Parameter Description:
offset: Offset (column or tag).value: Boolean value.
-
func (p *Param) SetNull(offset int)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set a null value.
- Parameter Description:
offset: Offset (column or tag).
-
func (p *Param) SetTinyint(offset int, value int)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set Tinyint value.
- Parameter Description:
offset: Offset (column or tag).value: Tinyint value.
-
func (p *Param) SetSmallint(offset int, value int)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set Smallint value.
- Parameter Description:
offset: Offset (column or tag).value: Smallint value.
-
func (p *Param) SetInt(offset int, value int)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set Int value.
- Parameter Description:
offset: Offset (column or tag).value: Int value.
-
func (p *Param) SetBigint(offset int, value int)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set Bigint value.
- Parameter Description:
offset: Offset (column or tag).value: Bigint value.
-
func (p *Param) SetUTinyint(offset int, value uint)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set UTinyint value.
- Parameter Description:
offset: Offset (column or tag).value: UTinyint value.
-
func (p *Param) SetUSmallint(offset int, value uint)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set USmallint value.
- Parameter Description:
offset: Offset (column or tag).value: USmallint value.
-
func (p *Param) SetUInt(offset int, value uint)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set UInt value.
- Parameter Description:
offset: Offset (column or tag).value: UInt value.
-
func (p *Param) SetUBigint(offset int, value uint)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set UBigint value.
- Parameter Description:
offset: Offset (column or tag).value: UBigint value.
-
func (p *Param) SetFloat(offset int, value float32)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set Float value.
- Parameter Description:
offset: Offset (column or tag).value: Float value.
-
func (p *Param) SetDouble(offset int, value float64)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set Double value.
- Parameter Description:
offset: Offset (column or tag).value: Double value.
-
func (p *Param) SetBinary(offset int, value []byte)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set Binary value.
- Parameter Description:
offset: Offset (column or tag).value: Binary value.
-
func (p *Param) SetVarBinary(offset int, value []byte)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set VarBinary value.
- Parameter Description:
offset: Offset (column or tag).value: VarBinary value.
-
func (p *Param) SetNchar(offset int, value string)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Set Nchar value.
- Parameter Description:
offset: Offset (column or tag).value: Nchar value.
-
func (p *Param) SetTimestamp(offset int, value time.Time, precision int)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Sets the Timestamp value.
- Parameter Description:
offset: Offset (column or tag).value: Timestamp value.precision: Time precision.
-
func (p *Param) SetJson(offset int, value []byte)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Sets the Json value.
- Parameter Description:
offset: Offset (column or tag).value: Json value.
-
func (p *Param) SetGeometry(offset int, value []byte)(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Sets the Geometry value.
- Parameter Description:
offset: Offset (column or tag).value: Geometry value.
Below are the interfaces for setting parameters via chain calls (Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified):
func (p *Param) AddBool(value bool) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)- Interface Description: Adds a boolean value.
- Parameter Description:
value: Boolean value.
- Return Value: Param object.
Other types similar to boolean are as follows (all Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified):
func (p *Param) AddNull() *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddTinyint(value int) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddSmallint(value int) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddInt(value int) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddBigint(value int) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddUTinyint(value uint) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddUSmallint(value uint) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddUInt(value uint) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddUBigint(value uint) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddFloat(value float32) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddDouble(value float64) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddBinary(value []byte) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddVarBinary(value []byte) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddNchar(value string) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddTimestamp(value time.Time, precision int) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddJson(value []byte) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)func (p *Param) AddGeometry(value []byte) *Param(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified)
Below are the interfaces for setting column type information (Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified Bind(params []*stmt.TaosStmt2BindData)):
-
func NewColumnType(size int) *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))- Interface Description: Creates a column type information data structure.
- Parameter Description:
size: Number of columns.
- Return Value: ColumnType object.
-
func (c *ColumnType) AddBool() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))- Interface Description: Adds a boolean type.
- Return Value: ColumnType object.
Other types similar to boolean are as follows (all Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unified Bind(params []*stmt.TaosStmt2BindData)):
func (c *ColumnType) AddTinyint() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddSmallint() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddInt() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddBigint() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddUTinyint() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddUSmallint() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddUInt() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddUBigint() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddFloat() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddDouble() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddBinary(strMaxLen int) *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddVarBinary(strMaxLen int) *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddNchar(strMaxLen int) *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddTimestamp() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddJson(strMaxLen int) *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddGeometry(strMaxLen int) *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddDecimal() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))func (c *ColumnType) AddBlob() *ColumnType(Deprecated since v3.8.0; marked for removal in a future release; migrate to ws/unifiedBind(params []*stmt.TaosStmt2BindData))
Data Subscription
The Go driver supports data subscription features, providing interfaces for data subscription via native connections and WebSocket connections. Native implementation is in the af/tmq package, WebSocket implementation is in the ws/tmq package.
Consumer
func NewConsumer(conf *tmq.ConfigMap) (*Consumer, error)- Interface Description: Creates a consumer.
- Parameter Description:
conf: Configuration information.
- Return Value: Consumer object, error information.
Configuration information is defined as:
type ConfigValue interface{}
type ConfigMap map[string]ConfigValue
Creating a consumer supports the following properties:
ws.url: WebSocket connection URL. Starting fromv3.8.0, multi-endpoint failover is supported, for example:ws://node1:6041,ws://node2:6041.ws.message.channelLen: WebSocket message channel buffer length, default 0.ws.message.timeout: WebSocket message timeout, default 5m.ws.message.writeWait: WebSocket message write timeout, default 10s.ws.message.enableCompression: Whether WebSocket compression is enabled, default false.ws.autoReconnect: Whether WebSocket automatically reconnects, default false.ws.reconnectIntervalMs: WebSocket reconnect interval in milliseconds, default 2000.ws.reconnectRetryCount: WebSocket reconnect retry count, default 3.timezone: The timezone used for parsing time-type data in subscription results, using the IANA timezone format, e.g.,Asia/Shanghai(supported in v3.7.4 and above).
Starting from v3.8.0, multi-endpoint failover is supported. The following example enables automatic reconnect:
conf := &tmq.ConfigMap{
"ws.url": "ws://node1:6041,ws://node2:6041",
"ws.autoReconnect": true,
"ws.reconnectIntervalMs": 2000,
"ws.reconnectRetryCount": 10,
}
For other parameters, please refer to: Consumer Parameter List, note that starting from version 3.2.0.0 of the TDengine server, the default value of auto.offset.reset in message subscriptions has changed.
-
func (c *Consumer) Subscribe(topic string, rebalanceCb RebalanceCb) error- Interface Description: Subscribe to a topic.
- Parameter Description:
topic: Topic.rebalanceCb: Rebalance callback (unused).
- Return Value: Error information.
-
func (c *Consumer) SubscribeTopics(topics []string, rebalanceCb RebalanceCb) error- Interface Description: Subscribe to a list of topics.
- Parameter Description:
topics: List of topics.rebalanceCb: Rebalance callback (unused).
- Return Value: Error information.
-
func (c *Consumer) Unsubscribe() error- Interface Description: Unsubscribe.
- Return Value: Error information.
-
func (c *Consumer) Poll(timeoutMs int) tmq.Event- Interface Description: Poll for events.
- Parameter Description:
timeoutMs: Timeout in milliseconds.
- Return Value: Event.
-
func (c *Consumer) Commit() ([]tmq.TopicPartition, error)- Interface Description: Commit offsets.
- Return Value: List of TopicPartition, error information.
-
func (c *Consumer) Assignment() (partitions []tmq.TopicPartition, err error)- Interface Description: Get assignment information.
- Return Value: List of TopicPartition, error information.
-
func (c *Consumer) Seek(partition tmq.TopicPartition, ignoredTimeoutMs int) error- Interface Description: Seek to an offset.
- Parameter Description:
partition: Partition and offset information.ignoredTimeoutMs: Timeout in milliseconds (unused).
- Return Value: Error information.
-
func (c *Consumer) Committed(partitions []tmq.TopicPartition, timeoutMs int) (offsets []tmq.TopicPartition, err error)- Interface Description: Get committed offsets.
- Parameter Description:
partitions: List of partitions.timeoutMs: Timeout in milliseconds.
- Return Value: List of TopicPartition, error information.
-
func (c *Consumer) CommitOffsets(offsets []tmq.TopicPartition) ([]tmq.TopicPartition, error)- Interface Description: Commit offsets.
- Parameter Description:
offsets: List of offsets.
- Return Value: List of TopicPartition, error information.
-
func (c *Consumer) Position(partitions []tmq.TopicPartition) (offsets []tmq.TopicPartition, err error)- Interface Description: Get current offsets.
- Parameter Description:
partitions: List of partitions.
- Return Value: List of TopicPartition, error information.
-
func (c *Consumer) Close() error- Interface Description: Close the consumer.
- Return Value: Error information.
Consumption Records
When Poll returns a tmq.Event event, you can obtain the consumption record or error information by determining the type of tmq.Event. When the type is *tmq.DataMessage, you can get the consumption record.
-
func (m *DataMessage) Topic() string- Interface Description: Get the topic.
- Return Value: Topic.
-
func (m *DataMessage) DBName() string- Interface Description: Get the database name.
- Return Value: Database name.
-
func (m *DataMessage) Offset() Offset- Interface Description: Get the offset.
- Return Value: Offset.
-
func (m *DataMessage) Value() interface{}- Interface Description: Get the value, the specific value is
[]*tmq.data. - Return Value: Consumed value.
- Interface Description: Get the value, the specific value is
Structure of tmq.data:
type Data struct {
TableName string
Data [][]driver.Value
}
- TableName is the table name.
- Data is the data, each element is a row of data, each row of data is an array, and the elements of the array are column values.
When Poll returns a type of tmq.Error, you can use func (e Error) Error() string to get the error information.
Partition Information
When the consumed data type is *tmq.DataMessage, you can obtain partition information from the TopicPartition attribute.
type TopicPartition struct {
Topic *string
Partition int32
Offset Offset
Metadata *string
Error error
}
Topic: Topic.Partition: Partition.Offset: Offset.Metadata: Metadata (unused).Error: Error information.
You can use func (p TopicPartition) String() string to get partition information.
Offset Metadata
The offset information obtained from TopicPartition can be accessed through the Offset attribute. When the offset is -2147467247, it indicates that the offset is not set.
Deserialization
When the consumed data type is *tmq.DataMessage, you can use func (m *DataMessage) Value() interface{} to get the data, the data type is []*tmq.data.