sqlmodel 0.2.2

SQL databases in Rust, designed to be intuitive and type-safe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Connection session management for SQLModel Rust.
//!
//! This module provides a small "connection + optional console" wrapper plus a builder.
//!
//! Important: this is **not** the SQLAlchemy/SQLModel ORM Session (unit of work / identity map).
//! The ORM-style session lives in `sqlmodel::session` and is re-exported from the
//! `sqlmodel-session` crate.
//!
//! # Example
//!
//! ```rust,ignore
//! use sqlmodel::prelude::*;
//!
//! // Basic connection session without console
//! let session = ConnectionSession::builder().build_with(connection);
//!
//! // Connection session with auto-detected console
//! #[cfg(feature = "console")]
//! let session = ConnectionSession::builder()
//!     .with_auto_console()
//!     .build_with(connection);
//! ```

#[cfg(feature = "console")]
use std::sync::Arc;

#[cfg(feature = "console")]
use sqlmodel_console::{ConsoleAware, SqlModelConsole};

#[cfg(feature = "console")]
use crate::global_console::global_console;

use sqlmodel_core::Connection;

/// A database session that combines connection management with optional console output.
///
/// This type is a lightweight wrapper around a `Connection` and optional console.
/// For ORM-style behavior (identity map, unit of work, lazy loading), use
/// `sqlmodel::Session` (from `sqlmodel-session`).
#[derive(Debug)]
pub struct ConnectionSession<C: Connection> {
    /// The underlying connection
    connection: C,
    /// Optional console for rich output
    #[cfg(feature = "console")]
    console: Option<Arc<SqlModelConsole>>,
}

impl<C: Connection> ConnectionSession<C> {
    /// Create a new session with a connection.
    pub fn new(connection: C) -> Self {
        Self {
            connection,
            #[cfg(feature = "console")]
            console: None,
        }
    }

    /// Create a session builder.
    #[must_use]
    pub fn builder() -> ConnectionSessionBuilder<C> {
        ConnectionSessionBuilder::new()
    }

    /// Get a reference to the underlying connection.
    #[must_use]
    pub fn connection(&self) -> &C {
        &self.connection
    }

    /// Get a mutable reference to the underlying connection.
    pub fn connection_mut(&mut self) -> &mut C {
        &mut self.connection
    }

    /// Consume the session and return the underlying connection.
    pub fn into_connection(self) -> C {
        self.connection
    }
}

#[cfg(feature = "console")]
impl<C: Connection> ConsoleAware for ConnectionSession<C> {
    fn set_console(&mut self, console: Option<Arc<SqlModelConsole>>) {
        self.console = console;
    }

    fn console(&self) -> Option<&Arc<SqlModelConsole>> {
        self.console.as_ref()
    }

    fn has_console(&self) -> bool {
        self.console.is_some()
    }
}

/// Builder for creating ConnectionSession instances with fluent API.
///
/// # Example
///
/// ```rust,ignore
/// let session = ConnectionSession::builder()
///     .with_auto_console()  // Only available with "console" feature
///     .build_with(connection);
/// ```
#[derive(Debug, Default)]
pub struct ConnectionSessionBuilder<C: Connection> {
    #[cfg(feature = "console")]
    console: Option<Arc<SqlModelConsole>>,
    #[cfg(not(feature = "console"))]
    _marker: std::marker::PhantomData<C>,
    #[cfg(feature = "console")]
    _marker: std::marker::PhantomData<C>,
}

impl<C: Connection> ConnectionSessionBuilder<C> {
    /// Create a new session builder.
    #[must_use]
    pub fn new() -> Self {
        Self {
            #[cfg(feature = "console")]
            console: None,
            _marker: std::marker::PhantomData,
        }
    }

    /// Attach a console for rich output.
    ///
    /// The console will be used to emit progress information, query results,
    /// and error messages in a visually rich format.
    #[cfg(feature = "console")]
    #[must_use]
    pub fn with_console(mut self, console: SqlModelConsole) -> Self {
        self.console = Some(Arc::new(console));
        self
    }

    /// Attach a shared console for rich output.
    ///
    /// Use this when multiple sessions should share the same console
    /// (e.g., for coordinated output or shared theme).
    #[cfg(feature = "console")]
    #[must_use]
    pub fn with_shared_console(mut self, console: Arc<SqlModelConsole>) -> Self {
        self.console = Some(console);
        self
    }

    /// Use auto-detected output mode for the console.
    ///
    /// This creates a console that automatically detects whether
    /// the terminal supports rich output or should fall back to plain text.
    /// Uses `SqlModelConsole::new()` which performs environment detection.
    #[cfg(feature = "console")]
    #[must_use]
    pub fn with_auto_console(mut self) -> Self {
        self.console = Some(Arc::new(SqlModelConsole::new()));
        self
    }

    /// Build the session with the provided connection.
    ///
    /// Console selection follows these priorities (highest first):
    /// 1. Explicit console set via `with_console()` or similar
    /// 2. Global console (if set via `set_global_console()` or `init_auto_console()`)
    /// 3. No console (silent operation)
    #[allow(unused_mut)] // mut only used with console feature
    pub fn build_with(self, connection: C) -> ConnectionSession<C> {
        let mut session = ConnectionSession::new(connection);

        #[cfg(feature = "console")]
        {
            // Use explicit console if set, otherwise fall back to global console
            session.console = self.console.or_else(global_console);
        }

        session
    }
}

/// Builder for creating connections with console support.
///
/// This trait extends connection factories to support console integration.
/// Implement this for driver-specific connection builders.
#[cfg(feature = "console")]
pub trait ConnectionBuilderExt {
    /// The connection type produced by this builder.
    type Connection: Connection + ConsoleAware;

    /// Attach a console for rich output.
    fn with_console(self, console: SqlModelConsole) -> Self;

    /// Attach a shared console for rich output.
    fn with_shared_console(self, console: Arc<SqlModelConsole>) -> Self;

    /// Use auto-detected output mode for the console.
    fn with_auto_console(self) -> Self;
}

#[cfg(test)]
#[allow(clippy::manual_async_fn)] // Mock trait impls must match trait signatures
mod tests {
    use super::*;

    // Mock connection for testing
    #[derive(Debug)]
    struct MockConnection;

    impl sqlmodel_core::Connection for MockConnection {
        type Tx<'conn>
            = MockTransaction
        where
            Self: 'conn;

        fn query(
            &self,
            _cx: &asupersync::Cx,
            _sql: &str,
            _params: &[sqlmodel_core::Value],
        ) -> impl std::future::Future<
            Output = asupersync::Outcome<Vec<sqlmodel_core::Row>, sqlmodel_core::Error>,
        > + Send {
            async { asupersync::Outcome::Ok(vec![]) }
        }

        fn query_one(
            &self,
            _cx: &asupersync::Cx,
            _sql: &str,
            _params: &[sqlmodel_core::Value],
        ) -> impl std::future::Future<
            Output = asupersync::Outcome<Option<sqlmodel_core::Row>, sqlmodel_core::Error>,
        > + Send {
            async { asupersync::Outcome::Ok(None) }
        }

        fn execute(
            &self,
            _cx: &asupersync::Cx,
            _sql: &str,
            _params: &[sqlmodel_core::Value],
        ) -> impl std::future::Future<Output = asupersync::Outcome<u64, sqlmodel_core::Error>> + Send
        {
            async { asupersync::Outcome::Ok(0) }
        }

        fn insert(
            &self,
            _cx: &asupersync::Cx,
            _sql: &str,
            _params: &[sqlmodel_core::Value],
        ) -> impl std::future::Future<Output = asupersync::Outcome<i64, sqlmodel_core::Error>> + Send
        {
            async { asupersync::Outcome::Ok(0) }
        }

        fn batch(
            &self,
            _cx: &asupersync::Cx,
            _statements: &[(String, Vec<sqlmodel_core::Value>)],
        ) -> impl std::future::Future<Output = asupersync::Outcome<Vec<u64>, sqlmodel_core::Error>> + Send
        {
            async { asupersync::Outcome::Ok(vec![]) }
        }

        fn begin(
            &self,
            _cx: &asupersync::Cx,
        ) -> impl std::future::Future<
            Output = asupersync::Outcome<Self::Tx<'_>, sqlmodel_core::Error>,
        > + Send {
            async { asupersync::Outcome::Ok(MockTransaction) }
        }

        fn begin_with(
            &self,
            _cx: &asupersync::Cx,
            _isolation: sqlmodel_core::connection::IsolationLevel,
        ) -> impl std::future::Future<
            Output = asupersync::Outcome<Self::Tx<'_>, sqlmodel_core::Error>,
        > + Send {
            async { asupersync::Outcome::Ok(MockTransaction) }
        }

        fn prepare(
            &self,
            _cx: &asupersync::Cx,
            _sql: &str,
        ) -> impl std::future::Future<
            Output = asupersync::Outcome<
                sqlmodel_core::connection::PreparedStatement,
                sqlmodel_core::Error,
            >,
        > + Send {
            async {
                asupersync::Outcome::Ok(sqlmodel_core::connection::PreparedStatement::new(
                    0,
                    String::new(),
                    0,
                ))
            }
        }

        fn query_prepared(
            &self,
            _cx: &asupersync::Cx,
            _stmt: &sqlmodel_core::connection::PreparedStatement,
            _params: &[sqlmodel_core::Value],
        ) -> impl std::future::Future<
            Output = asupersync::Outcome<Vec<sqlmodel_core::Row>, sqlmodel_core::Error>,
        > + Send {
            async { asupersync::Outcome::Ok(vec![]) }
        }

        fn execute_prepared(
            &self,
            _cx: &asupersync::Cx,
            _stmt: &sqlmodel_core::connection::PreparedStatement,
            _params: &[sqlmodel_core::Value],
        ) -> impl std::future::Future<Output = asupersync::Outcome<u64, sqlmodel_core::Error>> + Send
        {
            async { asupersync::Outcome::Ok(0) }
        }

        fn ping(
            &self,
            _cx: &asupersync::Cx,
        ) -> impl std::future::Future<Output = asupersync::Outcome<(), sqlmodel_core::Error>> + Send
        {
            async { asupersync::Outcome::Ok(()) }
        }

        fn close(
            self,
            _cx: &asupersync::Cx,
        ) -> impl std::future::Future<Output = sqlmodel_core::error::Result<()>> + Send {
            async { Ok(()) }
        }
    }

    struct MockTransaction;

    impl sqlmodel_core::connection::TransactionOps for MockTransaction {
        fn query(
            &self,
            _cx: &asupersync::Cx,
            _sql: &str,
            _params: &[sqlmodel_core::Value],
        ) -> impl std::future::Future<
            Output = asupersync::Outcome<Vec<sqlmodel_core::Row>, sqlmodel_core::Error>,
        > + Send {
            async { asupersync::Outcome::Ok(vec![]) }
        }

        fn query_one(
            &self,
            _cx: &asupersync::Cx,
            _sql: &str,
            _params: &[sqlmodel_core::Value],
        ) -> impl std::future::Future<
            Output = asupersync::Outcome<Option<sqlmodel_core::Row>, sqlmodel_core::Error>,
        > + Send {
            async { asupersync::Outcome::Ok(None) }
        }

        fn execute(
            &self,
            _cx: &asupersync::Cx,
            _sql: &str,
            _params: &[sqlmodel_core::Value],
        ) -> impl std::future::Future<Output = asupersync::Outcome<u64, sqlmodel_core::Error>> + Send
        {
            async { asupersync::Outcome::Ok(0) }
        }

        fn savepoint(
            &self,
            _cx: &asupersync::Cx,
            _name: &str,
        ) -> impl std::future::Future<Output = asupersync::Outcome<(), sqlmodel_core::Error>> + Send
        {
            async { asupersync::Outcome::Ok(()) }
        }

        fn rollback_to(
            &self,
            _cx: &asupersync::Cx,
            _name: &str,
        ) -> impl std::future::Future<Output = asupersync::Outcome<(), sqlmodel_core::Error>> + Send
        {
            async { asupersync::Outcome::Ok(()) }
        }

        fn release(
            &self,
            _cx: &asupersync::Cx,
            _name: &str,
        ) -> impl std::future::Future<Output = asupersync::Outcome<(), sqlmodel_core::Error>> + Send
        {
            async { asupersync::Outcome::Ok(()) }
        }

        fn commit(
            self,
            _cx: &asupersync::Cx,
        ) -> impl std::future::Future<Output = asupersync::Outcome<(), sqlmodel_core::Error>> + Send
        {
            async { asupersync::Outcome::Ok(()) }
        }

        fn rollback(
            self,
            _cx: &asupersync::Cx,
        ) -> impl std::future::Future<Output = asupersync::Outcome<(), sqlmodel_core::Error>> + Send
        {
            async { asupersync::Outcome::Ok(()) }
        }
    }

    #[test]
    fn test_connection_session_builder_basic() {
        let conn = MockConnection;
        let session = ConnectionSession::builder().build_with(conn);
        assert!(std::ptr::eq(session.connection(), session.connection()));
    }

    #[test]
    fn test_connection_session_new() {
        let conn = MockConnection;
        let session = ConnectionSession::new(conn);
        let _ = session.connection();
    }

    #[test]
    fn test_connection_session_connection_access() {
        let conn = MockConnection;
        let mut session = ConnectionSession::new(conn);
        let _ = session.connection();
        let _ = session.connection_mut();
    }

    #[test]
    fn test_connection_session_into_connection() {
        let conn = MockConnection;
        let session = ConnectionSession::new(conn);
        let _recovered: MockConnection = session.into_connection();
    }

    #[cfg(feature = "console")]
    #[test]
    fn test_connection_session_builder_with_console() {
        let console = SqlModelConsole::new();
        let conn = MockConnection;
        let session = ConnectionSession::builder()
            .with_console(console)
            .build_with(conn);
        assert!(session.has_console());
    }

    #[cfg(feature = "console")]
    #[test]
    fn test_connection_session_builder_with_shared_console() {
        let console = Arc::new(SqlModelConsole::new());
        let conn1 = MockConnection;
        let conn2 = MockConnection;

        let session1 = ConnectionSession::builder()
            .with_shared_console(console.clone())
            .build_with(conn1);
        let session2 = ConnectionSession::builder()
            .with_shared_console(console)
            .build_with(conn2);

        assert!(session1.has_console());
        assert!(session2.has_console());
    }

    #[cfg(feature = "console")]
    #[test]
    fn test_connection_session_builder_with_auto_console() {
        let conn = MockConnection;
        let session = ConnectionSession::builder()
            .with_auto_console()
            .build_with(conn);
        assert!(session.has_console());
    }

    #[cfg(feature = "console")]
    #[test]
    fn test_connection_session_console_aware() {
        let conn = MockConnection;
        let mut session = ConnectionSession::new(conn);

        assert!(!session.has_console());
        assert!(session.console().is_none());

        let console = Arc::new(SqlModelConsole::new());
        session.set_console(Some(console));
        assert!(session.has_console());
        assert!(session.console().is_some());

        session.set_console(None);
        assert!(!session.has_console());
    }

    #[test]
    fn test_builder_chain_fluent_api() {
        let conn = MockConnection;
        let builder = ConnectionSession::<MockConnection>::builder();
        let _session = builder.build_with(conn);
    }
}