-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathmod.rs
84 lines (71 loc) · 2.6 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::collections::hash_map;
use std::collections::HashMap;
use std::sync::Mutex;
use once_cell::sync::Lazy;
use sqlx_core::connection::Connection;
use sqlx_core::database::Database;
use sqlx_core::describe::Describe;
use sqlx_core::executor::Executor;
use sqlx_core::type_checking::TypeChecking;
#[cfg(any(feature = "postgres", feature = "mysql", feature = "_sqlite"))]
mod impls;
pub trait DatabaseExt: Database + TypeChecking {
const DATABASE_PATH: &'static str;
const ROW_PATH: &'static str;
fn db_path() -> syn::Path {
syn::parse_str(Self::DATABASE_PATH).unwrap()
}
fn row_path() -> syn::Path {
syn::parse_str(Self::ROW_PATH).unwrap()
}
fn describe_blocking(query: &str, database_url: &str) -> sqlx_core::Result<Describe<Self>>;
}
#[allow(dead_code)]
pub struct CachingDescribeBlocking<DB: DatabaseExt> {
connections: Lazy<Mutex<HashMap<String, DB::Connection>>>,
}
#[allow(dead_code)]
impl<DB: DatabaseExt> CachingDescribeBlocking<DB> {
pub const fn new() -> Self {
CachingDescribeBlocking {
connections: Lazy::new(|| Mutex::new(HashMap::new())),
}
}
pub fn describe(&self, query: &str, database_url: &str) -> sqlx_core::Result<Describe<DB>>
where
for<'a> &'a mut DB::Connection: Executor<'a, Database = DB>,
{
let mut cache = self
.connections
.lock()
.expect("previous panic in describe call");
crate::block_on(async {
let conn = match cache.entry(database_url.to_string()) {
hash_map::Entry::Occupied(hit) => hit.into_mut(),
hash_map::Entry::Vacant(miss) => {
let conn = miss.insert(DB::Connection::connect(database_url).await?);
#[cfg(feature = "postgres")]
if DB::NAME == sqlx_postgres::Postgres::NAME {
conn.execute(
"
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM pg_settings
WHERE name = 'plan_cache_mode'
) THEN
SET SESSION plan_cache_mode = 'force_generic_plan';
END IF;
END $$;
",
)
.await?;
}
conn
}
};
conn.describe(query).await
})
}
}