Skip to main content

type_bridge/
connection.rs

1//! One connection, direct or proxy, chosen by configuration.
2//!
3//! A program that opens a [`Connection`] and runs its queries through
4//! [`Connection::query`] runs unchanged against TypeDB or a TypeBridge server;
5//! only the [`ConnectionPolicy`] differs.
6
7use type_bridge_orm::{AnswerCancellation, QueryExecutionResourceLimits};
8
9use crate::Result;
10use crate::query::QuerySession;
11use crate::remote::{ProxyConnectionPolicy, ProxyDatabase};
12use crate::schema::Schema;
13use crate::session::Database;
14
15/// Where a connection's queries run.
16#[derive(Debug)]
17pub enum ConnectionPolicy {
18    /// Directly against TypeDB.
19    #[cfg(feature = "typedb")]
20    Direct(type_bridge_orm::DirectConnectionPolicy),
21    /// Through a TypeBridge server.
22    Proxy(ProxyConnectionPolicy),
23}
24
25#[cfg(feature = "typedb")]
26impl From<type_bridge_orm::DirectConnectionPolicy> for ConnectionPolicy {
27    fn from(policy: type_bridge_orm::DirectConnectionPolicy) -> Self {
28        Self::Direct(policy)
29    }
30}
31
32impl From<ProxyConnectionPolicy> for ConnectionPolicy {
33    fn from(policy: ProxyConnectionPolicy) -> Self {
34        Self::Proxy(policy)
35    }
36}
37
38/// A schema-bound connection opened by [`crate::SchemaPackage::connect`].
39///
40/// Queries behave the same on both variants. Match on the variant only for
41/// what one of them alone offers, such as CRUD managers on a direct
42/// [`Database`].
43pub enum Connection<S: Schema> {
44    /// Directly against TypeDB.
45    Direct(Database<S>),
46    /// Through a TypeBridge server.
47    Proxy(ProxyDatabase<S>),
48}
49
50impl<S: Schema> std::fmt::Debug for Connection<S> {
51    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        formatter.write_str(match self {
53            Self::Direct(_) => "Connection::Direct",
54            Self::Proxy(_) => "Connection::Proxy",
55        })
56    }
57}
58
59impl<S: Schema> Connection<S> {
60    /// Start one query session under this connection's answer-limit ceiling.
61    pub fn query(&self) -> Result<QuerySession<'_, S>> {
62        self.query_with_resources(
63            QueryExecutionResourceLimits::default(),
64            AnswerCancellation::default(),
65        )
66    }
67
68    /// Start one query session whose resources are `resources` constrained by
69    /// this connection's answer-limit ceiling.
70    pub fn query_with_resources(
71        &self,
72        resources: QueryExecutionResourceLimits,
73        cancellation: AnswerCancellation,
74    ) -> Result<QuerySession<'_, S>> {
75        match self {
76            Self::Direct(database) => database.query_with_resources(resources, cancellation),
77            Self::Proxy(proxy) => proxy.query_with_resources(resources, cancellation),
78        }
79    }
80}