2024-11-11 13:45:02 +08:00
|
|
|
// sql/psotgresql.rs
|
2024-11-11 19:31:40 +08:00
|
|
|
/*
|
2024-11-11 13:45:02 +08:00
|
|
|
为postgresql数据库实现具体的方法
|
|
|
|
*/
|
|
|
|
use super::DatabaseTrait;
|
|
|
|
use crate::config;
|
2024-11-09 00:05:18 +08:00
|
|
|
use async_trait::async_trait;
|
2024-11-11 13:45:02 +08:00
|
|
|
use sqlx::{Column, PgPool, Row};
|
2024-11-11 01:38:58 +08:00
|
|
|
use std::{collections::HashMap, error::Error};
|
2024-11-09 00:05:18 +08:00
|
|
|
|
2024-11-11 01:38:58 +08:00
|
|
|
#[derive(Clone)]
|
2024-11-09 00:05:18 +08:00
|
|
|
pub struct Postgresql {
|
2024-11-11 01:38:58 +08:00
|
|
|
pool: PgPool,
|
2024-11-09 00:05:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
#[async_trait]
|
2024-11-11 13:45:02 +08:00
|
|
|
impl DatabaseTrait for Postgresql {
|
2024-11-12 20:25:43 +08:00
|
|
|
async fn connect(db_config: config::DbConfig) -> Result<Self, Box<dyn Error>> {
|
2024-11-11 01:38:58 +08:00
|
|
|
let connection_str = format!(
|
|
|
|
"postgres://{}:{}@{}:{}/{}",
|
2024-11-12 20:25:43 +08:00
|
|
|
db_config.user, db_config.password, db_config.address, db_config.prot, db_config.db_name
|
2024-11-11 01:38:58 +08:00
|
|
|
);
|
|
|
|
|
2024-11-11 19:31:40 +08:00
|
|
|
// 连接到数据库池
|
2024-11-11 01:38:58 +08:00
|
|
|
let pool = PgPool::connect(&connection_str)
|
|
|
|
.await
|
|
|
|
.map_err(|e| Box::new(e) as Box<dyn Error>)?;
|
|
|
|
|
2024-11-11 19:31:40 +08:00
|
|
|
// 返回Postgresql实例
|
2024-11-11 01:38:58 +08:00
|
|
|
Ok(Postgresql { pool })
|
2024-11-09 00:05:18 +08:00
|
|
|
}
|
2024-11-11 19:31:40 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 异步执行查询并返回结果。
|
|
|
|
*/
|
2024-11-11 13:45:02 +08:00
|
|
|
async fn query<'a>(
|
|
|
|
&'a self,
|
|
|
|
query: String,
|
|
|
|
) -> Result<Vec<HashMap<String, String>>, Box<dyn Error + 'a>> {
|
2024-11-11 19:31:40 +08:00
|
|
|
// 执行查询并获取所有行
|
2024-11-11 01:38:58 +08:00
|
|
|
let rows = sqlx::query(&query)
|
|
|
|
.fetch_all(&self.pool)
|
|
|
|
.await
|
|
|
|
.map_err(|e| Box::new(e) as Box<dyn Error>)?;
|
|
|
|
|
2024-11-11 19:31:40 +08:00
|
|
|
// 存储查询结果
|
2024-11-11 01:38:58 +08:00
|
|
|
let mut results = Vec::new();
|
|
|
|
|
2024-11-11 19:31:40 +08:00
|
|
|
// 遍历每一行并构建结果映射
|
2024-11-11 01:38:58 +08:00
|
|
|
for row in rows {
|
|
|
|
let mut map = HashMap::new();
|
|
|
|
for column in row.columns() {
|
2024-11-11 19:31:40 +08:00
|
|
|
// 获取列的值,若失败则使用默认值
|
2024-11-11 01:38:58 +08:00
|
|
|
let value: String = row.try_get(column.name()).unwrap_or_default();
|
|
|
|
map.insert(column.name().to_string(), value);
|
|
|
|
}
|
|
|
|
results.push(map);
|
|
|
|
}
|
2024-11-09 00:05:18 +08:00
|
|
|
|
2024-11-11 19:31:40 +08:00
|
|
|
// 返回查询结果
|
2024-11-11 01:38:58 +08:00
|
|
|
Ok(results)
|
2024-11-09 00:05:18 +08:00
|
|
|
}
|
2024-11-11 13:45:02 +08:00
|
|
|
}
|