CHECK THIS COMMIT I HAVE NO CLUE IF ITS CORRECT
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
// src/tables_data/handlers/put_table_data.rs
|
||||
|
||||
// TODO WORK ON SCRIPTS INPUT OUTPUT HAS TO BE CHECKED
|
||||
|
||||
use tonic::Status;
|
||||
@@ -14,9 +13,7 @@ use rust_decimal::Decimal;
|
||||
use std::str::FromStr;
|
||||
|
||||
use crate::steel::server::execution::{self, Value};
|
||||
use crate::steel::server::functions::SteelContext;
|
||||
use crate::indexer::{IndexCommand, IndexCommandData};
|
||||
use crate::table_script::handlers::dependency_analyzer::DependencyAnalyzer;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::error;
|
||||
|
||||
@@ -29,6 +26,10 @@ pub async fn put_table_data(
|
||||
let table_name = request.table_name;
|
||||
let record_id = request.id;
|
||||
|
||||
println!("=== PUT TABLE DATA START ===");
|
||||
println!("Profile: {}, Table: {}, Record ID: {}", profile_name, table_name, record_id);
|
||||
println!("Request data: {:?}", request.data);
|
||||
|
||||
if request.data.is_empty() {
|
||||
return Ok(PutTableDataResponse {
|
||||
success: true,
|
||||
@@ -56,7 +57,6 @@ pub async fn put_table_data(
|
||||
.map_err(|e| Status::internal(format!("Column parsing error: {}", e)))?;
|
||||
|
||||
let mut columns = Vec::new();
|
||||
let mut user_column_names = Vec::new();
|
||||
for col_def in columns_json {
|
||||
let parts: Vec<&str> = col_def.splitn(2, ' ').collect();
|
||||
if parts.len() != 2 {
|
||||
@@ -64,10 +64,11 @@ pub async fn put_table_data(
|
||||
}
|
||||
let name = parts[0].trim_matches('"').to_string();
|
||||
let sql_type = parts[1].to_string();
|
||||
user_column_names.push(name.clone());
|
||||
columns.push((name, sql_type));
|
||||
}
|
||||
|
||||
println!("Table columns: {:?}", columns);
|
||||
|
||||
// --- Validate Column Permissions ---
|
||||
let fk_columns = sqlx::query!(
|
||||
r#"SELECT ltd.table_name
|
||||
@@ -81,7 +82,6 @@ pub async fn put_table_data(
|
||||
.map_err(|e| Status::internal(format!("Foreign key lookup error: {}", e)))?;
|
||||
|
||||
let mut system_columns = vec!["deleted".to_string()];
|
||||
// FIX 1: Change from `fk_columns` to `&fk_columns` to avoid move
|
||||
for fk in &fk_columns {
|
||||
system_columns.push(format!("{}_id", fk.table_name));
|
||||
}
|
||||
@@ -96,11 +96,16 @@ pub async fn put_table_data(
|
||||
}
|
||||
}
|
||||
|
||||
// --- [OPTIMIZATION] Smart Data Fetching: Only fetch what scripts need ---
|
||||
let scripts = sqlx::query!("SELECT target_column, script FROM table_scripts WHERE table_definitions_id = $1", table_def.id)
|
||||
// --- Smart Data Fetching using script_dependencies table ---
|
||||
let scripts = sqlx::query!("SELECT id, 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)))?;
|
||||
|
||||
println!("Found {} scripts for table", scripts.len());
|
||||
for script in &scripts {
|
||||
println!("Script ID {}: target_column='{}', script='{}'", script.id, script.target_column, script.script);
|
||||
}
|
||||
|
||||
let mut required_columns = std::collections::HashSet::new();
|
||||
|
||||
// Always need: id, target columns of scripts, and columns being updated
|
||||
@@ -112,35 +117,45 @@ pub async fn put_table_data(
|
||||
required_columns.insert(key.clone());
|
||||
}
|
||||
|
||||
// Analyze script dependencies to find what columns scripts actually access
|
||||
// Use pre-computed dependencies from script_dependencies table
|
||||
if !scripts.is_empty() {
|
||||
let analyzer = DependencyAnalyzer::new(schema_id, db_pool.clone());
|
||||
let script_ids: Vec<i64> = scripts.iter().map(|s| s.id).collect();
|
||||
|
||||
for script_record in &scripts {
|
||||
let dependencies = analyzer
|
||||
.analyze_script_dependencies(&script_record.script)
|
||||
.map_err(|e| Status::internal(format!("Failed to analyze script dependencies: {:?}", e)))?;
|
||||
let dependencies = sqlx::query!(
|
||||
r#"SELECT sd.target_table_id, sd.dependency_type, sd.context_info, td.table_name as target_table
|
||||
FROM script_dependencies sd
|
||||
JOIN table_definitions td ON sd.target_table_id = td.id
|
||||
WHERE sd.script_id = ANY($1)"#,
|
||||
&script_ids
|
||||
)
|
||||
.fetch_all(db_pool)
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("Failed to fetch script dependencies: {}", e)))?;
|
||||
|
||||
for dep in dependencies {
|
||||
// If it references this table, add the columns it uses
|
||||
if dep.target_table == table_name {
|
||||
match dep.dependency_type {
|
||||
crate::table_script::handlers::dependency_analyzer::DependencyType::ColumnAccess { column } |
|
||||
crate::table_script::handlers::dependency_analyzer::DependencyType::IndexedAccess { column, .. } => {
|
||||
required_columns.insert(column);
|
||||
for dep in dependencies {
|
||||
// If it references this table, add the columns it uses
|
||||
if dep.target_table == table_name {
|
||||
match dep.dependency_type.as_str() {
|
||||
"column_access" | "indexed_access" => {
|
||||
if let Some(context) = dep.context_info {
|
||||
if let Some(column) = context.get("column").and_then(|v| v.as_str()) {
|
||||
required_columns.insert(column.to_string());
|
||||
}
|
||||
}
|
||||
_ => {} // SQL queries handled differently
|
||||
}
|
||||
_ => {} // SQL queries handled differently
|
||||
}
|
||||
// If it references linked tables, add their foreign key columns
|
||||
else {
|
||||
let fk_column = format!("{}_id", dep.target_table.split('_').last().unwrap_or(&dep.target_table));
|
||||
required_columns.insert(fk_column);
|
||||
}
|
||||
}
|
||||
// If it references linked tables, add their foreign key columns
|
||||
else {
|
||||
let fk_column = format!("{}_id", dep.target_table.split('_').last().unwrap_or(&dep.target_table));
|
||||
required_columns.insert(fk_column);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("Required columns for context: {:?}", required_columns);
|
||||
|
||||
// Build optimized SELECT query with only required columns
|
||||
let qualified_table = crate::shared::schema_qualifier::qualify_table_name_for_data(db_pool, &profile_name, &table_name).await?;
|
||||
|
||||
@@ -151,6 +166,7 @@ pub async fn put_table_data(
|
||||
.join(", ");
|
||||
|
||||
let select_sql = format!("SELECT {} FROM {} WHERE id = $1", columns_clause, qualified_table);
|
||||
println!("SELECT SQL: {}", select_sql);
|
||||
|
||||
let current_row = sqlx::query(&select_sql).bind(record_id).fetch_optional(db_pool).await
|
||||
.map_err(|e| Status::internal(format!("Failed to fetch current row state: {}", e)))?
|
||||
@@ -162,8 +178,12 @@ pub async fn put_table_data(
|
||||
current_row_data.insert(col_name.clone(), value);
|
||||
}
|
||||
|
||||
println!("=== CURRENT ROW DATA FROM DB ===");
|
||||
println!("{:?}", current_row_data);
|
||||
|
||||
// --- Data Merging Logic ---
|
||||
let mut update_data = HashMap::new();
|
||||
println!("=== EXTRACTING UPDATE DATA FROM REQUEST ===");
|
||||
for (key, proto_value) in &request.data {
|
||||
let str_val = match &proto_value.kind {
|
||||
Some(Kind::StringValue(s)) => s.trim().to_string(),
|
||||
@@ -172,18 +192,26 @@ pub async fn put_table_data(
|
||||
Some(Kind::NullValue(_)) | None => String::new(),
|
||||
_ => return Err(Status::invalid_argument(format!("Unsupported type for column '{}'", key))),
|
||||
};
|
||||
if !str_val.is_empty() {
|
||||
update_data.insert(key.clone(), str_val);
|
||||
}
|
||||
println!("UPDATE_DATA[{}] = '{}'", key, str_val);
|
||||
// Always add the value, even if empty (to properly override current values)
|
||||
update_data.insert(key.clone(), str_val);
|
||||
}
|
||||
|
||||
println!("=== UPDATE DATA EXTRACTED ===");
|
||||
println!("{:?}", update_data);
|
||||
|
||||
let mut final_context_data = current_row_data.clone();
|
||||
final_context_data.extend(update_data.clone());
|
||||
|
||||
// FIX 2: Type-aware script validation
|
||||
println!("=== FINAL CONTEXT DATA FOR STEEL ===");
|
||||
println!("{:?}", final_context_data);
|
||||
|
||||
// Script validation with type-aware comparison
|
||||
for script_record in scripts {
|
||||
let target_column = script_record.target_column;
|
||||
|
||||
println!("=== PROCESSING SCRIPT FOR COLUMN: {} ===", target_column);
|
||||
|
||||
// Find the SQL type for this target column
|
||||
let target_sql_type = if let Some((_, stype)) = columns.iter().find(|(name, _)| name == &target_column) {
|
||||
stype.as_str()
|
||||
@@ -191,16 +219,11 @@ pub async fn put_table_data(
|
||||
"TEXT" // Default fallback for system columns
|
||||
};
|
||||
|
||||
let context = SteelContext {
|
||||
current_table: table_name.clone(),
|
||||
schema_id,
|
||||
schema_name: profile_name.clone(),
|
||||
row_data: final_context_data.clone(),
|
||||
db_pool: Arc::new(db_pool.clone()),
|
||||
};
|
||||
println!("Target column SQL type: {}", target_sql_type);
|
||||
println!("Executing script: {}", script_record.script);
|
||||
|
||||
let script_result = execution::execute_script(
|
||||
script_record.script,
|
||||
script_record.script.clone(),
|
||||
"STRINGS",
|
||||
Arc::new(db_pool.clone()),
|
||||
schema_id,
|
||||
@@ -209,82 +232,100 @@ pub async fn put_table_data(
|
||||
final_context_data.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| Status::invalid_argument(format!("Script execution failed for '{}': {}", target_column, e)))?;
|
||||
.map_err(|e| {
|
||||
error!("Script execution failed for '{}': {:?}", target_column, e);
|
||||
Status::invalid_argument(format!("Script execution failed for '{}': {}", target_column, e))
|
||||
})?;
|
||||
|
||||
let Value::Strings(mut script_output_vec) = script_result else {
|
||||
return Err(Status::internal("Script must return string values"));
|
||||
};
|
||||
let script_output = script_output_vec.pop().ok_or_else(|| Status::internal("Script returned no values"))?;
|
||||
|
||||
println!("Script output: '{}'", script_output);
|
||||
|
||||
if update_data.contains_key(&target_column) {
|
||||
// Case A: Column is being updated. Validate user input against script.
|
||||
let user_value = update_data.get(&target_column).unwrap();
|
||||
|
||||
println!("Case A: Validating user value '{}' against script output '{}'", user_value, script_output);
|
||||
|
||||
// TYPE-AWARE COMPARISON based on SQL type
|
||||
let values_match = match target_sql_type {
|
||||
s if s.starts_with("NUMERIC") => {
|
||||
// For NUMERIC columns, compare as decimals
|
||||
let user_decimal = Decimal::from_str(user_value).map_err(|_| Status::invalid_argument(format!("Invalid decimal format for column '{}'", target_column)))?;
|
||||
let script_decimal = Decimal::from_str(&script_output).map_err(|_| Status::internal(format!("Script for '{}' produced invalid decimal", target_column)))?;
|
||||
println!("Decimal comparison: user={}, script={}", user_decimal, script_decimal);
|
||||
user_decimal == script_decimal
|
||||
},
|
||||
"INTEGER" | "BIGINT" => {
|
||||
// For integer columns, compare as integers
|
||||
let user_int: i64 = user_value.parse().map_err(|_| Status::invalid_argument(format!("Invalid integer format for column '{}'", target_column)))?;
|
||||
let script_int: i64 = script_output.parse().map_err(|_| Status::internal(format!("Script for '{}' produced invalid integer", target_column)))?;
|
||||
println!("Integer comparison: user={}, script={}", user_int, script_int);
|
||||
user_int == script_int
|
||||
},
|
||||
"BOOLEAN" => {
|
||||
// For boolean columns, compare as booleans
|
||||
let user_bool: bool = user_value.parse().map_err(|_| Status::invalid_argument(format!("Invalid boolean format for column '{}'", target_column)))?;
|
||||
let script_bool: bool = script_output.parse().map_err(|_| Status::internal(format!("Script for '{}' produced invalid boolean", target_column)))?;
|
||||
println!("Boolean comparison: user={}, script={}", user_bool, script_bool);
|
||||
user_bool == script_bool
|
||||
},
|
||||
_ => {
|
||||
// For TEXT, TIMESTAMPTZ, DATE, etc. - compare as strings
|
||||
println!("String comparison: user='{}', script='{}'", user_value, script_output);
|
||||
user_value == &script_output
|
||||
}
|
||||
};
|
||||
|
||||
println!("Values match: {}", values_match);
|
||||
|
||||
if !values_match {
|
||||
return Err(Status::invalid_argument(format!("Validation failed for column '{}': Script calculated '{}', but user provided '{}'", target_column, script_output, user_value)));
|
||||
}
|
||||
} else {
|
||||
// Case B: Column is NOT being updated. Prevent unauthorized changes.
|
||||
let current_value = current_row_data.get(&target_column).cloned().unwrap_or_default();
|
||||
|
||||
println!("Case B: Checking if script would change current value '{}' to '{}'", current_value, script_output);
|
||||
|
||||
let values_match = match target_sql_type {
|
||||
s if s.starts_with("NUMERIC") => {
|
||||
let current_decimal = Decimal::from_str(¤t_value).unwrap_or_default();
|
||||
let script_decimal = Decimal::from_str(&script_output).unwrap_or_default();
|
||||
println!("Decimal comparison: current={}, script={}", current_decimal, script_decimal);
|
||||
current_decimal == script_decimal
|
||||
},
|
||||
"INTEGER" | "BIGINT" => {
|
||||
let current_int: i64 = current_value.parse().unwrap_or_default();
|
||||
let script_int: i64 = script_output.parse().unwrap_or_default();
|
||||
println!("Integer comparison: current={}, script={}", current_int, script_int);
|
||||
current_int == script_int
|
||||
},
|
||||
"BOOLEAN" => {
|
||||
let current_bool: bool = current_value.parse().unwrap_or(false);
|
||||
let script_bool: bool = script_output.parse().unwrap_or(false);
|
||||
println!("Boolean comparison: current={}, script={}", current_bool, script_bool);
|
||||
current_bool == script_bool
|
||||
},
|
||||
_ => {
|
||||
println!("String comparison: current='{}', script='{}'", current_value, script_output);
|
||||
current_value == script_output
|
||||
}
|
||||
};
|
||||
|
||||
println!("Values match: {}", values_match);
|
||||
|
||||
if !values_match {
|
||||
return Err(Status::failed_precondition(format!("Script for column '{}' was triggered and would change its value from '{}' to '{}'. To apply this change, please include '{}' in your update request.", target_column, current_value, script_output, target_column)));
|
||||
}
|
||||
}
|
||||
println!("=== END PROCESSING SCRIPT FOR COLUMN: {} ===", target_column);
|
||||
}
|
||||
|
||||
// --- Database Update with Full Validation ---
|
||||
// --- Database Update ---
|
||||
let mut params = PgArguments::default();
|
||||
let mut set_clauses = Vec::new();
|
||||
let mut param_idx = 1;
|
||||
|
||||
println!("=== BUILDING UPDATE QUERY ===");
|
||||
|
||||
for (col, proto_value) in request.data {
|
||||
let sql_type = if system_columns_set.contains(col.as_str()) {
|
||||
match col.as_str() {
|
||||
@@ -321,7 +362,6 @@ pub async fn put_table_data(
|
||||
if sql_type == "TEXT" {
|
||||
if let Kind::StringValue(value) = kind {
|
||||
let trimmed_value = value.trim();
|
||||
|
||||
if trimmed_value.is_empty() {
|
||||
params.add(None::<String>).map_err(|e| Status::internal(format!("Failed to add null parameter for {}: {}", col, e)))?;
|
||||
} else {
|
||||
@@ -424,6 +464,8 @@ pub async fn put_table_data(
|
||||
param_idx
|
||||
);
|
||||
|
||||
println!("UPDATE SQL: {}", sql);
|
||||
|
||||
params.add(record_id).map_err(|e| Status::internal(format!("Failed to add record_id parameter: {}", e)))?;
|
||||
|
||||
let result = sqlx::query_scalar_with::<_, i64, _>(&sql, params)
|
||||
@@ -459,6 +501,9 @@ pub async fn put_table_data(
|
||||
);
|
||||
}
|
||||
|
||||
println!("=== PUT TABLE DATA SUCCESS ===");
|
||||
println!("Updated record ID: {}", updated_id);
|
||||
|
||||
Ok(PutTableDataResponse {
|
||||
success: true,
|
||||
message: "Data updated successfully".into(),
|
||||
|
||||
Reference in New Issue
Block a user