yamlbase 0.7.2

A lightweight SQL server that serves YAML-defined tables over standard SQL protocols
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;
use tokio::sync::RwLock;
use tracing::{debug, error, info};

/// Query log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryLogEntry {
    pub timestamp: DateTime<Local>,
    pub query: String,
    pub execution_time_ms: f64,
    pub rows_returned: usize,
    pub success: bool,
    pub error: Option<String>,
    pub client_addr: String,
    pub protocol: String,
}

/// Query logging configuration
#[derive(Debug, Clone, Deserialize)]
pub struct QueryLogConfig {
    /// Enable query logging
    pub enabled: bool,

    /// Log file path (if specified, writes to file)
    pub file_path: Option<PathBuf>,

    /// Maximum number of queries to keep in memory
    pub max_memory_entries: usize,

    /// Log slow queries (threshold in milliseconds)
    pub slow_query_threshold_ms: Option<f64>,

    /// Include query results in log
    pub include_results: bool,

    /// Log only failed queries
    pub only_errors: bool,
}

impl Default for QueryLogConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            file_path: None,
            max_memory_entries: 1000,
            slow_query_threshold_ms: Some(100.0),
            include_results: false,
            only_errors: false,
        }
    }
}

/// Query logger for tracking and analyzing SQL queries
pub struct QueryLogger {
    config: QueryLogConfig,
    entries: Arc<RwLock<VecDeque<QueryLogEntry>>>,
    stats: Arc<RwLock<QueryStats>>,
}

/// Aggregated query statistics
#[derive(Debug, Clone, Default, Serialize)]
pub struct QueryStats {
    pub total_queries: u64,
    pub successful_queries: u64,
    pub failed_queries: u64,
    pub total_execution_time_ms: f64,
    pub avg_execution_time_ms: f64,
    pub max_execution_time_ms: f64,
    pub min_execution_time_ms: f64,
    pub slow_queries: u64,
    pub total_rows_returned: u64,
}

impl QueryLogger {
    /// Create a new query logger
    pub fn new(config: QueryLogConfig) -> Self {
        Self {
            config,
            entries: Arc::new(RwLock::new(VecDeque::new())),
            stats: Arc::new(RwLock::new(QueryStats::default())),
        }
    }

    /// Log a query execution
    #[allow(clippy::too_many_arguments)]
    pub async fn log_query(
        &self,
        query: &str,
        execution_time: Duration,
        rows_returned: usize,
        success: bool,
        error: Option<String>,
        client_addr: String,
        protocol: &str,
    ) {
        if !self.config.enabled {
            return;
        }

        let execution_time_ms = execution_time.as_secs_f64() * 1000.0;

        // Check if we should log this query
        if self.config.only_errors && success {
            return;
        }

        // Check slow query threshold
        let is_slow = self
            .config
            .slow_query_threshold_ms
            .map(|threshold| execution_time_ms >= threshold)
            .unwrap_or(false);

        let entry = QueryLogEntry {
            timestamp: Local::now(),
            query: query.to_string(),
            execution_time_ms,
            rows_returned,
            success,
            error: error.clone(),
            client_addr,
            protocol: protocol.to_string(),
        };

        // Update statistics
        {
            let mut stats = self.stats.write().await;
            stats.total_queries += 1;
            if success {
                stats.successful_queries += 1;
            } else {
                stats.failed_queries += 1;
            }
            stats.total_execution_time_ms += execution_time_ms;
            stats.avg_execution_time_ms =
                stats.total_execution_time_ms / stats.total_queries as f64;

            if execution_time_ms > stats.max_execution_time_ms {
                stats.max_execution_time_ms = execution_time_ms;
            }
            if stats.min_execution_time_ms == 0.0 || execution_time_ms < stats.min_execution_time_ms
            {
                stats.min_execution_time_ms = execution_time_ms;
            }

            if is_slow {
                stats.slow_queries += 1;
            }

            stats.total_rows_returned += rows_returned as u64;
        }

        // Add to memory buffer
        {
            let mut entries = self.entries.write().await;
            entries.push_back(entry.clone());

            // Trim old entries if needed
            while entries.len() > self.config.max_memory_entries {
                entries.pop_front();
            }
        }

        // Write to file if configured
        if let Some(ref file_path) = self.config.file_path {
            if let Err(e) = self.write_to_file(&entry, file_path).await {
                error!("Failed to write query log to file: {}", e);
            }
        }

        // Log to tracing
        if is_slow {
            info!(
                "🐌 Slow query detected: {} ms - {}",
                execution_time_ms,
                truncate_query(query, 100)
            );
        } else if !success {
            info!(
                "❌ Query failed: {} - {}",
                truncate_query(query, 100),
                error.unwrap_or_default()
            );
        } else {
            debug!(
                "✅ Query executed: {} ms - {}",
                execution_time_ms,
                truncate_query(query, 100)
            );
        }
    }

    /// Write log entry to file
    async fn write_to_file(&self, entry: &QueryLogEntry, file_path: &PathBuf) -> crate::Result<()> {
        let mut file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(file_path)
            .await?;

        let log_line = if self.config.include_results {
            serde_json::to_string(entry).map_err(|e| {
                crate::YamlBaseError::Io(std::io::Error::other(format!(
                    "Failed to serialize log entry: {}",
                    e
                )))
            })?
        } else {
            // Simplified log format
            format!(
                "[{}] {} | {:.2}ms | {} rows | {} | {}\n",
                entry.timestamp.format("%Y-%m-%d %H:%M:%S"),
                if entry.success { "OK" } else { "FAIL" },
                entry.execution_time_ms,
                entry.rows_returned,
                entry.client_addr,
                truncate_query(&entry.query, 200)
            )
        };

        file.write_all(log_line.as_bytes()).await?;
        file.write_all(b"\n").await?;

        Ok(())
    }

    /// Get recent queries
    pub async fn get_recent_queries(&self, limit: usize) -> Vec<QueryLogEntry> {
        let entries = self.entries.read().await;
        entries.iter().rev().take(limit).cloned().collect()
    }

    /// Get slow queries
    pub async fn get_slow_queries(&self, limit: usize) -> Vec<QueryLogEntry> {
        let threshold = self.config.slow_query_threshold_ms.unwrap_or(100.0);
        let entries = self.entries.read().await;

        let mut slow_queries: Vec<_> = entries
            .iter()
            .filter(|e| e.execution_time_ms >= threshold)
            .cloned()
            .collect();

        slow_queries.sort_by(|a, b| {
            b.execution_time_ms
                .partial_cmp(&a.execution_time_ms)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        slow_queries.into_iter().take(limit).collect()
    }

    /// Get failed queries
    pub async fn get_failed_queries(&self, limit: usize) -> Vec<QueryLogEntry> {
        let entries = self.entries.read().await;
        entries
            .iter()
            .filter(|e| !e.success)
            .rev()
            .take(limit)
            .cloned()
            .collect()
    }

    /// Get query statistics
    pub async fn get_stats(&self) -> QueryStats {
        self.stats.read().await.clone()
    }

    /// Clear query log
    pub async fn clear(&self) {
        self.entries.write().await.clear();
        *self.stats.write().await = QueryStats::default();
        info!("Query log cleared");
    }

    /// Export queries to JSON
    pub async fn export_to_json(&self, path: &PathBuf) -> crate::Result<()> {
        let entries = self.entries.read().await;
        let json = serde_json::to_string_pretty(&*entries).map_err(|e| {
            crate::YamlBaseError::Io(std::io::Error::other(format!(
                "Failed to serialize queries: {}",
                e
            )))
        })?;

        tokio::fs::write(path, json).await?;
        info!("Exported {} queries to {}", entries.len(), path.display());

        Ok(())
    }

    /// Generate performance report
    pub async fn generate_report(&self) -> String {
        let stats = self.stats.read().await;
        let entries = self.entries.read().await;

        let mut report = String::new();
        report.push_str("=== Query Performance Report ===\n\n");

        report.push_str("📊 Overall Statistics:\n");
        report.push_str(&format!("  Total Queries: {}\n", stats.total_queries));
        report.push_str(&format!(
            "  Successful: {} ({:.1}%)\n",
            stats.successful_queries,
            (stats.successful_queries as f64 / stats.total_queries as f64) * 100.0
        ));
        report.push_str(&format!(
            "  Failed: {} ({:.1}%)\n",
            stats.failed_queries,
            (stats.failed_queries as f64 / stats.total_queries as f64) * 100.0
        ));
        report.push('\n');

        report.push_str("⏱️  Performance Metrics:\n");
        report.push_str(&format!(
            "  Average Time: {:.2} ms\n",
            stats.avg_execution_time_ms
        ));
        report.push_str(&format!(
            "  Min Time: {:.2} ms\n",
            stats.min_execution_time_ms
        ));
        report.push_str(&format!(
            "  Max Time: {:.2} ms\n",
            stats.max_execution_time_ms
        ));
        report.push_str(&format!(
            "  Slow Queries: {} ({:.1}%)\n",
            stats.slow_queries,
            (stats.slow_queries as f64 / stats.total_queries as f64) * 100.0
        ));
        report.push('\n');

        report.push_str("📈 Throughput:\n");
        report.push_str(&format!("  Total Rows: {}\n", stats.total_rows_returned));
        report.push_str(&format!(
            "  Avg Rows/Query: {:.1}\n",
            stats.total_rows_returned as f64 / stats.total_queries as f64
        ));

        // Top slow queries
        if stats.slow_queries > 0 {
            report.push_str("\n🐌 Top 5 Slowest Queries:\n");
            let mut slow_queries: Vec<_> = entries
                .iter()
                .filter(|e| {
                    e.execution_time_ms >= self.config.slow_query_threshold_ms.unwrap_or(100.0)
                })
                .collect();
            slow_queries.sort_by(|a, b| {
                b.execution_time_ms
                    .partial_cmp(&a.execution_time_ms)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });

            for (i, entry) in slow_queries.iter().take(5).enumerate() {
                report.push_str(&format!(
                    "  {}. {:.2} ms - {}\n",
                    i + 1,
                    entry.execution_time_ms,
                    truncate_query(&entry.query, 60)
                ));
            }
        }

        // Most frequent queries
        let mut query_counts = std::collections::HashMap::new();
        for entry in entries.iter() {
            *query_counts
                .entry(normalize_query(&entry.query))
                .or_insert(0) += 1;
        }

        if !query_counts.is_empty() {
            let mut freq_queries: Vec<_> = query_counts.iter().collect();
            freq_queries.sort_by(|a, b| b.1.cmp(a.1));

            report.push_str("\n🔥 Top 5 Most Frequent Queries:\n");
            for (i, (query, count)) in freq_queries.iter().take(5).enumerate() {
                report.push_str(&format!(
                    "  {}. {} times - {}\n",
                    i + 1,
                    count,
                    truncate_query(query, 60)
                ));
            }
        }

        report
    }
}

/// Truncate query for display
fn truncate_query(query: &str, max_len: usize) -> String {
    let normalized = query.replace(['\n', '\t'], " ");
    if normalized.len() <= max_len {
        normalized
    } else {
        // Reserve 3 characters for "..."
        let truncate_at = max_len.saturating_sub(3);
        format!("{}...", &normalized[..truncate_at])
    }
}

/// Normalize query for comparison (remove whitespace, lowercase)
fn normalize_query(query: &str) -> String {
    query
        .to_lowercase()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_query_logging() {
        let config = QueryLogConfig {
            enabled: true,
            ..Default::default()
        };

        let logger = QueryLogger::new(config);

        // Log some queries
        logger
            .log_query(
                "SELECT * FROM users",
                Duration::from_millis(10),
                5,
                true,
                None,
                "127.0.0.1:12345".to_string(),
                "postgresql",
            )
            .await;

        logger
            .log_query(
                "SELECT * FROM products WHERE price > 100",
                Duration::from_millis(150),
                20,
                true,
                None,
                "127.0.0.1:12346".to_string(),
                "postgresql",
            )
            .await;

        logger
            .log_query(
                "SELECT * FROM invalid_table",
                Duration::from_millis(5),
                0,
                false,
                Some("Table not found".to_string()),
                "127.0.0.1:12347".to_string(),
                "postgresql",
            )
            .await;

        // Check stats
        let stats = logger.get_stats().await;
        assert_eq!(stats.total_queries, 3);
        assert_eq!(stats.successful_queries, 2);
        assert_eq!(stats.failed_queries, 1);
        assert_eq!(stats.slow_queries, 1);

        // Check recent queries
        let recent = logger.get_recent_queries(10).await;
        assert_eq!(recent.len(), 3);

        // Check slow queries
        let slow = logger.get_slow_queries(10).await;
        assert_eq!(slow.len(), 1);
        assert!(slow[0].query.contains("products"));

        // Check failed queries
        let failed = logger.get_failed_queries(10).await;
        assert_eq!(failed.len(), 1);
        assert!(failed[0].query.contains("invalid_table"));
    }

    #[test]
    fn test_query_truncation() {
        let query = "SELECT very_long_column_name_1, very_long_column_name_2, very_long_column_name_3 FROM table";
        let truncated = truncate_query(query, 30);
        // Should truncate at 27 characters + "..."
        assert_eq!(truncated, "SELECT very_long_column_nam...");
    }

    #[test]
    fn test_query_normalization() {
        let query1 = "SELECT  *\n  FROM\t users  WHERE   id = 1";
        let query2 = "select * from users where id = 1";

        assert_eq!(normalize_query(query1), normalize_query(query2));
    }
}