docker_wrapper/template/database/
mysql.rs1#![allow(clippy::doc_markdown)]
4#![allow(clippy::must_use_candidate)]
5#![allow(clippy::return_self_not_must_use)]
6#![allow(clippy::map_unwrap_or)]
7#![allow(clippy::format_push_string)]
8#![allow(clippy::uninlined_format_args)]
9
10use crate::template::{HealthCheck, Template, TemplateConfig, VolumeMount};
11use async_trait::async_trait;
12use std::collections::HashMap;
13
14pub struct MysqlTemplate {
16 config: TemplateConfig,
17}
18
19impl MysqlTemplate {
20 pub fn new(name: impl Into<String>) -> Self {
22 let name = name.into();
23 let mut env = HashMap::new();
24
25 env.insert("MYSQL_ROOT_PASSWORD".to_string(), "mysql".to_string());
27 env.insert("MYSQL_DATABASE".to_string(), "mysql".to_string());
28
29 let config = TemplateConfig {
30 name: name.clone(),
31 image: "mysql".to_string(),
32 tag: "8.0".to_string(),
33 ports: vec![(3306, 3306)],
34 env,
35 volumes: Vec::new(),
36 network: None,
37 health_check: Some(HealthCheck {
38 test: vec![
39 "mysqladmin".to_string(),
40 "ping".to_string(),
41 "-h".to_string(),
42 "localhost".to_string(),
43 ],
44 interval: "10s".to_string(),
45 timeout: "5s".to_string(),
46 retries: 5,
47 start_period: "30s".to_string(),
48 }),
49 auto_remove: false,
50 memory_limit: None,
51 cpu_limit: None,
52 platform: None,
53 };
54
55 Self { config }
56 }
57
58 pub fn port(mut self, port: u16) -> Self {
60 self.config.ports = vec![(port, 3306)];
61 self
62 }
63
64 pub fn root_password(mut self, password: impl Into<String>) -> Self {
66 self.config
67 .env
68 .insert("MYSQL_ROOT_PASSWORD".to_string(), password.into());
69 self
70 }
71
72 pub fn database(mut self, db: impl Into<String>) -> Self {
74 self.config
75 .env
76 .insert("MYSQL_DATABASE".to_string(), db.into());
77 self
78 }
79
80 pub fn user(mut self, user: impl Into<String>) -> Self {
82 self.config
83 .env
84 .insert("MYSQL_USER".to_string(), user.into());
85 self
86 }
87
88 pub fn password(mut self, password: impl Into<String>) -> Self {
90 self.config
91 .env
92 .insert("MYSQL_PASSWORD".to_string(), password.into());
93 self
94 }
95
96 pub fn allow_empty_password(mut self) -> Self {
98 self.config.env.remove("MYSQL_ROOT_PASSWORD");
99 self.config
100 .env
101 .insert("MYSQL_ALLOW_EMPTY_PASSWORD".to_string(), "yes".to_string());
102 self
103 }
104
105 pub fn random_root_password(mut self) -> Self {
107 self.config.env.remove("MYSQL_ROOT_PASSWORD");
108 self.config
109 .env
110 .insert("MYSQL_RANDOM_ROOT_PASSWORD".to_string(), "yes".to_string());
111 self
112 }
113
114 pub fn with_persistence(mut self, volume_name: impl Into<String>) -> Self {
116 self.config.volumes.push(VolumeMount {
117 source: volume_name.into(),
118 target: "/var/lib/mysql".to_string(),
119 read_only: false,
120 });
121 self
122 }
123
124 pub fn init_scripts(mut self, scripts_path: impl Into<String>) -> Self {
126 self.config.volumes.push(VolumeMount {
127 source: scripts_path.into(),
128 target: "/docker-entrypoint-initdb.d".to_string(),
129 read_only: true,
130 });
131 self
132 }
133
134 pub fn config_file(mut self, config_path: impl Into<String>) -> Self {
136 self.config.volumes.push(VolumeMount {
137 source: config_path.into(),
138 target: "/etc/mysql/conf.d/custom.cnf".to_string(),
139 read_only: true,
140 });
141 self
142 }
143
144 pub fn memory_limit(mut self, limit: impl Into<String>) -> Self {
146 self.config.memory_limit = Some(limit.into());
147 self
148 }
149
150 pub fn character_set(mut self, charset: impl Into<String>) -> Self {
152 let charset = charset.into();
153 self.config
154 .env
155 .insert("MYSQL_CHARSET".to_string(), charset.clone());
156 let current_cmd = self
157 .config
158 .env
159 .get("MYSQL_COMMAND")
160 .map(|s| format!("{} --character-set-server={}", s, charset))
161 .unwrap_or_else(|| format!("--character-set-server={}", charset));
162 self.config
163 .env
164 .insert("MYSQL_COMMAND".to_string(), current_cmd);
165 self
166 }
167
168 pub fn collation(mut self, collation: impl Into<String>) -> Self {
170 let collation = collation.into();
171 self.config
172 .env
173 .insert("MYSQL_COLLATION".to_string(), collation.clone());
174 let current_cmd = self
175 .config
176 .env
177 .get("MYSQL_COMMAND")
178 .map(|s| format!("{} --collation-server={}", s, collation))
179 .unwrap_or_else(|| format!("--collation-server={}", collation));
180 self.config
181 .env
182 .insert("MYSQL_COMMAND".to_string(), current_cmd);
183 self
184 }
185
186 pub fn version(mut self, version: impl Into<String>) -> Self {
188 self.config.tag = version.into();
189 self
190 }
191
192 pub fn network(mut self, network: impl Into<String>) -> Self {
194 self.config.network = Some(network.into());
195 self
196 }
197
198 pub fn auto_remove(mut self) -> Self {
200 self.config.auto_remove = true;
201 self
202 }
203
204 pub fn custom_image(mut self, image: impl Into<String>, tag: impl Into<String>) -> Self {
206 self.config.image = image.into();
207 self.config.tag = tag.into();
208 self
209 }
210
211 pub fn platform(mut self, platform: impl Into<String>) -> Self {
213 self.config.platform = Some(platform.into());
214 self
215 }
216}
217
218#[async_trait]
219impl Template for MysqlTemplate {
220 fn name(&self) -> &str {
221 &self.config.name
222 }
223
224 fn config(&self) -> &TemplateConfig {
225 &self.config
226 }
227
228 fn config_mut(&mut self) -> &mut TemplateConfig {
229 &mut self.config
230 }
231}
232
233pub struct MysqlConnectionString {
235 host: String,
236 port: u16,
237 database: String,
238 user: String,
239 password: String,
240}
241
242impl MysqlConnectionString {
243 pub fn from_template(template: &MysqlTemplate) -> Self {
245 let config = template.config();
246 let port = config.ports.first().map(|(h, _)| *h).unwrap_or(3306);
247
248 let (user, password) = if let Some(user) = config.env.get("MYSQL_USER") {
250 let password = config
251 .env
252 .get("MYSQL_PASSWORD")
253 .cloned()
254 .unwrap_or_default();
255 (user.clone(), password)
256 } else {
257 let password = config
258 .env
259 .get("MYSQL_ROOT_PASSWORD")
260 .cloned()
261 .unwrap_or_else(|| "mysql".to_string());
262 ("root".to_string(), password)
263 };
264
265 Self {
266 host: "localhost".to_string(),
267 port,
268 database: config
269 .env
270 .get("MYSQL_DATABASE")
271 .cloned()
272 .unwrap_or_else(|| "mysql".to_string()),
273 user,
274 password,
275 }
276 }
277
278 pub fn url(&self) -> String {
280 format!(
281 "mysql://{}:{}@{}:{}/{}",
282 self.user, self.password, self.host, self.port, self.database
283 )
284 }
285
286 pub fn jdbc(&self) -> String {
288 format!(
289 "jdbc:mysql://{}:{}/{}?user={}&password={}",
290 self.host, self.port, self.database, self.user, self.password
291 )
292 }
293}
294
295#[cfg(test)]
296mod tests {
297 use super::*;
298
299 #[test]
300 fn test_mysql_template_basic() {
301 let template = MysqlTemplate::new("test-mysql");
302 assert_eq!(template.name(), "test-mysql");
303 assert_eq!(template.config().image, "mysql");
304 assert_eq!(template.config().tag, "8.0");
305 assert_eq!(template.config().ports, vec![(3306, 3306)]);
306 }
307
308 #[test]
309 fn test_mysql_template_custom_config() {
310 let template = MysqlTemplate::new("test-mysql")
311 .database("mydb")
312 .user("myuser")
313 .password("secret123")
314 .port(13306);
315
316 assert_eq!(
317 template.config().env.get("MYSQL_DATABASE"),
318 Some(&"mydb".to_string())
319 );
320 assert_eq!(
321 template.config().env.get("MYSQL_USER"),
322 Some(&"myuser".to_string())
323 );
324 assert_eq!(
325 template.config().env.get("MYSQL_PASSWORD"),
326 Some(&"secret123".to_string())
327 );
328 assert_eq!(template.config().ports, vec![(13306, 3306)]);
329 }
330
331 #[test]
332 fn test_mysql_template_with_persistence() {
333 let template = MysqlTemplate::new("test-mysql").with_persistence("mysql-data");
334
335 assert_eq!(template.config().volumes.len(), 1);
336 assert_eq!(template.config().volumes[0].source, "mysql-data");
337 assert_eq!(template.config().volumes[0].target, "/var/lib/mysql");
338 }
339
340 #[test]
341 fn test_mysql_connection_string() {
342 let template = MysqlTemplate::new("test-mysql")
343 .database("testdb")
344 .user("testuser")
345 .password("testpass")
346 .port(13306);
347
348 let conn = MysqlConnectionString::from_template(&template);
349
350 assert_eq!(
351 conn.url(),
352 "mysql://testuser:testpass@localhost:13306/testdb"
353 );
354
355 assert_eq!(
356 conn.jdbc(),
357 "jdbc:mysql://localhost:13306/testdb?user=testuser&password=testpass"
358 );
359 }
360}