Parse INSERT statement to extract column names and values
(sql: &str, conn: &Connection, table_name: &str)
| 348 | |
| 349 | /// Parse INSERT statement to extract column names and values |
| 350 | fn parse_insert_statement(sql: &str, conn: &Connection, table_name: &str) -> Option<Vec<(String, String)>> { |
| 351 | // Try multi-row INSERT first (with or without column names) |
| 352 | |
| 353 | // Multi-row INSERT with column names: INSERT INTO table (col1, col2) VALUES (val1, val2), (val3, val4) |
| 354 | static MULTI_INSERT_WITH_COLS_REGEX: Lazy<Regex> = Lazy::new(|| { |
| 355 | Regex::new(r"(?si)INSERT\s+INTO\s+\w+\s*\(([^)]+)\)\s*VALUES\s*(.+)").unwrap() |
| 356 | }); |
| 357 | |
| 358 | if let Some(caps) = MULTI_INSERT_WITH_COLS_REGEX.captures(sql) { |
| 359 | let columns_str = caps.get(1)?.as_str(); |
| 360 | let all_values_str = caps.get(2)?.as_str(); |
| 361 | |
| 362 | let columns: Vec<String> = columns_str |
| 363 | .split(',') |
| 364 | .map(|s| s.trim().to_string()) |
| 365 | .collect(); |
| 366 | |
| 367 | // Parse all value sets |
| 368 | let value_sets = parse_multi_row_values(all_values_str); |
| 369 | if !value_sets.is_empty() { |
| 370 | let mut all_data = Vec::new(); |
| 371 | |
| 372 | for values in value_sets { |
| 373 | if columns.len() != values.len() { |
| 374 | continue; |
| 375 | } |
| 376 | |
| 377 | for (col, val) in columns.iter().zip(values.iter()) { |
| 378 | all_data.push((col.clone(), val.clone())); |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | if !all_data.is_empty() { |
| 383 | return Some(all_data); |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | // Multi-row INSERT without column names: INSERT INTO table VALUES (val1, val2), (val3, val4) |
| 389 | static MULTI_INSERT_NO_COLS_REGEX: Lazy<Regex> = Lazy::new(|| { |
| 390 | Regex::new(r"(?si)INSERT\s+INTO\s+\w+\s+VALUES\s+(.+)").unwrap() |
| 391 | }); |
| 392 | |
| 393 | if let Some(caps) = MULTI_INSERT_NO_COLS_REGEX.captures(sql) { |
| 394 | let all_values_str = caps.get(1)?.as_str(); |
| 395 | |
| 396 | // Get column names from table schema |
| 397 | let mut stmt = conn.prepare(&format!("PRAGMA table_info({table_name})")).ok()?; |
| 398 | let column_info = stmt.query_map([], |row| { |
| 399 | Ok(( |
| 400 | row.get::<_, i32>(0)?, // cid |
| 401 | row.get::<_, String>(1)? // name |
| 402 | )) |
| 403 | }).ok()?; |
| 404 | |
| 405 | let mut columns: Vec<(i32, String)> = Vec::new(); |
| 406 | for col in column_info { |
| 407 | let (cid, name) = col.ok()?; |
no test coverage detected