1#[cfg(feature = "db-postgres")]
2use crate::hash;
3use crate::{
4 app::{AppContext, Hooks},
5 db, Error, Result,
6};
7#[cfg(feature = "db-postgres")]
8use sqlx::{AssertSqlSafe, Pool, Postgres};
9use std::future::Future;
10use std::path::PathBuf;
11use std::pin::Pin;
12use tree_fs::TreeBuilder;
13#[cfg(feature = "db-postgres")]
14use url::Url;
15
16pub async fn seed<H: Hooks>(ctx: &AppContext) -> Result<()> {
41 let path = std::path::Path::new("src/fixtures");
42 H::seed(ctx, path).await
43}
44
45pub fn init_test_db_creation(conn_str: &str) -> Result<Box<dyn TestSupport>> {
50 #[cfg(feature = "db-postgres")]
51 if conn_str.starts_with("postgres://") {
52 return PostgresTest::new(conn_str).map(|test| Box::new(test) as Box<dyn TestSupport>);
53 }
54 if conn_str.starts_with("sqlite://") {
55 SqliteTest::new(conn_str).map(|test| Box::new(test) as Box<dyn TestSupport>)
56 } else {
57 Ok(Box::new(Any::new(conn_str)))
58 }
59}
60
61pub trait TestSupport: Send + Sync {
62 fn init_db<'a>(&'a self) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
64 fn get_connection_str(&self) -> &str;
66 fn cleanup_db(&self);
68}
69
70#[cfg(feature = "db-postgres")]
71pub struct PostgresTest {
72 root_connection_string: String,
73 connection_string: String,
74 schema_name: String,
75}
76
77#[cfg(feature = "db-postgres")]
78impl PostgresTest {
79 pub fn new(conn_str: &str) -> Result<Self> {
84 let _db_name = db::extract_db_name(conn_str)?;
89
90 let current_timestamp = chrono::Utc::now().timestamp();
91 let test_schema_name: String = hash::random_string(10).to_lowercase();
92 let test_schema_name = format!("_loco_test_{test_schema_name}_{current_timestamp}");
93
94 let mut root_url = Url::parse(conn_str).map_err(|err| {
99 Error::string(&format!(
100 "could not parse Postgres connection string: {err}"
101 ))
102 })?;
103 root_url.set_path("/postgres");
104
105 let mut test_url = Url::parse(conn_str).map_err(|err| {
106 Error::string(&format!(
107 "could not parse Postgres connection string: {err}"
108 ))
109 })?;
110 test_url.set_path(&format!("/{test_schema_name}"));
111
112 Ok(Self {
113 root_connection_string: root_url.to_string(),
114 connection_string: test_url.to_string(),
115 schema_name: test_schema_name,
116 })
117 }
118}
119
120#[cfg(feature = "db-postgres")]
121impl TestSupport for PostgresTest {
122 fn get_connection_str(&self) -> &str {
123 &self.connection_string
124 }
125
126 fn init_db<'a>(&'a self) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
127 Box::pin(async move {
128 let pool = Pool::<Postgres>::connect(&self.root_connection_string)
129 .await
130 .expect("db connection should success");
131 let query = format!("CREATE DATABASE {};", self.schema_name);
132
133 sqlx::query(AssertSqlSafe(query))
134 .execute(&pool)
135 .await
136 .expect("create DB schema");
137 })
138 }
139
140 fn cleanup_db(&self) {
141 let connection_string = self.root_connection_string.clone();
142 let table_name = self.schema_name.clone();
143
144 std::thread::spawn(move || {
151 let rt = tokio::runtime::Builder::new_current_thread()
152 .enable_all()
153 .build()
154 .expect("create cleanup runtime");
155
156 rt.block_on(async {
157 let pool = Pool::<Postgres>::connect(&connection_string)
158 .await
159 .expect("db connection should success");
160 let query = format!("drop database if exists {table_name};");
161 sqlx::query(AssertSqlSafe(query))
162 .execute(&pool)
163 .await
164 .expect("Drop database");
165 });
166 })
167 .join()
168 .expect("db cleanup thread panicked");
169 }
170}
171
172pub struct SqliteTest {
173 connection_string: String,
174 db_folder: PathBuf,
175 _tree: tree_fs::Tree, }
177
178impl SqliteTest {
179 pub fn new(conn_str: &str) -> Result<Self> {
184 let db_name = db::extract_db_name(conn_str)?;
185
186 let tree = TreeBuilder::default()
187 .add_empty_file("test.sqlite")
188 .create()
189 .map_err(|err| {
190 Error::string(&format!(
191 "could not create test database directory. err: {err}"
192 ))
193 })?;
194
195 Ok(Self {
196 connection_string: conn_str.replace(
197 db_name,
198 &tree.root.join("test.sqlite").display().to_string(),
199 ),
200 db_folder: tree.root.clone(),
201 _tree: tree,
202 })
203 }
204}
205
206impl TestSupport for SqliteTest {
207 fn get_connection_str(&self) -> &str {
208 &self.connection_string
209 }
210 fn init_db<'a>(&'a self) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
211 Box::pin(async move {})
212 }
213
214 fn cleanup_db(&self) {
215 std::fs::remove_dir_all(&self.db_folder).expect("Could not delete sqlite test db");
216 }
217}
218
219pub struct Any {
220 connection_string: String,
221}
222impl Any {
223 #[must_use]
224 pub fn new(conn_str: &str) -> Self {
225 Self {
226 connection_string: conn_str.to_string(),
227 }
228 }
229}
230
231impl TestSupport for Any {
232 fn get_connection_str(&self) -> &str {
233 &self.connection_string
234 }
235 fn init_db<'a>(&'a self) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
236 Box::pin(async move {})
237 }
238
239 fn cleanup_db(&self) {}
240}
241
242#[cfg(test)]
243mod tests {
244
245 use super::*;
246 use sqlx::Row;
247
248 async fn schema_exists(pool: &sqlx::PgPool, schema_name: &str) -> bool {
249 let row =
250 sqlx::query("SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_database WHERE datname = $1)")
251 .bind(schema_name)
252 .fetch_one(pool)
253 .await
254 .expect("check if table exists");
255
256 println!("schema_name: {row:#?}");
257 row.get(0)
258 }
259
260 #[tokio::test]
261 async fn sqlite_test_support() {
262 let conn = "sqlite://test.sqlite?mode=rwc";
263 let sqlite = SqliteTest::new(conn).expect("create Sqlite test support");
264
265 sqlite.init_db().await;
266
267 assert!(sqlite.db_folder.exists());
268 sqlite.cleanup_db();
269 assert!(!sqlite.db_folder.exists());
270 }
271
272 #[tokio::test]
273 async fn postgres_test_support() {
274 let (conn, _container) = crate::tests_cfg::postgres::setup_postgres_container().await;
275 let pg: PostgresTest = PostgresTest::new(&conn).expect("create Postgres test support");
276
277 pg.init_db().await;
278
279 let pool = Pool::<Postgres>::connect(&conn)
280 .await
281 .expect("db connection should success");
282
283 assert!(schema_exists(&pool, &pg.schema_name).await);
284
285 pg.cleanup_db();
286
287 assert!(!schema_exists(&pool, &pg.schema_name).await);
290 }
291
292 #[test]
293 fn postgres_test_new_does_not_corrupt_host_or_user_when_db_name_is_substring() {
294 let conn_str = "postgres://loco:pass@loco-db.host:5432/loco";
298
299 let pg = PostgresTest::new(conn_str).expect("create Postgres test support");
300
301 let root =
302 Url::parse(&pg.root_connection_string).expect("root connection string is a valid URL");
303 assert_eq!(root.path(), "/postgres");
304 assert_eq!(root.username(), "loco");
305 assert_eq!(root.password(), Some("pass"));
306 assert_eq!(root.host_str(), Some("loco-db.host"));
307 assert_eq!(root.port(), Some(5432));
308
309 let test_conn =
310 Url::parse(&pg.connection_string).expect("test connection string is a valid URL");
311 assert_eq!(test_conn.path(), format!("/{}", pg.schema_name));
312 assert_eq!(test_conn.username(), "loco");
313 assert_eq!(test_conn.password(), Some("pass"));
314 assert_eq!(test_conn.host_str(), Some("loco-db.host"));
315 assert_eq!(test_conn.port(), Some(5432));
316 }
317}