docs/en/14-reference/05-connector/26-rust.md
import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; import Preparation from "../../assets/resources/_preparation.mdx"; import RequestId from "../../assets/resources/_request_id.mdx";
taos is the official Rust language connector for TDengine. Rust developers can use it to develop applications that access the TDengine database.
The source code for this Rust connector is hosted on GitHub.
Supports Rust 1.70 and above.
| Rust Connector Version | Major Changes | TDengine Version |
|---|---|---|
| v0.12.3 | 1. Optimized WebSocket query and insert performance. |
After an error occurs, you can obtain detailed information about the error:
match conn.exec(sql) {
Ok(_) => {
Ok(())
}
Err(e) => {
eprintln!("ERROR: {:?}", e);
Err(e)
}
}
For specific error codes, please refer to Error Codes
TDengine currently supports timestamp, numeric, character, and boolean types, with corresponding Rust type conversions 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: The JSON type is only supported in tags.
Please refer to: rust example
Please refer to FAQ
The Rust connector interfaces are divided into synchronous and asynchronous interfaces, where the synchronous interfaces are generally implemented by the asynchronous ones, and the method signatures are basically the same except for the async keyword. For interfaces where the synchronous and asynchronous functionalities are the same, this document only provides explanations for the synchronous interfaces.
For WebSocket connections and native connections, other than the different DSNs required to establish the connections, there is no difference in calling other interfaces.
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>@][<host1>:<port1>[,...<hostN>:<portN>]][/<database>][?<key1>=<value1>[&...<keyN>=<valueN>]]
|------|------------|---|----------|-----------|-------------------------------------|------------|--------------------------------------|
|driver| protocol | | username | password | addresses | database | params |
The meanings of each part are as follows:
taos+ws://localhost:6041 specifies establishing a connection via WebSocket.
localhost:6030.
taos://localhost:6030 or taos:// (equivalent to the former).localhost:6041.
ws://host1:6041,host2:6041 or ws:// (equivalent to ws://localhost:6041).token: Authentication for the TDengine TSDB cloud service.timezone: Time zone setting, in the format of an IANA time zone name (e.g., Asia/Shanghai). The default is the local time zone.compression: Whether to enable data compression. The default is false.conn_retries: Maximum number of retries upon connection failure. The default is 5.retry_backoff_ms: Initial wait time (in milliseconds) upon connection failure. The default is 200. This value increases exponentially with consecutive failures until the maximum wait time is reached.retry_backoff_max_ms: Maximum wait time (in milliseconds) upon connection failure. The default is 2000.A complete DSN description string example is as follows: taos+ws://localhost:6041/test, indicating using WebSocket (ws) mode to connect to the server localhost through port 6041, and specifying the default database as test.
The TaosBuilder struct primarily provides methods for building Taos objects based on DSN, as well as features for checking connections and obtaining the client version number.
fn available_params() -> &'static [&'static str]
fn from_dsn<D: IntoDsn>(dsn: D) -> RawResult<Self>
dsn: DSN string or a type that can be converted into a DSN.RawResult of its own type; on failure, returns an error.fn client_version() -> &'static str
fn ping(&self, _: &mut Self::Target) -> RawResult<()>
_: Mutable reference to the target connection.RawResult; on failure, returns an error.fn ready(&self) -> bool
true, indicating the address is ready for connection.fn build(&self) -> RawResult<Self::Target>
RawResult of the target connection type; on failure, returns an error.Executing SQL primarily uses the Taos struct, and obtaining the result set and metadata requires the ResultSet struct and Field struct introduced in the next section.
The Taos struct provides multiple database operation APIs, including: executing SQL, schema-less writing, and some common database query encapsulations (such as creating databases, fetching)
pub fn is_native(&self) -> bool
true if using a native protocol, otherwise returns false.pub fn is_ws(&self) -> bool
true if using the WebSocket protocol, otherwise returns false.fn query<T: AsRef<str>>(&self, sql: T) -> RawResult<Self::ResultSet>
sql: The SQL statement to execute.RawResult of the ResultSet; on failure, returns an error.fn query_with_req_id<T: AsRef<str>>(&self, sql: T, req_id: u64) -> RawResult<Self::ResultSet>
sql: The SQL statement to execute.req_id: Request ID.RawResult of the ResultSet; on failure, returns an error.fn exec<T: AsRef<str>>(&self, sql: T) -> RawResult<usize>
sql: The SQL statement to execute.fn exec_many<T: AsRef<str>, I: IntoIterator<Item = T>>(&self, input: I) -> RawResult<usize>
input: Collection of SQL statements to execute.fn query_one<T: AsRef<str>, O: DeserializeOwned>(&self, sql: T) -> RawResult<Option<O>>
sql: The SQL statement to execute.fn server_version(&self) -> RawResult<Cow<str>>
RawResult; on failure, returns an error.fn create_topic(&self, name: impl AsRef<str>, sql: impl AsRef<str>) -> RawResult<()>
name: The name of the topic.sql: The associated SQL statement.RawResult; on failure, returns an error.fn databases(&self) -> RawResult<Vec<ShowDatabase>>
RawResult; on failure, returns an error.fn topics(&self) -> RawResult<Vec<Topic>>
RawResult; on failure, returns an error.fn describe(&self, table: &str) -> RawResult<Describe>
table: The name of the table.RawResult; on failure, returns an error.fn database_exists(&self, name: &str) -> RawResult<bool>
name: The name of the database.RawResult indicating whether the database exists; on failure, returns an error.fn put(&self, data: &SmlData) -> RawResult<()>
data: Schema-less data.RawResult; on failure, returns an error.The SmlData structure provides a data structure for schema-less writing and methods for accessing properties.
pub struct SmlData
SmlData structure is used to store schema-less data and related information.protocol: Schema-less protocol, supports InfluxDB Line, OpenTSDB Telnet, OpenTSDB Json.precision: Timestamp precision, supports Hours, Minutes, Seconds, Millisecond (default), Microsecond, Nanosecond.data: List of data.ttl: Data time-to-live, in seconds.req_id: Request ID.pub fn protocol(&self) -> SchemalessProtocol
Line, OpenTSDB Telnet, OpenTSDB Json.pub fn precision(&self) -> SchemalessPrecision
Hours, Minutes, Seconds, Millisecond (default), Microsecond, Nanosecond.pub fn data(&self) -> &Vec<String>
pub fn ttl(&self) -> Option<i32>
pub fn req_id(&self) -> Option<u64>
The ResultSet structure provides methods for accessing the data and metadata of the result set.
fn affected_rows(&self) -> i32
i32.fn precision(&self) -> Precision
Precision.fn fields(&self) -> &[Field]
fn summary(&self) -> (usize, usize)
usize types, representing some statistical information.fn num_of_fields(&self) -> usize
usize.fn blocks(&mut self) -> IBlockIter<'_, Self>
IBlockIter<'_, Self>.fn rows(&mut self) -> IRowsIter<'_, Self>
IRowsIter<'_, Self>.fn deserialize<T>(&mut self) -> Map<IRowsIter<'_, Self>, fn(_: Result<RowView<'_>, Error>) -> Result<T, Error>>
T: Target type, must implement DeserializeOwned.Map<IRowsIter<'_, Self>, fn(_: Result<RowView<'_>, Error>) -> Result<T, Error>>.fn to_rows_vec(&mut self) -> Result<Vec<Vec<Value>>, Error>
Result<Vec<Vec<Value>>, Error>.The Field structure provides methods for accessing field information.
pub const fn empty() -> Field
Field instance.Field instance.pub fn new(name: impl Into<String>, ty: Ty, bytes: u32) -> Field
Field instance.name: Field name.ty: Field type.bytes: Field data length.Field instance.pub fn name(&self) -> &str
pub fn escaped_name(&self) -> String
pub const fn ty(&self) -> Ty
pub const fn bytes(&self) -> u32
pub fn to_c_field(&self) -> c_field_t
Field instance into a C language structure.pub fn sql_repr(&self) -> String
Parameter binding functionality is mainly supported by the Stmt structure.
The Stmt structure provides functionality related to parameter binding, used for efficient writing.
fn init(taos: &Q) -> RawResult<Self>
taos: Database connection instance.fn init_with_req_id(taos: &Q, req_id: u64) -> RawResult<Self>
taos: Database connection instance.req_id: Request ID.fn prepare<S: AsRef<str>>(&mut self, sql: S) -> RawResult<&mut Self>
sql: SQL statement to prepare.fn set_tbname<S: AsRef<str>>(&mut self, name: S) -> RawResult<&mut Self>
name: Table name.fn set_tags(&mut self, tags: &[Value]) -> RawResult<&mut Self>
tags: Array of tags.fn set_tbname_tags<S: AsRef<str>>(&mut self, name: S, tags: &[Value]) -> RawResult<&mut Self>
name: Table name.tags: Array of tags.fn bind(&mut self, params: &[ColumnView]) -> RawResult<&mut Self>
params: Array of parameters.fn add_batch(&mut self) -> RawResult<&mut Self>
fn execute(&mut self) -> RawResult<usize>
fn affected_rows(&self) -> usize
Data subscription mainly involves three structures, providing connection establishment with TmqBuilder, consuming data and committing offsets with Consumer, and the Offset structure.
Similar to TaosBuilder, TmqBuilder provides the functionality to create consumer objects.
fn available_params() -> &'static [&'static str]
fn from_dsn<D: IntoDsn>(dsn: D) -> RawResult<Self>
dsn: DSN string or a type that can be converted into DSN.RawResult of its own type, on failure returns an error.fn client_version() -> &'static str
fn ping(&self, conn: &mut Self::Target) -> RawResult<()>
conn: Mutable reference to the target connection.RawResult, on failure returns an error.fn ready(&self) -> bool
true, indicating that the address is ready to connect.fn build(&self) -> RawResult<Self::Target>
RawResult of the target connection type, on failure returns an error.The Consumer structure provides subscription-related functionalities, including subscribing, fetching messages, committing offsets, setting offsets, etc.
fn subscribe<T: Into<String>, I: IntoIterator<Item = T> + Send>(&mut self, topics: I) -> RawResult<()>
topics: List of topics to subscribe to.RawResult, on failure returns an error.fn recv_timeout(&self, timeout: Timeout) -> RawResult<Option<(Self::Offset, MessageSet<Self::Meta, Self::Data>)>>
timeout: Timeout period.fn commit(&self, offset: Self::Offset) -> RawResult<()>
offset: The offset to commit, see the Offset structure below.RawResult, on failure returns an error.fn commit_offset(&self, topic_name: &str, vgroup_id: VGroupId, offset: i64) -> RawResult<()>
topic_name: Topic name.vgroup_id: Partition ID.offset: The offset to commit.RawResult, on failure returns an error.fn list_topics(&self) -> RawResult<Vec<String>>
fn assignments(&self) -> Option<Vec<(String, Vec<Assignment>)>>
None.fn offset_seek(&mut self, topic: &str, vg_id: VGroupId, offset: i64) -> RawResult<()>
topic: Topic name.vg_id: Partition ID.offset: The offset to set.RawResult, on failure returns an error.fn committed(&self, topic: &str, vgroup_id: VGroupId) -> RawResult<i64>
topic: Topic name.vgroup_id: Partition ID.fn position(&self, topic: &str, vgroup_id: VGroupId) -> RawResult<i64>
topic: Topic name.vgroup_id: Partition ID.The Offset structure provides information about the database, topic, and partition to which the current message belongs.
fn database(&self) -> &str
fn topic(&self) -> &str
fn vgroup_id(&self) -> VGroupId