-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathembedded.rs
More file actions
93 lines (80 loc) · 2.75 KB
/
embedded.rs
File metadata and controls
93 lines (80 loc) · 2.75 KB
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
use anyhow::Context;
use postgresql_embedded::{PostgreSQL, Settings, VersionReq};
use std::path::{Path, PathBuf};
use tracing::{Instrument, info_span};
use trustify_common::{db::Database, decompress::decompress_async_read};
/// Create common default settings for the embedded database
pub fn default_settings() -> anyhow::Result<Settings> {
// **NOTE:** Changing the default version here, one should also change the env-var in the CI job
let version = VersionReq::parse(option_env!("POSTGRESQL_VERSION").unwrap_or("=17.2.0"))
.context("valid psql version")?;
Ok(Settings {
version,
username: "postgres".to_string(),
password: "trustify".to_string(),
temporary: true,
..Default::default()
})
}
/// Create a new, embedded database instance
pub async fn create() -> anyhow::Result<(Database, PostgreSQL)> {
create_for(default_settings()?, Default::default()).await
}
/// Create a new, embedded database instance in a specific directory
pub async fn create_in(base: impl AsRef<Path>) -> anyhow::Result<(Database, PostgreSQL)> {
let base = base.as_ref();
create_for(
Settings {
data_dir: base.join("data"),
installation_dir: base.join("instance"),
..default_settings()?
},
Default::default(),
)
.await
}
#[derive(Default, Debug)]
pub enum Source {
#[default]
Bootstrap,
Import(PathBuf),
}
#[derive(Default, Debug)]
pub struct Options {
pub source: Source,
}
/// Create a new, embedded database instance, using the provided settings
pub async fn create_for(
settings: Settings,
options: Options,
) -> anyhow::Result<(Database, PostgreSQL)> {
log::info!("creating embedded database - version: {}", settings.version);
let postgresql = async {
let mut postgresql = PostgreSQL::new(settings);
postgresql
.setup()
.await
.context("Setting up the test database")?;
postgresql
.start()
.await
.context("Starting the test database")?;
Ok::<_, anyhow::Error>(postgresql)
}
.instrument(info_span!("start database"))
.await?;
let config = crate::config::Database::from_port(postgresql.settings().port)?;
let db = match options.source {
Source::Bootstrap => super::Database::bootstrap(&config)
.await
.context("Bootstrapping the test database")?,
Source::Import(path) => {
log::info!("Importing database from: {}", path.display());
let source = decompress_async_read(path).await?;
super::Database::import(&config, source)
.await
.context("Bootstrapping the test database")?
}
};
Ok((db, postgresql))
}