db-pool 0.6.0

A thread-safe database pool for running database-tied integration tests in parallel
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
use std::{borrow::Cow, fmt::Debug, ops::Deref};

use r2d2::{ManageConnection, Pool, PooledConnection};
use uuid::Uuid;

use crate::common::statement::mysql;

use super::super::error::Error as BackendError;

pub(super) trait MySQLBackend {
    type ConnectionManager: ManageConnection;
    type ConnectionError: Into<BackendError<Self::ConnectionError, Self::QueryError>> + Debug;
    type QueryError: Into<BackendError<Self::ConnectionError, Self::QueryError>> + Debug;

    fn get_connection(&self) -> Result<PooledConnection<Self::ConnectionManager>, r2d2::Error>;

    fn execute(
        &self,
        query: &str,
        conn: &mut <Self::ConnectionManager as ManageConnection>::Connection,
    ) -> Result<(), Self::QueryError>;
    fn batch_execute<'a>(
        &self,
        query: impl IntoIterator<Item = Cow<'a, str>>,
        conn: &mut <Self::ConnectionManager as ManageConnection>::Connection,
    ) -> Result<(), Self::QueryError>;

    fn get_host(&self) -> Cow<str>;

    fn get_previous_database_names(
        &self,
        conn: &mut <Self::ConnectionManager as ManageConnection>::Connection,
    ) -> Result<Vec<String>, Self::QueryError>;
    fn create_entities(&self, conn: &mut <Self::ConnectionManager as ManageConnection>::Connection);
    fn create_connection_pool(
        &self,
        db_id: Uuid,
    ) -> Result<Pool<Self::ConnectionManager>, r2d2::Error>;

    fn get_table_names(
        &self,
        db_name: &str,
        conn: &mut <Self::ConnectionManager as ManageConnection>::Connection,
    ) -> Result<Vec<String>, Self::QueryError>;

    fn get_drop_previous_databases(&self) -> bool;
}

pub(super) struct MySQLBackendWrapper<'a, B: MySQLBackend>(&'a B);

impl<'a, B: MySQLBackend> MySQLBackendWrapper<'a, B> {
    pub(super) fn new(backend: &'a B) -> Self {
        Self(backend)
    }
}

impl<B: MySQLBackend> Deref for MySQLBackendWrapper<'_, B> {
    type Target = B;

    fn deref(&self) -> &Self::Target {
        self.0
    }
}

impl<B: MySQLBackend> MySQLBackendWrapper<'_, B> {
    pub(super) fn init(&self) -> Result<(), BackendError<B::ConnectionError, B::QueryError>> {
        // Drop previous databases if needed
        if self.get_drop_previous_databases() {
            // Get privileged connection
            let conn = &mut self.get_connection()?;

            // Get previous database names
            self.execute(mysql::USE_DEFAULT_DATABASE, conn)
                .map_err(Into::into)?;
            let db_names = self.get_previous_database_names(conn).map_err(Into::into)?;

            // Drop databases
            for db_name in &db_names {
                self.execute(
                    crate::common::statement::mysql::drop_database(db_name.as_str()).as_str(),
                    conn,
                )
                .map_err(Into::into)?;
            }
        }

        Ok(())
    }

    #[allow(clippy::complexity)]
    pub(super) fn create(
        &self,
        db_id: uuid::Uuid,
        restrict_privileges: bool,
    ) -> Result<Pool<B::ConnectionManager>, BackendError<B::ConnectionError, B::QueryError>> {
        // Get database name based on UUID
        let db_name = crate::util::get_db_name(db_id);
        let db_name = db_name.as_str();

        let host = &self.get_host();

        // Get privileged connection
        let conn = &mut self.get_connection()?;

        // Create database
        self.execute(mysql::create_database(db_name).as_str(), conn)
            .map_err(Into::into)?;

        // Create user
        self.execute(mysql::create_user(db_name, host).as_str(), conn)
            .map_err(Into::into)?;

        // Create entities
        self.execute(mysql::use_database(db_name).as_str(), conn)
            .map_err(Into::into)?;
        self.create_entities(conn);
        self.execute(mysql::USE_DEFAULT_DATABASE, conn)
            .map_err(Into::into)?;

        if restrict_privileges {
            // Grant privileges to restricted user
            self.execute(
                mysql::grant_restricted_privileges(db_name, host).as_str(),
                conn,
            )
            .map_err(Into::into)?;
        } else {
            // Grant all privileges to database-unrestricted user
            self.execute(mysql::grant_all_privileges(db_name, host).as_str(), conn)
                .map_err(Into::into)?;
        }

        // Create connection pool with attached user
        let pool = self.create_connection_pool(db_id)?;

        Ok(pool)
    }

    pub(super) fn clean(
        &self,
        db_id: uuid::Uuid,
    ) -> Result<(), BackendError<B::ConnectionError, B::QueryError>> {
        // Get database name based on UUID
        let db_name = crate::util::get_db_name(db_id);
        let db_name = db_name.as_str();

        // Get privileged connection
        let conn = &mut self.get_connection()?;

        // Get table names
        let mut table_names = self.get_table_names(db_name, conn).map_err(Into::into)?;

        // Generate truncate statements
        let stmts = table_names
            .drain(..)
            .map(|table_name| mysql::truncate_table(table_name.as_str(), db_name).into());

        // Turn off foreign key checks
        self.execute(mysql::TURN_OFF_FOREIGN_KEY_CHECKS, conn)
            .map_err(Into::into)?;

        // Truncate tables
        self.batch_execute(stmts, conn).map_err(Into::into)?;

        // Turn on foreign key checks
        self.execute(mysql::TURN_ON_FOREIGN_KEY_CHECKS, conn)
            .map_err(Into::into)?;

        Ok(())
    }

    pub(super) fn drop(
        &self,
        db_id: uuid::Uuid,
    ) -> Result<(), BackendError<B::ConnectionError, B::QueryError>> {
        // Get database name based on UUID
        let db_name = crate::util::get_db_name(db_id);
        let db_name = db_name.as_str();

        let host = &self.get_host();

        // Get privileged connection
        let conn = &mut self.get_connection()?;

        // Drop database
        self.execute(mysql::drop_database(db_name).as_str(), conn)
            .map_err(Into::into)?;

        // Drop CRUD user
        self.execute(mysql::drop_user(db_name, host).as_str(), conn)
            .map_err(Into::into)?;

        Ok(())
    }
}

#[cfg(test)]
pub(super) mod tests {
    #![allow(unused_variables, clippy::unwrap_used)]

    use std::sync::OnceLock;

    use diesel::{
        dsl::exists, insert_into, r2d2::ConnectionManager, select, sql_query, table,
        ExpressionMethods, Insertable, MysqlConnection, QueryDsl, RunQueryDsl,
        TextExpressionMethods,
    };
    use r2d2::Pool as R2d2Pool;
    use tokio::sync::{RwLockReadGuard, RwLockWriteGuard};
    use uuid::Uuid;

    use crate::{
        common::statement::mysql::tests::{DDL_STATEMENTS, DML_STATEMENTS},
        r#sync::{backend::r#trait::Backend, db_pool::DatabasePoolBuilder},
        tests::{get_privileged_mysql_config, MYSQL_DROP_LOCK},
        util::get_db_name,
    };

    pub type Pool = R2d2Pool<ConnectionManager<MysqlConnection>>;

    table! {
        schemata (schema_name) {
            schema_name -> Text
        }
    }

    pub fn lock_drop<'a>() -> RwLockWriteGuard<'a, ()> {
        MYSQL_DROP_LOCK.blocking_write()
    }

    pub fn lock_read<'a>() -> RwLockReadGuard<'a, ()> {
        MYSQL_DROP_LOCK.blocking_read()
    }

    fn get_privileged_connection_pool() -> &'static Pool {
        static POOL: OnceLock<Pool> = OnceLock::new();
        POOL.get_or_init(|| {
            let config = get_privileged_mysql_config();
            let database_url = config.default_connection_url();
            let manager = ConnectionManager::new(database_url);
            R2d2Pool::builder().build(manager).unwrap()
        })
    }

    fn create_restricted_connection_pool(db_name: &str) -> Pool {
        let config = get_privileged_mysql_config();
        let database_url =
            config.restricted_database_connection_url(db_name, Some(db_name), db_name);
        let manager = ConnectionManager::new(database_url);
        R2d2Pool::builder().build(manager).unwrap()
    }

    fn create_database(conn: &mut MysqlConnection) -> String {
        let db_id = Uuid::new_v4();
        let db_name = get_db_name(db_id);
        sql_query(format!("CREATE DATABASE {db_name}"))
            .execute(conn)
            .unwrap();
        db_name
    }

    fn create_databases(count: i64, conn: &mut MysqlConnection) -> Vec<String> {
        (0..count).map(|_| create_database(conn)).collect()
    }

    fn use_database(db_name: &str, conn: &mut MysqlConnection) {
        sql_query(format!("USE {db_name}")).execute(conn).unwrap();
    }

    fn use_information_schema(conn: &mut MysqlConnection) {
        use_database("information_schema", conn);
    }

    fn count_databases(db_names: &Vec<String>, conn: &mut MysqlConnection) -> i64 {
        use_information_schema(conn);

        schemata::table
            .filter(schemata::schema_name.eq_any(db_names))
            .count()
            .get_result(conn)
            .unwrap()
    }

    fn count_all_databases(conn: &mut MysqlConnection) -> i64 {
        use_information_schema(conn);

        schemata::table
            .filter(schemata::schema_name.like("db_pool_%"))
            .count()
            .get_result(conn)
            .unwrap()
    }

    fn database_exists(db_name: &str, conn: &mut MysqlConnection) -> bool {
        use_information_schema(conn);

        select(exists(
            schemata::table.filter(schemata::schema_name.eq(db_name)),
        ))
        .get_result(conn)
        .unwrap()
    }

    pub fn test_backend_drops_previous_databases<B: Backend>(default: B, enabled: B, disabled: B) {
        const NUM_DBS: i64 = 3;

        let conn_pool = get_privileged_connection_pool();
        let conn = &mut conn_pool.get().unwrap();

        let guard = lock_drop();

        for (backend, cleans) in [(default, true), (enabled, true), (disabled, false)] {
            let db_names = create_databases(NUM_DBS, conn);
            assert_eq!(count_databases(&db_names, conn), NUM_DBS);
            backend.init().unwrap();
            assert_eq!(
                count_databases(&db_names, conn),
                if cleans { 0 } else { NUM_DBS }
            );
        }
    }

    pub fn test_backend_creates_database_with_restricted_privileges(backend: &impl Backend) {
        let db_id = Uuid::new_v4();
        let db_name = get_db_name(db_id);
        let db_name = db_name.as_str();

        let guard = lock_read();

        // privileged operations
        {
            let conn_pool = get_privileged_connection_pool();
            let conn = &mut conn_pool.get().unwrap();

            // database must not exist
            assert!(!database_exists(db_name, conn));

            // database must exist after creating through backend
            backend.init().unwrap();
            backend.create(db_id, true).unwrap();
            assert!(database_exists(db_name, conn));
        }

        // restricted operations
        {
            let conn_pool = create_restricted_connection_pool(db_name);
            let conn = &mut conn_pool.get().unwrap();

            // // DDL statements must fail
            for stmt in DDL_STATEMENTS {
                assert!(sql_query(stmt).execute(conn).is_err());
            }

            // DML statements must succeed
            for stmt in DML_STATEMENTS {
                assert!(sql_query(stmt).execute(conn).is_ok());
            }
        }
    }

    pub fn test_backend_creates_database_with_unrestricted_privileges(backend: &impl Backend) {
        let guard = lock_read();

        {
            let db_id = Uuid::new_v4();
            let db_name = get_db_name(db_id);
            let db_name = db_name.as_str();

            // privileged operations
            {
                let conn_pool = get_privileged_connection_pool();
                let conn = &mut conn_pool.get().unwrap();

                // database must not exist
                assert!(!database_exists(db_name, conn));

                // database must exist after creating through backend
                backend.init().unwrap();
                backend.create(db_id, false).unwrap();
                assert!(database_exists(db_name, conn));
            }

            // DML statements must succeed
            {
                let conn_pool = create_restricted_connection_pool(db_name);
                let conn = &mut conn_pool.get().unwrap();
                for stmt in DML_STATEMENTS {
                    assert!(sql_query(stmt).execute(conn).is_ok());
                }
            }
        }

        // DDL statements must succeed
        for stmt in DDL_STATEMENTS {
            let db_id = Uuid::new_v4();
            let db_name = get_db_name(db_id);
            let db_name = db_name.as_str();

            backend.create(db_id, false).unwrap();
            let conn_pool = create_restricted_connection_pool(db_name);
            let conn = &mut conn_pool.get().unwrap();

            assert!(sql_query(stmt).execute(conn).is_ok());
        }
    }

    pub fn test_backend_cleans_database_with_tables(backend: &impl Backend) {
        const NUM_BOOKS: i64 = 3;

        let db_id = Uuid::new_v4();
        let db_name = get_db_name(db_id);
        let db_name = db_name.as_str();

        let guard = lock_read();

        backend.init().unwrap();
        backend.create(db_id, true).unwrap();

        table! {
            book (id) {
                id -> Int4,
                title -> Text
            }
        }

        #[derive(Insertable)]
        #[diesel(table_name = book)]
        struct NewBook {
            title: String,
        }

        let conn_pool = create_restricted_connection_pool(db_name);
        let conn = &mut conn_pool.get().unwrap();

        let new_books = (0..NUM_BOOKS)
            .map(|i| NewBook {
                title: format!("Title {} {}", db_name, i + 1),
            })
            .collect::<Vec<_>>();
        insert_into(book::table)
            .values(&new_books)
            .execute(conn)
            .unwrap();

        // there must be books
        assert_eq!(
            book::table.count().get_result::<i64>(conn).unwrap(),
            NUM_BOOKS
        );

        backend.clean(db_id).unwrap();

        // there must be no books
        assert_eq!(book::table.count().get_result::<i64>(conn).unwrap(), 0);
    }

    pub fn test_backend_cleans_database_without_tables(backend: &impl Backend) {
        let db_id = Uuid::new_v4();

        let guard = lock_read();

        backend.init().unwrap();
        backend.create(db_id, true).unwrap();
        backend.clean(db_id).unwrap();
    }

    pub fn test_backend_drops_database(backend: &impl Backend, restricted: bool) {
        let db_id = Uuid::new_v4();
        let db_name = get_db_name(db_id);
        let db_name = db_name.as_str();

        let conn_pool = get_privileged_connection_pool();
        let conn = &mut conn_pool.get().unwrap();

        let guard = lock_read();

        // database must exist
        backend.init().unwrap();
        backend.create(db_id, restricted).unwrap();
        assert!(database_exists(db_name, conn));

        // database must not exist
        backend.drop(db_id, restricted).unwrap();
        assert!(!database_exists(db_name, conn));
    }

    pub fn test_pool_drops_previous_databases<B: Backend>(default: B, enabled: B, disabled: B) {
        const NUM_DBS: i64 = 3;

        let conn_pool = get_privileged_connection_pool();
        let conn = &mut conn_pool.get().unwrap();

        let guard = lock_drop();

        for (backend, cleans) in [(default, true), (enabled, true), (disabled, false)] {
            let db_names = create_databases(NUM_DBS, conn);
            assert_eq!(count_databases(&db_names, conn), NUM_DBS);
            backend.create_database_pool().unwrap();
            assert_eq!(
                count_databases(&db_names, conn),
                if cleans { 0 } else { NUM_DBS }
            );
        }
    }

    pub fn test_pool_drops_created_restricted_databases(backend: impl Backend) {
        const NUM_DBS: i64 = 3;

        let conn_pool = get_privileged_connection_pool();
        let conn = &mut conn_pool.get().unwrap();

        let guard = lock_drop();

        let db_pool = backend.create_database_pool().unwrap();

        // there must be no databases
        assert_eq!(count_all_databases(conn), 0);

        // fetch connection pools
        let conn_pools = (0..NUM_DBS)
            .map(|_| db_pool.pull_immutable())
            .collect::<Vec<_>>();

        // there must be databases
        assert_eq!(count_all_databases(conn), NUM_DBS);

        // must release databases back to pool
        drop(conn_pools);

        // there must be databases
        assert_eq!(count_all_databases(conn), NUM_DBS);

        // must drop databases
        drop(db_pool);

        // there must be no databases
        assert_eq!(count_all_databases(conn), 0);
    }

    pub fn test_pool_drops_created_unrestricted_database(backend: impl Backend) {
        let conn_pool = get_privileged_connection_pool();
        let conn = &mut conn_pool.get().unwrap();

        let guard = lock_drop();

        let db_pool = backend.create_database_pool().unwrap();

        // there must be no databases
        assert_eq!(count_all_databases(conn), 0);

        // fetch connection pool
        let conn_pool = db_pool.create_mutable().unwrap();

        // there must be a database
        assert_eq!(count_all_databases(conn), 1);

        // must drop database
        drop(conn_pool);

        // there must be no databases
        assert_eq!(count_all_databases(conn), 0);

        drop(db_pool);

        // there must be no databases
        assert_eq!(count_all_databases(conn), 0);
    }
}