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
#![cfg_attr(target_arch = "wasm32", allow(unused_imports))]
#![cfg_attr(not(target_arch = "wasm32"), allow(clippy::large_enum_variant))]

use crate::error::{Error, ErrorKind};
use std::{borrow::Cow, fmt};
use url::Url;

#[cfg(feature = "mssql")]
use crate::connector::MssqlUrl;
#[cfg(feature = "mysql")]
use crate::connector::MysqlUrl;
#[cfg(feature = "postgresql")]
use crate::connector::PostgresUrl;
#[cfg(feature = "sqlite")]
use crate::connector::SqliteParams;
#[cfg(feature = "sqlite")]
use std::convert::TryFrom;

use super::ExternalConnectionInfo;

#[cfg(not(target_arch = "wasm32"))]
use super::NativeConnectionInfo;

/// General information about a SQL connection.
#[derive(Debug, Clone)]
#[cfg_attr(target_arch = "wasm32", repr(transparent))]
pub enum ConnectionInfo {
    #[cfg(not(target_arch = "wasm32"))]
    Native(NativeConnectionInfo),
    External(ExternalConnectionInfo),
}

impl ConnectionInfo {
    /// Parse `ConnectionInfo` out from an SQL connection string.
    ///
    /// Will fail if URI is invalid or the scheme points to an unsupported
    /// database.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn from_url(url_str: &str) -> crate::Result<Self> {
        let url_result: Result<Url, _> = url_str.parse();

        // Non-URL database strings are interpreted as SQLite file paths.
        match url_str {
            #[cfg(feature = "sqlite")]
            s if s.starts_with("file") => {
                if url_result.is_err() {
                    let params = SqliteParams::try_from(s)?;

                    return Ok(ConnectionInfo::Native(NativeConnectionInfo::Sqlite {
                        file_path: params.file_path,
                        db_name: params.db_name,
                    }));
                }
            }
            #[cfg(feature = "mssql")]
            s if s.starts_with("jdbc:sqlserver") || s.starts_with("sqlserver") => {
                return Ok(ConnectionInfo::Native(NativeConnectionInfo::Mssql(MssqlUrl::new(
                    url_str,
                )?)));
            }
            _ => (),
        }

        let url = url_result?;

        let sql_family = SqlFamily::from_scheme(url.scheme()).ok_or_else(|| {
            let kind =
                ErrorKind::DatabaseUrlIsInvalid(format!("{} is not a supported database URL scheme.", url.scheme()));

            Error::builder(kind).build()
        })?;

        match sql_family {
            #[cfg(feature = "mysql")]
            SqlFamily::Mysql => Ok(ConnectionInfo::Native(NativeConnectionInfo::Mysql(MysqlUrl::new(url)?))),
            #[cfg(feature = "sqlite")]
            SqlFamily::Sqlite => {
                let params = SqliteParams::try_from(url_str)?;

                Ok(ConnectionInfo::Native(NativeConnectionInfo::Sqlite {
                    file_path: params.file_path,
                    db_name: params.db_name,
                }))
            }
            #[cfg(feature = "postgresql")]
            SqlFamily::Postgres => Ok(ConnectionInfo::Native(NativeConnectionInfo::Postgres(
                PostgresUrl::new(url)?,
            ))),
            #[allow(unreachable_patterns)]
            _ => unreachable!(),
        }
    }

    /// The provided database name. This will be `None` on SQLite.
    pub fn dbname(&self) -> Option<&str> {
        match self {
            #[cfg(not(target_arch = "wasm32"))]
            ConnectionInfo::Native(info) => match info {
                #[cfg(feature = "postgresql")]
                NativeConnectionInfo::Postgres(url) => Some(url.dbname()),
                #[cfg(feature = "mysql")]
                NativeConnectionInfo::Mysql(url) => Some(url.dbname()),
                #[cfg(feature = "mssql")]
                NativeConnectionInfo::Mssql(url) => Some(url.dbname()),
                #[cfg(feature = "sqlite")]
                NativeConnectionInfo::Sqlite { .. } | NativeConnectionInfo::InMemorySqlite { .. } => None,
            },
            ConnectionInfo::External(_) => None,
        }
    }

    /// This is what item names are prefixed with in queries.
    ///
    /// - In SQLite, this is the schema name that the database file was attached as.
    /// - In Postgres, it is the selected schema inside the current database.
    /// - In MySQL, it is the database name.
    pub fn schema_name(&self) -> &str {
        match self {
            #[cfg(not(target_arch = "wasm32"))]
            ConnectionInfo::Native(info) => match info {
                #[cfg(feature = "postgresql")]
                NativeConnectionInfo::Postgres(url) => url.schema(),
                #[cfg(feature = "mysql")]
                NativeConnectionInfo::Mysql(url) => url.dbname(),
                #[cfg(feature = "mssql")]
                NativeConnectionInfo::Mssql(url) => url.schema(),
                #[cfg(feature = "sqlite")]
                NativeConnectionInfo::Sqlite { db_name, .. } => db_name,
                #[cfg(feature = "sqlite")]
                NativeConnectionInfo::InMemorySqlite { db_name } => db_name,
            },
            ConnectionInfo::External(info) => &info.schema_name,
        }
    }

    /// The provided database host. This will be `"localhost"` on SQLite.
    pub fn host(&self) -> &str {
        match self {
            #[cfg(not(target_arch = "wasm32"))]
            ConnectionInfo::Native(info) => match info {
                #[cfg(feature = "postgresql")]
                NativeConnectionInfo::Postgres(url) => url.host(),
                #[cfg(feature = "mysql")]
                NativeConnectionInfo::Mysql(url) => url.host(),
                #[cfg(feature = "mssql")]
                NativeConnectionInfo::Mssql(url) => url.host(),
                #[cfg(feature = "sqlite")]
                NativeConnectionInfo::Sqlite { .. } | NativeConnectionInfo::InMemorySqlite { .. } => "localhost",
            },
            ConnectionInfo::External(_) => "external",
        }
    }

    /// The provided database user name. This will be `None` on SQLite.
    pub fn username(&self) -> Option<Cow<str>> {
        // TODO: why do some of the native `.username()` methods return an `Option<&str>` and others a `Cow<str>`?
        match self {
            #[cfg(not(target_arch = "wasm32"))]
            ConnectionInfo::Native(info) => match info {
                #[cfg(feature = "postgresql")]
                NativeConnectionInfo::Postgres(url) => Some(url.username()),
                #[cfg(feature = "mysql")]
                NativeConnectionInfo::Mysql(url) => Some(url.username()),
                #[cfg(feature = "mssql")]
                NativeConnectionInfo::Mssql(url) => url.username().map(Cow::from),
                #[cfg(feature = "sqlite")]
                NativeConnectionInfo::Sqlite { .. } | NativeConnectionInfo::InMemorySqlite { .. } => None,
            },
            ConnectionInfo::External(_) => None,
        }
    }

    /// The database file for SQLite, otherwise `None`.
    pub fn file_path(&self) -> Option<&str> {
        match self {
            #[cfg(not(target_arch = "wasm32"))]
            ConnectionInfo::Native(info) => match info {
                #[cfg(feature = "postgresql")]
                NativeConnectionInfo::Postgres(_) => None,
                #[cfg(feature = "mysql")]
                NativeConnectionInfo::Mysql(_) => None,
                #[cfg(feature = "mssql")]
                NativeConnectionInfo::Mssql(_) => None,
                #[cfg(feature = "sqlite")]
                NativeConnectionInfo::Sqlite { file_path, .. } => Some(file_path),
                #[cfg(feature = "sqlite")]
                NativeConnectionInfo::InMemorySqlite { .. } => None,
            },
            ConnectionInfo::External(_) => None,
        }
    }

    /// The family of databases connected.
    pub fn sql_family(&self) -> SqlFamily {
        match self {
            #[cfg(not(target_arch = "wasm32"))]
            ConnectionInfo::Native(info) => match info {
                #[cfg(feature = "postgresql")]
                NativeConnectionInfo::Postgres(_) => SqlFamily::Postgres,
                #[cfg(feature = "mysql")]
                NativeConnectionInfo::Mysql(_) => SqlFamily::Mysql,
                #[cfg(feature = "mssql")]
                NativeConnectionInfo::Mssql(_) => SqlFamily::Mssql,
                #[cfg(feature = "sqlite")]
                NativeConnectionInfo::Sqlite { .. } | NativeConnectionInfo::InMemorySqlite { .. } => SqlFamily::Sqlite,
            },
            ConnectionInfo::External(info) => info.sql_family.to_owned(),
        }
    }

    /// The provided database port, if applicable.
    pub fn port(&self) -> Option<u16> {
        match self {
            #[cfg(not(target_arch = "wasm32"))]
            ConnectionInfo::Native(info) => match info {
                #[cfg(feature = "postgresql")]
                NativeConnectionInfo::Postgres(url) => Some(url.port()),
                #[cfg(feature = "mysql")]
                NativeConnectionInfo::Mysql(url) => Some(url.port()),
                #[cfg(feature = "mssql")]
                NativeConnectionInfo::Mssql(url) => Some(url.port()),
                #[cfg(feature = "sqlite")]
                NativeConnectionInfo::Sqlite { .. } | NativeConnectionInfo::InMemorySqlite { .. } => None,
            },
            ConnectionInfo::External(_) => None,
        }
    }

    /// Whether the pgbouncer mode is enabled.
    pub fn pg_bouncer(&self) -> bool {
        match self {
            #[cfg(all(not(target_arch = "wasm32"), feature = "postgresql"))]
            ConnectionInfo::Native(NativeConnectionInfo::Postgres(url)) => url.pg_bouncer(),
            _ => false,
        }
    }

    /// A string describing the database location, meant for error messages. It will be the host
    /// and port on MySQL/Postgres, and the file path on SQLite.
    pub fn database_location(&self) -> String {
        match self {
            #[cfg(not(target_arch = "wasm32"))]
            ConnectionInfo::Native(info) => match info {
                #[cfg(feature = "postgresql")]
                NativeConnectionInfo::Postgres(url) => format!("{}:{}", url.host(), url.port()),
                #[cfg(feature = "mysql")]
                NativeConnectionInfo::Mysql(url) => format!("{}:{}", url.host(), url.port()),
                #[cfg(feature = "mssql")]
                NativeConnectionInfo::Mssql(url) => format!("{}:{}", url.host(), url.port()),
                #[cfg(feature = "sqlite")]
                NativeConnectionInfo::Sqlite { file_path, .. } => file_path.clone(),
                #[cfg(feature = "sqlite")]
                NativeConnectionInfo::InMemorySqlite { .. } => "in-memory".into(),
            },
            ConnectionInfo::External(_) => "external".into(),
        }
    }
}

/// One of the supported SQL variants.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum SqlFamily {
    #[cfg(feature = "postgresql")]
    Postgres,
    #[cfg(feature = "mysql")]
    Mysql,
    #[cfg(feature = "sqlite")]
    Sqlite,
    #[cfg(feature = "mssql")]
    Mssql,
}

impl SqlFamily {
    /// Get a string representation of the family.
    pub fn as_str(self) -> &'static str {
        match self {
            #[cfg(feature = "postgresql")]
            SqlFamily::Postgres => "postgresql",
            #[cfg(feature = "mysql")]
            SqlFamily::Mysql => "mysql",
            #[cfg(feature = "sqlite")]
            SqlFamily::Sqlite => "sqlite",
            #[cfg(feature = "mssql")]
            SqlFamily::Mssql => "mssql",
        }
    }

    /// Convert url scheme to an SqlFamily.
    pub fn from_scheme(url_scheme: &str) -> Option<Self> {
        match url_scheme {
            #[cfg(feature = "sqlite")]
            "file" => Some(SqlFamily::Sqlite),
            #[cfg(feature = "postgresql")]
            "postgres" | "postgresql" => Some(SqlFamily::Postgres),
            #[cfg(feature = "mysql")]
            "mysql" => Some(SqlFamily::Mysql),
            _ => None,
        }
    }

    /// Get the default max rows for a batch insert.
    pub fn max_insert_rows(&self) -> Option<usize> {
        match self {
            #[cfg(feature = "postgresql")]
            SqlFamily::Postgres => None,
            #[cfg(feature = "mysql")]
            SqlFamily::Mysql => None,
            #[cfg(feature = "sqlite")]
            SqlFamily::Sqlite => Some(999),
            #[cfg(feature = "mssql")]
            SqlFamily::Mssql => Some(1000),
        }
    }

    /// Get the max number of bind parameters for a single query, which in targets other
    /// than Wasm can be controlled with the env var QUERY_BATCH_SIZE.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn max_bind_values(&self) -> usize {
        use std::sync::OnceLock;
        static BATCH_SIZE_OVERRIDE: OnceLock<Option<usize>> = OnceLock::new();
        BATCH_SIZE_OVERRIDE
            .get_or_init(|| {
                std::env::var("QUERY_BATCH_SIZE")
                    .ok()
                    .map(|size| size.parse().expect("QUERY_BATCH_SIZE: not a valid size"))
            })
            .unwrap_or(self.default_max_bind_values())
    }

    /// Get the max number of bind parameters for a single query, in Wasm there's no
    /// environment, and we omit that knob.
    #[cfg(target_arch = "wasm32")]
    pub fn max_bind_values(&self) -> usize {
        self.default_max_bind_values()
    }

    /// Get the default max number of bind parameters for a single query.
    pub fn default_max_bind_values(&self) -> usize {
        match self {
            #[cfg(feature = "postgresql")]
            SqlFamily::Postgres => 32766,
            #[cfg(feature = "mysql")]
            SqlFamily::Mysql => 65535,
            #[cfg(feature = "sqlite")]
            SqlFamily::Sqlite => 999,
            #[cfg(feature = "mssql")]
            SqlFamily::Mssql => 2099,
        }
    }

    /// Check if a family exists for the given scheme.
    pub fn scheme_is_supported(url_scheme: &str) -> bool {
        Self::from_scheme(url_scheme).is_some()
    }

    /// True, if family is PostgreSQL.
    #[cfg(feature = "postgresql")]
    pub fn is_postgres(&self) -> bool {
        matches!(self, SqlFamily::Postgres)
    }

    /// True, if family is PostgreSQL.
    #[cfg(not(feature = "postgresql"))]
    pub fn is_postgres(&self) -> bool {
        false
    }

    /// True, if family is MySQL.
    #[cfg(feature = "mysql")]
    pub fn is_mysql(&self) -> bool {
        matches!(self, SqlFamily::Mysql)
    }

    /// True, if family is MySQL.
    #[cfg(not(feature = "mysql"))]
    pub fn is_mysql(&self) -> bool {
        false
    }

    /// True, if family is SQLite.
    #[cfg(feature = "sqlite")]
    pub fn is_sqlite(&self) -> bool {
        matches!(self, SqlFamily::Sqlite)
    }

    /// True, if family is SQLite.
    #[cfg(not(feature = "sqlite"))]
    pub fn is_sqlite(&self) -> bool {
        false
    }

    /// True, if family is SQL Server.
    #[cfg(feature = "mssql")]
    pub fn is_mssql(&self) -> bool {
        matches!(self, SqlFamily::Mssql)
    }

    /// True, if family is SQL Server.
    #[cfg(not(feature = "mssql"))]
    pub fn is_mssql(&self) -> bool {
        false
    }
}

impl fmt::Display for SqlFamily {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

#[cfg(test)]
mod tests {
    #[cfg(any(feature = "sqlite", feature = "mysql"))]
    use super::*;

    #[test]
    #[cfg(feature = "sqlite")]
    fn sqlite_connection_info_from_str_interprets_relative_path_correctly() {
        let conn_info = ConnectionInfo::from_url("file:dev.db").unwrap();

        #[allow(irrefutable_let_patterns)]
        if let ConnectionInfo::Native(NativeConnectionInfo::Sqlite { file_path, db_name: _ }) = conn_info {
            assert_eq!(file_path, "dev.db");
        } else {
            panic!("Wrong type of connection info, should be Sqlite");
        }
    }

    #[test]
    #[cfg(feature = "mysql")]
    fn mysql_connection_info_from_str() {
        let conn_info = ConnectionInfo::from_url("mysql://myuser:my%23pass%23word@lclhst:5432/mydb").unwrap();

        #[allow(irrefutable_let_patterns)]
        if let ConnectionInfo::Native(NativeConnectionInfo::Mysql(url)) = conn_info {
            assert_eq!(url.password().unwrap(), "my#pass#word");
            assert_eq!(url.host(), "lclhst");
            assert_eq!(url.username(), "myuser");
            assert_eq!(url.dbname(), "mydb");
        } else {
            panic!("Wrong type of connection info, should be Mysql");
        }
    }
}