Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TD-32234] docs(rust): add Rust connector stmt2 doc #29283

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/en/07-develop/05-stmt.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ This is a [more detailed parameter binding example](https://github.com/taosdata/
<TabItem label="Rust" value="rust">

```rust
{{#include docs/examples/rust/restexample/examples/stmt.rs}}
{{#include docs/examples/rust/restexample/examples/stmt2.rs}}
```

</TabItem>
Expand Down
43 changes: 42 additions & 1 deletion docs/en/14-reference/05-connector/26-rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Supports Rust 1.70 and above.

| Rust Connector Version | Major Changes | TDengine Version |
| ---------------------- | ----------------------------------------------------------------------------------------------------- | ------------------ |
| v0.12.4 | Optimized the performance of WebSocket connection parameter binding. | 3.3.5.0 and higher |
| v0.12.3 | 1. Optimized WebSocket query and insert performance. <br/> 2. Supported VARBINARY and GEOMETRY types. | 3.3.0.0 and higher |
| v0.12.0 | WebSocket supports compression. | 3.2.3.0 and higher |
| v0.11.0 | TMQ feature optimization. | 3.2.0.0 and higher |
Expand Down Expand Up @@ -393,7 +394,47 @@ The Field structure provides methods for accessing field information.

### Parameter Binding

Parameter binding functionality is mainly supported by the Stmt structure.
> Tips: Stmt2 is recommended.

#### Stmt2

The Stmt2 structure provides functionality related to parameter binding, used for efficient writing.

- `fn init(taos: &Q) -> RawResult<Self>`

- **Interface Description**: Initialize the parameter binding instance.
- **Parameter Description**:
- `taos`: Database connection instance.
- **Return Value**: On success, returns the initialized instance; on failure, returns an error.

- `fn prepare(&mut self, sql: &str) -> RawResult<&mut Self>`

- **Interface Description**: Prepare the SQL statement to be bound.
- **Parameter Description**:
- `sql`: SQL statement to prepare.
- **Return Value**: On success, returns a mutable reference to itself; on failure, returns an error.

- `fn bind(&mut self, params: &[Stmt2BindParam]) -> RawResult<&mut Self>`

- **Interface Description**: Bind parameters.
- **Parameter Description**:
- `params`: Array of parameters.
- **Return Value**: On success, returns a mutable reference to itself; on failure, returns an error.

- `fn exec(&mut self) -> RawResult<usize>`

- **Interface Description**: Execute the statement.
- **Return Value**: On success, returns the number of affected rows; on failure, returns an error.

- `fn affected_rows(&self) -> usize`

- **Interface Description**: Get the number of affected rows.
- **Return Value**: Number of affected rows.

- `fn result_set(&self) -> RawResult<Q::AsyncResultSet>`

- **Interface Description**: Get the result set.
- **Return Value**: On success, returns the result set; on failure, returns an error.

#### Stmt

Expand Down
2 changes: 1 addition & 1 deletion docs/examples/rust/restexample/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ tokio = { version = "1", features = ["rt", "macros", "rt-multi-thread"] }
log = "0.4"
pretty_env_logger = "0.5.0"

taos = "*"
taos = { git = "https://github.com/taosdata/taos-connector-rust.git", branch = "feat/TD-32234" }
69 changes: 69 additions & 0 deletions docs/examples/rust/restexample/examples/stmt2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use taos::*;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
qevolg marked this conversation as resolved.
Show resolved Hide resolved
let dsn = "ws://";
let taos = TaosBuilder::from_dsn(dsn)?.build().await?;

taos.exec("DROP DATABASE IF EXISTS power").await?;
taos.create_database("power").await?;
taos.use_database("power").await?;
taos.exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))").await?;

let mut stmt2 = Stmt2::init(&taos).await?;
stmt2.prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)").await?;

const NUM_TABLES: usize = 10;
const NUM_ROWS: usize = 10;

let mut params = Vec::with_capacity(NUM_TABLES);
for i in 0..NUM_TABLES {
let table_name = format!("d_bind_{}", i);
let tags = vec![
Value::Int(i as i32),
Value::VarChar(format!("location_{}", i).into()),
];

let mut timestamps = Vec::with_capacity(NUM_ROWS);
let mut currents = Vec::with_capacity(NUM_ROWS);
let mut voltages = Vec::with_capacity(NUM_ROWS);
let mut phases = Vec::with_capacity(NUM_ROWS);

for j in 0..NUM_ROWS {
timestamps.push(1648432611249 + j as i64);
currents.push(10.3 + j as f32);
voltages.push(219 + j as i32);
phases.push(0.31 + j as f32);
}

let columns = vec![
ColumnView::from_millis_timestamp(timestamps),
ColumnView::from_floats(currents),
ColumnView::from_ints(voltages),
ColumnView::from_floats(phases),
];

let param = Stmt2BindParam::new(Some(table_name), Some(tags), Some(columns));
params.push(param);
}

// Bind params to the prepared statement
stmt2.bind(&params).await?;

// Execute
match stmt2.exec().await {
Ok(affected_rows) => println!(
"Successfully inserted {} rows to power.meters.",
affected_rows
),
Err(err) => {
eprintln!(
"Failed to insert to table meters using stmt2, ErrMessage: {}",
err
);
return Err(err.into());
}
}

Ok(())
}
2 changes: 1 addition & 1 deletion docs/zh/07-develop/05-stmt.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import TabItem from "@theme/TabItem";
<TabItem label="Rust" value="rust">

```rust
{{#include docs/examples/rust/restexample/examples/stmt.rs}}
{{#include docs/examples/rust/restexample/examples/stmt2.rs}}
```

</TabItem>
Expand Down
45 changes: 43 additions & 2 deletions docs/zh/14-reference/05-connector/26-rust.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ import RequestId from "./_request_id.mdx";
## 版本历史

| Rust 连接器版本 | 主要变化 | TDengine 版本 |
| -------------- | ---------------------------------------------------------------------------- | ----------------- |
| --------------- | ----------------------------------------------------------------------------- | ------------------ |
| v0.12.4 | 优化了 WebSocket 连接参数绑定性能 | 3.3.5.0 及更高版本 |
| v0.12.3 | 1. 优化了 WebSocket 查询和插入性能 <br/> 2. 支持了 VARBINARY 和 GEOMETRY 类型 | 3.3.0.0 及更高版本 |
| v0.12.0 | WebSocket 支持压缩 | 3.2.3.0 及更高版本 |
| v0.11.0 | TMQ 功能优化 | 3.2.0.0 及更高版本 |
Expand Down Expand Up @@ -395,7 +396,47 @@ Feild 结构体提供了字段信息的一些方法。

### 参数绑定

参数绑定功能主要由 Stmt 结构体支持。
> Tips: 推荐使用 Stmt2

#### Stmt2

Stmt2 结构体提供了参数绑定相关功能,用于实现高效写入。

- `fn init(taos: &Q) -> RawResult<Self>`

- **接口说明**:初始化参数绑定实例。
- **参数说明**:
- `taos`:数据库连接实例。
- **返回值**:成功时返回初始化的实例,失败时返回错误。

- `fn prepare(&mut self, sql: &str) -> RawResult<&mut Self>`

- **接口说明**:准备要绑定的 SQL 语句。
- **参数说明**:
- `sql`:要准备的 SQL 语句。
- **返回值**:成功时返回自身的可变引用,失败时返回错误。

- `fn bind(&mut self, params: &[Stmt2BindParam]) -> RawResult<&mut Self>`

- **接口说明**:绑定参数。
- **参数说明**:
- `params`:参数数组。
- **返回值**:成功时返回自身的可变引用,失败时返回错误。

- `fn exec(&mut self) -> RawResult<usize>`

- **接口说明**:执行语句。
- **返回值**:成功时返回受影响的行数,失败时返回错误。

- `fn affected_rows(&self) -> usize`

- **接口说明**:获取受影响的行数。
- **返回值**:受影响的行数。

- `fn result_set(&self) -> RawResult<Q::AsyncResultSet>`

- **接口说明**:获取结果集。
- **返回值**:成功时返回结果集,失败时返回错误。

#### Stmt

Expand Down
30 changes: 13 additions & 17 deletions tests/docs-examples-test/rust.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,18 @@

set -e


check_transactions() {
for i in {1..30}
do
output=$(taos -s "show transactions;")
if [[ $output == *"Query OK, 0 row(s)"* ]]; then
echo "Success: No transactions are in progress."
return 0
fi
sleep 1
done

echo "Error: Transactions are still in progress after 30 attempts."
return 1
for i in {1..30}; do
output=$(taos -s "show transactions;")
if [[ $output == *"Query OK, 0 row(s)"* ]]; then
echo "Success: No transactions are in progress."
return 0
fi
sleep 1
done

echo "Error: Transactions are still in progress after 30 attempts."
return 1
}

reset_cache() {
Expand Down Expand Up @@ -54,13 +52,10 @@ taos -s "drop database if exists power"
check_transactions || exit 1
reset_cache || exit 1


cargo run --example stmt

cargo run --example tmq



cd ../restexample

cargo run --example connect
Expand All @@ -81,7 +76,8 @@ taos -s "drop database if exists power"
check_transactions || exit 1
reset_cache || exit 1


cargo run --example stmt

cargo run --example stmt2

cargo run --example tmq