use std::fmt;
use std::marker::PhantomData;
use futures_core::stream::BoxStream;
use futures_util::StreamExt;
use sqlx::postgres::{PgListener, PgNotification};
use crate::{Db, Error, Executor, Expr, Model, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Notification {
pub channel: String,
pub payload: String,
pub process_id: u32,
}
impl From<PgNotification> for Notification {
fn from(n: PgNotification) -> Self {
Self {
channel: n.channel().to_owned(),
payload: n.payload().to_owned(),
process_id: n.process_id(),
}
}
}
pub struct Listener {
inner: PgListener,
}
impl Listener {
pub async fn recv(&mut self) -> Result<Notification> {
Ok(self.inner.recv().await?.into())
}
pub fn try_recv(&mut self) -> Option<Notification> {
self.inner.next_buffered().map(Into::into)
}
pub async fn listen(&mut self, channel: &str) -> Result<()> {
Ok(self.inner.listen(channel).await?)
}
pub async fn unlisten(&mut self, channel: &str) -> Result<()> {
Ok(self.inner.unlisten(channel).await?)
}
pub fn into_stream(self) -> BoxStream<'static, Result<Notification>> {
self.inner
.into_stream()
.map(|n| n.map(Notification::from).map_err(Error::from))
.boxed()
}
}
impl fmt::Debug for Listener {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Listener")
}
}
impl Db {
pub async fn listen(&self, channels: &[&str]) -> Result<Listener> {
let mut inner = PgListener::connect_with(self.pool()).await?;
inner.listen_all(channels.iter().copied()).await?;
Ok(Listener { inner })
}
pub async fn notify(&self, channel: &str, payload: &str) -> Result<()> {
crate::raw("SELECT pg_notify(?, ?)")
.bind(channel)
.bind(payload)
.execute(self)
.await?;
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeOp {
Insert,
Update,
Delete,
}
pub struct Change<M> {
pub op: ChangeOp,
pub key: String,
_model: PhantomData<fn() -> M>,
}
impl<M: Model> Change<M> {
pub async fn fetch<'e, E: Executor<'e>>(&self, executor: E) -> Result<Option<M>> {
let pk = quoted(M::PRIMARY_KEY);
M::filter(Expr::raw(format!("{pk}::text = ?"), [self.key.as_str()]))
.with_trashed()
.unscoped()
.on_primary()
.first(executor)
.await
}
fn parse(payload: &str) -> Result<Self> {
let (op, key) = payload.split_once(':').ok_or_else(|| {
Error::InvalidQuery(format!("malformed change notification {payload:?}"))
})?;
let op = match op {
"INSERT" => ChangeOp::Insert,
"UPDATE" => ChangeOp::Update,
"DELETE" => ChangeOp::Delete,
other => {
return Err(Error::InvalidQuery(format!(
"unknown change operation {other:?}"
)));
}
};
Ok(Self {
op,
key: key.to_owned(),
_model: PhantomData,
})
}
}
impl<M> Clone for Change<M> {
fn clone(&self) -> Self {
Self {
op: self.op,
key: self.key.clone(),
_model: PhantomData,
}
}
}
impl<M> fmt::Debug for Change<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Change")
.field("op", &self.op)
.field("key", &self.key)
.finish()
}
}
impl<M> PartialEq for Change<M> {
fn eq(&self, other: &Self) -> bool {
self.op == other.op && self.key == other.key
}
}
pub struct ChangeStream<M> {
listener: Listener,
_model: PhantomData<fn() -> M>,
}
impl<M: Model> ChangeStream<M> {
pub(crate) fn new(listener: Listener) -> Self {
Self {
listener,
_model: PhantomData,
}
}
pub async fn recv(&mut self) -> Result<Change<M>> {
let n = self.listener.recv().await?;
Change::parse(&n.payload)
}
pub fn into_stream(self) -> BoxStream<'static, Result<Change<M>>> {
self.listener
.into_stream()
.map(|n| n.and_then(|n| Change::parse(&n.payload)))
.boxed()
}
}
impl<M> fmt::Debug for ChangeStream<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ChangeStream")
}
}
pub(crate) fn channel<M: Model>() -> String {
format!("rok:{}", M::TABLE)
}
fn quoted(ident: &str) -> String {
let mut s = String::new();
crate::sql::push_ident(&mut s, ident);
s
}
fn literal(s: &str) -> String {
format!("'{}'", s.replace('\'', "''"))
}
pub(crate) fn install_sql<M: Model>() -> Result<String> {
let channel = channel::<M>();
if channel.len() > 63 {
return Err(Error::InvalidQuery(format!(
"change channel {channel:?} exceeds PostgreSQL's 63-byte identifier limit"
)));
}
let table = quoted(M::TABLE);
Ok(format!(
r#"CREATE OR REPLACE FUNCTION rok_db_notify_change() RETURNS trigger LANGUAGE plpgsql AS $rok$
DECLARE rec record;
BEGIN
IF TG_OP = 'DELETE' THEN rec := OLD; ELSE rec := NEW; END IF;
PERFORM pg_notify(TG_ARGV[0], TG_OP || ':' || coalesce(to_jsonb(rec) ->> TG_ARGV[1], ''));
RETURN NULL;
END
$rok$;
DROP TRIGGER IF EXISTS rok_db_notify_change ON {table};
CREATE TRIGGER rok_db_notify_change AFTER INSERT OR UPDATE OR DELETE ON {table}
FOR EACH ROW EXECUTE FUNCTION rok_db_notify_change({}, {});"#,
literal(&channel),
literal(M::PRIMARY_KEY),
))
}
pub(crate) fn uninstall_sql<M: Model>() -> String {
format!(
"DROP TRIGGER IF EXISTS rok_db_notify_change ON {}",
quoted(M::TABLE)
)
}
#[cfg(test)]
mod tests {
#[test]
fn literals_are_escaped() {
assert_eq!(super::literal("it's"), "'it''s'");
}
}