diff --git a/src/server/csv_import_export.rs b/src/server/csv_import_export.rs new file mode 100644 index 0000000..01d3c61 --- /dev/null +++ b/src/server/csv_import_export.rs @@ -0,0 +1,302 @@ +// src/server/csv_import_export.rs +//! Модуль для импорта/экспорта данных в формате CSV +//! +//! Обеспечивает lock-free операции импорта CSV в базу данных +//! и экспорта коллекций в CSV формат. + +use std::sync::Arc; +use std::fs::File; +use std::io::{BufReader, BufWriter}; +use std::path::Path; +use csv::{Reader, Writer}; +use serde_json::Value; +use dashmap::DashMap; + +use crate::common::Result; +use crate::common::config::CsvConfig; +use crate::server::database::Database; + +/// Менеджер CSV операций +#[derive(Clone)] +pub struct CsvManager { + database: Arc, + config: CsvConfig, + import_progress: Arc>, // Lock-free отслеживание прогресса +} + +impl CsvManager { + /// Создание нового менеджера CSV + pub fn new(database: Arc, config: CsvConfig) -> Self { + // Создаем директории, если они не существуют + let _ = std::fs::create_dir_all(&config.import_dir); + let _ = std::fs::create_dir_all(&config.export_dir); + + Self { + database, + config, + import_progress: Arc::new(DashMap::new()), + } + } + + /// Импорт CSV файла в коллекцию + pub fn import_csv(&self, collection_name: &str, file_path: &str) -> Result { + // Проверяем размер файла + let metadata = std::fs::metadata(file_path) + .map_err(|e| crate::common::FutriixError::IoError(e))?; + + if metadata.len() > self.config.max_file_size { + return Err(crate::common::FutriixError::CsvError( + format!("File size {} exceeds maximum allowed size {}", + metadata.len(), self.config.max_file_size) + )); + } + + println!("Importing CSV file '{}' into collection '{}'", file_path, collection_name); + + let file = File::open(file_path) + .map_err(|e| crate::common::FutriixError::IoError(e))?; + + let mut reader = Reader::from_reader(BufReader::new(file)); + + // Получаем заголовки + let headers: Vec = reader.headers()? + .iter() + .map(|s| s.to_string()) + .collect(); + + let mut record_count = 0; + let mut error_count = 0; + + // Устанавливаем начальный прогресс + self.import_progress.insert(collection_name.to_string(), 0.0); + + for result in reader.records() { + let record = result?; + + // Преобразуем CSV запись в JSON документ + let mut document = serde_json::Map::new(); + + for (i, field) in record.iter().enumerate() { + let header = if i < headers.len() { + &headers[i] + } else { + &format!("field_{}", i) + }; + + // Пытаемся определить тип данных + let value = Self::parse_field_value(field); + document.insert(header.to_string(), value); + } + + // Сохраняем документ в базу данных + let json_value = Value::Object(document); + let json_string = serde_json::to_string(&json_value)?; + + let command = crate::common::protocol::Command::Create { + collection: collection_name.to_string(), + document: json_string.into_bytes(), + }; + + match self.database.execute_command(command) { + Ok(_) => { + record_count += 1; + + if record_count % 100 == 0 { + println!("Imported {} records...", record_count); + } + } + Err(e) => { + error_count += 1; + eprintln!("Failed to import record {}: {}", record_count + error_count, e); + // Продолжаем импорт остальных записей + } + } + } + + // Завершаем импорт + self.import_progress.insert(collection_name.to_string(), 100.0); + + if error_count > 0 { + println!("Import completed with {} successful records and {} errors", + record_count, error_count); + } else { + println!("Successfully imported {} records into collection '{}'", + record_count, collection_name); + } + + Ok(record_count) + } + + /// Парсинг значения поля CSV + fn parse_field_value(field: &str) -> Value { + if field.is_empty() { + return Value::Null; + } + + // Пробуем парсить как число + if let Ok(int_val) = field.parse::() { + return Value::Number(int_val.into()); + } + + if let Ok(float_val) = field.parse::() { + if let Some(num) = serde_json::Number::from_f64(float_val) { + return Value::Number(num); + } + } + + // Пробуем парсить как булево значение + match field.to_lowercase().as_str() { + "true" => return Value::Bool(true), + "false" => return Value::Bool(false), + _ => {} + } + + // Оставляем как строку + Value::String(field.to_string()) + } + + /// Экспорт коллекции в CSV файл + pub fn export_csv(&self, collection_name: &str, file_path: &str) -> Result { + println!("Exporting collection '{}' to CSV file '{}'", collection_name, file_path); + + let file = File::create(file_path) + .map_err(|e| crate::common::FutriixError::IoError(e))?; + + let mut writer = Writer::from_writer(BufWriter::new(file)); + + // Получаем все документы из коллекции + let command = crate::common::protocol::Command::Query { + collection: collection_name.to_string(), + filter: vec![], // Без фильтра + }; + + let response = self.database.execute_command(command)?; + + let documents = match response { + crate::common::protocol::Response::Success(data) => { + serde_json::from_slice::>(&data)? + } + crate::common::protocol::Response::Error(e) => { + return Err(crate::common::FutriixError::DatabaseError(e)); + } + }; + + if documents.is_empty() { + println!("Collection '{}' is empty", collection_name); + return Ok(0); + } + + // Определяем заголовки из всех документов (объединение всех полей) + let mut all_headers = std::collections::HashSet::new(); + for document in &documents { + if let Value::Object(obj) = document { + for key in obj.keys() { + all_headers.insert(key.clone()); + } + } + } + + let headers: Vec = all_headers.into_iter().collect(); + + // Записываем заголовки + writer.write_record(&headers)?; + + let mut record_count = 0; + + // Записываем данные + for document in documents { + if let Value::Object(obj) = document { + let mut record = Vec::new(); + + // Сохраняем порядок полей согласно заголовкам + for header in &headers { + let value = obj.get(header).unwrap_or(&Value::Null); + let value_str = Self::value_to_string(value); + record.push(value_str); + } + + writer.write_record(&record)?; + record_count += 1; + + if record_count % 100 == 0 { + println!("Exported {} records...", record_count); + } + } + } + + writer.flush()?; + + println!("Successfully exported {} records to '{}'", record_count, file_path); + Ok(record_count) + } + + /// Преобразование JSON значения в строку + fn value_to_string(value: &Value) -> String { + match value { + Value::String(s) => s.clone(), + Value::Number(n) => n.to_string(), + Value::Bool(b) => b.to_string(), + Value::Null => "".to_string(), + Value::Array(arr) => { + // Для массивов создаем строку с разделителями + let items: Vec = arr.iter().map(Self::value_to_string).collect(); + format!("[{}]", items.join(",")) + } + Value::Object(_) => { + // Для объектов используем JSON строку + value.to_string() + } + } + } + + /// Получение прогресса импорта + pub fn get_import_progress(&self, collection_name: &str) -> f64 { + self.import_progress.get(collection_name) + .map(|entry| *entry.value()) + .unwrap_or(0.0) + } + + /// Список CSV файлов в директории импорта + pub fn list_csv_files(&self) -> Result> { + let csv_dir = &self.config.import_dir; + let mut csv_files = Vec::new(); + + if let Ok(entries) = std::fs::read_dir(csv_dir) { + for entry in entries.flatten() { + let path = entry.path(); + if path.is_file() { + if let Some(extension) = path.extension() { + if extension == "csv" || extension == "CSV" { + if let Some(file_name) = path.file_name() { + csv_files.push(file_name.to_string_lossy().to_string()); + } + } + } + } + } + } + + Ok(csv_files) + } + + /// Полный путь к файлу импорта + pub fn get_import_file_path(&self, file_name: &str) -> String { + Path::new(&self.config.import_dir) + .join(file_name) + .to_string_lossy() + .to_string() + } + + /// Полный путь к файлу экспорта + pub fn get_export_file_path(&self, file_name: &str) -> String { + Path::new(&self.config.export_dir) + .join(file_name) + .to_string_lossy() + .to_string() + } + + /// Проверка существования файла + pub fn file_exists(&self, file_path: &str) -> bool { + Path::new(file_path).exists() + } +}