glacier-web 0.1.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! The database layer: connections, the ambient repo, transactions and raw
//! SQL. Models and queries build on this (see `glacier::Model`).
//!
//! # The ambient repo
//!
//! Model calls don't take a connection argument. They use the **current**
//! one: the app's repo during a request (`App::database`), whatever
//! `db::with` set, or the transaction `db::transaction` opened. Pass one
//! explicitly with `.on(..)` when you need to:
//!
//! ```no_run
//! # use glacier::prelude::*;
//! # #[derive(Model)] struct Post { id: i64, title: String }
//! # async fn demo(replica: glacier::db::Repo) -> glacier::Result<()> {
//! let post = Post::find(1).await?;                 // current repo
//! let posts = Post::all().on(&replica).await?;     // explicit repo
//! # Ok(()) }
//! ```
//!
//! Note that task-locals don't cross `tokio::spawn`; wrap spawned work in
//! `db::with`.

pub mod assoc;
mod cast;
mod changeset;
mod decimal;
pub mod migration;
mod query;
pub(crate) mod record;
mod sql;
mod value;

#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
compile_error!("glacier needs at least one database feature: `postgres` or `sqlite`");

use std::future::Future;
use std::sync::Arc;
use tracing::Instrument;
use tracing::field::Empty;

use sqlx::{AssertSqlSafe, Row as _};
use tokio::sync::Mutex;

pub use assoc::{Association, BelongsTo, HasMany, Nested, Preload};
pub use cast::Cast;
pub use changeset::{Changeset, Numericality, Save};
pub use decimal::Decimal;
pub use query::{Aggregable, Assign, Col, Expr, Grouped, Order, Query, Summable};
pub use record::{Errors, IntoField, Record, field};
pub use sql::{Dialect, Sql, quote_ident};
/// A UUID, for `uuid` columns.
pub use uuid::Uuid;
pub use value::{Date, FromColumn, JsonValue, NaiveTimestamp, Timestamp, ToValue, Value};
pub use value::{StoreSource, StoreTarget, store_get, store_set};

use crate::config::Config;
use crate::error::{Error, Result};

/// A pool of connections to one database.
#[derive(Clone)]
pub struct Repo {
    pool: Pool,
}

#[derive(Clone)]
enum Pool {
    #[cfg(feature = "postgres")]
    Postgres(sqlx::PgPool),
    #[cfg(feature = "sqlite")]
    Sqlite(sqlx::SqlitePool),
}

impl Repo {
    /// Connects to `postgres://…` or `sqlite:…` URLs. SQLite files (and their
    /// directories) are created if missing; `sqlite::memory:` gives a private
    /// in-memory database.
    pub async fn connect(url: &str) -> Result<Self> {
        Self::connect_with(url, None).await
    }

    /// Connects using `database.url` and optional `database.pool_size`.
    pub async fn from_config(config: &Config) -> Result<Self> {
        let url: String = config.get("database.url")?;
        let pool_size: Option<u32> = config.get_opt("database.pool_size")?;
        Self::connect_with(&url, pool_size).await
    }

    async fn connect_with(url: &str, pool_size: Option<u32>) -> Result<Self> {
        let pool = if url.starts_with("postgres://") || url.starts_with("postgresql://") {
            Self::postgres(url, pool_size).await?
        } else if url.starts_with("sqlite:") {
            Self::sqlite(url, pool_size).await?
        } else {
            return Err(Error::internal(format!(
                "unsupported database URL `{url}`; expected postgres:// or sqlite:"
            )));
        };
        Ok(Self { pool })
    }

    #[cfg(feature = "postgres")]
    async fn postgres(url: &str, pool_size: Option<u32>) -> Result<Pool> {
        use std::str::FromStr;

        let mut options = sqlx::postgres::PgConnectOptions::from_str(url)?;
        // Without a user in the URL or `PGUSER`, connect as the OS user, as
        // `psql` and Rails do.
        if !has_user(url)
            && std::env::var_os("PGUSER").is_none()
            && let Some(user) = std::env::var("USER").ok().filter(|u| !u.is_empty())
        {
            options = options.username(&user);
        }
        let pool = sqlx::postgres::PgPoolOptions::new()
            .max_connections(pool_size.unwrap_or(10))
            .connect_with(options)
            .await?;
        Ok(Pool::Postgres(pool))
    }

    #[cfg(not(feature = "postgres"))]
    async fn postgres(_url: &str, _pool_size: Option<u32>) -> Result<Pool> {
        Err(Error::internal(
            "Postgres support needs glacier's `postgres` feature",
        ))
    }

    #[cfg(feature = "sqlite")]
    async fn sqlite(url: &str, pool_size: Option<u32>) -> Result<Pool> {
        use std::path::Path;
        use std::str::FromStr;

        use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};

        let memory = url.contains(":memory:") || url.contains("mode=memory");
        if !memory {
            let path = url
                .trim_start_matches("sqlite://")
                .trim_start_matches("sqlite:");
            let path = path.split('?').next().unwrap_or(path);
            if let Some(dir) = Path::new(path)
                .parent()
                .filter(|d| !d.as_os_str().is_empty())
            {
                std::fs::create_dir_all(dir)?;
            }
        }
        let options = SqliteConnectOptions::from_str(url)?
            .create_if_missing(true)
            .foreign_keys(true);
        let pool = if memory {
            // Each connection to `:memory:` is a separate database, so keep
            // exactly one connection alive for the pool's lifetime.
            SqlitePoolOptions::new()
                .max_connections(1)
                .min_connections(1)
                .idle_timeout(None)
                .max_lifetime(None)
        } else {
            SqlitePoolOptions::new().max_connections(pool_size.unwrap_or(5))
        };
        Ok(Pool::Sqlite(pool.connect_with(options).await?))
    }

    #[cfg(not(feature = "sqlite"))]
    async fn sqlite(_url: &str, _pool_size: Option<u32>) -> Result<Pool> {
        Err(Error::internal(
            "SQLite support needs glacier's `sqlite` feature",
        ))
    }

    /// The underlying sqlx pool when this is a Postgres database, to share
    /// it with other libraries: raw sqlx, or SeaORM 2 (built on the same
    /// sqlx 0.9) through `SqlxPostgresConnector::from_sqlx_postgres_pool`.
    /// Use [`glacier::sqlx`](crate::sqlx) so the versions match.
    ///
    /// Queries made through it don't join Glacier's ambient transactions.
    #[cfg(feature = "postgres")]
    pub fn postgres_pool(&self) -> Option<&sqlx::PgPool> {
        match &self.pool {
            Pool::Postgres(pool) => Some(pool),
            #[allow(unreachable_patterns)]
            _ => None,
        }
    }

    /// The underlying sqlx pool when this is a SQLite database; see
    /// [`Repo::postgres_pool`].
    #[cfg(feature = "sqlite")]
    pub fn sqlite_pool(&self) -> Option<&sqlx::SqlitePool> {
        match &self.pool {
            Pool::Sqlite(pool) => Some(pool),
            #[allow(unreachable_patterns)]
            _ => None,
        }
    }

    /// Closes every connection; later queries fail. For a clean shutdown,
    /// once the app has stopped serving.
    pub async fn close(&self) {
        match &self.pool {
            #[cfg(feature = "postgres")]
            Pool::Postgres(pool) => pool.close().await,
            #[cfg(feature = "sqlite")]
            Pool::Sqlite(pool) => pool.close().await,
        }
    }

    pub fn dialect(&self) -> Dialect {
        match self.pool {
            #[cfg(feature = "postgres")]
            Pool::Postgres(_) => Dialect::Postgres,
            #[cfg(feature = "sqlite")]
            Pool::Sqlite(_) => Dialect::Sqlite,
        }
    }

    /// Starts an explicit transaction. Most code should prefer
    /// `db::transaction`, which makes it ambient.
    pub async fn begin(&self) -> Result<Transaction> {
        let inner = match &self.pool {
            #[cfg(feature = "postgres")]
            Pool::Postgres(pool) => TxInner::Postgres(pool.begin().await?),
            #[cfg(feature = "sqlite")]
            Pool::Sqlite(pool) => TxInner::Sqlite(pool.begin().await?),
        };
        Ok(Transaction {
            inner: Arc::new(Mutex::new(Some(inner))),
            dialect: self.dialect(),
        })
    }
}

/// An open transaction. Cloning shares it. Dropping the last clone without
/// committing rolls it back.
#[derive(Clone)]
pub struct Transaction {
    inner: Arc<Mutex<Option<TxInner>>>,
    dialect: Dialect,
}

enum TxInner {
    #[cfg(feature = "postgres")]
    Postgres(sqlx::Transaction<'static, sqlx::Postgres>),
    #[cfg(feature = "sqlite")]
    Sqlite(sqlx::Transaction<'static, sqlx::Sqlite>),
}

impl Transaction {
    pub async fn commit(&self) -> Result<()> {
        match self.inner.lock().await.take() {
            #[cfg(feature = "postgres")]
            Some(TxInner::Postgres(tx)) => tx.commit().await?,
            #[cfg(feature = "sqlite")]
            Some(TxInner::Sqlite(tx)) => tx.commit().await?,
            None => return Err(Error::internal("transaction already finished")),
        }
        Ok(())
    }

    pub async fn rollback(&self) -> Result<()> {
        match self.inner.lock().await.take() {
            #[cfg(feature = "postgres")]
            Some(TxInner::Postgres(tx)) => tx.rollback().await?,
            #[cfg(feature = "sqlite")]
            Some(TxInner::Sqlite(tx)) => tx.rollback().await?,
            None => {}
        }
        Ok(())
    }
}

/// Somewhere to run queries: a repo or a transaction. Built implicitly from
/// `&Repo` or `&Transaction` by `.on(..)`.
#[derive(Clone)]
pub struct Connection(Conn);

#[derive(Clone)]
enum Conn {
    Repo(Repo),
    Tx(Transaction),
}

impl From<&Repo> for Connection {
    fn from(repo: &Repo) -> Self {
        Connection(Conn::Repo(repo.clone()))
    }
}

impl From<&Transaction> for Connection {
    fn from(tx: &Transaction) -> Self {
        Connection(Conn::Tx(tx.clone()))
    }
}

tokio::task_local! {
    static CURRENT: Connection;
}

/// The ambient connection, or an error explaining how to provide one.
pub fn current() -> Result<Connection> {
    CURRENT.try_with(Connection::clone).map_err(|_| {
        Error::internal(
            "no database connection here: register one with App::database(repo), \
             wrap the code in glacier::db::with(&repo, ..), or call .on(&repo)",
        )
    })
}

pub(crate) fn scope<F: Future>(conn: Connection, fut: F) -> impl Future<Output = F::Output> {
    CURRENT.scope(conn, fut)
}

/// Whether an ambient connection is set.
pub fn active() -> bool {
    CURRENT.try_with(|_| ()).is_ok()
}

/// Runs `fut` with `repo` as the ambient connection, e.g. in a background
/// job, a script or a spawned task.
pub async fn with<F: Future>(repo: &Repo, fut: F) -> F::Output {
    CURRENT.scope(Connection::from(repo), fut).await
}

/// Runs `fut` inside a transaction that every model call within it joins.
/// It commits if `fut` returns `Ok` and rolls back on `Err` (or a panic).
/// A nested call joins the outer transaction.
///
/// ```no_run
/// # use glacier::prelude::*;
/// # use glacier::db;
/// # async fn demo() -> glacier::Result<()> {
/// db::transaction(async {
///     // ... several writes that must succeed or fail together
///     Ok(())
/// })
/// .await?;
/// # Ok(()) }
/// ```
pub async fn transaction<T, F>(fut: F) -> Result<T>
where
    F: Future<Output = Result<T>>,
{
    let repo = match current()?.0 {
        Conn::Tx(_) => return fut.await,
        Conn::Repo(repo) => repo,
    };
    let tx = repo.begin().await?;
    let result = CURRENT.scope(Connection::from(&tx), fut).await;
    match result {
        Ok(value) => {
            tx.commit().await?;
            Ok(value)
        }
        Err(err) => {
            tx.rollback().await?;
            Err(err)
        }
    }
}

/// Like [`transaction`], but inside an open transaction the work gets its
/// own savepoint, so an error undoes just this work and the enclosing
/// transaction carries on.
pub async fn savepoint<T, F>(fut: F) -> Result<T>
where
    F: Future<Output = Result<T>>,
{
    static SAVEPOINTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let conn = current()?;
    if !conn.in_transaction() {
        return transaction(fut).await;
    }
    let name = format!(
        "glacier_nested_{}",
        SAVEPOINTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    );
    conn.execute(Sql::new().push(&format!("SAVEPOINT {name}")))
        .await?;
    let result = fut.await;
    let finish = if result.is_ok() {
        format!("RELEASE SAVEPOINT {name}")
    } else {
        format!("ROLLBACK TO SAVEPOINT {name}")
    };
    conn.execute(Sql::new().push(&finish)).await?;
    result
}

/// Runs `fut` in a transaction that is always rolled back, for tests: every
/// write, including those made by requests through `TestClient`, disappears
/// afterwards.
pub async fn sandbox<F: Future>(repo: &Repo, fut: F) -> Result<F::Output> {
    let tx = repo.begin().await?;
    let output = CURRENT.scope(Connection::from(&tx), fut).await;
    tx.rollback().await?;
    Ok(output)
}

/// A row from a query, read by column name.
pub struct Row(RowInner);

enum RowInner {
    #[cfg(feature = "postgres")]
    Postgres(sqlx::postgres::PgRow),
    #[cfg(feature = "sqlite")]
    Sqlite(sqlx::sqlite::SqliteRow),
}

impl Row {
    pub fn get<T: FromColumn>(&self, column: &str) -> Result<T> {
        let result = match &self.0 {
            #[cfg(feature = "postgres")]
            RowInner::Postgres(row) => row.try_get(column),
            #[cfg(feature = "sqlite")]
            RowInner::Sqlite(row) => row.try_get(column),
        };
        result.map_err(|e| Error::internal(format!("reading column `{column}`: {e}")))
    }
}

macro_rules! bind_all {
    ($query:expr, $values:expr) => {{
        let mut query = $query;
        for value in $values {
            query = match value {
                Value::Null => unreachable!("NULL is rendered inline"),
                Value::Bool(v) => query.bind(v),
                Value::Int(v) => query.bind(v),
                Value::Float(v) => query.bind(v),
                Value::Text(v) => query.bind(v),
                Value::Bytes(v) => query.bind(v),
                Value::Json(v) => query.bind(sqlx::types::Json(v)),
                Value::Decimal(v) => query.bind(v),
                Value::Uuid(v) => query.bind(v),
                Value::Timestamp(v) => query.bind(v),
                Value::Date(v) => query.bind(v),
            };
        }
        query
    }};
}

/// Runs a statement on `conn` and returns its rows.
macro_rules! run {
    ($conn:expr, $sql:expr, |$query:ident, $executor:ident| $body:expr) => {{
        let conn: &Connection = $conn;
        let (text, values) = $sql;
        match &conn.0 {
            Conn::Repo(repo) => match &repo.pool {
                #[cfg(feature = "postgres")]
                Pool::Postgres(pool) => {
                    let $query =
                        bind_all!(sqlx::query::<sqlx::Postgres>(AssertSqlSafe(text)), values);
                    let $executor = pool;
                    $body
                }
                #[cfg(feature = "sqlite")]
                Pool::Sqlite(pool) => {
                    let $query =
                        bind_all!(sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)), values);
                    let $executor = pool;
                    $body
                }
            },
            Conn::Tx(tx) => {
                let mut guard = tx.inner.lock().await;
                match guard.as_mut() {
                    #[cfg(feature = "postgres")]
                    Some(TxInner::Postgres(tx)) => {
                        let $query =
                            bind_all!(sqlx::query::<sqlx::Postgres>(AssertSqlSafe(text)), values);
                        let $executor = &mut **tx;
                        $body
                    }
                    #[cfg(feature = "sqlite")]
                    Some(TxInner::Sqlite(tx)) => {
                        let $query =
                            bind_all!(sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)), values);
                        let $executor = &mut **tx;
                        $body
                    }
                    None => Err(sqlx::Error::Protocol("transaction already finished".into())),
                }
            }
        }
    }};
}

impl Connection {
    pub fn dialect(&self) -> Dialect {
        match &self.0 {
            Conn::Repo(repo) => repo.dialect(),
            Conn::Tx(tx) => tx.dialect,
        }
    }

    pub(crate) fn in_transaction(&self) -> bool {
        matches!(self.0, Conn::Tx(_))
    }

    pub(crate) async fn fetch_all(&self, sql: &Sql) -> std::result::Result<Vec<Row>, sqlx::Error> {
        let (text, values) = sql.render(self.dialect());
        let span = query_span(self.dialect(), &text);
        let rows: std::result::Result<Vec<Row>, sqlx::Error> =
            run!(self, (text, values), |query, executor| {
                query
                    .fetch_all(executor)
                    .instrument(span.clone())
                    .await
                    .map(|rows| rows.into_iter().map(Row::from).collect())
            });
        finish_query(&span, rows.as_ref().map(Vec::len));
        rows
    }

    pub(crate) async fn execute(&self, sql: &Sql) -> std::result::Result<u64, sqlx::Error> {
        let (text, values) = sql.render(self.dialect());
        let span = query_span(self.dialect(), &text);
        let done: std::result::Result<u64, sqlx::Error> =
            run!(self, (text, values), |query, executor| {
                query
                    .execute(executor)
                    .instrument(span.clone())
                    .await
                    .map(|done| done.rows_affected())
            });
        finish_query(&span, done.as_ref().map(|n| *n as usize));
        done
    }
}

/// A statement's span, per OpenTelemetry's database conventions. The SQL
/// has placeholders (`$1`, `?1`), never the values bound to them, so no
/// user data reaches traces.
fn query_span(dialect: Dialect, text: &str) -> tracing::Span {
    let operation = text
        .split_whitespace()
        .next()
        .unwrap_or_default()
        .to_ascii_uppercase();
    tracing::info_span!(
        target: "glacier",
        "glacier.db.query",
        otel.name = %operation,
        otel.kind = "client",
        otel.status_code = Empty,
        db.system.name = match dialect {
            Dialect::Postgres => "postgresql",
            Dialect::Sqlite => "sqlite",
        },
        db.operation.name = %operation,
        db.query.text = %text,
        db.response.returned_rows = Empty,
        error.message = Empty,
    )
}

fn finish_query(span: &tracing::Span, rows: std::result::Result<usize, &sqlx::Error>) {
    match rows {
        Ok(rows) => {
            span.record(
                "db.response.returned_rows",
                i64::try_from(rows).unwrap_or(i64::MAX),
            );
        }
        Err(err) => {
            span.record("otel.status_code", "ERROR");
            span.record("error.message", tracing::field::display(err));
        }
    }
}

impl Connection {}

#[cfg(feature = "postgres")]
impl From<sqlx::postgres::PgRow> for Row {
    fn from(row: sqlx::postgres::PgRow) -> Self {
        Row(RowInner::Postgres(row))
    }
}

#[cfg(feature = "sqlite")]
impl From<sqlx::sqlite::SqliteRow> for Row {
    fn from(row: sqlx::sqlite::SqliteRow) -> Self {
        Row(RowInner::Sqlite(row))
    }
}

/// Raw SQL with portable `?` placeholders, for what the query builder
/// doesn't cover.
///
/// ```no_run
/// # async fn demo() -> glacier::Result<()> {
/// let rows = glacier::db::sql("SELECT title FROM posts WHERE id > ?")
///     .bind(10)
///     .fetch_all()
///     .await?;
/// let title: String = rows[0].get("title")?;
/// # Ok(()) }
/// ```
pub fn sql(text: &str) -> RawQuery {
    RawQuery {
        text: text.to_owned(),
        values: Vec::new(),
        conn: None,
    }
}

pub struct RawQuery {
    text: String,
    values: Vec<Value>,
    conn: Option<Connection>,
}

impl RawQuery {
    pub fn bind(mut self, value: impl ToValue) -> Self {
        self.values.push(value.to_value());
        self
    }

    pub fn on(mut self, conn: impl Into<Connection>) -> Self {
        self.conn = Some(conn.into());
        self
    }

    fn statement(&self) -> Result<(Connection, Sql)> {
        let conn = match &self.conn {
            Some(conn) => conn.clone(),
            None => current()?,
        };
        Ok((conn, Sql::raw(&self.text, self.values.clone())))
    }

    pub async fn fetch_all(self) -> Result<Vec<Row>> {
        let (conn, sql) = self.statement()?;
        Ok(conn.fetch_all(&sql).await?)
    }

    /// Runs the statement, returning the number of rows affected.
    pub async fn execute(self) -> Result<u64> {
        let (conn, sql) = self.statement()?;
        Ok(conn.execute(&sql).await?)
    }
}

/// Whether a database URL names a user: `postgres://me@host/db`.
#[cfg_attr(not(feature = "postgres"), allow(dead_code))]
fn has_user(url: &str) -> bool {
    let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
    let authority = rest.split(['/', '?']).next().unwrap_or(rest);
    authority.contains('@')
}

#[cfg(test)]
mod url_tests {
    #[test]
    fn finds_users_in_urls() {
        assert!(super::has_user("postgres://me@localhost/db"));
        assert!(super::has_user(
            "postgres://me:secret@localhost:5432/db?sslmode=disable"
        ));
        assert!(!super::has_user("postgres://localhost/db"));
        assert!(!super::has_user("postgres://localhost/db?options=a@b"));
    }
}