TDengine Rust Client Library
taos
is the official Rust client library for TDengine. Rust developers can develop applications to access the TDengine instance data.
The source code for the Rust client library is located on GitHub.
Version support
Please refer to version support list and history
Connection types
taos
provides Native Connection and WebSocket connection
More details about establishing a connection, please checkDeveloper Guide - Connectd - Rust
Installation
Pre-installation
Install the Rust development toolchain.
Adding taos dependencies
The taos connector uses the WebSocket to access TDengine Cloud instances. You need to add the taos
dependency to your Rust project and enable the ws
and ws-rustls
features.
Add taos to your Cargo.toml file and enable features. Both of the following methods are acceptable:
- Enable default features
[dependencies]
taos = { version = "*"} - Disable default features and enable ws and ws-rustls features
[dependencies]
taos = { version = "*", default-features = false, features = ["ws", "ws-rustls"] }
Expampe
Before you run the code below,please create a database named power
on theTDengine Cloud - Explorer page.
Establish a connection
TaosBuilder creates a connection builder through a DSN. The DSN is composed of the following format: wss://<host>?token=<token>
.
let builder = TaosBuilder::from_dsn(DSN)?;
You can now use this object to create a connection:
let conn = builder.build()?;
Multiple connection objects can be created:
let conn1 = builder.build()?;
let conn2 = builder.build()?;
Insert data
exec
: Execute some non-query SQL statements, such as CREATE
, ALTER
, INSERT
, etc.
taos.exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)").await?;
taos.exec("INSERT INTO
power.d1001 USING power.meters
TAGS('California.SanFrancisco', 2)
VALUES (NOW, 12.3, 219, 0.31000) (NOW - 1s, 12.60000, 218, 0.33000) (NOW - 3s, 12.30000, 221, 0.31000)
power.d1002 USING power.meters
TAGS('California.SanFrancisco', 3)
VALUES ('2018-10-03 14:39:16.650', 23.4, 218, 0.25000)
").await?;
exec_many
: Run multiple SQL statements simultaneously or in order.
taos.use_database("power").await?;
taos.exec_many([
"CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)",
"CREATE TABLE IF NOT EXISTS d0 USING power.meters TAGS('California.LosAngles',0)",
"INSERT INTO d0 values(now - 10s, 10, 116, 0.32)",
"INSERT INTO d1 USING meters TAGS('California.SanFrancisco', 4) values (now-8s, 10, 120, 0.33) (now - 6s, 10, 119, 0.34)",
]).await?;
Query data
query
: Run a query statement and return a ResultSet object.
let mut result = taos.query("SELECT * FROM power.meters limit 5").await?;
Get column meta from the result
You can obtain column information by using [.fields()].
let fields = result.fields();
for column in fields {
println!("name: {}, type: {:?} , bytes: {}", column.name(), column.ty(), column.bytes());
}
Get first 5 rows and print each row:
let rows = result.rows();
rows.try_for_each(|row| async {
println!("{}", row.into_value_iter().join(","));
Ok(())
}).await?;
Get first 5 rows and print each row and each column:
let mut query_restult = taos.query("SELECT * FROM power.meters limit 5").await?;
let mut ressult_rows = query_restult.rows();
let mut nrows = 0;
while let Some(row) = ressult_rows.try_next().await? {
for (col, (name, value)) in row.enumerate() {
println!(
"[{}] got value in col {} (named `{:>8}`): {}",
nrows, col, name, value
);
}
nrows += 1;
}
Use the serde deserialization framework.
use anyhow::Result;
use chrono::{DateTime, Local};
use serde::Deserialize;
use taos::*;
#[derive(Debug, Deserialize)]
struct Record {
// deserialize timestamp to chrono::DateTime<Local>
ts: DateTime<Local>,
// float to f32
current: Option<f32>,
// int to i32
voltage: Option<i32>,
phase: Option<f32>,
groupid: i32,
// binary/varchar to String
location: String,
}
#[tokio::main]
async fn main() -> Result<()> {
let dsn = std::env::var("TDENGINE_CLOUD_DSN")?;
let builder = TaosBuilder::from_dsn(dsn)?;
let taos = builder.build().await?;
let records: Vec<Record> = taos.query("select * from power.meters limit 5")
.await?
.deserialize()
.try_collect()
.await?;
println!("length of records: {}", records.len());
records.iter().for_each(|record| {
println!("{:?}", record);
});
Ok(())
}
连接池
In complex applications, we recommend enabling connection pools. taos implements connection pools based on r2d2.
As follows, a connection pool with default parameters can be generated.
let pool = TaosBuilder::from_dsn(dsn)?.pool()?;
In the application code, use pool.get()?
to get a connection object Taos.
let taos = pool.get()?;