now not creating tables with the year_ prefix and living in the gen schema by default

This commit is contained in:
filipriec
2025-06-17 11:45:55 +02:00
parent 3eb9523103
commit 8ebe74484c
8 changed files with 82 additions and 41 deletions

View File

@@ -1,34 +1,48 @@
// src/shared/schema_qualifier.rs
// src/shared/schema_qualifier.rs
use sqlx::PgPool;
use tonic::Status;
/// Qualifies table names with the appropriate schema
///
/// Qualifies a table name by checking for its existence in the table_definitions table.
/// This is the robust, "source of truth" approach.
///
/// Rules:
/// - Tables created via PostTableDefinition (dynamically created tables) are in 'gen' schema
/// - System tables (like users, profiles) remain in 'public' schema
pub fn qualify_table_name(table_name: &str) -> String {
// Check if table matches the pattern of dynamically created tables (e.g., 2025_something)
if table_name.starts_with(|c: char| c.is_ascii_digit()) && table_name.contains('_') {
format!("gen.\"{}\"", table_name)
/// - If a table is found in `table_definitions`, it is qualified with the 'gen' schema.
/// - Otherwise, it is assumed to be a system table in the 'public' schema.
pub async fn qualify_table_name(
db_pool: &PgPool,
profile_name: &str,
table_name: &str,
) -> Result<String, Status> {
// Check if a definition exists for this table in the given profile.
let definition_exists = sqlx::query!(
r#"SELECT EXISTS (
SELECT 1 FROM table_definitions td
JOIN profiles p ON td.profile_id = p.id
WHERE p.name = $1 AND td.table_name = $2
)"#,
profile_name,
table_name
)
.fetch_one(db_pool)
.await
.map_err(|e| Status::internal(format!("Schema lookup failed: {}", e)))?
.exists
.unwrap_or(false);
if definition_exists {
// It's a user-defined table, so it lives in 'gen'.
Ok(format!("gen.\"{}\"", table_name))
} else {
format!("\"{}\"", table_name)
// It's not a user-defined table, so it must be a system table in 'public'.
Ok(format!("\"{}\"", table_name))
}
}
/// Qualifies table names for data operations
pub fn qualify_table_name_for_data(table_name: &str) -> Result<String, Status> {
Ok(qualify_table_name(table_name))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_qualify_table_name() {
assert_eq!(qualify_table_name("2025_test_schema3"), "gen.\"2025_test_schema3\"");
assert_eq!(qualify_table_name("users"), "\"users\"");
assert_eq!(qualify_table_name("profiles"), "\"profiles\"");
assert_eq!(qualify_table_name("adresar"), "\"adresar\"");
}
pub async fn qualify_table_name_for_data(
db_pool: &PgPool,
profile_name: &str,
table_name: &str,
) -> Result<String, Status> {
qualify_table_name(db_pool, profile_name, table_name).await
}