put working now doing post general test
This commit is contained in:
@@ -1,8 +1,11 @@
|
||||
// src/server/services/tables_data_service.rs
|
||||
use tonic::{Request, Response, Status};
|
||||
use common::proto::multieko2::tables_data::tables_data_server::TablesData;
|
||||
use common::proto::multieko2::tables_data::{PostTableDataRequest, PostTableDataResponse};
|
||||
use crate::tables_data::handlers::post_table_data;
|
||||
use common::proto::multieko2::tables_data::{
|
||||
PostTableDataRequest, PostTableDataResponse,
|
||||
PutTableDataRequest, PutTableDataResponse // Add this import
|
||||
};
|
||||
use crate::tables_data::handlers::{post_table_data, put_table_data}; // Add put_table_data
|
||||
use sqlx::PgPool;
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -18,6 +21,16 @@ impl TablesData for TablesDataService {
|
||||
) -> Result<Response<PostTableDataResponse>, Status> {
|
||||
let request = request.into_inner();
|
||||
let response = post_table_data(&self.db_pool, request).await?;
|
||||
Ok(Response::new(response)) // Wrap the response in a Response
|
||||
Ok(Response::new(response))
|
||||
}
|
||||
|
||||
// Add the new method implementation
|
||||
async fn put_table_data(
|
||||
&self,
|
||||
request: Request<PutTableDataRequest>,
|
||||
) -> Result<Response<PutTableDataResponse>, Status> {
|
||||
let request = request.into_inner();
|
||||
let response = put_table_data(&self.db_pool, request).await?;
|
||||
Ok(Response::new(response))
|
||||
}
|
||||
}
|
||||
|
||||
36
server/src/tables_data/docs/put_data.txt
Normal file
36
server/src/tables_data/docs/put_data.txt
Normal file
@@ -0,0 +1,36 @@
|
||||
❯ grpcurl -plaintext -d '{
|
||||
"profile_name": "default",
|
||||
"table_name": "2025_company_data1",
|
||||
"id": 1,
|
||||
"data": {
|
||||
"firma": "ACME Corporation Updated",
|
||||
"company_name": "ACME Corp Updated",
|
||||
"textfield": "Updated sample text",
|
||||
"textfield2": "Updated additional information",
|
||||
"textfield3": "Updated more details",
|
||||
"headquarters_psc": "54321",
|
||||
"contact_phone": "987-654-3210",
|
||||
"office_address": "456 Updated St, Springfield",
|
||||
"support_email": "updated-support@acmecorp.com",
|
||||
"is_active": "false"
|
||||
}
|
||||
}' localhost:50051 multieko2.tables_data.TablesData/PutTableData
|
||||
{
|
||||
"success": true,
|
||||
"message": "Data updated successfully",
|
||||
"updatedId": "1"
|
||||
}
|
||||
❯ grpcurl -plaintext -d '{
|
||||
"profile_name": "default",
|
||||
"table_name": "2025_company_data1",
|
||||
"id": 2,
|
||||
"data": {
|
||||
"firma": "1",
|
||||
"is_active": "true"
|
||||
}
|
||||
}' localhost:50051 multieko2.tables_data.TablesData/PutTableData
|
||||
{
|
||||
"success": true,
|
||||
"message": "Data updated successfully",
|
||||
"updatedId": "2"
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
// server/src/tables_data/handlers.rs
|
||||
pub mod post_table_data;
|
||||
pub mod put_table_data;
|
||||
|
||||
pub use post_table_data::post_table_data;
|
||||
pub use put_table_data::put_table_data;
|
||||
|
||||
140
server/src/tables_data/handlers/put_table_data.rs
Normal file
140
server/src/tables_data/handlers/put_table_data.rs
Normal file
@@ -0,0 +1,140 @@
|
||||
// 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);
|
||||
},
|
||||
"BOOLEAN" => {
|
||||
let val = value.parse::<bool>()
|
||||
.map_err(|_| Status::invalid_argument(format!("Invalid boolean for {}", col)))?;
|
||||
params.add(val);
|
||||
},
|
||||
"TIMESTAMPTZ" => {
|
||||
let dt = DateTime::parse_from_rfc3339(value)
|
||||
.map_err(|_| Status::invalid_argument(format!("Invalid timestamp for {}", col)))?;
|
||||
params.add(dt.with_timezone(&Utc));
|
||||
},
|
||||
_ => 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);
|
||||
|
||||
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")),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user