Skip to main content

rok_db_core/
context.rs

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
10/// Default threshold above which a query is logged as slow.
11pub(crate) const DEFAULT_SLOW_QUERY: Duration = Duration::from_secs(1);
12
13/// Per-[`Db`](crate::Db) settings shared with every query run through it.
14#[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    /// The next replica in round-robin order, if any.
25    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
45/// Anything that can run a query: [`&Db`](crate::Db), `&mut Tx`, a plain
46/// sqlx `&PgPool` or `&mut PgConnection`.
47///
48/// Executors created by rok-db (`&Db`, `&mut Tx`) also carry the pool's
49/// settings — the [query cache](crate::QueryCache) and the slow-query
50/// threshold. Plain sqlx executors run queries uncached with the default
51/// settings.
52pub trait Executor<'c>: sqlx::Executor<'c, Database = Postgres> {
53    #[doc(hidden)]
54    fn __context(&self) -> Option<Arc<Context>> {
55        None
56    }
57
58    /// A read replica to run a read-only query on, if configured.
59    #[doc(hidden)]
60    fn __replica(&self) -> Option<PgPool> {
61        None
62    }
63
64    /// Called before a write to `table` runs through this executor.
65    #[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 {}