[![crates.io](https://img.shields.io/crates/v/spring-postgres.svg)](https://crates.io/crates/spring-postgres) [![Documentation](https://docs.rs/spring-postgres/badge.svg)](https://docs.rs/spring-postgres) [tokio-postgres](https://github.com/sfackler/rust-postgres)是和sqlx类似的数æ®åº“连接工具,和sqlxä¸åŒçš„是它åªä¸“注于实现postgresqlçš„æ•°æ®åº“连接。 ## ä¾èµ– ```toml spring-postgres = { version = "<version>" } ``` å¯é€‰çš„features: * `array-impls` * `js` * `with-bit-vec-0_6` * `with-chrono-0_4` * `with-eui48-0_4` * `with-eui48-1` * `with-geo-types-0_6` * `with-geo-types-0_7` * `with-serde_json-1` * `with-smol_str-01` * `with-time-0_2` * `with-time-0_3` * `with-uuid-0_8` * `with-uuid-1` ## é…置项 ```toml [postgres] connect = "postgres://root:12341234@localhost:5432/myapp_development" # è¦è¿žæŽ¥çš„æ•°æ®åº“åœ°å€ ``` ## 组件 é…置完上述é…置项åŽï¼Œæ’件会自动注册一个[`Postgres`](https://docs.rs/tokio-postgres/latest/tokio_postgres/struct.Client.html)对象。该对象包装了[`tokio_postgres::Client`](https://docs.rs/tokio-postgres/latest/tokio_postgres/struct.Client.html)。 ```rust pub struct Postgres(Arc<tokio_postgres::Client>); ``` ## æå–æ’件注册的Component `PgPlugin`æ’件为我们自动注册了一个[`Postgres`](https://docs.rs/tokio-postgres/latest/tokio_postgres/struct.Client.html)对象,我们å¯ä»¥ä½¿ç”¨`Component`从AppStateä¸æå–è¿™ä¸ªè¿žæŽ¥æ± ï¼Œ[`Component`](https://docs.rs/spring-web/latest/spring_web/extractor/struct.Component.html)是一个axumçš„[extractor](https://docs.rs/axum/latest/axum/extract/index.html)。 ```rust #[get("/postgres")] async fn hello_postgres(Component(pg): Component<Postgres>) -> Result<impl IntoResponse> { let rows = pg .query("select version() as version", &[]) .await .context("query postgresql failed")?; let version: String = rows[0].get("version"); Ok(Json(version)) } ``` 完整代ç å‚考[`postgres-example`](https://github.com/spring-rs/spring-rs/tree/master/examples/postgres-example)