atomicity when creating tables
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
// src/table_definition/handlers/post_table_definition.rs
|
// src/table_definition/handlers/post_table_definition.rs
|
||||||
use tonic::Status;
|
use tonic::Status;
|
||||||
use sqlx::PgPool;
|
use sqlx::{PgPool, Transaction, Postgres};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use time::OffsetDateTime;
|
use time::OffsetDateTime;
|
||||||
use common::proto::multieko2::table_definition::{PostTableDefinitionRequest, TableDefinitionResponse};
|
use common::proto::multieko2::table_definition::{PostTableDefinitionRequest, TableDefinitionResponse};
|
||||||
@@ -55,6 +55,35 @@ pub async fn post_table_definition(
|
|||||||
return Err(Status::invalid_argument("Invalid table name"));
|
return Err(Status::invalid_argument("Invalid table name"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Start a transaction to ensure atomicity
|
||||||
|
let mut tx = db_pool.begin().await
|
||||||
|
.map_err(|e| Status::internal(format!("Failed to start transaction: {}", e)))?;
|
||||||
|
|
||||||
|
// Execute all database operations within the transaction
|
||||||
|
let result = execute_table_definition(&mut tx, request, table_name).await;
|
||||||
|
|
||||||
|
// Commit or rollback based on the result
|
||||||
|
match result {
|
||||||
|
Ok(response) => {
|
||||||
|
// Commit the transaction
|
||||||
|
tx.commit().await
|
||||||
|
.map_err(|e| Status::internal(format!("Failed to commit transaction: {}", e)))?;
|
||||||
|
Ok(response)
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
// Transaction will be automatically rolled back when dropped
|
||||||
|
// But we can explicitly roll it back too
|
||||||
|
let _ = tx.rollback().await;
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute_table_definition(
|
||||||
|
tx: &mut Transaction<'_, Postgres>,
|
||||||
|
mut request: PostTableDefinitionRequest,
|
||||||
|
table_name: String,
|
||||||
|
) -> Result<TableDefinitionResponse, Status> {
|
||||||
// Lookup or create profile
|
// Lookup or create profile
|
||||||
let profile = sqlx::query!(
|
let profile = sqlx::query!(
|
||||||
"INSERT INTO profiles (name) VALUES ($1)
|
"INSERT INTO profiles (name) VALUES ($1)
|
||||||
@@ -62,7 +91,7 @@ pub async fn post_table_definition(
|
|||||||
RETURNING id",
|
RETURNING id",
|
||||||
request.profile_name
|
request.profile_name
|
||||||
)
|
)
|
||||||
.fetch_one(db_pool)
|
.fetch_one(&mut **tx)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Status::internal(format!("Profile error: {}", e)))?;
|
.map_err(|e| Status::internal(format!("Profile error: {}", e)))?;
|
||||||
|
|
||||||
@@ -75,7 +104,7 @@ pub async fn post_table_definition(
|
|||||||
profile.id,
|
profile.id,
|
||||||
link.linked_table_name
|
link.linked_table_name
|
||||||
)
|
)
|
||||||
.fetch_optional(db_pool)
|
.fetch_optional(&mut **tx)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Status::internal(format!("Linked table lookup failed: {}", e)))?;
|
.map_err(|e| Status::internal(format!("Linked table lookup failed: {}", e)))?;
|
||||||
|
|
||||||
@@ -108,7 +137,7 @@ pub async fn post_table_definition(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Generate SQL with multiple links
|
// Generate SQL with multiple links
|
||||||
let (create_sql, index_sql) = generate_table_sql(db_pool, &table_name, &columns, &indexes, &links).await?;
|
let (create_sql, index_sql) = generate_table_sql(tx, &table_name, &columns, &indexes, &links).await?;
|
||||||
|
|
||||||
// Store main table definition
|
// Store main table definition
|
||||||
let table_def = sqlx::query!(
|
let table_def = sqlx::query!(
|
||||||
@@ -121,7 +150,7 @@ pub async fn post_table_definition(
|
|||||||
json!(columns),
|
json!(columns),
|
||||||
json!(indexes)
|
json!(indexes)
|
||||||
)
|
)
|
||||||
.fetch_one(db_pool)
|
.fetch_one(&mut **tx)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
if let Some(db_err) = e.as_database_error() {
|
if let Some(db_err) = e.as_database_error() {
|
||||||
@@ -142,20 +171,20 @@ pub async fn post_table_definition(
|
|||||||
linked_id,
|
linked_id,
|
||||||
is_required
|
is_required
|
||||||
)
|
)
|
||||||
.execute(db_pool)
|
.execute(&mut **tx)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Status::internal(format!("Failed to save link: {}", e)))?;
|
.map_err(|e| Status::internal(format!("Failed to save link: {}", e)))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute generated SQL
|
// Execute generated SQL
|
||||||
sqlx::query(&create_sql)
|
sqlx::query(&create_sql)
|
||||||
.execute(db_pool)
|
.execute(&mut **tx)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Status::internal(format!("Table creation failed: {}", e)))?;
|
.map_err(|e| Status::internal(format!("Table creation failed: {}", e)))?;
|
||||||
|
|
||||||
for sql in &index_sql {
|
for sql in &index_sql {
|
||||||
sqlx::query(sql)
|
sqlx::query(sql)
|
||||||
.execute(db_pool)
|
.execute(&mut **tx)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Status::internal(format!("Index creation failed: {}", e)))?;
|
.map_err(|e| Status::internal(format!("Index creation failed: {}", e)))?;
|
||||||
}
|
}
|
||||||
@@ -167,7 +196,7 @@ pub async fn post_table_definition(
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn generate_table_sql(
|
async fn generate_table_sql(
|
||||||
db_pool: &PgPool,
|
tx: &mut Transaction<'_, Postgres>,
|
||||||
table_name: &str,
|
table_name: &str,
|
||||||
columns: &[String],
|
columns: &[String],
|
||||||
indexes: &[String],
|
indexes: &[String],
|
||||||
@@ -181,7 +210,7 @@ async fn generate_table_sql(
|
|||||||
// Add foreign key columns
|
// Add foreign key columns
|
||||||
let mut link_info = Vec::new();
|
let mut link_info = Vec::new();
|
||||||
for (linked_id, required) in links {
|
for (linked_id, required) in links {
|
||||||
let linked_table = get_table_name_by_id(db_pool, *linked_id).await?;
|
let linked_table = get_table_name_by_id(tx, *linked_id).await?;
|
||||||
|
|
||||||
// Extract base name after year prefix
|
// Extract base name after year prefix
|
||||||
let base_name = linked_table.split_once('_')
|
let base_name = linked_table.split_once('_')
|
||||||
@@ -231,12 +260,15 @@ async fn generate_table_sql(
|
|||||||
Ok((create_sql, all_indexes))
|
Ok((create_sql, all_indexes))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_table_name_by_id(db_pool: &PgPool, table_id: i64) -> Result<String, Status> {
|
async fn get_table_name_by_id(
|
||||||
|
tx: &mut Transaction<'_, Postgres>,
|
||||||
|
table_id: i64
|
||||||
|
) -> Result<String, Status> {
|
||||||
let record = sqlx::query!(
|
let record = sqlx::query!(
|
||||||
"SELECT table_name FROM table_definitions WHERE id = $1",
|
"SELECT table_name FROM table_definitions WHERE id = $1",
|
||||||
table_id
|
table_id
|
||||||
)
|
)
|
||||||
.fetch_one(db_pool)
|
.fetch_one(&mut **tx)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Status::internal(format!("Table lookup failed: {}", e)))?;
|
.map_err(|e| Status::internal(format!("Table lookup failed: {}", e)))?;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user