// src/tables_data/handlers/put_table_data.rs use tonic::Status; use sqlx::{PgPool, Arguments, Postgres}; use sqlx::postgres::PgArguments; use chrono::{DateTime, Utc}; use common::proto::multieko2::tables_data::{PutTableDataRequest, PutTableDataResponse}; use std::collections::HashMap; use crate::shared::schema_qualifier::qualify_table_name_for_data; // Import schema qualifier pub async fn put_table_data( db_pool: &PgPool, request: PutTableDataRequest, ) -> Result { let profile_name = request.profile_name; let table_name = request.table_name; let record_id = request.id; // Preprocess and validate data let mut processed_data = HashMap::new(); let mut null_fields = Vec::new(); // CORRECTED: Generic handling for all fields. // Any field with an empty string will be added to the null_fields list. // The special, hardcoded logic for "firma" has been removed. for (key, value) in request.data { let trimmed = value.trim().to_string(); if trimmed.is_empty() { null_fields.push(key); } else { processed_data.insert(key, trimmed); } } // Lookup profile let profile = sqlx::query!( "SELECT id FROM profiles WHERE name = $1", profile_name ) .fetch_optional(db_pool) .await .map_err(|e| Status::internal(format!("Profile lookup error: {}", e)))?; let profile_id = profile.ok_or_else(|| Status::not_found("Profile not found"))?.id; // Lookup table_definition let table_def = sqlx::query!( r#"SELECT id, columns FROM table_definitions WHERE profile_id = $1 AND table_name = $2"#, profile_id, table_name ) .fetch_optional(db_pool) .await .map_err(|e| Status::internal(format!("Table lookup error: {}", e)))?; let table_def = table_def.ok_or_else(|| Status::not_found("Table not found"))?; // Parse columns from JSON let columns_json: Vec = serde_json::from_value(table_def.columns.clone()) .map_err(|e| Status::internal(format!("Column parsing error: {}", e)))?; let mut columns = Vec::new(); for col_def in columns_json { let parts: Vec<&str> = col_def.splitn(2, ' ').collect(); if parts.len() != 2 { return Err(Status::internal("Invalid column format")); } let name = parts[0].trim_matches('"').to_string(); let sql_type = parts[1].to_string(); columns.push((name, sql_type)); } // CORRECTED: "firma" is not a system column. // It should be treated as a user-defined column. let system_columns = ["deleted"]; let user_columns: Vec<&String> = columns.iter().map(|(name, _)| name).collect(); // Validate input columns for key in processed_data.keys() { if !system_columns.contains(&key.as_str()) && !user_columns.contains(&key) { return Err(Status::invalid_argument(format!("Invalid column: {}", key))); } } // Prepare SQL parameters let mut params = PgArguments::default(); let mut set_clauses = Vec::new(); let mut param_idx = 1; // Add data parameters for non-empty fields for (col, value) in &processed_data { // CORRECTED: The logic for "firma" is removed from this match. // It will now fall through to the `else` block and have its type // correctly looked up from the `columns` vector. let sql_type = if system_columns.contains(&col.as_str()) { match col.as_str() { "deleted" => "BOOLEAN", _ => return Err(Status::invalid_argument("Invalid system column")), } } else { columns.iter() .find(|(name, _)| name == col) .map(|(_, sql_type)| sql_type.as_str()) .ok_or_else(|| Status::invalid_argument(format!("Column not found: {}", col)))? }; match sql_type { "TEXT" | "VARCHAR(15)" | "VARCHAR(255)" => { if let Some(max_len) = sql_type.strip_prefix("VARCHAR(") .and_then(|s| s.strip_suffix(')')) .and_then(|s| s.parse::().ok()) { if value.len() > max_len { return Err(Status::internal(format!("Value too long for {}", col))); } } params.add(value) .map_err(|e| Status::internal(format!("Failed to add text parameter for {}: {}", col, e)))?; }, "BOOLEAN" => { let val = value.parse::() .map_err(|_| Status::invalid_argument(format!("Invalid boolean for {}", col)))?; params.add(val) .map_err(|e| Status::internal(format!("Failed to add boolean parameter for {}: {}", col, e)))?; }, "TIMESTAMPTZ" => { let dt = DateTime::parse_from_rfc3339(value) .map_err(|_| Status::invalid_argument(format!("Invalid timestamp for {}", col)))?; params.add(dt.with_timezone(&Utc)) .map_err(|e| Status::internal(format!("Failed to add timestamp parameter for {}: {}", col, e)))?; }, // ADDED: BIGINT handling for completeness, if needed for other columns. "BIGINT" => { let val = value.parse::() .map_err(|_| Status::invalid_argument(format!("Invalid integer for {}", col)))?; params.add(val) .map_err(|e| Status::internal(format!("Failed to add integer parameter for {}: {}", col, e)))?; }, _ => return Err(Status::invalid_argument(format!("Unsupported type {}", sql_type))), } set_clauses.push(format!("\"{}\" = ${}", col, param_idx)); param_idx += 1; } // Add NULL clauses for empty fields for field in null_fields { // Make sure the field is valid if !system_columns.contains(&field.as_str()) && !user_columns.contains(&&field) { return Err(Status::invalid_argument(format!("Invalid column to set NULL: {}", field))); } set_clauses.push(format!("\"{}\" = NULL", field)); } // Ensure we have at least one field to update if set_clauses.is_empty() { return Err(Status::invalid_argument("No valid fields to update")); } // Add ID parameter at the end params.add(record_id) .map_err(|e| Status::internal(format!("Failed to add record_id parameter: {}", e)))?; // Qualify table name with schema let qualified_table = qualify_table_name_for_data(&table_name)?; let set_clause = set_clauses.join(", "); let sql = format!( "UPDATE {} SET {} WHERE id = ${} AND deleted = FALSE RETURNING id", qualified_table, set_clause, param_idx ); let result = sqlx::query_scalar_with::(&sql, params) .fetch_optional(db_pool) .await; match result { Ok(Some(updated_id)) => Ok(PutTableDataResponse { success: true, message: "Data updated successfully".into(), updated_id, }), Ok(None) => Err(Status::not_found("Record not found or already deleted")), Err(e) => { // Handle "relation does not exist" error specifically if let Some(db_err) = e.as_database_error() { if db_err.code() == Some(std::borrow::Cow::Borrowed("42P01")) { return Err(Status::internal(format!( "Table '{}' is defined but does not physically exist in the database as {}", table_name, qualified_table ))); } } Err(Status::internal(format!("Update failed: {}", e))) } } }