145 lines
5.3 KiB
Rust
145 lines
5.3 KiB
Rust
// 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};
|
|
|
|
pub async fn put_table_data(
|
|
db_pool: &PgPool,
|
|
request: PutTableDataRequest,
|
|
) -> Result<PutTableDataResponse, Status> {
|
|
let profile_name = request.profile_name;
|
|
let table_name = request.table_name;
|
|
let record_id = request.id;
|
|
let data = request.data;
|
|
|
|
// Lookup profile (same as POST)
|
|
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 (same as POST)
|
|
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 (same as POST)
|
|
let columns_json: Vec<String> = 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));
|
|
}
|
|
|
|
// Validate system columns
|
|
let system_columns = ["firma", "deleted"];
|
|
let user_columns: Vec<&String> = columns.iter().map(|(name, _)| name).collect();
|
|
|
|
// Validate input columns
|
|
for key in 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 (col, value) in &data {
|
|
let sql_type = if system_columns.contains(&col.as_str()) {
|
|
match col.as_str() {
|
|
"firma" => "TEXT",
|
|
"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::<usize>().ok())
|
|
{
|
|
if value.len() > max_len {
|
|
return Err(Status::invalid_argument(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::<bool>()
|
|
.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)))?;
|
|
},
|
|
_ => return Err(Status::invalid_argument(format!("Unsupported type {}", sql_type))),
|
|
}
|
|
|
|
set_clauses.push(format!("\"{}\" = ${}", col, param_idx));
|
|
param_idx += 1;
|
|
}
|
|
|
|
// Add ID parameter at the end
|
|
params.add(record_id)
|
|
.map_err(|e| Status::internal(format!("Failed to add record_id parameter: {}", e)))?;
|
|
|
|
let set_clause = set_clauses.join(", ");
|
|
let sql = format!(
|
|
"UPDATE \"{}\" SET {} WHERE id = ${} AND deleted = FALSE RETURNING id",
|
|
table_name,
|
|
set_clause,
|
|
param_idx
|
|
);
|
|
|
|
let result = sqlx::query_scalar_with::<Postgres, i64, _>(&sql, params)
|
|
.fetch_optional(db_pool)
|
|
.await
|
|
.map_err(|e| Status::internal(format!("Update failed: {}", e)))?;
|
|
|
|
match result {
|
|
Some(updated_id) => Ok(PutTableDataResponse {
|
|
success: true,
|
|
message: "Data updated successfully".into(),
|
|
updated_id,
|
|
}),
|
|
None => Err(Status::not_found("Record not found or already deleted")),
|
|
}
|
|
}
|