|
| 1 | +#![allow(clippy::cargo, clippy::pedantic)] |
| 2 | + |
| 3 | +use fltk::{app, input::IntInput}; |
| 4 | +use serde::{Deserialize, Serialize}; |
| 5 | +use space_query::db::{ConnectionInfo, DatabaseConnection, DatabaseType}; |
| 6 | +use space_query::ui::sql_editor::{QueryProgress, SqlEditorWidget}; |
| 7 | +use std::collections::HashMap; |
| 8 | +use std::env; |
| 9 | +use std::path::Path; |
| 10 | +use std::sync::atomic::{AtomicBool, Ordering}; |
| 11 | +use std::sync::{Arc, Mutex}; |
| 12 | +use std::time::{Duration, Instant}; |
| 13 | + |
| 14 | +#[derive(Debug, Serialize, Deserialize)] |
| 15 | +struct GridSnapshot { |
| 16 | + sql: String, |
| 17 | + columns: Vec<String>, |
| 18 | + rows: Vec<Vec<String>>, |
| 19 | +} |
| 20 | + |
| 21 | +#[derive(Debug, Serialize, Deserialize)] |
| 22 | +struct RunSnapshot { |
| 23 | + failures: Vec<String>, |
| 24 | + grids: Vec<GridSnapshot>, |
| 25 | +} |
| 26 | + |
| 27 | +fn database_type(value: &str) -> Result<DatabaseType, String> { |
| 28 | + match value.to_ascii_lowercase().as_str() { |
| 29 | + "mysql" => Ok(DatabaseType::MySQL), |
| 30 | + "mariadb" => Ok(DatabaseType::MariaDB), |
| 31 | + other => Err(format!("unknown MySQL-family database type `{other}`")), |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +fn connection_info(db_type: DatabaseType) -> ConnectionInfo { |
| 36 | + let host = env::var("SPACE_QUERY_TEST_MYSQL_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()); |
| 37 | + let port = env::var("SPACE_QUERY_TEST_MYSQL_PORT") |
| 38 | + .ok() |
| 39 | + .and_then(|value| value.parse::<u16>().ok()) |
| 40 | + .unwrap_or(3306); |
| 41 | + let database = env::var("SPACE_QUERY_TEST_MYSQL_DATABASE") |
| 42 | + .unwrap_or_else(|_| "query_tool_test".to_string()); |
| 43 | + let username = env::var("SPACE_QUERY_TEST_MYSQL_USER").unwrap_or_else(|_| "root".to_string()); |
| 44 | + let password = |
| 45 | + env::var("SPACE_QUERY_TEST_MYSQL_PASSWORD").unwrap_or_else(|_| "password".to_string()); |
| 46 | + ConnectionInfo::new_with_type( |
| 47 | + "MYSQL_FIXTURE_SNAPSHOT", |
| 48 | + &username, |
| 49 | + &password, |
| 50 | + &host, |
| 51 | + port, |
| 52 | + &database, |
| 53 | + db_type, |
| 54 | + ) |
| 55 | +} |
| 56 | + |
| 57 | +fn progress_inner(event: &QueryProgress) -> &QueryProgress { |
| 58 | + match event { |
| 59 | + QueryProgress::Operation { progress, .. } => progress_inner(progress), |
| 60 | + other => other, |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +fn run_script(db_type: DatabaseType, sql: &str) -> Result<Vec<QueryProgress>, String> { |
| 65 | + let mut connection = DatabaseConnection::new(); |
| 66 | + connection.set_auto_commit(true)?; |
| 67 | + connection.connect(connection_info(db_type))?; |
| 68 | + let shared_connection = Arc::new(Mutex::new(connection)); |
| 69 | + let timeout_input = IntInput::default(); |
| 70 | + let mut widget = SqlEditorWidget::new(Arc::clone(&shared_connection), timeout_input); |
| 71 | + let progress = Arc::new(Mutex::new(Vec::new())); |
| 72 | + let done = Arc::new(AtomicBool::new(false)); |
| 73 | + { |
| 74 | + let progress = Arc::clone(&progress); |
| 75 | + let done = Arc::clone(&done); |
| 76 | + widget.set_progress_callback(move |event| { |
| 77 | + if matches!(progress_inner(&event), QueryProgress::BatchFinished) { |
| 78 | + done.store(true, Ordering::SeqCst); |
| 79 | + } |
| 80 | + progress |
| 81 | + .lock() |
| 82 | + .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 83 | + .push(event); |
| 84 | + }); |
| 85 | + } |
| 86 | + |
| 87 | + widget.execute_script_for_harness(sql); |
| 88 | + let timeout_secs = env::var("MYSQL_FIXTURE_TIMEOUT_SECS") |
| 89 | + .ok() |
| 90 | + .and_then(|value| value.parse::<u64>().ok()) |
| 91 | + .filter(|value| *value > 0) |
| 92 | + .unwrap_or(600); |
| 93 | + let deadline = Instant::now() + Duration::from_secs(timeout_secs); |
| 94 | + while !done.load(Ordering::SeqCst) && Instant::now() < deadline { |
| 95 | + if !app::wait() { |
| 96 | + app::check(); |
| 97 | + std::thread::sleep(Duration::from_millis(10)); |
| 98 | + } |
| 99 | + } |
| 100 | + if !done.load(Ordering::SeqCst) { |
| 101 | + return Err(format!( |
| 102 | + "{db_type:?} script execution timed out after {timeout_secs}s" |
| 103 | + )); |
| 104 | + } |
| 105 | + let drain_deadline = Instant::now() + Duration::from_millis(750); |
| 106 | + while Instant::now() < drain_deadline { |
| 107 | + if !app::wait() { |
| 108 | + app::check(); |
| 109 | + std::thread::sleep(Duration::from_millis(10)); |
| 110 | + } |
| 111 | + } |
| 112 | + let events = progress |
| 113 | + .lock() |
| 114 | + .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 115 | + .clone(); |
| 116 | + Ok(events) |
| 117 | +} |
| 118 | + |
| 119 | +fn failures(progress: &[QueryProgress]) -> Vec<String> { |
| 120 | + progress |
| 121 | + .iter() |
| 122 | + .filter_map(|event| match progress_inner(event) { |
| 123 | + QueryProgress::StatementFinished { index, result, .. } if !result.success => Some( |
| 124 | + format!("#{index}: {} => {}", result.sql.trim(), result.message), |
| 125 | + ), |
| 126 | + QueryProgress::WorkerPanicked { message } => { |
| 127 | + Some(format!("worker panicked: {message}")) |
| 128 | + } |
| 129 | + _ => None, |
| 130 | + }) |
| 131 | + .collect() |
| 132 | +} |
| 133 | + |
| 134 | +fn grids(progress: &[QueryProgress]) -> Vec<GridSnapshot> { |
| 135 | + let mut columns_by_index = HashMap::<usize, Vec<String>>::new(); |
| 136 | + let mut rows_by_index = HashMap::<usize, Vec<Vec<String>>>::new(); |
| 137 | + let mut snapshots = Vec::new(); |
| 138 | + for event in progress { |
| 139 | + match progress_inner(event) { |
| 140 | + QueryProgress::SelectStart { index, columns, .. } => { |
| 141 | + columns_by_index.insert(*index, columns.clone()); |
| 142 | + } |
| 143 | + QueryProgress::Rows { index, rows } => { |
| 144 | + rows_by_index |
| 145 | + .entry(*index) |
| 146 | + .or_default() |
| 147 | + .extend(rows.iter().cloned()); |
| 148 | + } |
| 149 | + QueryProgress::StatementFinished { index, result, .. } |
| 150 | + if result.success && result.is_select => |
| 151 | + { |
| 152 | + let columns = columns_by_index.remove(index).unwrap_or_else(|| { |
| 153 | + result |
| 154 | + .columns |
| 155 | + .iter() |
| 156 | + .map(|column| column.name.clone()) |
| 157 | + .collect() |
| 158 | + }); |
| 159 | + let rows = rows_by_index |
| 160 | + .remove(index) |
| 161 | + .unwrap_or_else(|| result.rows.clone()); |
| 162 | + snapshots.push(GridSnapshot { |
| 163 | + sql: result.sql.trim().to_string(), |
| 164 | + columns, |
| 165 | + rows, |
| 166 | + }); |
| 167 | + } |
| 168 | + _ => {} |
| 169 | + } |
| 170 | + } |
| 171 | + snapshots |
| 172 | +} |
| 173 | + |
| 174 | +fn snapshot(db_type: DatabaseType, path: &Path) -> Result<RunSnapshot, String> { |
| 175 | + let sql = std::fs::read_to_string(path) |
| 176 | + .map_err(|err| format!("failed to read {}: {err}", path.display()))?; |
| 177 | + let progress = run_script(db_type, &sql)?; |
| 178 | + Ok(RunSnapshot { |
| 179 | + failures: failures(&progress), |
| 180 | + grids: grids(&progress), |
| 181 | + }) |
| 182 | +} |
| 183 | + |
| 184 | +fn main() { |
| 185 | + let _app = app::App::default(); |
| 186 | + let args = env::args().skip(1).collect::<Vec<_>>(); |
| 187 | + if args.len() != 2 && args.len() != 3 { |
| 188 | + eprintln!("usage: mysql_fixture_snapshot <mysql|mariadb> <path> [out-json]"); |
| 189 | + std::process::exit(2); |
| 190 | + } |
| 191 | + let db_type = match database_type(&args[0]) { |
| 192 | + Ok(db_type) => db_type, |
| 193 | + Err(err) => { |
| 194 | + eprintln!("{err}"); |
| 195 | + std::process::exit(2); |
| 196 | + } |
| 197 | + }; |
| 198 | + match snapshot(db_type, Path::new(&args[1])) { |
| 199 | + Ok(snapshot) => { |
| 200 | + let json = match serde_json::to_string(&snapshot) { |
| 201 | + Ok(json) => json, |
| 202 | + Err(err) => { |
| 203 | + eprintln!("failed to serialize snapshot: {err}"); |
| 204 | + std::process::exit(1); |
| 205 | + } |
| 206 | + }; |
| 207 | + if let Some(path) = args.get(2) { |
| 208 | + if let Err(err) = std::fs::write(path, json) { |
| 209 | + eprintln!("failed to write snapshot {path}: {err}"); |
| 210 | + std::process::exit(1); |
| 211 | + } |
| 212 | + } else { |
| 213 | + println!("{json}"); |
| 214 | + } |
| 215 | + } |
| 216 | + Err(err) => { |
| 217 | + eprintln!("{err}"); |
| 218 | + std::process::exit(1); |
| 219 | + } |
| 220 | + } |
| 221 | +} |
0 commit comments