Rust Client Library
taos
is the official Rust language connector for TDengine. Rust developers can use it to develop applications that access TDengine databases.
The source code for this Rust connector is hosted on GitHub.
Connection Method
taos
provides two ways to establish a connection. Generally, we recommend using WebSocket connection.
- Native connection, which connects to the TDengine running instance through the TDengine client driver (taosc).
- WebSocket connection, which connects to the TDengine running instance via the WebSocket interface of taosAdapter.
You can specify which connector to use through different "features" (i.e., Cargo keyword features
) (default supports both).
For a detailed introduction to connection methods, please refer to: Connection Methods
Supported Platforms
The platforms supported by native connections are consistent with those supported by the TDengine client driver. WebSocket connections are supported on all platforms that can run Rust.
Version History
Rust Connector Version | TDengine Version | Main Features |
---|---|---|
v0.12.3 | 3.3.0.0 or later | Optimized WebSocket query and insert performance, supported VARBINARY and GEOMETRY types |
v0.12.0 | 3.2.3.0 or later | WS supports compression. |
v0.11.0 | 3.2.0.0 | TMQ function optimization. |
v0.10.0 | 3.1.0.0 | WS endpoint changes. |
v0.9.2 | 3.0.7.0 | STMT: Obtain tag_fields and col_fields under ws. |
v0.8.12 | 3.0.5.0 | Message subscription: Get consumption progress and start consumption from specified progress. |
v0.8.0 | 3.0.4.0 | Supports schemaless writing. |
v0.7.6 | 3.0.3.0 | Supports using req_id in requests. |
v0.6.0 | 3.0.0.0 | Basic functionality. |
Error Handling
After an error occurs, you can obtain the specific information about the error:
match conn.exec(sql) {
Ok(_) => {
Ok(())
}
Err(e) => {
eprintln!("ERROR: {:?}", e);
Err(e)
}
}
Error codes for error messages can be referenced here: Error Codes
Data Type Mapping
TDengine currently supports timestamp, number, character, and boolean types. The corresponding type conversions to Rust are as follows:
TDengine DataType | Rust DataType |
---|---|
TIMESTAMP | Timestamp |
INT | i32 |
BIGINT | i64 |
FLOAT | f32 |
DOUBLE | f64 |
SMALLINT | i16 |
TINYINT | i8 |
BOOL | bool |
BINARY | Vec<u8> |
NCHAR | String |
JSON | serde_json::Value |
VARBINARY | Bytes |
GEOMETRY | Bytes |
Note: JSON type is only supported in tags.
Example Program Summary
For example program source code, please refer to: rust example
Frequently Asked Questions
Please refer to Frequently Asked Questions
API Reference
The Rust connector interfaces are divided into synchronous and asynchronous interfaces, with the synchronous interfaces generally implemented by asynchronous interfaces. The method signatures are basically the same except for the async keyword. This document only provides descriptions of synchronous interfaces for those with the same functionality.
For both WebSocket and native connection methods, there are no differences in the calls of other interfaces except for the DSN used to establish the connection.
Connection Functionality
DSN
TaosBuilder creates a connection builder through a DSN connection description string. The basic structure of the DSN description string is as follows:
<driver>[+<protocol>]://[[<username>:<password>@]<host>:<port>][/<database>][?<p1>=<v1>[&<p2>=<v2>]]
|------|------------|---|-----------|-----------|------|------|------------|-----------------------|
|driver| protocol | | username | password | host | port | database | params |
The meaning of each part is shown in the following table:
- driver: The driver name must be specified to enable the connector to choose how to create the connection. The following driver names are supported:
- taos: Uses the TDengine connector driver, the default is to use the taos driver.
- tmq: Uses TMQ to subscribe to data.
- protocol: Specifies how to establish the connection, for example:
taos+ws://localhost:6041
specifies that the connection is established using WebSocket.- http/ws: Creates a connection using WebSocket.
- https/wss: Indicates SSL/TLS connection when establishing a connection using WebSocket.
- username/password: The username and password used to create the connection.
- host/port: Specifies the server and port for creating the connection. When the server address and port are not specified (
taos://
), the native connection defaults tolocalhost:6030
, and the WebSocket connection defaults tolocalhost:6041
. - database: Specifies the default database name for the connection, optional parameter.
- params: Other optional parameters.
An example of a complete DSN description string is: taos+ws://localhost:6041/test
, indicating a connection to the server localhost
via port 6041
using WebSocket (ws
), and specifying the default database as test
.
TaosBuilder
The TaosBuilder struct mainly provides methods for constructing Taos objects based on the DSN, as well as functions for checking the connection and obtaining the client version number.
-
fn available_params() -> &'static [&'static str]
- Interface Description: Retrieves the list of available parameters in the DSN.
- Return Value: Returns a reference to a static string slice containing the available parameter names.
-
fn from_dsn<D: IntoDsn>(dsn: D) -> RawResult<Self>
- Interface Description: Creates a connection using the DSN string without checking the connection.
- Parameter Description:
dsn
: The DSN string or a type convertible to a DSN.
- Return Value: Returns a
RawResult
of the self type if successful, otherwise returns an error.
-
fn client_version() -> &'static str
- Interface Description: Retrieves the client version.
- Return Value: Returns the static string of the client version.
-
fn ping(&self, _: &mut Self::Target) -> RawResult<()>
- Interface Description: Checks if the connection is still alive.
- Parameter Description:
_
: A mutable reference to the target connection.
- Return Value: Returns an empty
RawResult
if successful, otherwise returns an error.
-
fn ready(&self) -> bool
- Interface Description: Checks if the connection is ready.
- Return Value: Returns
true
most of the time, indicating that the address is ready for connection.
-
fn build(&self) -> RawResult<Self::Target>
- Interface Description: Creates a new Taos object from this struct.
- Return Value: Returns a
RawResult
of the target connection type if successful, otherwise returns an error.
Executing SQL
SQL execution mainly uses the Taos struct, and obtaining result sets and metadata requires using the ResultSet struct and the Field struct for column information introduced in the next section.
Taos
The Taos struct provides multiple APIs for database operations, including: executing SQL, schemaless writing, and encapsulation of some common database queries (such as creating and retrieving databases).
-
pub fn is_native(&self) -> bool
- Interface Description: Determines whether the connection uses the native protocol.
- Return Value: Returns
true
if the native protocol is used, otherwise returnsfalse
.
-
pub fn is_ws(&self) -> bool
- Interface Description: Determines whether the connection uses the WebSocket protocol.
- Return Value: Returns
true
if the WebSocket protocol is used, otherwise returnsfalse
.
-
fn query<T: AsRef<str>>(&self, sql: T) -> RawResult<Self::ResultSet>
- Interface Description: Executes an SQL query.
- Parameter Description:
sql
: The SQL statement to execute.
- Return Value: Returns the
RawResult
of the result setResultSet
if successful, otherwise returns an error.
-
fn query_with_req_id<T: AsRef<str>>(&self, sql: T, req_id: u64) -> RawResult<Self::ResultSet>
- Interface Description: Executes an SQL query with a request ID.
- Parameter Description:
sql
: The SQL statement to execute.req_id
: The request ID.
- Return Value: Returns the
RawResult
of the result setResultSet
if successful, otherwise returns an error.
-
fn exec<T: AsRef<str>>(&self, sql: T) -> RawResult<usize>
- Interface Description: Executes an SQL statement.
- Parameter Description:
sql
: The SQL statement to execute.
- Return Value: Returns the number of affected rows if successful, otherwise returns an error.
-
fn exec_many<T: AsRef<str>, I: IntoIterator<Item = T>>(&self, input: I) -> RawResult<usize>
- Interface Description: Executes multiple SQL statements.
- Parameter Description:
input
: A collection of SQL statements to execute.
- Return Value: Returns the total number of affected rows if successful, otherwise returns an error.
-
fn query_one<T: AsRef<str>, O: DeserializeOwned>(&self, sql: T) -> RawResult<Option<O>>
- Interface Description: Executes an SQL query and returns a single result.
- Parameter Description:
sql
: The SQL statement to execute.
- Return Value: Returns an optional result object if successful, otherwise returns an error.
-
fn server_version(&self) -> RawResult<Cow<str>>
- Interface Description: Retrieves the server version.
- Return Value: Returns the
RawResult
of the server version string if successful, otherwise returns an error.
-
fn create_topic(&self, name: impl AsRef<str>, sql: impl AsRef<str>) -> RawResult<()>
- Interface Description: Creates a topic.
- Parameter Description:
name
: The topic name.sql
: The associated SQL statement.
- Return Value: Returns an empty
RawResult
if successful, otherwise returns an error.
-
fn databases(&self) -> RawResult<Vec<ShowDatabase>>
- Interface Description: Retrieves the list of databases.
- Return Value: Returns the
RawResult
of the database list if successful, otherwise returns an error.
-
fn topics(&self) -> RawResult<Vec<Topic>>
- Interface Description: Retrieves topic information.
- Return Value: Returns the
RawResult
of the topic list if successful, otherwise returns an error.
-
fn describe(&self, table: &str) -> RawResult<Describe>
- Interface Description: Describes the table structure.
- Parameter Description:
table
: The table name.
- Return Value: Returns the
RawResult
of the table structure description if successful, otherwise returns an error.
-
fn database_exists(&self, name: &str) -> RawResult<bool>
- Interface Description: Checks if the database exists.
- Parameter Description:
name
: The database name.
- Return Value: Returns the
RawResult
of a boolean indicating whether the database exists if successful, otherwise returns an error.
-
fn put(&self, data: &SmlData) -> RawResult<()>
- Interface Description: Writes schemaless data; for the SmlData structure introduction, see below.
- Parameter Description:
data
: The schemaless data.
- Return Value: Returns an empty
RawResult
if successful, otherwise returns an error.
SmlData
The SmlData
struct provides a data structure for schemaless writing, as well as methods to access its properties.
-
pub struct SmlData
- Struct Description: The
SmlData
struct is used to store schemaless data and its related information. - Field Description:
protocol
: Schemaless protocol, supports InfluxDBLine
, OpenTSDBTelnet
, OpenTSDBJson
, three types.precision
: Timestamp precision, supportsHours
,Minutes
,Seconds
,Millisecond
(default),Microsecond
,Nanosecond
.data
: Data list.ttl
: Data lifetime, in seconds.req_id
: Request ID.
- Struct Description: The
-
pub fn protocol(&self) -> SchemalessProtocol
- Interface Description: Get the schemaless protocol.
- Return Value: The schemaless protocol type, supporting InfluxDB
Line
, OpenTSDBTelnet
, OpenTSDBJson
, three types.
-
pub fn precision(&self) -> SchemalessPrecision
- Interface Description: Get the timestamp precision.
- Return Value: The timestamp precision type, supporting
Hours
,Minutes
,Seconds
,Millisecond
(default),Microsecond
,Nanosecond
.
-
pub fn data(&self) -> &Vec<String>
- Interface Description: Get the data list.
- Return Value: A reference to the data list.
-
pub fn ttl(&self) -> Option<i32>
- Interface Description: Get the data lifetime.
- Return Value: Data lifetime (optional), in seconds.
-
pub fn req_id(&self) -> Option<u64>
- Interface Description: Get the request ID.
- Return Value: Request ID (optional).
Result Retrieval
ResultSet
The ResultSet
struct provides several methods for the result set, which can be used to retrieve the data and metadata of the result set.
-
fn affected_rows(&self) -> i32
- Interface Description: Get the number of affected rows.
- Return Value: The number of affected rows, type
i32
.
-
fn precision(&self) -> Precision
- Interface Description: Get precision information.
- Return Value: Precision information, type
Precision
.
-
fn fields(&self) -> &[Field]
- Interface Description: Get field information. See the description of the
Field
struct below. - Return Value: A reference to the array of field information.
- Interface Description: Get field information. See the description of the
-
fn summary(&self) -> (usize, usize)
- Interface Description: Get summary information.
- Return Value: A tuple containing two
usize
types, representing certain statistics.
-
fn num_of_fields(&self) -> usize
- Interface Description: Get the number of fields.
- Return Value: The number of fields, type
usize
.
-
fn blocks(&mut self) -> IBlockIter<'_, Self>
- Interface Description: Get an iterator for the raw data blocks.
- Return Value: An iterator for the raw data blocks, type
IBlockIter<'_, Self>
.
-
fn rows(&mut self) -> IRowsIter<'_, Self>
- Interface Description: Get an iterator for row queries.
- Return Value: An iterator for row queries, type
IRowsIter<'_, Self>
.
-
fn deserialize<T>(&mut self) -> Map<IRowsIter<'_, Self>, fn(_: Result<RowView<'_>, Error>) -> Result<T, Error>>
- Interface Description: Deserialize row data.
- Generic Parameter:
T
: Target type, must implementDeserializeOwned
.
- Return Value: A mapping of deserialization results, type
Map<IRowsIter<'_, Self>, fn(_: Result<RowView<'_>, Error>) -> Result<T, Error>>
.
-
fn to_rows_vec(&mut self) -> Result<Vec<Vec<Value>>, Error>
- Interface Description: Convert the result set to a two-dimensional vector of values.
- Return Value: Returns a two-dimensional vector of values if successful, or an error, type
Result<Vec<Vec<Value>>, Error>
.
Field
The Field
struct provides methods for field information.
-
pub const fn empty() -> Field
- Interface Description: Create an empty
Field
instance. - Return Value: Returns an empty
Field
instance.
- Interface Description: Create an empty
-
pub fn new(name: impl Into<String>, ty: Ty, bytes: u32) -> Field
- Interface Description: Create a new
Field
instance. - Parameter Description:
name
: Field name.ty
: Field type.bytes
: Length of field data.
- Return Value: Returns a new
Field
instance.
- Interface Description: Create a new
-
pub fn name(&self) -> &str
- Interface Description: Get the field name.
- Return Value: Returns the name of the field.
-
pub fn escaped_name(&self) -> String
- Interface Description: Get the escaped field name.
- Return Value: Returns the escaped field name.
-
pub const fn ty(&self) -> Ty
- Interface Description: Get the field type.
- Return Value: Returns the type of the field.
-
pub const fn bytes(&self) -> u32
- Interface Description: Get the preset length of the field.
- Return Value: Returns the preset length for variable-length data types; for other types, returns their byte width.
-
pub fn to_c_field(&self) -> c_field_t
- Interface Description: Convert the
Field
instance to a C language struct. - Return Value: Returns the field represented by the C language struct.
- Interface Description: Convert the
-
pub fn sql_repr(&self) -> String
- Interface Description: Represent the field's data type in SQL.
- Return Value: SQL data type representation, e.g., "INT", "VARCHAR(100)", etc.
Parameter Binding
The parameter binding functionality is mainly supported by the Stmt
struct.
Stmt
The Stmt
struct provides functionality related to parameter binding for efficient writing.
-
fn init(taos: &Q) -> RawResult<Self>
- Interface Description: Initialize the parameter binding instance.
- Parameter Description:
taos
: Database connection instance.
- Return Value: Returns the initialized instance if successful, otherwise returns an error.
-
fn init_with_req_id(taos: &Q, req_id: u64) -> RawResult<Self>
- Interface Description: Initializes the parameter binding instance using a request ID.
- Parameter Description:
taos
: Database connection instance.req_id
: Request ID.
- Return Value: Returns the initialized instance if successful, otherwise returns an error.
-
fn prepare<S: AsRef<str>>(&mut self, sql: S) -> RawResult<&mut Self>
- Interface Description: Prepare the SQL statement to be bound.
- Parameter Description:
sql
: The SQL statement to prepare.
- Return Value: Returns a mutable reference to itself if successful, otherwise returns an error.
-
fn set_tbname<S: AsRef<str>>(&mut self, name: S) -> RawResult<&mut Self>
- Interface Description: Set the table name.
- Parameter Description:
name
: Table name.
- Return Value: Returns a mutable reference to itself if successful, otherwise returns an error.
-
fn set_tags(&mut self, tags: &[Value]) -> RawResult<&mut Self>
- Interface Description: Set the tags.
- Parameter Description:
tags
: Array of tags.
- Return Value: Returns a mutable reference to itself if successful, otherwise returns an error.
-
fn set_tbname_tags<S: AsRef<str>>(&mut self, name: S, tags: &[Value]) -> RawResult<&mut Self>
- Interface Description: Set the table name and tags.
- Parameter Description:
name
: Table name.tags
: Array of tags.
- Return Value: Returns a mutable reference to itself if successful, otherwise returns an error.
-
fn bind(&mut self, params: &[ColumnView]) -> RawResult<&mut Self>
- Interface Description: Bind parameters.
- Parameter Description:
params
: Array of parameters.
- Return Value: Returns a mutable reference to itself if successful, otherwise returns an error.
-
fn add_batch(&mut self) -> RawResult<&mut Self>
- Interface Description: Add a batch.
- Return Value: Returns a mutable reference to itself if successful, otherwise returns an error.
-
fn execute(&mut self) -> RawResult<usize>
- Interface Description: Execute the statement.
- Return Value: Returns the number of affected rows if successful, otherwise returns an error.
-
fn affected_rows(&self) -> usize
- Interface Description: Get the number of affected rows.
- Return Value: The number of affected rows.
Data Subscription
Data subscription mainly involves three structs, providing functionality for creating a consumer object via TmqBuilder
, consuming data and committing offsets via Consumer
, and offset information via Offset
.
TmqBuilder
Similar to TaosBuilder
, TmqBuilder
provides functionality for creating consumer objects.
-
fn available_params() -> &'static [&'static str]
- Interface Description: Get the list of available parameters in the DSN.
- Return Value: Returns a reference to a static string slice containing the available parameter names.
-
fn from_dsn<D: IntoDsn>(dsn: D) -> RawResult<Self>
- Interface Description: Creates a connection using the DSN string without checking the connection.
- Parameter Description:
dsn
: DSN string or a type that can be converted to DSN.
- Return Value: Returns a
RawResult
of the self type if successful, otherwise returns an error.
-
fn client_version() -> &'static str
- Interface Description: Get the client version.
- Return Value: Returns a static string of the client version.
-
fn ping(&self, conn: &mut Self::Target) -> RawResult<()>
- Interface Description: Checks whether the connection is still alive.
- Parameter Description:
conn
: A mutable reference to the target connection.
- Return Value: Returns an empty
RawResult
if successful, otherwise returns an error.
-
fn ready(&self) -> bool
- Interface Description: Checks if the connection is ready.
- Return Value: Generally returns
true
, indicating that the address is ready to connect.
-
fn build(&self) -> RawResult<Self::Target>
- Interface Description: Creates a new connection from this struct.
- Return Value: Returns a
RawResult
of the target connection type if successful, otherwise returns an error.
Consumer
The Consumer
struct provides functionalities related to subscription, including subscribing, receiving messages, committing offsets, setting offsets, and more.
-
fn subscribe<T: Into<String>, I: IntoIterator<Item = T> + Send>(&mut self, topics: I) -> RawResult<()>
- Interface Description: Subscribes to a series of topics.
- Parameter Description:
topics
: The list of topics to subscribe to.
- Return Value: Returns an empty
RawResult
if successful, otherwise returns an error.
-
fn recv_timeout(&self, timeout: Timeout) -> RawResult<Option<(Self::Offset, MessageSet<Self::Meta, Self::Data>)>>
- Interface Description: Receives messages within the specified timeout.
- Parameter Description:
timeout
: The timeout duration.
- Return Value: Returns messages if successful, otherwise returns an error.
-
fn commit(&self, offset: Self::Offset) -> RawResult<()>
- Interface Description: Commits the specified offset.
- Parameter Description:
offset
: The offset to commit, see theOffset
struct below.
- Return Value: Returns an empty
RawResult
if successful, otherwise returns an error.
-
fn commit_offset(&self, topic_name: &str, vgroup_id: VGroupId, offset: i64) -> RawResult<()>
- Interface Description: Commits the offset for a specific topic and partition.
- Parameter Description:
topic_name
: The topic name.vgroup_id
: The partition ID.offset
: The offset to commit.
- Return Value: Returns an empty
RawResult
if successful, otherwise returns an error.
-
fn list_topics(&self) -> RawResult<Vec<String>>
- Interface Description: Lists all available topics.
- Return Value: Returns the list of topics if successful, otherwise returns an error.
-
fn assignments(&self) -> Option<Vec<(String, Vec<Assignment>)>>
- Interface Description: Gets the currently assigned topics and partitions.
- Return Value: Returns the assignment information if successful, otherwise returns
None
.
-
fn offset_seek(&mut self, topic: &str, vg_id: VGroupId, offset: i64) -> RawResult<()>
- Interface Description: Sets the offset for a specific topic and partition.
- Parameter Description:
topic
: The topic name.vg_id
: The partition ID.offset
: The offset to set.
- Return Value: Returns an empty
RawResult
if successful, otherwise returns an error.
-
fn committed(&self, topic: &str, vgroup_id: VGroupId) -> RawResult<i64>
- Interface Description: Retrieves the committed offset for a specific topic and partition.
- Parameter Description:
topic
: The topic name.vgroup_id
: The partition ID.
- Return Value: Returns the offset if successful, otherwise returns an error.
-
fn position(&self, topic: &str, vgroup_id: VGroupId) -> RawResult<i64>
- Interface Description: Retrieves the current position for a specific topic and partition.
- Parameter Description:
topic
: The topic name.vgroup_id
: The partition ID.
- Return Value: Returns the current position if successful, otherwise returns an error.
Offset
The Offset
struct provides methods to retrieve the current message's database, topic, and partition information.
-
fn database(&self) -> &str
- Interface Description: Retrieves the database name for the current message.
- Return Value: A reference to the database name.
-
fn topic(&self) -> &str
- Interface Description: Retrieves the topic name for the current message.
- Return Value: A reference to the topic name.
-
fn vgroup_id(&self) -> VGroupId
- Interface Description: Retrieves the partition ID for the current message.
- Return Value: The partition ID.