surrealdb/api/method/
use_ns.rs

1use crate::api::conn::Command;
2use crate::api::method::BoxFuture;
3use crate::api::method::UseDb;
4use crate::api::Connection;
5use crate::api::Result;
6use crate::method::OnceLockExt;
7use crate::Surreal;
8use std::borrow::Cow;
9use std::future::IntoFuture;
10
11/// Stores the namespace to use
12#[derive(Debug)]
13#[must_use = "futures do nothing unless you `.await` or poll them"]
14pub struct UseNs<'r, C: Connection> {
15	pub(super) client: Cow<'r, Surreal<C>>,
16	pub(super) ns: String,
17}
18
19impl<C> UseNs<'_, C>
20where
21	C: Connection,
22{
23	/// Converts to an owned type which can easily be moved to a different thread
24	pub fn into_owned(self) -> UseNs<'static, C> {
25		UseNs {
26			client: Cow::Owned(self.client.into_owned()),
27			..self
28		}
29	}
30}
31
32impl<'r, C> UseNs<'r, C>
33where
34	C: Connection,
35{
36	/// Switch to a specific database
37	pub fn use_db(self, db: impl Into<String>) -> UseDb<'r, C> {
38		UseDb {
39			ns: self.ns.into(),
40			db: db.into(),
41			client: self.client,
42		}
43	}
44}
45
46impl<'r, Client> IntoFuture for UseNs<'r, Client>
47where
48	Client: Connection,
49{
50	type Output = Result<()>;
51	type IntoFuture = BoxFuture<'r, Self::Output>;
52
53	fn into_future(self) -> Self::IntoFuture {
54		Box::pin(async move {
55			let router = self.client.router.extract()?;
56			router
57				.execute_unit(Command::Use {
58					namespace: Some(self.ns),
59					database: None,
60				})
61				.await
62		})
63	}
64}