1use crate::traits::DatabaseDriver;
8use crate::types::*;
9
10pub fn build_create_table_sql(
12 quote_ident: &dyn Fn(&str) -> String,
13 schema: &TableSchema,
14) -> String {
15 let tname = &schema.table_name;
16 let cols_sql: Vec<String> = schema
17 .columns
18 .iter()
19 .map(|c| {
20 let mut def = format!(" {} {}", quote_ident(&c.name), c.data_type);
21 if !c.nullable {
22 def.push_str(" NOT NULL");
23 }
24 if let Some(ref dv) = c.default_value {
25 def.push_str(&format!(" DEFAULT {}", dv));
26 }
27 def
28 })
29 .collect();
30
31 let mut create = format!(
32 "CREATE TABLE IF NOT EXISTS {} (\n{}",
33 quote_ident(tname),
34 cols_sql.join(",\n")
35 );
36 if !schema.primary_keys.is_empty() {
37 let pks: Vec<String> = schema.primary_keys.iter().map(|k| quote_ident(k)).collect();
38 create.push_str(&format!(",\n PRIMARY KEY ({})", pks.join(", ")));
39 }
40 create.push_str("\n);\n");
41 create
42}
43
44pub async fn dump_table_ddl_from_schema<D>(
46 driver: &D,
47 handle: &ConnectionHandle,
48 table: &str,
49) -> Result<String, DriverError>
50where
51 D: DatabaseDriver + ?Sized,
52{
53 let schema = driver.get_table_schema(handle, table).await?;
54 Ok(build_create_table_sql(&|n| driver.quote_ident(n), &schema))
55}
56
57pub async fn dump_sql_database<D>(
61 driver: &D,
62 handle: &ConnectionHandle,
63 database: &str,
64 opts: &BackupDumpOptions,
65) -> Result<String, DriverError>
66where
67 D: DatabaseDriver + ?Sized,
68{
69 let tables = driver.get_tables(handle, database).await?;
70
71 let mut out = String::new();
72 out.push_str(&format!("-- DataZen backup: {}\n", database));
73 out.push_str(&format!("-- Date: {}\n", chrono::Utc::now().to_rfc3339()));
74 let mut opt_flags = Vec::new();
75 if opts.schema_only {
76 opt_flags.push("schema-only");
77 }
78 if opts.data_only {
79 opt_flags.push("data-only");
80 }
81 if opts.clean {
82 opt_flags.push("clean");
83 }
84 if opts.create_database {
85 opt_flags.push("create");
86 }
87 if opts.no_owner {
88 opt_flags.push("no-owner");
89 }
90 if opts.single_transaction {
91 opt_flags.push("single-transaction");
92 }
93 if opts.routines {
94 opt_flags.push("routines");
95 }
96 if opts.triggers {
97 opt_flags.push("triggers");
98 }
99 if !opt_flags.is_empty() {
100 out.push_str(&format!("-- Options: {}\n", opt_flags.join(", ")));
101 }
102 if opts.no_owner {
103 out.push_str("-- no-owner: OWNER clauses omitted\n");
104 }
105 out.push('\n');
106
107 for table in &tables {
108 let tname = &table.name;
109 out.push_str(&format!("-- Table: {}\n", tname));
110
111 if opts.clean {
112 out.push_str(&format!(
113 "DROP TABLE IF EXISTS {};\n",
114 driver.quote_ident(tname)
115 ));
116 }
117
118 if !opts.data_only {
119 let ddl = driver.dump_table_ddl(handle, tname).await?;
120 out.push_str(&ddl);
121 if !ddl.ends_with('\n') {
122 out.push('\n');
123 }
124 out.push('\n');
125 }
126
127 if !opts.schema_only {
128 let schema = driver.get_table_schema(handle, tname).await?;
129 let col_names: Vec<String> = schema
130 .columns
131 .iter()
132 .map(|c| driver.quote_ident(&c.name))
133 .collect();
134 let select_sql = format!(
135 "SELECT {} FROM {}",
136 col_names.join(", "),
137 driver.quote_ident(tname)
138 );
139
140 match driver.query(handle, &select_sql).await {
141 Ok(result) => {
142 for row in &result.rows {
143 let vals: Vec<String> =
144 row.iter().map(|v| driver.format_sql_literal(v)).collect();
145 out.push_str(&format!(
146 "INSERT INTO {} ({}) VALUES ({});\n",
147 driver.quote_ident(tname),
148 col_names.join(", "),
149 vals.join(", ")
150 ));
151 }
152 out.push('\n');
153 }
154 Err(e) => {
155 out.push_str(&format!("-- Error dumping data for {tname}: {e}\n\n"));
156 }
157 }
158 }
159 }
160
161 Ok(out)
162}
163
164pub fn split_sql_statements(input: &str) -> Vec<String> {
169 let bytes = input.as_bytes();
170 let len = bytes.len();
171 let mut stmts: Vec<String> = Vec::new();
172 let mut start = 0;
173 let mut i = 0;
174
175 while i < len {
176 match bytes[i] {
177 b'\'' => {
178 i += 1;
179 while i < len {
180 if bytes[i] == b'\'' {
181 i += 1;
182 if i < len && bytes[i] == b'\'' {
183 i += 1; } else {
185 break;
186 }
187 } else {
188 i += 1;
189 }
190 }
191 }
192 b'"' => {
193 i += 1;
194 while i < len {
195 if bytes[i] == b'"' {
196 i += 1;
197 if i < len && bytes[i] == b'"' {
198 i += 1;
199 } else {
200 break;
201 }
202 } else {
203 i += 1;
204 }
205 }
206 }
207 b'$' => {
208 if let Some(tag_end) = find_dollar_tag(bytes, i) {
209 let tag = &input[i..tag_end];
210 i = tag_end;
211 loop {
212 if i >= len {
213 break;
214 }
215 if bytes[i] == b'$' && input[i..].starts_with(tag) {
216 i += tag.len();
217 break;
218 }
219 i += 1;
220 }
221 } else {
222 i += 1;
223 }
224 }
225 b'-' if i + 1 < len && bytes[i + 1] == b'-' => {
226 while i < len && bytes[i] != b'\n' {
227 i += 1;
228 }
229 }
230 b'/' if i + 1 < len && bytes[i + 1] == b'*' => {
231 i += 2;
232 let mut depth = 1u32;
233 while i + 1 < len && depth > 0 {
234 if bytes[i] == b'/' && bytes[i + 1] == b'*' {
235 depth += 1;
236 i += 2;
237 } else if bytes[i] == b'*' && bytes[i + 1] == b'/' {
238 depth -= 1;
239 i += 2;
240 } else {
241 i += 1;
242 }
243 }
244 }
245 b';' => {
246 let fragment = input[start..i].trim();
247 if !fragment.is_empty() {
248 stmts.push(fragment.to_string());
249 }
250 i += 1;
251 start = i;
252 }
253 _ => {
254 i += 1;
255 }
256 }
257 }
258
259 let tail = input[start..].trim();
260 if !tail.is_empty() {
261 stmts.push(tail.to_string());
262 }
263 stmts
264}
265
266pub fn find_dollar_tag(bytes: &[u8], pos: usize) -> Option<usize> {
269 if pos >= bytes.len() || bytes[pos] != b'$' {
270 return None;
271 }
272 let mut j = pos + 1;
273 while j < bytes.len() {
274 if bytes[j] == b'$' {
275 return Some(j + 1);
276 }
277 if !bytes[j].is_ascii_alphanumeric() && bytes[j] != b'_' {
278 return None;
279 }
280 j += 1;
281 }
282 None
283}
284
285fn is_comment_only_or_empty(stmt: &str) -> bool {
287 let bytes = stmt.as_bytes();
288 let len = bytes.len();
289 let mut i = 0;
290
291 while i < len {
292 while i < len && bytes[i].is_ascii_whitespace() {
293 i += 1;
294 }
295 if i >= len {
296 return true;
297 }
298 if i + 1 < len && bytes[i] == b'-' && bytes[i + 1] == b'-' {
299 while i < len && bytes[i] != b'\n' {
300 i += 1;
301 }
302 continue;
303 }
304 if i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'*' {
305 i += 2;
306 while i + 1 < len {
307 if bytes[i] == b'*' && bytes[i + 1] == b'/' {
308 i += 2;
309 break;
310 }
311 i += 1;
312 }
313 continue;
314 }
315 return false;
316 }
317
318 true
319}
320
321pub fn dump_header_requests_single_transaction(sql: &str) -> bool {
323 for line in sql.lines().take(20) {
324 let trimmed = line.trim();
325 if let Some(rest) = trimmed.strip_prefix("-- Options:") {
326 return rest
327 .split(',')
328 .any(|part| part.trim() == "single-transaction");
329 }
330 }
331 false
332}
333
334pub async fn restore_sql_statements<D>(
336 driver: &D,
337 handle: &ConnectionHandle,
338 sql: &str,
339 opts: Option<&BackupRestoreOptions>,
340) -> Result<(), DriverError>
341where
342 D: DatabaseDriver + ?Sized,
343{
344 let statements: Vec<String> = split_sql_statements(sql)
345 .into_iter()
346 .filter(|s| !is_comment_only_or_empty(s))
347 .collect();
348
349 let use_tx = opts.map(|o| o.single_transaction).unwrap_or(false)
350 || dump_header_requests_single_transaction(sql);
351
352 if use_tx {
353 driver.execute(handle, "BEGIN").await?;
354 }
355
356 let mut errors = Vec::new();
357 for stmt in &statements {
358 let full = format!("{};", stmt);
359 if let Err(e) = driver.execute(handle, &full).await {
360 if use_tx {
361 let _ = driver.execute(handle, "ROLLBACK").await;
362 }
363 let max = 80;
364 let end = if stmt.len() <= max {
365 stmt.len()
366 } else {
367 let mut e = max;
368 while e > 0 && !stmt.is_char_boundary(e) {
369 e -= 1;
370 }
371 e
372 };
373 errors.push(format!("Error executing: {}... -> {e}", &stmt[..end]));
374 }
375 }
376
377 if !errors.is_empty() {
378 return Err(DriverError::QueryFailed(format!(
379 "Partial restore failure ({}/{} statements failed):\n{}",
380 errors.len(),
381 statements.len(),
382 errors.join("\n")
383 )));
384 }
385
386 if use_tx {
387 driver.execute(handle, "COMMIT").await?;
388 }
389
390 Ok(())
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396
397 #[test]
398 fn build_create_table_sql_includes_pk_and_not_null() {
399 let schema = TableSchema {
400 table_name: "users".into(),
401 columns: vec![
402 ColumnSchema {
403 name: "id".into(),
404 data_type: "integer".into(),
405 nullable: false,
406 default_value: None,
407 comment: None,
408 is_primary_key: true,
409 is_auto_increment: false,
410 },
411 ColumnSchema {
412 name: "name".into(),
413 data_type: "text".into(),
414 nullable: true,
415 default_value: Some("'anon'".into()),
416 comment: None,
417 is_primary_key: false,
418 is_auto_increment: false,
419 },
420 ],
421 primary_keys: vec!["id".into()],
422 indexes: vec![],
423 foreign_keys: vec![],
424 };
425 let sql = build_create_table_sql(&|n| format!("\"{}\"", n), &schema);
426 assert!(sql.contains("CREATE TABLE IF NOT EXISTS \"users\""));
427 assert!(sql.contains("\"id\" integer NOT NULL"));
428 assert!(sql.contains("DEFAULT 'anon'"));
429 assert!(sql.contains("PRIMARY KEY (\"id\")"));
430 assert!(sql.ends_with(";\n"));
431 }
432
433 #[test]
434 fn split_sql_respects_semicolon_in_single_quotes() {
435 let stmts = split_sql_statements("SELECT 'a;b'; SELECT 1;");
436 assert_eq!(stmts.len(), 2);
437 assert_eq!(stmts[0], "SELECT 'a;b'");
438 assert_eq!(stmts[1], "SELECT 1");
439 }
440
441 #[test]
442 fn split_sql_respects_dollar_quoted_body_with_semicolon() {
443 let stmts = split_sql_statements("SELECT $$foo;bar$$; SELECT 1;");
444 assert_eq!(stmts.len(), 2);
445 assert_eq!(stmts[0], "SELECT $$foo;bar$$");
446 assert_eq!(stmts[1], "SELECT 1");
447 }
448
449 #[test]
450 fn split_sql_respects_line_comment_with_semicolon() {
451 let stmts = split_sql_statements("SELECT 1; -- trailing; comment\nSELECT 2;");
452 assert_eq!(stmts.len(), 2);
453 assert_eq!(stmts[0], "SELECT 1");
454 assert_eq!(stmts[1], "-- trailing; comment\nSELECT 2");
455 }
456
457 #[test]
458 fn split_sql_respects_block_comment_with_semicolon() {
459 let stmts = split_sql_statements("SELECT 1; /* block; comment */ SELECT 2;");
460 assert_eq!(stmts.len(), 2);
461 assert_eq!(stmts[0], "SELECT 1");
462 assert_eq!(stmts[1], "/* block; comment */ SELECT 2");
463 }
464
465 #[test]
466 fn is_comment_only_or_empty_detects_comment_statements() {
467 assert!(is_comment_only_or_empty("-- only a comment"));
468 assert!(is_comment_only_or_empty("/* block */"));
469 assert!(!is_comment_only_or_empty("SELECT 1"));
470 }
471
472 #[test]
473 fn dump_header_single_transaction_flag() {
474 let sql = "-- DataZen backup: app\n-- Options: clean, single-transaction\n";
475 assert!(dump_header_requests_single_transaction(sql));
476 assert!(!dump_header_requests_single_transaction(
477 "-- Options: clean\n"
478 ));
479 }
480}