Skip to main content

type_bridge/
session.rs

1//! Database session handles and connection options.
2
3use std::fmt;
4use std::sync::Arc;
5
6#[allow(unused_imports)]
7use crate::error::{Error, Result};
8use crate::schema::{Schema, SchemaPackage, Unbound};
9use type_bridge_orm::_registry::DescriptorRegistry;
10
11/// Normalized outcome of creating the database bound to a generated client.
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub enum DatabaseCreateOutcome {
14    /// This operation created the database.
15    Created,
16    /// The database already existed or a concurrent creator won the race.
17    AlreadyExists,
18}
19
20/// Normalized outcome of deleting the database bound to a generated client.
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22pub enum DatabaseDeleteOutcome {
23    /// This operation observed the database present and established its absence.
24    Deleted,
25    /// The database was already absent before destructive dispatch.
26    AlreadyAbsent,
27}
28
29/// Read-only state of one exact managed database and reserved journal pair.
30#[cfg(feature = "typedb")]
31#[derive(Clone, Copy, Debug, Eq, PartialEq)]
32pub enum ManagedDatabasePairState {
33    /// Neither member exists.
34    Absent,
35    /// Only a standalone managed database without TypeBridge control state exists.
36    StandaloneManaged,
37    /// Both members exist and the journal owns this exact database and scope.
38    OwnedPair,
39    /// Only the exact owner-verified journal remains.
40    OwnedJournalOrphan,
41}
42
43/// Outcome of executing one pair-aware database deletion plan.
44#[cfg(feature = "typedb")]
45#[derive(Clone, Copy, Debug, Eq, PartialEq)]
46pub enum ManagedDatabaseDeleteOutcome {
47    /// Neither member existed when execution began.
48    AlreadyAbsent,
49    /// A standalone managed database was deleted.
50    DeletedStandaloneManaged,
51    /// The owner-verified journal was deleted before its managed database.
52    DeletedOwnedPair,
53    /// An owner-verified orphan journal was deleted.
54    DeletedOwnedJournalOrphan,
55}
56
57/// Owned, single-use destructive admission for one inspected database pair.
58#[cfg(feature = "typedb")]
59pub struct ManagedDatabaseDeletionPlan {
60    inner: type_bridge_schema_migration_typedb::ManagedDatabasePairDeletionPlan,
61}
62
63#[cfg(feature = "typedb")]
64impl ManagedDatabaseDeletionPlan {
65    /// Return the exact pair state admitted by this plan.
66    #[must_use]
67    pub fn inspected_state(&self) -> ManagedDatabasePairState {
68        map_pair_state(self.inner.inspected_state())
69    }
70
71    /// Revalidate and execute journal-first deletion.
72    pub async fn execute(self) -> Result<ManagedDatabaseDeleteOutcome> {
73        self.inner
74            .execute()
75            .await
76            .map(map_delete_outcome)
77            .map_err(administration_error)
78    }
79
80    /// Revalidate interruptibly, then execute without masking provider outcomes.
81    pub async fn execute_controlled(
82        self,
83        control: &crate::MigrationExecutionControl,
84    ) -> Result<ManagedDatabaseDeleteOutcome> {
85        self.inner
86            .execute_controlled(control)
87            .await
88            .map(map_delete_outcome)
89            .map_err(administration_error)
90    }
91}
92
93/// Connection options for TypeDB servers.
94#[derive(Clone, PartialEq, Eq)]
95pub struct ConnectionOptions {
96    address: String,
97    database: String,
98    username: Option<String>,
99    password: Option<String>,
100    http_port: u16,
101    tls: bool,
102}
103
104impl fmt::Debug for ConnectionOptions {
105    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
106        formatter
107            .debug_struct("ConnectionOptions")
108            .field("address", &self.address)
109            .field("database", &self.database)
110            .field("username", &self.username)
111            .field("password", &self.password.as_ref().map(|_| "[REDACTED]"))
112            .field("http_port", &self.http_port)
113            .field("tls", &self.tls)
114            .finish()
115    }
116}
117
118impl ConnectionOptions {
119    /// Create connection options targeting a database server.
120    #[must_use]
121    pub fn new(address: impl Into<String>, database: impl Into<String>) -> Self {
122        Self {
123            address: address.into(),
124            database: database.into(),
125            username: None,
126            password: None,
127            http_port: 8000,
128            tls: false,
129        }
130    }
131
132    /// Set authentication credentials.
133    #[must_use]
134    pub fn credentials(mut self, username: impl Into<String>, password: impl Into<String>) -> Self {
135        self.username = Some(username.into());
136        self.password = Some(password.into());
137        self
138    }
139
140    /// Set the HTTP probe port.
141    #[must_use]
142    pub fn http_port(mut self, port: u16) -> Self {
143        self.http_port = port;
144        self
145    }
146
147    /// Enable or disable TLS.
148    #[must_use]
149    pub fn tls(mut self, enabled: bool) -> Self {
150        self.tls = enabled;
151        self
152    }
153
154    /// Return the server address.
155    #[must_use]
156    pub fn address(&self) -> &str {
157        &self.address
158    }
159
160    /// Return the target database name.
161    #[must_use]
162    pub fn database(&self) -> &str {
163        &self.database
164    }
165
166    /// Return the HTTP probe port.
167    #[must_use]
168    pub fn get_http_port(&self) -> u16 {
169        self.http_port
170    }
171
172    /// Return whether TLS is enabled.
173    #[must_use]
174    pub fn is_tls(&self) -> bool {
175        self.tls
176    }
177}
178
179impl From<(&str, &str)> for ConnectionOptions {
180    fn from((address, database): (&str, &str)) -> Self {
181        Self::new(address, database)
182    }
183}
184
185/// Primary database session handle type-branded by schema `S`.
186pub struct Database<S: Schema = Unbound> {
187    inner: type_bridge_orm::Database,
188    installed_schema: Option<Arc<type_bridge_orm::InstalledRuntimeProjection>>,
189    match_registry: Option<Arc<DescriptorRegistry>>,
190    #[cfg_attr(not(feature = "typedb"), allow(dead_code))]
191    managed_scope_id: Option<type_bridge_contract::managed_scope::ManagedScopeId>,
192    marker: std::marker::PhantomData<fn() -> S>,
193}
194
195pub(crate) fn build_match_registry(
196    installed: &type_bridge_orm::InstalledRuntimeProjection,
197) -> Result<Arc<DescriptorRegistry>> {
198    installed
199        .match_registry()
200        .map(Arc::new)
201        .map_err(Error::from_orm)
202}
203
204impl Database<Unbound> {
205    /// Connect to a TypeDB server returning an unbound database handle.
206    #[cfg(feature = "typedb")]
207    pub async fn connect(options: impl Into<ConnectionOptions>) -> Result<Database<Unbound>> {
208        let opts = options.into();
209        let username = opts.username.as_deref().unwrap_or("admin");
210        let password = opts.password.as_deref().unwrap_or("password");
211        let orm_opts = type_bridge_orm::ConnectOptions {
212            http_port: opts.http_port,
213            tls: opts.tls,
214            ..type_bridge_orm::ConnectOptions::default()
215        };
216
217        let inner = type_bridge_orm::Database::connect_with_options(
218            &opts.address,
219            &opts.database,
220            username,
221            password,
222            orm_opts,
223        )
224        .await
225        .map_err(Error::from_orm)?;
226
227        Ok(Database {
228            inner,
229            installed_schema: None,
230            match_registry: None,
231            managed_scope_id: None,
232            marker: std::marker::PhantomData,
233        })
234    }
235
236    /// Construct a Database session wrapping an existing ORM Database (crate-internal).
237    #[allow(dead_code)]
238    pub(crate) fn from_orm_database(inner: type_bridge_orm::Database) -> Self {
239        Self {
240            inner,
241            installed_schema: None,
242            match_registry: None,
243            managed_scope_id: None,
244            marker: std::marker::PhantomData,
245        }
246    }
247
248    /// Bind and verify a generated schema package, transitioning to `Database<S>`.
249    pub fn with_schema<S: Schema>(self, schema: SchemaPackage<S>) -> Result<Database<S>> {
250        let (installed, authority) = schema.verify_and_install_with_authority()?;
251        let match_registry = build_match_registry(&installed)?;
252        Ok(Database::from_bound_parts(
253            self.inner,
254            installed,
255            match_registry,
256            authority.map(|authority| authority.managed_scope().id().clone()),
257        ))
258    }
259}
260
261impl<S: Schema> Database<S> {
262    pub(crate) fn from_bound_parts(
263        inner: type_bridge_orm::Database,
264        installed: Arc<type_bridge_orm::InstalledRuntimeProjection>,
265        match_registry: Arc<DescriptorRegistry>,
266        managed_scope_id: Option<type_bridge_contract::managed_scope::ManagedScopeId>,
267    ) -> Self {
268        Self {
269            inner,
270            installed_schema: Some(installed),
271            match_registry: Some(match_registry),
272            managed_scope_id,
273            marker: std::marker::PhantomData,
274        }
275    }
276
277    #[cfg(test)]
278    pub(crate) fn from_test_parts(
279        inner: type_bridge_orm::Database,
280        installed: type_bridge_orm::InstalledRuntimeProjection,
281    ) -> Self {
282        let installed = Arc::new(installed);
283        let match_registry =
284            build_match_registry(&installed).expect("test projection descriptors register");
285        Self {
286            inner,
287            installed_schema: Some(installed),
288            match_registry: Some(match_registry),
289            managed_scope_id: None,
290            marker: std::marker::PhantomData,
291        }
292    }
293    #[cfg(test)]
294    pub(crate) fn from_test_unbound_parts(inner: type_bridge_orm::Database) -> Self {
295        Self {
296            inner,
297            installed_schema: None,
298            match_registry: None,
299            managed_scope_id: None,
300            marker: std::marker::PhantomData,
301        }
302    }
303    /// Create a lightweight client-owned exact entity manager.
304    pub fn entities<M>(&self) -> crate::entity_manager::EntityManager<'_, S, M>
305    where
306        M: crate::__codegen::EntityModel<Schema = S>,
307    {
308        crate::entity_manager::EntityManager::new(self)
309    }
310    /// Create a lightweight client-owned exact relation manager.
311    pub fn relations<M>(&self) -> crate::relation_manager::RelationManager<'_, S, M>
312    where
313        M: crate::__codegen::RelationModel<Schema = S>,
314    {
315        crate::relation_manager::RelationManager::new(self)
316    }
317    /// Create a staged transaction. Nothing opens until
318    /// [`commit`](crate::staged::Transaction::commit), which runs every
319    /// staged plan in order as one provider transaction.
320    ///
321    /// The kind is [`TransactionOptions::kind`](crate::staged::TransactionOptions),
322    /// or `Write` when a staged plan writes. A `Schema` transaction stages
323    /// no plans; schema changes go through migrations.
324    #[must_use]
325    pub fn transaction(
326        &self,
327        options: crate::staged::TransactionOptions,
328    ) -> crate::staged::Transaction<S> {
329        crate::staged::Transaction::new(self.inner.transaction(options))
330    }
331    /// Open one client-owned write transaction over this schema-bound
332    /// database. Operations on its borrowed managers never auto-commit;
333    /// the caller terminally commits or rolls back, and dropping the open
334    /// transaction releases the context without commit.
335    pub async fn write(&self) -> Result<crate::transaction::WriteTransaction<'_, S>> {
336        crate::transaction::WriteTransaction::open(self).await
337    }
338    /// Open one reusable client-owned read transaction. Query terminals
339    /// borrow and reuse its retained context until explicit close or drop.
340    pub async fn read(&self) -> Result<crate::transaction::ReadTransaction<'_, S>> {
341        crate::transaction::ReadTransaction::open(self).await
342    }
343    /// Return the target database name.
344    #[must_use]
345    pub fn database_name(&self) -> &str {
346        self.inner.database_name()
347    }
348
349    /// Return whether the one configured database exists.
350    pub async fn database_exists(&self) -> Result<bool> {
351        self.inner.database_exists().await.map_err(Error::from_orm)
352    }
353
354    /// Return whether the managed database exists, honoring execution controls.
355    #[cfg(feature = "typedb")]
356    pub async fn database_exists_controlled(
357        &self,
358        control: &crate::MigrationExecutionControl,
359    ) -> Result<bool> {
360        if let Some(scope) = &self.managed_scope_id {
361            return self
362                .pair_administrator(scope.clone())?
363                .database_exists_controlled(control)
364                .await
365                .map_err(administration_error);
366        }
367        control.check().map_err(administration_error)?;
368        self.database_exists().await
369    }
370
371    /// Create the one configured database and return its normalized outcome.
372    pub async fn create_database(&self) -> Result<DatabaseCreateOutcome> {
373        #[cfg(feature = "typedb")]
374        if let Some(scope) = &self.managed_scope_id {
375            return self
376                .pair_administrator(scope.clone())?
377                .create_database_outcome()
378                .await
379                .map(|outcome| match outcome {
380                    type_bridge_schema_migration_typedb::ManagedDatabasePairCreateOutcome::Created => DatabaseCreateOutcome::Created,
381                    type_bridge_schema_migration_typedb::ManagedDatabasePairCreateOutcome::AlreadyExists => DatabaseCreateOutcome::AlreadyExists,
382                })
383                .map_err(administration_error);
384        }
385        self.inner
386            .create_database_outcome()
387            .await
388            .map(|outcome| match outcome {
389                type_bridge_orm::session::DatabaseCreateOutcome::Created => {
390                    DatabaseCreateOutcome::Created
391                }
392                type_bridge_orm::session::DatabaseCreateOutcome::AlreadyExists => {
393                    DatabaseCreateOutcome::AlreadyExists
394                }
395            })
396            .map_err(Error::from_orm)
397    }
398
399    /// Create the configured database with cancellation and deadline control.
400    #[cfg(feature = "typedb")]
401    pub async fn create_database_controlled(
402        &self,
403        control: &crate::MigrationExecutionControl,
404    ) -> Result<DatabaseCreateOutcome> {
405        if let Some(scope) = &self.managed_scope_id {
406            return self
407                .pair_administrator(scope.clone())?
408                .create_database_outcome_controlled(control)
409                .await
410                .map(|outcome| match outcome {
411                    type_bridge_schema_migration_typedb::ManagedDatabasePairCreateOutcome::Created => DatabaseCreateOutcome::Created,
412                    type_bridge_schema_migration_typedb::ManagedDatabasePairCreateOutcome::AlreadyExists => DatabaseCreateOutcome::AlreadyExists,
413                })
414                .map_err(administration_error);
415        }
416        control.check().map_err(administration_error)?;
417        self.create_database().await
418    }
419
420    /// Delete the one configured database and return its normalized outcome.
421    pub async fn delete_database(&self) -> Result<DatabaseDeleteOutcome> {
422        #[cfg(feature = "typedb")]
423        if self.managed_scope_id.is_some() {
424            return Err(Error::Database {
425                message: "managed database deletion requires plan_database_delete() and explicit plan execution"
426                    .to_owned(),
427                source: None,
428            });
429        }
430        self.inner
431            .delete_database_outcome()
432            .await
433            .map(|outcome| match outcome {
434                type_bridge_orm::session::DatabaseDeleteOutcome::Deleted => {
435                    DatabaseDeleteOutcome::Deleted
436                }
437                type_bridge_orm::session::DatabaseDeleteOutcome::AlreadyAbsent => {
438                    DatabaseDeleteOutcome::AlreadyAbsent
439                }
440            })
441            .map_err(Error::from_orm)
442    }
443
444    /// Inspect the exact managed database and reserved journal pair.
445    #[cfg(feature = "typedb")]
446    pub async fn inspect_database_pair(&self) -> Result<ManagedDatabasePairState> {
447        let scope = self
448            .managed_scope_id
449            .clone()
450            .ok_or_else(|| Error::Database {
451                message:
452                    "managed database administration requires verified generated schema authority"
453                        .to_owned(),
454                source: None,
455            })?;
456        self.pair_administrator(scope)?
457            .inspect()
458            .await
459            .map(map_pair_state)
460            .map_err(administration_error)
461    }
462
463    /// Inspect the managed pair while honoring cancellation and a deadline.
464    #[cfg(feature = "typedb")]
465    pub async fn inspect_database_pair_controlled(
466        &self,
467        control: &crate::MigrationExecutionControl,
468    ) -> Result<ManagedDatabasePairState> {
469        let scope = self
470            .managed_scope_id
471            .clone()
472            .ok_or_else(|| Error::Database {
473                message:
474                    "managed database administration requires verified generated schema authority"
475                        .to_owned(),
476                source: None,
477            })?;
478        self.pair_administrator(scope)?
479            .inspect_controlled(control)
480            .await
481            .map(map_pair_state)
482            .map_err(administration_error)
483    }
484
485    /// Inspect and retain an explicit pair-aware destructive deletion plan.
486    #[cfg(feature = "typedb")]
487    pub async fn plan_database_delete(&self) -> Result<ManagedDatabaseDeletionPlan> {
488        let scope = self
489            .managed_scope_id
490            .clone()
491            .ok_or_else(|| Error::Database {
492                message: "managed database deletion requires verified generated schema authority"
493                    .to_owned(),
494                source: None,
495            })?;
496        self.pair_administrator(scope)?
497            .plan_delete()
498            .await
499            .map(|inner| ManagedDatabaseDeletionPlan { inner })
500            .map_err(administration_error)
501    }
502
503    /// Inspect and retain a deletion plan while honoring execution controls.
504    #[cfg(feature = "typedb")]
505    pub async fn plan_database_delete_controlled(
506        &self,
507        control: &crate::MigrationExecutionControl,
508    ) -> Result<ManagedDatabaseDeletionPlan> {
509        let scope = self
510            .managed_scope_id
511            .clone()
512            .ok_or_else(|| Error::Database {
513                message: "managed database deletion requires verified generated schema authority"
514                    .to_owned(),
515                source: None,
516            })?;
517        self.pair_administrator(scope)?
518            .plan_delete_controlled(control)
519            .await
520            .map(|inner| ManagedDatabaseDeletionPlan { inner })
521            .map_err(administration_error)
522    }
523
524    #[cfg(feature = "typedb")]
525    fn pair_administrator(
526        &self,
527        scope: type_bridge_contract::managed_scope::ManagedScopeId,
528    ) -> Result<type_bridge_schema_migration_typedb::ManagedDatabasePairAdministrator> {
529        type_bridge_schema_migration_typedb::ManagedDatabasePairAdministrator::from_managed_database(
530            Arc::new(self.inner.clone()),
531            scope,
532        )
533        .map_err(administration_error)
534    }
535
536    /// Explicitly close this database's provider connection.
537    ///
538    /// Closing is idempotent. Once closed, the database cannot admit new
539    /// provider work, while repeated calls remain harmless.
540    pub fn close(&self) -> Result<()> {
541        self.inner.close().map_err(Error::from_orm)
542    }
543
544    /// Return whether this database handle is bound to a verified schema.
545    #[must_use]
546    pub fn is_schema_bound(&self) -> bool {
547        self.installed_schema.is_some()
548    }
549
550    /// Return the internal ORM handle for engine mechanics (crate-internal).
551    #[allow(dead_code)]
552    pub(crate) fn inner_orm(&self) -> &type_bridge_orm::Database {
553        &self.inner
554    }
555
556    pub(crate) fn operation_limits(
557        &self,
558        requested: type_bridge_orm::QueryExecutionResourceLimits,
559    ) -> type_bridge_orm::QueryExecutionResourceLimits {
560        self.inner.answer_limits().map_or_else(
561            || requested.effective(),
562            |ceiling| requested.constrained_by(ceiling),
563        )
564    }
565
566    /// Return the installed projection if schema-bound (crate-internal).
567    #[allow(dead_code)]
568    pub(crate) fn installed_schema(
569        &self,
570    ) -> Option<&Arc<type_bridge_orm::InstalledRuntimeProjection>> {
571        self.installed_schema.as_ref()
572    }
573
574    /// Return the match descriptor registry if schema-bound (crate-internal).
575    #[allow(dead_code)]
576    pub(crate) fn match_registry(&self) -> Option<&Arc<DescriptorRegistry>> {
577        self.match_registry.as_ref()
578    }
579}
580
581#[cfg(feature = "typedb")]
582fn map_pair_state(
583    state: type_bridge_schema_migration_typedb::ManagedDatabasePairState,
584) -> ManagedDatabasePairState {
585    match state {
586        type_bridge_schema_migration_typedb::ManagedDatabasePairState::Absent => {
587            ManagedDatabasePairState::Absent
588        }
589        type_bridge_schema_migration_typedb::ManagedDatabasePairState::StandaloneManaged => {
590            ManagedDatabasePairState::StandaloneManaged
591        }
592        type_bridge_schema_migration_typedb::ManagedDatabasePairState::OwnedPair => {
593            ManagedDatabasePairState::OwnedPair
594        }
595        type_bridge_schema_migration_typedb::ManagedDatabasePairState::OwnedJournalOrphan => {
596            ManagedDatabasePairState::OwnedJournalOrphan
597        }
598    }
599}
600
601#[cfg(feature = "typedb")]
602fn map_delete_outcome(
603    outcome: type_bridge_schema_migration_typedb::ManagedDatabasePairDeleteOutcome,
604) -> ManagedDatabaseDeleteOutcome {
605    match outcome {
606        type_bridge_schema_migration_typedb::ManagedDatabasePairDeleteOutcome::AlreadyAbsent => {
607            ManagedDatabaseDeleteOutcome::AlreadyAbsent
608        }
609        type_bridge_schema_migration_typedb::ManagedDatabasePairDeleteOutcome::DeletedStandaloneManaged => ManagedDatabaseDeleteOutcome::DeletedStandaloneManaged,
610        type_bridge_schema_migration_typedb::ManagedDatabasePairDeleteOutcome::DeletedOwnedPair => {
611            ManagedDatabaseDeleteOutcome::DeletedOwnedPair
612        }
613        type_bridge_schema_migration_typedb::ManagedDatabasePairDeleteOutcome::DeletedOwnedJournalOrphan => ManagedDatabaseDeleteOutcome::DeletedOwnedJournalOrphan,
614    }
615}
616
617#[cfg(feature = "typedb")]
618fn administration_error(error: type_bridge_contract::diagnostic::Diagnostic) -> Error {
619    Error::from_contract_diagnostic(error)
620}
621
622#[cfg(test)]
623mod tests {
624    use std::collections::BTreeSet;
625    use std::sync::Arc;
626    use std::sync::Mutex;
627    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
628
629    use type_bridge_orm::error::OrmError;
630    use type_bridge_orm::session::backend::{BoxFuture, DriverBackend, TransactionOps, TxType};
631
632    use super::Database;
633    use crate::schema::Unbound;
634
635    struct CloseBackend {
636        closed: Arc<AtomicBool>,
637        close_calls: Arc<AtomicUsize>,
638    }
639
640    struct AdministrationBackend {
641        databases: Arc<Mutex<BTreeSet<String>>>,
642    }
643
644    impl DriverBackend for AdministrationBackend {
645        fn open_transaction(
646            &self,
647            _database: &str,
648            _tx_type: TxType,
649        ) -> BoxFuture<'_, std::result::Result<Box<dyn TransactionOps>, OrmError>> {
650            Box::pin(async { Err(OrmError::Connection("unexpected transaction".into())) })
651        }
652
653        fn is_open(&self) -> bool {
654            true
655        }
656
657        fn database_exists(
658            &self,
659            database: &str,
660        ) -> BoxFuture<'_, std::result::Result<bool, OrmError>> {
661            let exists = self.databases.lock().unwrap().contains(database);
662            Box::pin(async move { Ok(exists) })
663        }
664
665        fn create_database(
666            &self,
667            database: &str,
668        ) -> BoxFuture<'_, std::result::Result<(), OrmError>> {
669            self.databases.lock().unwrap().insert(database.to_owned());
670            Box::pin(async { Ok(()) })
671        }
672
673        fn delete_database(
674            &self,
675            database: &str,
676        ) -> BoxFuture<'_, std::result::Result<(), OrmError>> {
677            self.databases.lock().unwrap().remove(database);
678            Box::pin(async { Ok(()) })
679        }
680
681        fn schema_text(
682            &self,
683            _database: &str,
684        ) -> BoxFuture<'_, std::result::Result<String, OrmError>> {
685            Box::pin(async { Ok(String::new()) })
686        }
687    }
688
689    impl DriverBackend for CloseBackend {
690        fn open_transaction(
691            &self,
692            _database: &str,
693            _tx_type: TxType,
694        ) -> BoxFuture<'_, std::result::Result<Box<dyn TransactionOps>, OrmError>> {
695            Box::pin(async {
696                Err(OrmError::Connection(
697                    "closed test backend cannot open transactions".into(),
698                ))
699            })
700        }
701
702        fn is_open(&self) -> bool {
703            !self.closed.load(Ordering::SeqCst)
704        }
705
706        fn close_connection(&self) -> std::result::Result<(), OrmError> {
707            self.close_calls.fetch_add(1, Ordering::SeqCst);
708            self.closed.store(true, Ordering::SeqCst);
709            Ok(())
710        }
711    }
712
713    #[test]
714    fn explicit_database_close_is_idempotent() {
715        let closed = Arc::new(AtomicBool::new(false));
716        let close_calls = Arc::new(AtomicUsize::new(0));
717        let inner = type_bridge_orm::Database::with_backend(
718            Box::new(CloseBackend {
719                closed: Arc::clone(&closed),
720                close_calls: Arc::clone(&close_calls),
721            }),
722            "app",
723        );
724        let database: Database<Unbound> = Database::from_test_unbound_parts(inner);
725
726        database.close().unwrap();
727        database.close().unwrap();
728
729        assert!(closed.load(Ordering::SeqCst));
730        assert_eq!(close_calls.load(Ordering::SeqCst), 2);
731    }
732
733    #[cfg(feature = "typedb")]
734    #[tokio::test]
735    async fn generated_database_administration_is_pair_aware_and_plan_owned() {
736        let databases = Arc::new(Mutex::new(BTreeSet::new()));
737        let inner = type_bridge_orm::Database::with_backend(
738            Box::new(AdministrationBackend {
739                databases: Arc::clone(&databases),
740            }),
741            "app",
742        );
743        let database: Database<Unbound> = Database {
744            inner,
745            installed_schema: None,
746            match_registry: None,
747            managed_scope_id: Some(
748                type_bridge_contract::managed_scope::ManagedScopeId::new("generated-scope")
749                    .unwrap(),
750            ),
751            marker: std::marker::PhantomData,
752        };
753
754        let cancellation = type_bridge_schema_migration::MigrationCancellation::default();
755        cancellation.cancel();
756        let control = type_bridge_schema_migration::MigrationExecutionControl::new(
757            cancellation,
758            None,
759            type_bridge_schema_migration::MigrationExecutionResourceLimits::default(),
760        );
761        let cancelled = database
762            .database_exists_controlled(&control)
763            .await
764            .expect_err("pre-cancelled administration rejects before an effect");
765        assert_eq!(cancelled.code(), Some("migration_execution_cancelled"));
766        assert_eq!(cancelled.category(), crate::ErrorCategory::Cancelled);
767
768        assert_eq!(
769            database.create_database().await.unwrap(),
770            super::DatabaseCreateOutcome::Created
771        );
772        assert_eq!(
773            database.inspect_database_pair().await.unwrap(),
774            super::ManagedDatabasePairState::StandaloneManaged
775        );
776        assert!(database.delete_database().await.is_err());
777        let plan = database.plan_database_delete().await.unwrap();
778        drop(database);
779        assert_eq!(
780            plan.execute().await.unwrap(),
781            super::ManagedDatabaseDeleteOutcome::DeletedStandaloneManaged
782        );
783        assert!(databases.lock().unwrap().is_empty());
784    }
785}