Skip to content

Commit d85975b

Browse files
suristeramotl
authored andcommitted
Connect/Rust: How to do proper pooling using r2d2
1 parent bdd2e10 commit d85975b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

docs/connect/rust/index.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Connect to CrateDB from Rust applications.
1616
:::
1717

1818
[postgres] is a synchronous Rust client for the PostgreSQL database.
19+
[r2d2] is a generic connection pool for Rust.
1920

2021
:::{rubric} Synopsis (localhost)
2122
:::
@@ -73,12 +74,51 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
7374
Ok(())
7475
}
7576
```
77+
78+
:::{include} ../_cratedb.md
79+
:::
7680
```shell
7781
cargo init
7882
cargo add postgres postgres-native-tls native-tls
7983
cargo run
8084
```
8185

86+
:::{rubric} Synopsis (connection pool)
87+
:::
88+
89+
`main.rs`
90+
```rust
91+
use postgres::{NoTls, Row};
92+
use r2d2_postgres::{
93+
r2d2::{ManageConnection, Pool},
94+
PostgresConnectionManager,
95+
};
96+
fn main {
97+
let pg_manager = PostgresConnectionManager::new(
98+
"postgresql://crate:crate@localhost:5432/?sslmode=disable"
99+
.parse()
100+
.unwrap(),
101+
NoTls,
102+
);
103+
let pg_pool = Pool::builder()
104+
.max_size(5)
105+
.build(pg_manager)
106+
.expect("Postgres pool failed");
107+
let mut pg_conn = pg_pool.get().unwrap();
108+
let result = pg_conn.query("SELECT mountain, height FROM sys.summits ORDER BY height DESC LIMIT 3", &[]);
109+
let rows = result.unwrap().into_iter().collect::<Vec<Row>>();
110+
// TODO: Display results.
111+
Ok(())
112+
}
113+
```
114+
115+
:::{include} ../_cratedb.md
116+
:::
117+
```shell
118+
cargo init
119+
cargo add postgres r2d2
120+
cargo run
121+
```
82122

83123
## Example
84124

@@ -93,3 +133,4 @@ Demonstrates a basic example program that uses the Rust postgres package.
93133

94134

95135
[postgres]: https://crates.io/crates/postgres
136+
[r2d2]: https://crates.io/crates/r2d2

0 commit comments

Comments
 (0)