1use std::sync::Arc;
2use std::sync::atomic::{AtomicUsize, Ordering};
3use std::time::Duration;
4
5use sqlx::Postgres;
6use sqlx::postgres::{PgConnection, PgListener, PgPool};
7
8use crate::cache::QueryCache;
9
10pub(crate) const DEFAULT_SLOW_QUERY: Duration = Duration::from_secs(1);
12
13#[doc(hidden)]
15#[derive(Debug, Clone)]
16pub struct Context {
17 pub(crate) cache: Option<QueryCache>,
18 pub(crate) slow_query: Duration,
19 pub(crate) replicas: Vec<PgPool>,
20 pub(crate) next_replica: Arc<AtomicUsize>,
21}
22
23impl Context {
24 pub(crate) fn replica(&self) -> Option<PgPool> {
26 if self.replicas.is_empty() {
27 return None;
28 }
29 let i = self.next_replica.fetch_add(1, Ordering::Relaxed) % self.replicas.len();
30 Some(self.replicas[i].clone())
31 }
32}
33
34impl Default for Context {
35 fn default() -> Self {
36 Self {
37 cache: None,
38 slow_query: DEFAULT_SLOW_QUERY,
39 replicas: Vec::new(),
40 next_replica: Arc::default(),
41 }
42 }
43}
44
45pub trait Executor<'c>: sqlx::Executor<'c, Database = Postgres> {
53 #[doc(hidden)]
54 fn __context(&self) -> Option<Arc<Context>> {
55 None
56 }
57
58 #[doc(hidden)]
60 fn __replica(&self) -> Option<PgPool> {
61 None
62 }
63
64 #[doc(hidden)]
66 fn __touch(&self, _table: &'static str) {}
67}
68
69impl<'c> Executor<'c> for &'c PgPool {}
70impl<'c> Executor<'c> for &'c mut PgConnection {}
71impl<'c> Executor<'c> for &'c mut PgListener {}