#![doc = include_str!("../docs/guide/database.md")]
use std::{collections::HashMap, fmt, future::Future};
use gpui::{App, ElementId, Global, SharedString, Task, Window};
pub use rok_db;
pub use rok_db::Db;
use crate::hooks::use_keyed_state;
#[must_use]
pub fn runtime() -> &'static tokio::runtime::Runtime {
crate::runtime::get()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DbError {
NotConnected,
Failed(SharedString),
Cancelled,
}
impl fmt::Display for DbError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotConnected => formatter.write_str("not connected to a database"),
Self::Failed(message) => formatter.write_str(message),
Self::Cancelled => formatter.write_str("the database task was cancelled"),
}
}
}
impl std::error::Error for DbError {}
impl From<rok_db::Error> for DbError {
fn from(error: rok_db::Error) -> Self {
Self::Failed(error.to_string().into())
}
}
#[derive(Default)]
struct Connection {
db: Option<Db>,
epoch: u64,
generations: HashMap<SharedString, u64>,
}
impl Global for Connection {}
pub fn connect(url: impl Into<String>, cx: &mut App) -> Task<Result<(), DbError>> {
let url = url.into();
let connecting = runtime().spawn(async move { Db::connect(&url).await });
cx.spawn(async move |cx| {
let db = connecting.await.map_err(|_| DbError::Cancelled)??;
cx.update(|cx| set_connection(db, cx))
.map_err(|_| DbError::Cancelled)
})
}
pub fn set_connection(db: Db, cx: &mut App) {
crate::query::provide(cx, db.clone());
let connection = cx.default_global::<Connection>();
connection.db = Some(db);
connection.epoch += 1;
crate::query::invalidate(cx, &crate::query::QueryKey::root());
cx.refresh_windows();
}
pub fn db_query<T, Build, Fetch>(
key: crate::query::QueryKey,
build: Build,
) -> crate::query::QueryOptions<T>
where
T: Send + 'static,
Build: Fn(Db) -> Fetch + Send + Sync + 'static,
Fetch: Future<Output = rok_db::Result<T>> + Send + 'static,
{
let build = std::sync::Arc::new(build);
crate::query::QueryOptions::new(key, move |cx| {
let db = cx.get::<Db>().cloned();
let build = build.clone();
async move {
let db = db.ok_or(DbError::NotConnected)?;
build(db).await.map_err(DbError::from)
}
})
}
pub fn db_mutation<I, O, Build, Write>(build: Build) -> crate::query::MutationOptions<I, O, DbError>
where
I: Send + 'static,
O: Send + 'static,
Build: Fn(Db, I) -> Write + Send + Sync + 'static,
Write: Future<Output = rok_db::Result<O>> + Send + 'static,
{
let build = std::sync::Arc::new(build);
crate::query::MutationOptions::new(move |cx, input| {
let db = cx.get::<Db>().cloned();
let build = build.clone();
async move {
let db = db.ok_or(DbError::NotConnected)?;
build(db, input).await.map_err(DbError::from)
}
})
}
pub fn connection(cx: &App) -> Option<Db> {
cx.try_global::<Connection>()
.and_then(|connection| connection.db.clone())
}
fn start<T, Query>(query: Query) -> tokio::task::JoinHandle<rok_db::Result<T>>
where
T: Send + 'static,
Query: Future<Output = rok_db::Result<T>> + Send + 'static,
{
runtime().spawn(query)
}
pub fn run<T, Build, Query>(cx: &App, build: Build) -> Task<Result<T, DbError>>
where
T: Send + 'static,
Build: FnOnce(Db) -> Query,
Query: Future<Output = rok_db::Result<T>> + Send + 'static,
{
let Some(db) = connection(cx) else {
return Task::ready(Err(DbError::NotConnected));
};
let running = start(build(db));
cx.background_executor().spawn(async move {
match running.await {
Ok(result) => result.map_err(DbError::from),
Err(_) => Err(DbError::Cancelled),
}
})
}
pub fn invalidate(key: impl Into<SharedString>, cx: &mut App) {
let key = key.into();
crate::query::invalidate(cx, &crate::query_key![key.as_ref()]);
*cx.default_global::<Connection>()
.generations
.entry(key)
.or_default() += 1;
cx.refresh_windows();
}
pub fn invalidate_all(cx: &mut App) {
crate::query::invalidate(cx, &crate::query::QueryKey::root());
cx.default_global::<Connection>().epoch += 1;
cx.refresh_windows();
}
pub fn watch_changes<M>(cx: &mut App) -> Task<Result<(), DbError>>
where
M: rok_db::Model + 'static,
{
use futures::{
channel::{mpsc, oneshot},
future::Either,
StreamExt as _,
};
let Some(db) = connection(cx) else {
return Task::ready(Err(DbError::NotConnected));
};
let (changes_tx, mut changes_rx) = mpsc::unbounded::<()>();
let (stop, mut stopped) = oneshot::channel::<()>();
let listening = start(async move {
let mut changes = M::changes(&db).await?;
loop {
let next = std::pin::pin!(changes.recv());
match futures::future::select(&mut stopped, next).await {
Either::Left(_) => return Ok(()),
Either::Right((change, _)) => {
change?;
if changes_tx.unbounded_send(()).is_err() {
return Ok(());
}
}
}
}
});
cx.spawn(async move |cx| {
let _stop = stop;
while changes_rx.next().await.is_some() {
while changes_rx.try_recv().is_ok() {}
if cx.update(|cx| invalidate(M::TABLE, cx)).is_err() {
return Ok(());
}
}
match listening.await {
Ok(result) => result.map_err(DbError::from),
Err(_) => Err(DbError::Cancelled),
}
})
}
#[derive(Clone, Debug)]
pub struct Query<T> {
data: Option<T>,
error: Option<DbError>,
loading: bool,
}
impl<T> Query<T> {
pub fn data(&self) -> Option<&T> {
self.data.as_ref()
}
pub fn error(&self) -> Option<&DbError> {
self.error.as_ref()
}
pub fn is_loading(&self) -> bool {
self.loading
}
}
struct QueryCell<T> {
query: Query<T>,
fetched: Option<(u64, u64)>,
fetch_task: Option<Task<()>>,
}
#[deprecated(
since = "0.6.0",
note = "use `query::use_query(cx, db::db_query(query_key![..], |db| ..))`; removed in 0.8"
)]
pub fn use_query<T, Build, Fetch>(
key: impl Into<SharedString>,
window: &mut Window,
cx: &mut App,
build: Build,
) -> Query<T>
where
T: Clone + Send + 'static,
Build: FnOnce(Db) -> Fetch,
Fetch: Future<Output = rok_db::Result<T>> + Send + 'static,
{
let key = key.into();
let current = {
let connection = cx.default_global::<Connection>();
(
connection.epoch,
connection.generations.get(&key).copied().unwrap_or(0),
)
};
let state = use_keyed_state(
ElementId::Name(format!("rok-ui-db-query:{key}").into()),
window,
cx,
|| QueryCell::<T> {
query: Query {
data: None,
error: None,
loading: true,
},
fetched: None,
fetch_task: None,
},
);
if state.read(cx).fetched != Some(current) {
let fetching = run(cx, build);
let target = state.clone();
let fetch = window.spawn(cx, async move |cx| {
let result = fetching.await;
cx.update(|window, cx| {
target.update(cx, |cell| {
cell.query.loading = false;
match result {
Ok(data) => {
cell.query.data = Some(data);
cell.query.error = None;
}
Err(error) => cell.query.error = Some(error),
}
});
window.refresh();
})
.ok();
});
state.update(cx, |cell| {
cell.fetched = Some(current);
cell.query.loading = true;
cell.fetch_task = Some(fetch);
});
}
state.read(cx).query.clone()
}
#[cfg(test)]
mod tests {
use super::*;
#[gpui::test]
fn calls_without_a_connection_fail_fast(cx: &mut gpui::TestAppContext) {
let task = cx.update(|cx| run(cx, |db| async move { db.ping().await }));
let result = cx.executor().block_test(task);
assert_eq!(result, Err(DbError::NotConnected));
}
#[test]
fn database_errors_come_back_as_failures() {
let db = runtime()
.block_on(async {
Db::builder()
.acquire_timeout(std::time::Duration::from_secs(2))
.connect_lazy("postgres://rok:rok@127.0.0.1:1/rok")
})
.expect("a lazy pool is created without connecting");
let result = runtime()
.block_on(start(async move { db.ping().await }))
.expect("the task finishes");
let error = DbError::from(result.expect_err("there is no database"));
assert!(matches!(error, DbError::Failed(_)), "{error:?}");
}
}