integresql 0.1.1

Rust client for the IntegreSQL Postgres testing tool
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
use super::client::Client;
use crate::client::*;
use crate::server_models::*;
use http::Uri;
use log::{error, info, warn};
use std::env;
use std::fmt::Display;
use std::future::Future;
use std::hash::Hash;
use std::{
    collections::HashMap,
    error::Error,
    time::Duration,
};

const BASE_URL_ENV: &str = "INTEGRESQL_BASE_URL";
const DEFAULT_TIMEOUT_ENV: &str = "INTEGRESQL_IMEOUT_SECONDS";
pub(crate) const DEFAULT_BASE_URL: &str = "http://integresql:5000/api";

/// A template database setup function that should be called synchronously.
///
/// When a new template database is created, this function will be called
/// with Postgres credentials for the template database. The function should connect
/// to the database, perform any setup needed for your tests (i.e. creating tables,
/// inserting data, setting up role and permissions, etc), then close the database
/// connection and return `Ok(())`. If the setup fails, it should return an error-
/// this will trigger IntegreSQL to discard the template database.
///
/// It is important that this function close the database connection before
/// returning- if any connections are left open, attempts to create test
/// databases from this template will fail.
pub trait TemplateInitializer {
    fn setup(self, config: ConnectionSettings) -> Result<(), Box<dyn Error>>;
}

// Blanket implementation for any function/closure that matches the signature.
// We use `FnOnce` because the `setup` method consumes `self`.
impl<F> TemplateInitializer for F
where
    F: FnOnce(ConnectionSettings) -> Result<(), Box<dyn Error>>,
{
    fn setup(self, config: ConnectionSettings) -> Result<(), Box<dyn Error>> {
        // `self` in this context is the function/closure itself, so we just call it.
        self(config)
    }
}

/// A template database setup function that should be called asynchronously.
///
/// When a new template database is created, this function will be called
/// with Postgres credentials for the template database. The function should connect
/// to the database, perform any setup needed for your tests (i.e. creating tables,
/// inserting data, setting up role and permissions, etc), then close the database
/// connection and return `Ok(())`. If the setup fails, it should return an error-
/// this will trigger IntegreSQL to discard the template database.
///
/// It is important that this function close the database connection before
/// returning- if any connections are left open, attempts to create test
/// databases from this template will fail.
pub trait AsyncTemplateInitializer {
    fn setup(
        self,
        config: ConnectionSettings,
    ) -> impl Future<Output = Result<(), Box<dyn Error + 'static>>> + Send;
}

// Blanket implementation that allows any async function with signature
// `async fn(DatabaseConfig) -> Result<(), Box<dyn Error>>` to be used as
// an AsyncTemplateInitializer.
impl<F, Fut> AsyncTemplateInitializer for F
where
    F: FnOnce(ConnectionSettings) -> Fut + Send,
    Fut: Future<Output = Result<(), Box<dyn Error + 'static>>> + Send,
{
    fn setup(
        self,
        config: ConnectionSettings,
    ) -> impl Future<Output = Result<(), Box<dyn Error + 'static>>> + Send {
        self(config)
    }
}

/// A template database that can be used to create test databases.
pub struct TemplateDb {
    client: Client,
    template_hash: TemplateHash,
}

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

impl TemplateDb {
    /// Returns a `TestDb` instance for the template database associated with this supplier.
    ///
    /// This method will create a new test database from the template, or return an existing
    /// one if it has already been created.
    pub fn get_writable_test_db(&self) -> Result<ConnectionSettings, IntegresqlError> {
        let response = self.client.get_test_db(self.template_hash)?;
        Ok(self.make_test_db(response, false))
    }

    /// Returns a `TestDb` instance for the template database associated with this supplier.
    ///
    /// This method will create a new test database from the template, or return an existing
    /// one if it has already been created.
    pub fn get_readonly_test_db(&self) -> Result<ConnectionSettings, IntegresqlError> {
        let response = self.client.get_test_db(self.template_hash)?;
        Ok(self.make_test_db(response, true))
    }

    /// Returns the hash-based identifier for this template database.
    ///
    /// The returned value is a 16 character hexadecimal string based on hashing
    /// the template's unique key.
    pub fn get_template_id(&self) -> String {
        self.template_hash.to_string()
    }

    fn make_test_db(&self, response: GetTestDbResponse, reuse: bool) -> ConnectionSettings {
        let drop_action = if reuse {
            DropAction::Unlock(self.client.clone(), response.id)
        } else {
            DropAction::Recreate(self.client.clone(), response.id)
        };
        ConnectionSettings {
            host: response.database.config.host,
            port: response.database.config.port,
            username: response.database.config.username,
            password: response.database.config.password,
            database: response.database.config.database,
            additional_params: response.database.config.additional_params,
            template_hash: response.database.template_hash,
            id: Some(response.id),
            drop_action: Some(drop_action),
        }
    }
}

/// A manager for IntegreSQL template databases- the entry point for this crate.
///
/// DbManager allows users to create and delete IntegreSQL template databases,
/// and to create suppliers that can be used to obtain test databases based on
/// those templates.
#[derive(Debug, Clone)]
pub struct DbManager {
    client: Client,
}

/// Returns a DbManager configured from environment variables.
///
/// If any environment variable is set to an invalid value, this function
/// will panic.
impl Default for DbManager {
    fn default() -> Self {
        DbManager::from_env()
    }
}

impl DbManager {
    /// Create a new `DbManager` configured from environment variables.
    ///
    /// The IntegreSQL base URL and request timeout are read from the
    /// `INTEGRESQL_BASE_URL` and `INTEGRESQL_TIMEOUT_SECONDS` environment
    /// variables, respectively. If `INTEGRESQL_BASE_URL` is not set, it
    /// defaults to `http://integresql:5000/api`. If `INTEGRESQL_TIMEOUT` is not
    /// set, it defaults to `6`.
    ///
    /// If any environment variable is set to an invalid value, this function
    /// will panic. To create a `DbManager` without risk of panicing,
    /// use `DbManager::new` instead.
    pub fn from_env() -> Self {
        let base_url = env::var(BASE_URL_ENV)
            .unwrap_or_else(|_| DEFAULT_BASE_URL.to_string())
            .parse::<Uri>()
            .expect("Invalid URI in environment variable INTEGRESQL_CLIENT_BASE_URL");
        let timeout = match env::var(DEFAULT_TIMEOUT_ENV) {
            Ok(val) => val
                .parse::<u64>()
                .map(Duration::from_secs)
                .unwrap_or(DEFAULT_TIMEOUT),
            Err(_) => DEFAULT_TIMEOUT,
        };
        info!(
            "Configured Integresql client from environment: base_url={} timeout_seconds={}",
            base_url,
            timeout.as_secs()
        );
        let client = Client::new(base_url, timeout);
        DbManager { client }
    }

    pub fn new(base_uri: Uri, timeout: Duration) -> Self {
        let client = Client::new(base_uri, timeout);
        DbManager { client }
    }

    /// Drops all test databases, and deregisters all template databases.
    ///
    /// This method drops all existing test databases from Postgres and
    /// deregisters all template databases from the IntegreSQL server. It does
    /// not *drop* the template databases themselves, though. As such, it will
    /// disallow creation of new test databases from any current template
    /// databases, but will when intitializing new templates, will reuse an
    /// existing template database if one already exists with the same template
    /// hash.
    /// 
    /// To deregister *and* drop a template database, use `discard_template`.
    pub fn clear_db_tracking(&self) -> Result<(), IntegresqlError> {
        self.client.clear_db_tracking()
    }

    /// Deregisters and deletes the template database identified by the given
    /// template key, if one exists.
    ///
    /// The template_key should be the same value that was passed to
    /// `get_db_supplier_async` or `get_db_supplier_sync` when creating the
    /// template database.
    ///
    /// This prevents the creation of new test databases from this template, but
    /// does not delete any existing test databases that have already been
    /// created from this template.
    pub fn discard_template(&self, template_key: impl Hash) -> Result<(), IntegresqlError> {
        let template_hash = TemplateHash::from_hash(template_key);
        self.client.discard_template(template_hash)
    }

    /// Creates a new `DbSupplier` for the specified template key, using the
    /// provided synchronous initializer function to set up the template database.
    ///
    /// This method will create a new template database if one with the given
    /// key does not already exist, and will call the provided initializer
    /// to setup the database contents. If a template database with the same key
    /// already exists, the initializer will not be called and the existing
    /// template database will be used.
    ///
    /// The `template_key` should be a hashable value that uniquely identifies
    /// the initialization logic that will be used to setup the template
    /// database. For example, a `String` or `Vec<String>` containing the SQL
    /// scripts that will be used to setup the database.
    ///
    /// The `initializer` should return `Ok(())` if the template database was
    /// successfully set up, or an error if the setup failed.  A blanket
    /// implementation allows any non-async function or closure with signature
    /// `Result<(), Box<dyn Error + 'static>>` to be used as the initializer.
    pub async fn get_template_db_async(
        &self,
        template_key: impl Hash,
        initializer: impl AsyncTemplateInitializer,
    ) -> Result<TemplateDb, IntegresqlError> {
        let template_hash = TemplateHash::from_hash(template_key);
        let supplier = TemplateDb {
            client: self.client.clone(),
            template_hash,
        };

        let template_settings = match supplier.client.initialize_template(supplier.template_hash) {
            InitializeTemplateResult::Success(db) => db,
            InitializeTemplateResult::TemplateAlreadyInitialized => return Ok(supplier),
            InitializeTemplateResult::Err(e) => return Err(e),
        };

        let connection_settings = ConnectionSettings {
            host: template_settings.config.host,
            port: template_settings.config.port,
            username: template_settings.config.username,
            password: template_settings.config.password,
            database: template_settings.config.database,
            additional_params: template_settings.config.additional_params,
            template_hash: supplier.template_hash,
            id: None, // This is a template, so no ID is assigned
            drop_action: None, // No drop action for templates
        };

        let result = initializer.setup(connection_settings).await;
        Self::handle_template_setup_result(supplier, result)
    }

    /// Creates a new `DbSupplier` for the specified template key, using the
    /// provided asynchronous initializer function to set up the template database.
    ///
    /// This method will create a new template database if one with the given
    /// key does not already exist, and will call the provided initializer
    /// to setup the database contents. If a template database with the same key
    /// already exists, the initializer will not be called and the existing
    /// template database will be used.
    ///
    /// The `template_key` should be a hashable value that uniquely identifies
    /// the initialization logic that will be used to setup the template
    /// database. For example, a `String` or `Vec<String>` containing the SQL
    /// scripts that will be used to setup the database.
    ///
    /// The `initializer` should return `Ok(())` if the template database was
    /// successfully set up, or an error if the setup failed.  A blanket
    /// implementation allows any async function or closure with signature
    /// `Result<(), Box<dyn Error + 'static>>` to be used as the initializer.
    pub fn get_template_db_sync(
        &self,
        template_key: impl Hash,
        initializer: impl TemplateInitializer,
    ) -> Result<TemplateDb, IntegresqlError> {
        let template_hash = TemplateHash::from_hash(template_key);
        let supplier = TemplateDb {
            client: self.client.clone(),
            template_hash,
        };

        let template_settings = match supplier.client.initialize_template(supplier.template_hash) {
            InitializeTemplateResult::Success(db) => db,
            InitializeTemplateResult::TemplateAlreadyInitialized => return Ok(supplier),
            InitializeTemplateResult::Err(e) => return Err(e),
        };

        let connection_settings = ConnectionSettings {
            host: template_settings.config.host,
            port: template_settings.config.port,
            username: template_settings.config.username,
            password: template_settings.config.password,
            database: template_settings.config.database,
            additional_params: template_settings.config.additional_params,
            template_hash: supplier.template_hash,
            id: None, // This is a template, so no ID is assigned
            drop_action: None, // No drop action for templates
        };

        let result = initializer.setup(connection_settings);
        Self::handle_template_setup_result(supplier, result)
    }

    fn handle_template_setup_result(
        supplier: TemplateDb,
        result: Result<(), Box<dyn Error>>,
    ) -> Result<TemplateDb, IntegresqlError> {
        match result {
            // If the setup was successful, finalize the template and return the supplier
            Ok(_) => {
                info!(
                    "Template setup completed successfully template_hash={}",
                    supplier.template_hash
                );
                supplier.client.finalize_template(supplier.template_hash)?;
                Ok(supplier)
            }
            // If it failed, discard the template and return an error
            Err(e) => {
                warn!(
                    "Template setup failed for hash template_hash={} error={}",
                    supplier.template_hash, e
                );
                supplier.client.discard_template(supplier.template_hash)?;
                Err(IntegresqlError::SetupError(e.to_string()))
            }
        }
    }
}

#[derive(Debug, Clone)]
enum DropAction {
    Recreate(Client, i32),
    Unlock(Client, i32),
}

/// Credentials to connect to a database managed by IntegreSQL- either a 
/// template database or a test database.
/// 
/// If this is a writable test database, it will be deleted and recreated when
/// it goes out of scope. If this is a read-only test database, it will be
/// unlocked and made available to other tests when it goes out of scope.  If
/// this is a template database, no action will be taken when it goes out of
/// scope.
/// 
/// The `id` field can be used to determine if this is a test database or a
/// template database (if it's `None`, this is a template database).
#[derive(Debug, Clone)]
pub struct ConnectionSettings {
    /// The Postgres server hostname
    pub host: String,

    /// The Postgres server port
    pub port: u16,

    /// The username to connect as
    pub username: String,

    /// The password for this username
    pub password: String,

    /// The name of the test database
    pub database: String,

    /// Additional parameters to include in the connection string
    pub additional_params: Option<HashMap<String, String>>,

    /// If this is a test database, its unique test DB id. If it is a template
    /// database, `None`
    pub id: Option<i32>,

    /// The hash of this database's associated template database.
    /// 
    /// If this is a template database, this will be the template hash of the
    /// database itself.  If this is a test database, this will be the template
    /// hash of the DB's source template DB.
    template_hash: TemplateHash,

    drop_action: Option<DropAction>,
}

/// # Warning
///
/// The `Drop` implementation for `TestDb` performs an HTTP request to the IntegreSQL server
/// to cleanup the test database when the `TestDb` instance goes out of scope. Any errors
/// encountered during this cleanup will be logged but not propagated.
impl Drop for ConnectionSettings {
    fn drop(&mut self) {
        if let Some(drop_action) = self.drop_action.take() {
            match drop_action {
                DropAction::Recreate(client, id) => {
                    client.recreate_test_db(self.template_hash, id)
                        .unwrap_or_else(|e| {
                            error!("Failed to recreate test database template_hash={} test_db_id={} error={}", self.template_hash, id, e);
                        });
                }
                DropAction::Unlock(client, id) => {
                    client.unlock_test_db(self.template_hash, id)
                        .unwrap_or_else(|e| {
                            error!("Failed to unlock test database template_hash={} test_db_id={} error={}", self.template_hash, id, e);
                        });
                }
            }
        }
    }
}

impl ConnectionSettings {
    /// Returns a libpq-compatible Postgres connection string based on this configuration.
    ///
    /// The returned string will be in this format: `postgres://username:password@host:port/database?param1=value1`
    pub fn to_libpq_url(&self) -> String {
        {
            let host: &str = &self.host;
            let port = self.port;
            let username: &str = &self.username;
            let password: &str = &self.password;
            let database: &str = &self.database;
            let additional_params  = &self.additional_params;
            let additional_params = additional_params
                .as_ref()
                .map(|params| {
                    params
                        .iter()
                        .map(|(k, v)| format!("{}={}", k, v))
                        .collect::<Vec<_>>()
                        .join("&")
                })
                .unwrap_or_default();
            format!(
                "postgres://{}:{}@{}:{}/{}?{}",
                username, password, host, port, database, additional_params
            )
        }
    }

    /// The hash of this database's associated template database.
    /// 
    /// If this is a template database, this will be the template hash of the
    /// database itself.  If this is a test database, this will be the template
    /// hash of the DB's source template DB.
    pub fn template_hash(&self) -> String {
        self.template_hash.to_string()
    }
}