needs last one to be fixed, otherwise its getting perfect
This commit is contained in:
@@ -16,23 +16,41 @@ const PREDEFINED_FIELD_TYPES: &[(&str, &str)] = &[
|
||||
("date", "DATE"),
|
||||
];
|
||||
|
||||
fn is_valid_identifier(s: &str) -> bool {
|
||||
!s.is_empty() &&
|
||||
s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') &&
|
||||
!s.starts_with('_') &&
|
||||
!s.chars().next().unwrap().is_ascii_digit()
|
||||
}
|
||||
// NEW: Helper function to provide detailed error messages
|
||||
fn validate_identifier_format(s: &str, identifier_type: &str) -> Result<(), Status> {
|
||||
if s.is_empty() {
|
||||
return Err(Status::invalid_argument(format!("{} cannot be empty", identifier_type)));
|
||||
}
|
||||
|
||||
fn sanitize_table_name(s: &str) -> String {
|
||||
s.replace(|c: char| !c.is_ascii_alphanumeric() && c != '_', "")
|
||||
.trim()
|
||||
.to_lowercase()
|
||||
}
|
||||
if s.starts_with('_') {
|
||||
return Err(Status::invalid_argument(format!("{} cannot start with underscore", identifier_type)));
|
||||
}
|
||||
|
||||
fn sanitize_identifier(s: &str) -> String {
|
||||
s.replace(|c: char| !c.is_ascii_alphanumeric() && c != '_', "")
|
||||
.trim()
|
||||
.to_lowercase()
|
||||
if s.chars().next().unwrap().is_ascii_digit() {
|
||||
return Err(Status::invalid_argument(format!("{} cannot start with a number", identifier_type)));
|
||||
}
|
||||
|
||||
// Check for invalid characters
|
||||
let invalid_chars: Vec<char> = s.chars()
|
||||
.filter(|c| !c.is_ascii_lowercase() && !c.is_ascii_digit() && *c != '_')
|
||||
.collect();
|
||||
|
||||
if !invalid_chars.is_empty() {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"{} contains invalid characters: {:?}. Only lowercase letters, numbers, and underscores are allowed",
|
||||
identifier_type, invalid_chars
|
||||
)));
|
||||
}
|
||||
|
||||
// Check for uppercase letters specifically to give a helpful message
|
||||
if s.chars().any(|c| c.is_ascii_uppercase()) {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"{} contains uppercase letters. Only lowercase letters are allowed",
|
||||
identifier_type
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_field_type(field_type: &str) -> Result<String, Status> {
|
||||
@@ -107,65 +125,56 @@ fn is_reserved_schema(schema_name: &str) -> bool {
|
||||
|
||||
pub async fn post_table_definition(
|
||||
db_pool: &PgPool,
|
||||
request: PostTableDefinitionRequest,
|
||||
mut request: PostTableDefinitionRequest, // Changed to mutable
|
||||
) -> Result<TableDefinitionResponse, Status> {
|
||||
if request.profile_name.trim().is_empty() {
|
||||
return Err(Status::invalid_argument("Profile name cannot be empty"));
|
||||
}
|
||||
|
||||
// Apply same sanitization rules as table names
|
||||
let sanitized_profile_name = sanitize_identifier(&request.profile_name);
|
||||
// Create owned copies of the strings after validation
|
||||
let profile_name = {
|
||||
let trimmed = request.profile_name.trim();
|
||||
validate_identifier_format(trimmed, "Profile name")?;
|
||||
trimmed.to_string()
|
||||
};
|
||||
|
||||
// Add validation to prevent reserved schemas
|
||||
if is_reserved_schema(&sanitized_profile_name) {
|
||||
if is_reserved_schema(&profile_name) {
|
||||
return Err(Status::invalid_argument("Profile name is reserved and cannot be used"));
|
||||
}
|
||||
|
||||
if !is_valid_identifier(&sanitized_profile_name) {
|
||||
return Err(Status::invalid_argument("Invalid profile name"));
|
||||
}
|
||||
|
||||
const MAX_IDENTIFIER_LENGTH: usize = 63;
|
||||
|
||||
if sanitized_profile_name.len() > MAX_IDENTIFIER_LENGTH {
|
||||
if profile_name.len() > MAX_IDENTIFIER_LENGTH {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"Profile name '{}' exceeds the {} character limit.",
|
||||
sanitized_profile_name,
|
||||
profile_name,
|
||||
MAX_IDENTIFIER_LENGTH
|
||||
)));
|
||||
}
|
||||
|
||||
let base_name = sanitize_table_name(&request.table_name);
|
||||
if base_name.len() > MAX_IDENTIFIER_LENGTH {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"Identifier '{}' exceeds the {} character limit.",
|
||||
base_name,
|
||||
MAX_IDENTIFIER_LENGTH
|
||||
)));
|
||||
}
|
||||
let table_name = {
|
||||
let trimmed = request.table_name.trim();
|
||||
validate_identifier_format(trimmed, "Table name")?;
|
||||
|
||||
let user_part_cleaned = request.table_name
|
||||
.replace(|c: char| !c.is_ascii_alphanumeric() && c != '_', "")
|
||||
.trim_matches('_')
|
||||
.to_lowercase();
|
||||
if trimmed.len() > MAX_IDENTIFIER_LENGTH {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"Table name '{}' exceeds the {} character limit.",
|
||||
trimmed,
|
||||
MAX_IDENTIFIER_LENGTH
|
||||
)));
|
||||
}
|
||||
|
||||
// New validation check
|
||||
if is_invalid_table_name(&user_part_cleaned) {
|
||||
return Err(Status::invalid_argument(
|
||||
"Table name cannot be 'id', 'deleted', 'created_at' or end with '_id'"
|
||||
));
|
||||
}
|
||||
// Check invalid table names on the original input
|
||||
if is_invalid_table_name(trimmed) {
|
||||
return Err(Status::invalid_argument(
|
||||
"Table name cannot be 'id', 'deleted', 'created_at' or end with '_id'"
|
||||
));
|
||||
}
|
||||
|
||||
if !user_part_cleaned.is_empty() && !is_valid_identifier(&user_part_cleaned) {
|
||||
return Err(Status::invalid_argument("Invalid table name"));
|
||||
} else if user_part_cleaned.is_empty() {
|
||||
return Err(Status::invalid_argument("Table name cannot be empty"));
|
||||
}
|
||||
trimmed.to_string()
|
||||
};
|
||||
|
||||
let mut tx = db_pool.begin().await
|
||||
.map_err(|e| Status::internal(format!("Failed to start transaction: {}", e)))?;
|
||||
|
||||
match execute_table_definition(&mut tx, request, base_name, sanitized_profile_name).await {
|
||||
match execute_table_definition(&mut tx, request, table_name, profile_name).await {
|
||||
Ok(response) => {
|
||||
tx.commit().await
|
||||
.map_err(|e| Status::internal(format!("Failed to commit transaction: {}", e)))?;
|
||||
@@ -184,12 +193,12 @@ async fn execute_table_definition(
|
||||
table_name: String,
|
||||
profile_name: String,
|
||||
) -> Result<TableDefinitionResponse, Status> {
|
||||
// CHANGED: Use schemas table instead of profiles table
|
||||
// Use the validated profile_name for schema insertion
|
||||
let schema = sqlx::query!(
|
||||
"INSERT INTO schemas (name) VALUES ($1)
|
||||
ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name
|
||||
RETURNING id",
|
||||
request.profile_name
|
||||
profile_name // Use the validated profile name
|
||||
)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
@@ -209,7 +218,7 @@ async fn execute_table_definition(
|
||||
// Check for duplicate link
|
||||
if !seen_tables.insert(link.linked_table_name.clone()) {
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"Duplicate link to table '{}'",
|
||||
"Duplicate link to table '{}'",
|
||||
link.linked_table_name
|
||||
)));
|
||||
}
|
||||
@@ -233,32 +242,34 @@ async fn execute_table_definition(
|
||||
|
||||
let mut columns = Vec::new();
|
||||
for col_def in request.columns.drain(..) {
|
||||
let col_name = sanitize_identifier(&col_def.name);
|
||||
if !is_valid_identifier(&col_def.name) {
|
||||
return Err(Status::invalid_argument("Invalid column name"));
|
||||
}
|
||||
let col_name = col_def.name.trim().to_string();
|
||||
validate_identifier_format(&col_name, "Column name")?;
|
||||
|
||||
if col_name.ends_with("_id") || col_name == "id" || col_name == "deleted" || col_name == "created_at" {
|
||||
return Err(Status::invalid_argument("Column name cannot be 'id', 'deleted', 'created_at' or end with '_id'"));
|
||||
return Err(Status::invalid_argument(format!(
|
||||
"Column name '{}' cannot be 'id', 'deleted', 'created_at' or end with '_id'",
|
||||
col_name
|
||||
)));
|
||||
}
|
||||
|
||||
let sql_type = map_field_type(&col_def.field_type)?;
|
||||
columns.push(format!("\"{}\" {}", col_name, sql_type));
|
||||
}
|
||||
|
||||
let mut indexes = Vec::new();
|
||||
for idx in request.indexes.drain(..) {
|
||||
let idx_name = sanitize_identifier(&idx);
|
||||
if !is_valid_identifier(&idx) {
|
||||
return Err(Status::invalid_argument(format!("Invalid index name: {}", idx)));
|
||||
}
|
||||
let idx_name = idx.trim().to_string();
|
||||
validate_identifier_format(&idx_name, "Index name")?;
|
||||
|
||||
if !columns.iter().any(|c| c.starts_with(&format!("\"{}\"", idx_name))) {
|
||||
return Err(Status::invalid_argument(format!("Index column {} not found", idx_name)));
|
||||
return Err(Status::invalid_argument(format!("Index column '{}' not found", idx_name)));
|
||||
}
|
||||
indexes.push(idx_name);
|
||||
}
|
||||
|
||||
let (create_sql, index_sql) = generate_table_sql(tx, &profile_name, &table_name, &columns, &indexes, &links).await?;
|
||||
|
||||
// CHANGED: Use schema_id instead of profile_id
|
||||
// Use schema_id instead of profile_id
|
||||
let table_def = sqlx::query!(
|
||||
r#"INSERT INTO table_definitions
|
||||
(schema_id, table_name, columns, indexes)
|
||||
@@ -273,7 +284,7 @@ async fn execute_table_definition(
|
||||
.await
|
||||
.map_err(|e| {
|
||||
if let Some(db_err) = e.as_database_error() {
|
||||
// CHANGED: Update constraint name to match new schema
|
||||
// Update constraint name to match new schema
|
||||
if db_err.constraint() == Some("idx_table_definitions_schema_table") {
|
||||
return Status::already_exists("Table already exists in this profile");
|
||||
}
|
||||
@@ -321,7 +332,7 @@ async fn generate_table_sql(
|
||||
indexes: &[String],
|
||||
links: &[(i64, bool)],
|
||||
) -> Result<(String, Vec<String>), Status> {
|
||||
// CHANGE: Quote the schema name
|
||||
// Quote the schema name
|
||||
let qualified_table = format!("\"{}\".\"{}\"", profile_name, table_name);
|
||||
|
||||
let mut system_columns = vec![
|
||||
@@ -331,7 +342,7 @@ async fn generate_table_sql(
|
||||
|
||||
for (linked_id, required) in links {
|
||||
let linked_table = get_table_name_by_id(tx, *linked_id).await?;
|
||||
// CHANGE: Quote the schema name here too
|
||||
// Quote the schema name here too
|
||||
let qualified_linked_table = format!("\"{}\".\"{}\"", profile_name, linked_table);
|
||||
let base_name = linked_table.split_once('_')
|
||||
.map(|(_, rest)| rest)
|
||||
|
||||
Reference in New Issue
Block a user