232 lines
8.5 KiB
Rust
232 lines
8.5 KiB
Rust
// src/tables_data/handlers/post_table_data.rs
|
|
use tonic::Status;
|
|
use sqlx::{PgPool, Arguments};
|
|
use sqlx::postgres::PgArguments;
|
|
use chrono::{DateTime, Utc};
|
|
use common::proto::multieko2::tables_data::{PostTableDataRequest, PostTableDataResponse};
|
|
use crate::steel::handlers::execution::{self, ScriptOperation};
|
|
use std::collections::HashMap;
|
|
|
|
pub async fn post_table_data(
|
|
db_pool: &PgPool,
|
|
request: PostTableDataRequest,
|
|
) -> Result<PostTableDataResponse, Status> {
|
|
let profile_name = request.profile_name;
|
|
let table_name = request.table_name;
|
|
let mut data = HashMap::new();
|
|
|
|
// Process and validate all data values
|
|
for (key, value) in request.data {
|
|
let trimmed = value.trim().to_string();
|
|
|
|
// Handle firma specially - it cannot be empty
|
|
if key == "firma" && trimmed.is_empty() {
|
|
return Err(Status::invalid_argument("Firma cannot be empty"));
|
|
}
|
|
|
|
// Add trimmed non-empty values to data map
|
|
// Empty optional fields will be skipped in SQL generation
|
|
if !trimmed.is_empty() || key == "firma" {
|
|
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, linked_table_id 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<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));
|
|
}
|
|
|
|
// Check required system columns
|
|
let mut required_columns = vec!["firma".to_string()];
|
|
if let Some(linked_table_id) = table_def.linked_table_id {
|
|
let linked_table = sqlx::query!(
|
|
"SELECT table_name FROM table_definitions WHERE id = $1",
|
|
linked_table_id
|
|
)
|
|
.fetch_one(db_pool)
|
|
.await
|
|
.map_err(|e| Status::internal(format!("Linked table error: {}", e)))?;
|
|
|
|
let base_name = linked_table.table_name.splitn(2, '_').last().unwrap_or(&linked_table.table_name);
|
|
required_columns.push(format!("{}_id", base_name));
|
|
}
|
|
|
|
// Validate required columns
|
|
for col in &required_columns {
|
|
if !data.contains_key(col) {
|
|
return Err(Status::invalid_argument(format!("Missing required column: {}", col)));
|
|
}
|
|
}
|
|
|
|
// Validate all data columns
|
|
let system_columns = ["firma", "deleted"];
|
|
let user_columns: Vec<&String> = columns.iter().map(|(name, _)| name).collect();
|
|
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)));
|
|
}
|
|
}
|
|
|
|
|
|
// Validate Steel scripts
|
|
let scripts = sqlx::query!(
|
|
"SELECT target_column, script FROM table_scripts WHERE table_definitions_id = $1",
|
|
table_def.id
|
|
)
|
|
.fetch_all(db_pool)
|
|
.await
|
|
.map_err(|e| Status::internal(format!("Failed to fetch scripts: {}", e)))?;
|
|
|
|
for script_record in scripts {
|
|
let target_column = script_record.target_column;
|
|
|
|
// Check if target column is present in data
|
|
if !data.contains_key(&target_column) {
|
|
return Err(Status::invalid_argument(
|
|
format!("Column '{}' is required due to an associated script", target_column)
|
|
));
|
|
}
|
|
|
|
// Parse the script
|
|
let operation = execution::parse_script(&script_record.script, &target_column)
|
|
.map_err(|e| Status::invalid_argument(e.to_string()))?;
|
|
|
|
// Get source column from operation
|
|
let source_column = match operation {
|
|
ScriptOperation::SetToColumn { source } => source,
|
|
};
|
|
|
|
// Check source column presence
|
|
let source_value = data.get(&source_column)
|
|
.ok_or_else(|| Status::invalid_argument(
|
|
format!("Source column '{}' required by script for '{}' is missing", source_column, target_column)
|
|
))?;
|
|
|
|
// Get target value
|
|
let target_value = data.get(&target_column)
|
|
.ok_or_else(|| Status::invalid_argument(
|
|
format!("Target column '{}' is missing in data", target_column)
|
|
))?;
|
|
|
|
// Validate value match
|
|
if target_value != source_value {
|
|
return Err(Status::invalid_argument(
|
|
format!("Value for '{}' must match '{}' as per script. Expected '{}', got '{}'",
|
|
target_column, source_column, source_value, target_value)
|
|
));
|
|
}
|
|
}
|
|
|
|
// Prepare SQL parameters
|
|
let mut params = PgArguments::default();
|
|
let mut columns_list = Vec::new();
|
|
let mut placeholders = Vec::new();
|
|
let mut param_idx = 1;
|
|
|
|
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)))?
|
|
};
|
|
|
|
// TODO This needs heavy adjustement. More stuff to be added for user to only pick
|
|
// preprogrammed functions
|
|
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::internal(format!("Value too long for {}", col)));
|
|
}
|
|
}
|
|
params.add(value)
|
|
.map_err(|e| Status::invalid_argument(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::invalid_argument(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::invalid_argument(format!("Failed to add timestamp parameter for {}: {}", col, e)))?;
|
|
},
|
|
_ => return Err(Status::invalid_argument(format!("Unsupported type {}", sql_type))),
|
|
}
|
|
|
|
columns_list.push(format!("\"{}\"", col));
|
|
placeholders.push(format!("${}", param_idx));
|
|
param_idx += 1;
|
|
}
|
|
|
|
// Ensure we have at least one column to insert
|
|
if columns_list.is_empty() {
|
|
return Err(Status::invalid_argument("No valid columns to insert"));
|
|
}
|
|
|
|
let sql = format!(
|
|
"INSERT INTO \"{}\" ({}) VALUES ({}) RETURNING id",
|
|
table_name,
|
|
columns_list.join(", "),
|
|
placeholders.join(", ")
|
|
);
|
|
|
|
let inserted_id: i64 = sqlx::query_scalar_with(&sql, params)
|
|
.fetch_one(db_pool)
|
|
.await
|
|
.map_err(|e| Status::internal(format!("Insert failed: {}", e)))?;
|
|
|
|
Ok(PostTableDataResponse {
|
|
success: true,
|
|
message: "Data inserted successfully".into(),
|
|
inserted_id,
|
|
})
|
|
}
|