1use std::fmt;
23use std::marker::PhantomData;
24
25use futures_core::stream::BoxStream;
26use futures_util::StreamExt;
27use sqlx::postgres::{PgListener, PgNotification};
28
29use crate::{Db, Error, Executor, Expr, Model, Result};
30
31#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct Notification {
34 pub channel: String,
36 pub payload: String,
38 pub process_id: u32,
40}
41
42impl From<PgNotification> for Notification {
43 fn from(n: PgNotification) -> Self {
44 Self {
45 channel: n.channel().to_owned(),
46 payload: n.payload().to_owned(),
47 process_id: n.process_id(),
48 }
49 }
50}
51
52pub struct Listener {
56 inner: PgListener,
57}
58
59impl Listener {
60 pub async fn recv(&mut self) -> Result<Notification> {
62 Ok(self.inner.recv().await?.into())
63 }
64
65 pub fn try_recv(&mut self) -> Option<Notification> {
68 self.inner.next_buffered().map(Into::into)
69 }
70
71 pub async fn listen(&mut self, channel: &str) -> Result<()> {
73 Ok(self.inner.listen(channel).await?)
74 }
75
76 pub async fn unlisten(&mut self, channel: &str) -> Result<()> {
78 Ok(self.inner.unlisten(channel).await?)
79 }
80
81 pub fn into_stream(self) -> BoxStream<'static, Result<Notification>> {
83 self.inner
84 .into_stream()
85 .map(|n| n.map(Notification::from).map_err(Error::from))
86 .boxed()
87 }
88}
89
90impl fmt::Debug for Listener {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 f.write_str("Listener")
93 }
94}
95
96impl Db {
97 pub async fn listen(&self, channels: &[&str]) -> Result<Listener> {
99 let mut inner = PgListener::connect_with(self.pool()).await?;
100 inner.listen_all(channels.iter().copied()).await?;
101 Ok(Listener { inner })
102 }
103
104 pub async fn notify(&self, channel: &str, payload: &str) -> Result<()> {
108 crate::raw("SELECT pg_notify(?, ?)")
109 .bind(channel)
110 .bind(payload)
111 .execute(self)
112 .await?;
113 Ok(())
114 }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum ChangeOp {
120 Insert,
122 Update,
124 Delete,
126}
127
128pub struct Change<M> {
130 pub op: ChangeOp,
132 pub key: String,
135 _model: PhantomData<fn() -> M>,
136}
137
138impl<M: Model> Change<M> {
139 pub async fn fetch<'e, E: Executor<'e>>(&self, executor: E) -> Result<Option<M>> {
142 let key_sql = crate::key::key_text_sql::<M>();
143 M::filter(Expr::raw(format!("{key_sql} = ?"), [self.key.as_str()]))
144 .with_trashed()
145 .unscoped()
146 .on_primary()
147 .first(executor)
148 .await
149 }
150
151 fn parse(payload: &str) -> Result<Self> {
152 let (op, key) = payload.split_once(':').ok_or_else(|| {
153 Error::InvalidQuery(format!("malformed change notification {payload:?}"))
154 })?;
155 let op = match op {
156 "INSERT" => ChangeOp::Insert,
157 "UPDATE" => ChangeOp::Update,
158 "DELETE" => ChangeOp::Delete,
159 other => {
160 return Err(Error::InvalidQuery(format!(
161 "unknown change operation {other:?}"
162 )));
163 }
164 };
165 Ok(Self {
166 op,
167 key: key.to_owned(),
168 _model: PhantomData,
169 })
170 }
171}
172
173impl<M> Clone for Change<M> {
174 fn clone(&self) -> Self {
175 Self {
176 op: self.op,
177 key: self.key.clone(),
178 _model: PhantomData,
179 }
180 }
181}
182
183impl<M> fmt::Debug for Change<M> {
184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185 f.debug_struct("Change")
186 .field("op", &self.op)
187 .field("key", &self.key)
188 .finish()
189 }
190}
191
192impl<M> PartialEq for Change<M> {
193 fn eq(&self, other: &Self) -> bool {
194 self.op == other.op && self.key == other.key
195 }
196}
197
198pub struct ChangeStream<M> {
200 listener: Listener,
201 _model: PhantomData<fn() -> M>,
202}
203
204impl<M: Model> ChangeStream<M> {
205 pub(crate) fn new(listener: Listener) -> Self {
206 Self {
207 listener,
208 _model: PhantomData,
209 }
210 }
211
212 pub async fn recv(&mut self) -> Result<Change<M>> {
214 let n = self.listener.recv().await?;
215 Change::parse(&n.payload)
216 }
217
218 pub fn into_stream(self) -> BoxStream<'static, Result<Change<M>>> {
220 self.listener
221 .into_stream()
222 .map(|n| n.and_then(|n| Change::parse(&n.payload)))
223 .boxed()
224 }
225}
226
227impl<M> fmt::Debug for ChangeStream<M> {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 f.write_str("ChangeStream")
230 }
231}
232
233pub(crate) fn channel<M: Model>() -> String {
235 format!("rok:{}", M::TABLE)
236}
237
238fn quoted(ident: &str) -> String {
239 let mut s = String::new();
240 crate::sql::push_ident(&mut s, ident);
241 s
242}
243
244fn literal(s: &str) -> String {
245 format!("'{}'", s.replace('\'', "''"))
246}
247
248pub(crate) fn install_sql<M: Model>() -> Result<String> {
249 let channel = channel::<M>();
250 if channel.len() > 63 {
251 return Err(Error::InvalidQuery(format!(
252 "change channel {channel:?} exceeds PostgreSQL's 63-byte identifier limit"
253 )));
254 }
255 let table = quoted(M::TABLE);
256 Ok(format!(
257 r#"CREATE OR REPLACE FUNCTION rok_db_notify_change() RETURNS trigger LANGUAGE plpgsql AS $rok$
258DECLARE
259 rec record;
260 j jsonb;
261 keys text[] := string_to_array(TG_ARGV[1], ',');
262BEGIN
263 IF TG_OP = 'DELETE' THEN rec := OLD; ELSE rec := NEW; END IF;
264 j := to_jsonb(rec);
265 PERFORM pg_notify(TG_ARGV[0], TG_OP || ':' || coalesce({key}, ''));
266 RETURN NULL;
267END
268$rok$;
269DROP TRIGGER IF EXISTS rok_db_notify_change ON {table};
270CREATE TRIGGER rok_db_notify_change AFTER INSERT OR UPDATE OR DELETE ON {table}
271 FOR EACH ROW EXECUTE FUNCTION rok_db_notify_change({}, {});"#,
272 literal(&channel),
273 literal(&crate::key::key_columns_arg::<M>()),
274 key = crate::key::TRIGGER_KEY_SQL,
275 ))
276}
277
278pub(crate) fn uninstall_sql<M: Model>() -> String {
279 format!(
280 "DROP TRIGGER IF EXISTS rok_db_notify_change ON {}",
281 quoted(M::TABLE)
282 )
283}
284
285#[cfg(test)]
286mod tests {
287 #[test]
288 fn literals_are_escaped() {
289 assert_eq!(super::literal("it's"), "'it''s'");
290 }
291}