fmql 0.3.0

A fast and feature-rich file manager written in Rust
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
//! Executor for SQL-like file management commands.
//!
//! This module provides functionality to execute parsed SQL-like commands
//! on the file system, such as querying files or updating file attributes.

use chrono::{DateTime, Utc};
use regex::Regex;
use serde::Serialize;
use std::fs::{self, Permissions};
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use thiserror::Error;
use walkdir::WalkDir;

use crate::sql::ast::{ComparisonOperator, FileAttribute, FileCondition, FileQuery, FileValue};

/// Errors that can occur during query execution.
#[derive(Error, Debug)]
pub enum ExecutorError {
    /// Error from std::io operations.
    #[error("I/O error: {0}")]
    IoError(#[from] std::io::Error),

    /// Error when a file attribute is not supported.
    #[error("Unsupported file attribute: {0}")]
    UnsupportedAttribute(String),

    /// Error when an operation is not supported.
    #[error("Unsupported operation: {0}")]
    UnsupportedOperation(String),

    /// Error when a regular expression is invalid.
    #[error("Invalid regular expression: {0}")]
    InvalidRegex(#[from] regex::Error),

    /// Error when a value is of the wrong type.
    #[error("Type error: {0}")]
    TypeError(String),
}

/// Result type for executor operations.
pub type Result<T> = std::result::Result<T, ExecutorError>;

/// Represents a file that matches a query.
#[derive(Debug, Clone, Serialize)]
pub struct FileResult {
    /// The file path.
    pub path: PathBuf,
    /// The file name.
    pub name: String,
    /// The file size in bytes.
    pub size: u64,
    /// Whether the file is a directory.
    pub is_directory: bool,
    /// The file extension, if any.
    pub extension: Option<String>,
    /// The file permissions.
    pub permissions: u32,
    /// The file modification time.
    #[serde(with = "chrono::serde::ts_seconds")]
    pub modified: DateTime<Utc>,
    /// The file owner, if available.
    pub owner: Option<String>,
}

/// Executes a parsed FileQuery.
///
/// # Arguments
///
/// * `query` - The parsed FileQuery to execute.
///
/// # Returns
///
/// A Result containing a vector of FileResult instances or an ExecutorError.
///
/// # Examples
///
/// Example of using execute_query to process a parsed query:
///
/// ```no_run
/// use fmql::sql::{parse_sql, execute_query};
///
/// // Parse a query
/// let query = parse_sql("SELECT * FROM /var/log WHERE name LIKE '%.log'").unwrap();
///
/// // Execute the query to get matching files
/// let results = execute_query(&query).unwrap();
///
/// // Process the results
/// for file in results {
///     println!("{}: {} bytes", file.name, file.size);
/// }
/// ```
pub fn execute_query(query: &FileQuery) -> Result<Vec<FileResult>> {
    match query {
        FileQuery::Select {
            path,
            recursive,
            attributes,
            condition,
        } => execute_select(path, *recursive, attributes, condition.as_ref()),
        FileQuery::Update {
            path,
            updates,
            condition,
        } => execute_update(path, updates, condition.as_ref()),
    }
}

/// Executes a SELECT query.
fn execute_select(
    path: &Path,
    recursive: bool,
    _attributes: &[FileAttribute],
    condition: Option<&FileCondition>,
) -> Result<Vec<FileResult>> {
    let files = list_files(path, recursive)?;
    let filtered_files = if let Some(cond) = condition {
        files
            .into_iter()
            .filter(|file| evaluate_condition(file, cond).unwrap_or(false))
            .collect()
    } else {
        files
    };

    Ok(filtered_files)
}

/// Executes an UPDATE query.
fn execute_update(
    path: &Path,
    updates: &[crate::sql::ast::FileAttributeUpdate],
    condition: Option<&FileCondition>,
) -> Result<Vec<FileResult>> {
    let files = list_files(path, true)?;
    let filtered_files = if let Some(cond) = condition {
        files
            .into_iter()
            .filter(|file| evaluate_condition(file, cond).unwrap_or(false))
            .collect()
    } else {
        files
    };

    let mut updated_files = Vec::new();

    for file in filtered_files {
        let mut file_updated = false;

        for update in updates {
            match update.attribute {
                FileAttribute::Permissions => {
                    let perms = u32::from_str_radix(&update.value, 8).map_err(|_| {
                        ExecutorError::TypeError(format!(
                            "Invalid permissions value: {}",
                            update.value
                        ))
                    })?;

                    fs::set_permissions(&file.path, Permissions::from_mode(perms))?;
                    file_updated = true;
                }
                FileAttribute::Owner => {
                    // Note: Changing ownership requires platform-specific code and often root privileges
                    // This is a simplified example
                    return Err(ExecutorError::UnsupportedOperation(
                        "Changing file ownership is not implemented".to_string(),
                    ));
                }
                _ => {
                    return Err(ExecutorError::UnsupportedAttribute(format!(
                        "Cannot update attribute: {:?}",
                        update.attribute
                    )));
                }
            }
        }

        if file_updated {
            // Re-read the file info to get updated attributes
            let updated_file = create_file_result(&file.path)?;
            updated_files.push(updated_file);
        }
    }

    Ok(updated_files)
}

/// Lists files in a directory, optionally recursively.
fn list_files(dir_path: &Path, recursive: bool) -> Result<Vec<FileResult>> {
    let mut results = Vec::new();

    let walker = if recursive {
        WalkDir::new(dir_path).follow_links(false).into_iter()
    } else {
        WalkDir::new(dir_path)
            .max_depth(1)
            .follow_links(false)
            .into_iter()
    };

    for entry in walker {
        let entry = entry.map_err(|e| {
            ExecutorError::IoError(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to read directory entry: {}", e),
            ))
        })?;

        let file_result = create_file_result(entry.path())?;
        results.push(file_result);
    }

    Ok(results)
}

/// Creates a FileResult from a path.
fn create_file_result(path: &Path) -> Result<FileResult> {
    let metadata = fs::metadata(path)?;

    let name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("")
        .to_string();

    let extension = path
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.to_string());

    let modified = metadata
        .modified()
        .map(DateTime::<Utc>::from)
        .unwrap_or_else(|_| Utc::now());

    let permissions = metadata.permissions().mode();

    // Getting the owner requires platform-specific code
    // This is a simplified version
    let owner = None;

    Ok(FileResult {
        path: path.to_path_buf(),
        name,
        size: metadata.len(),
        is_directory: metadata.is_dir(),
        extension,
        permissions,
        modified,
        owner,
    })
}

/// Evaluates a condition against a file.
fn evaluate_condition(file: &FileResult, condition: &FileCondition) -> Result<bool> {
    match condition {
        FileCondition::Compare {
            attribute,
            operator,
            value,
        } => {
            let file_value = get_attribute_value(file, attribute)?;
            compare_values(&file_value, operator, value)
        }
        FileCondition::And(left, right) => {
            let left_result = evaluate_condition(file, left)?;
            if !left_result {
                return Ok(false);
            }
            evaluate_condition(file, right)
        }
        FileCondition::Or(left, right) => {
            let left_result = evaluate_condition(file, left)?;
            if left_result {
                return Ok(true);
            }
            evaluate_condition(file, right)
        }
        FileCondition::Not(inner) => {
            let inner_result = evaluate_condition(file, inner)?;
            Ok(!inner_result)
        }
        FileCondition::Like {
            attribute,
            pattern,
            case_sensitive,
        } => {
            let file_value = get_attribute_value(file, attribute)?;

            match file_value {
                FileValue::String(s) => {
                    let file_str = if *case_sensitive { s } else { s.to_lowercase() };
                    let pattern_str = if *case_sensitive {
                        pattern.clone()
                    } else {
                        pattern.to_lowercase()
                    };

                    // Convert SQL LIKE pattern to regex
                    let regex_pattern = pattern_str.replace('%', ".*").replace('_', ".");

                    let regex = Regex::new(&format!("^{}$", regex_pattern))?;
                    Ok(regex.is_match(&file_str))
                }
                _ => Err(ExecutorError::TypeError(format!(
                    "LIKE can only be used with string attributes, got {:?}",
                    file_value
                ))),
            }
        }
        FileCondition::Between {
            attribute,
            lower,
            upper,
        } => {
            let file_value = get_attribute_value(file, attribute)?;

            let greater_than_lower = compare_values(&file_value, &ComparisonOperator::GtEq, lower)?;
            let less_than_upper = compare_values(&file_value, &ComparisonOperator::LtEq, upper)?;

            Ok(greater_than_lower && less_than_upper)
        }
        FileCondition::Regexp { attribute, pattern } => {
            let file_value = get_attribute_value(file, attribute)?;

            match file_value {
                FileValue::String(s) => {
                    let regex = Regex::new(pattern)?;
                    Ok(regex.is_match(&s))
                }
                _ => Err(ExecutorError::TypeError(format!(
                    "REGEXP can only be used with string attributes, got {:?}",
                    file_value
                ))),
            }
        }
    }
}

/// Gets the value of a file attribute.
fn get_attribute_value(file: &FileResult, attribute: &FileAttribute) -> Result<FileValue> {
    match attribute {
        FileAttribute::Name => Ok(FileValue::String(file.name.clone())),
        FileAttribute::Path => Ok(FileValue::String(file.path.to_string_lossy().to_string())),
        FileAttribute::Size => Ok(FileValue::Number(file.size as f64)),
        FileAttribute::Extension => Ok(FileValue::String(
            file.extension.clone().unwrap_or_default(),
        )),
        FileAttribute::Modified => Ok(FileValue::DateTime(file.modified)),
        FileAttribute::Permissions => Ok(FileValue::Number(file.permissions as f64)),
        FileAttribute::IsDirectory => Ok(FileValue::Boolean(file.is_directory)),
        FileAttribute::Owner => {
            if let Some(owner) = &file.owner {
                Ok(FileValue::String(owner.clone()))
            } else {
                Ok(FileValue::Null)
            }
        }
        FileAttribute::IsExecutable => {
            // Check if file has executable bit set for user
            let is_executable = file.permissions & 0o100 != 0;
            Ok(FileValue::Boolean(is_executable))
        }
        _ => Err(ExecutorError::UnsupportedAttribute(format!(
            "Attribute not supported in conditions: {:?}",
            attribute
        ))),
    }
}

/// Compares two values.
fn compare_values(
    left: &FileValue,
    operator: &ComparisonOperator,
    right: &FileValue,
) -> Result<bool> {
    match (left, right) {
        (FileValue::String(l), FileValue::String(r)) => match operator {
            ComparisonOperator::Eq => Ok(l == r),
            ComparisonOperator::NotEq => Ok(l != r),
            ComparisonOperator::Lt => Ok(l < r),
            ComparisonOperator::LtEq => Ok(l <= r),
            ComparisonOperator::Gt => Ok(l > r),
            ComparisonOperator::GtEq => Ok(l >= r),
        },
        (FileValue::Number(l), FileValue::Number(r)) => match operator {
            ComparisonOperator::Eq => Ok(l == r),
            ComparisonOperator::NotEq => Ok(l != r),
            ComparisonOperator::Lt => Ok(l < r),
            ComparisonOperator::LtEq => Ok(l <= r),
            ComparisonOperator::Gt => Ok(l > r),
            ComparisonOperator::GtEq => Ok(l >= r),
        },
        (FileValue::DateTime(l), FileValue::DateTime(r)) => match operator {
            ComparisonOperator::Eq => Ok(l == r),
            ComparisonOperator::NotEq => Ok(l != r),
            ComparisonOperator::Lt => Ok(l < r),
            ComparisonOperator::LtEq => Ok(l <= r),
            ComparisonOperator::Gt => Ok(l > r),
            ComparisonOperator::GtEq => Ok(l >= r),
        },
        (FileValue::Boolean(l), FileValue::Boolean(r)) => match operator {
            ComparisonOperator::Eq => Ok(l == r),
            ComparisonOperator::NotEq => Ok(l != r),
            _ => Err(ExecutorError::UnsupportedOperation(format!(
                "Operator {:?} not supported for boolean values",
                operator
            ))),
        },
        (FileValue::Null, FileValue::Null) => match operator {
            ComparisonOperator::Eq => Ok(true),
            ComparisonOperator::NotEq => Ok(false),
            _ => Err(ExecutorError::UnsupportedOperation(
                "Null values only support equality comparisons".to_string(),
            )),
        },
        (_, FileValue::Null) | (FileValue::Null, _) => match operator {
            ComparisonOperator::Eq => Ok(false),
            ComparisonOperator::NotEq => Ok(true),
            _ => Err(ExecutorError::UnsupportedOperation(
                "Null values only support equality comparisons".to_string(),
            )),
        },
        _ => Err(ExecutorError::TypeError(format!(
            "Cannot compare values of different types: {:?} and {:?}",
            left, right
        ))),
    }
}

// Include the tests module
#[cfg(test)]
#[path = "executor_tests.rs"]
mod tests;