|
| 1 | +use crate::common::lazy::DB_SCHEMA; |
| 2 | +use crate::core::connection::DBConn; |
| 3 | +use crate::ts_generator::errors::TsGeneratorError; |
| 4 | +use crate::ts_generator::sql_parser::expressions::function_handlers::FunctionHandlersContext; |
| 5 | +use crate::ts_generator::sql_parser::expressions::translate_data_type::translate_value; |
| 6 | +use crate::ts_generator::sql_parser::expressions::translate_table_with_joins::translate_table_from_expr; |
| 7 | +use crate::ts_generator::sql_parser::quoted_strings::DisplayIndent; |
| 8 | +use crate::ts_generator::types::ts_query::TsFieldType; |
| 9 | +use sqlparser::ast::{Expr, FunctionArg, FunctionArgExpr, TableWithJoins, Value}; |
| 10 | + |
| 11 | +/// Extract key name from a function argument (should be a string literal) |
| 12 | +fn extract_key_name(arg: &FunctionArg) -> Option<String> { |
| 13 | + match arg { |
| 14 | + FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(val))) => match &val.value { |
| 15 | + Value::SingleQuotedString(s) | Value::DoubleQuotedString(s) => Some(s.clone()), |
| 16 | + _ => None, |
| 17 | + }, |
| 18 | + _ => None, |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +/// Extract expression from a function argument |
| 23 | +fn extract_expr_from_arg(arg: &FunctionArg) -> Option<&Expr> { |
| 24 | + match arg { |
| 25 | + FunctionArg::Unnamed(FunctionArgExpr::Expr(expr)) => Some(expr), |
| 26 | + FunctionArg::Named { |
| 27 | + arg: FunctionArgExpr::Expr(expr), |
| 28 | + .. |
| 29 | + } => Some(expr), |
| 30 | + _ => None, |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +/// Infer the TypeScript type from an SQL expression |
| 35 | +pub async fn infer_type_from_expr( |
| 36 | + expr: &Expr, |
| 37 | + single_table_name: &Option<&str>, |
| 38 | + table_with_joins: &Option<Vec<TableWithJoins>>, |
| 39 | + db_conn: &DBConn, |
| 40 | +) -> Option<(TsFieldType, bool)> { |
| 41 | + match expr { |
| 42 | + Expr::Identifier(ident) => { |
| 43 | + let column_name = DisplayIndent(ident).to_string(); |
| 44 | + if let Some(table_name) = single_table_name { |
| 45 | + let table_details = DB_SCHEMA.lock().await.fetch_table(&vec![table_name], db_conn).await; |
| 46 | + |
| 47 | + if let Some(table_details) = table_details { |
| 48 | + if let Some(field) = table_details.get(&column_name) { |
| 49 | + Some((field.field_type.to_owned(), field.is_nullable)) |
| 50 | + } else { |
| 51 | + Some((TsFieldType::Any, false)) |
| 52 | + } |
| 53 | + } else { |
| 54 | + Some((TsFieldType::Any, false)) |
| 55 | + } |
| 56 | + } else { |
| 57 | + Some((TsFieldType::Any, false)) |
| 58 | + } |
| 59 | + } |
| 60 | + Expr::CompoundIdentifier(idents) if idents.len() == 2 => { |
| 61 | + let column_name = DisplayIndent(&idents[1]).to_string(); |
| 62 | + if let Ok(table_name) = translate_table_from_expr(table_with_joins, expr) { |
| 63 | + let table_details = DB_SCHEMA |
| 64 | + .lock() |
| 65 | + .await |
| 66 | + .fetch_table(&vec![table_name.as_str()], db_conn) |
| 67 | + .await; |
| 68 | + |
| 69 | + if let Some(table_details) = table_details { |
| 70 | + if let Some(field) = table_details.get(&column_name) { |
| 71 | + Some((field.field_type.to_owned(), field.is_nullable)) |
| 72 | + } else { |
| 73 | + Some((TsFieldType::Any, false)) |
| 74 | + } |
| 75 | + } else { |
| 76 | + Some((TsFieldType::Any, false)) |
| 77 | + } |
| 78 | + } else { |
| 79 | + Some((TsFieldType::Any, false)) |
| 80 | + } |
| 81 | + } |
| 82 | + Expr::Value(val) => { |
| 83 | + if let Some(ts_field_type) = translate_value(&val.value) { |
| 84 | + Some((ts_field_type, false)) |
| 85 | + } else { |
| 86 | + Some((TsFieldType::Any, false)) |
| 87 | + } |
| 88 | + } |
| 89 | + _ => Some((TsFieldType::Any, false)), |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +/// Process key-value pairs from JSON build object arguments |
| 94 | +pub async fn process_json_build_object_args( |
| 95 | + args: &[FunctionArg], |
| 96 | + single_table_name: &Option<&str>, |
| 97 | + table_with_joins: &Option<Vec<TableWithJoins>>, |
| 98 | + db_conn: &DBConn, |
| 99 | +) -> Option<Vec<(String, TsFieldType, bool)>> { |
| 100 | + if !args.len().is_multiple_of(2) { |
| 101 | + // Invalid number of arguments |
| 102 | + return None; |
| 103 | + } |
| 104 | + |
| 105 | + let mut object_fields = vec![]; |
| 106 | + |
| 107 | + // Process key-value pairs |
| 108 | + for i in (0..args.len()).step_by(2) { |
| 109 | + let key_arg = &args[i]; |
| 110 | + let value_arg = &args[i + 1]; |
| 111 | + |
| 112 | + // Extract key name |
| 113 | + let key_name = extract_key_name(key_arg)?; |
| 114 | + |
| 115 | + // Extract value expression |
| 116 | + let value_expr = extract_expr_from_arg(value_arg)?; |
| 117 | + |
| 118 | + // Infer value type |
| 119 | + let (value_type, is_nullable) = |
| 120 | + infer_type_from_expr(value_expr, single_table_name, table_with_joins, db_conn).await?; |
| 121 | + |
| 122 | + object_fields.push((key_name, value_type, is_nullable)); |
| 123 | + } |
| 124 | + |
| 125 | + Some(object_fields) |
| 126 | +} |
| 127 | + |
| 128 | +/// Handle JSON build functions (jsonb_build_object, json_build_object, etc.) |
| 129 | +pub async fn handle_json_build_function( |
| 130 | + function_name: &str, |
| 131 | + args: &[FunctionArg], |
| 132 | + ctx: &mut FunctionHandlersContext<'_>, |
| 133 | +) -> Result<(), TsGeneratorError> { |
| 134 | + let expr_log = ctx.expr_for_logging.unwrap_or(""); |
| 135 | + |
| 136 | + // Handle jsonb_build_object / json_build_object / json_object (MySQL) |
| 137 | + let func_upper = function_name.to_uppercase(); |
| 138 | + if func_upper == "JSONB_BUILD_OBJECT" || func_upper == "JSON_BUILD_OBJECT" || func_upper == "JSON_OBJECT" { |
| 139 | + if let Some(object_fields) = |
| 140 | + process_json_build_object_args(args, ctx.single_table_name, ctx.table_with_joins, ctx.db_conn).await |
| 141 | + { |
| 142 | + let object_type = TsFieldType::StructuredObject(object_fields); |
| 143 | + return ctx |
| 144 | + .ts_query |
| 145 | + .insert_result(Some(ctx.alias), &[object_type], ctx.is_selection, false, expr_log); |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + // For other build functions or on failure, return Any |
| 150 | + ctx |
| 151 | + .ts_query |
| 152 | + .insert_result(Some(ctx.alias), &[TsFieldType::Any], ctx.is_selection, false, expr_log) |
| 153 | +} |
| 154 | + |
| 155 | +/// Handle JSON aggregation functions (jsonb_agg, json_agg, etc.) |
| 156 | +pub async fn handle_json_agg_function( |
| 157 | + args: &[FunctionArg], |
| 158 | + ctx: &mut FunctionHandlersContext<'_>, |
| 159 | +) -> Result<(), TsGeneratorError> { |
| 160 | + use super::super::functions::is_json_build_function; |
| 161 | + use sqlparser::ast::FunctionArguments; |
| 162 | + |
| 163 | + let expr_log = ctx.expr_for_logging.unwrap_or(""); |
| 164 | + |
| 165 | + // jsonb_agg typically takes a single expression |
| 166 | + if args.len() != 1 { |
| 167 | + return ctx |
| 168 | + .ts_query |
| 169 | + .insert_result(Some(ctx.alias), &[TsFieldType::Any], ctx.is_selection, false, expr_log); |
| 170 | + } |
| 171 | + |
| 172 | + let arg_expr = extract_expr_from_arg(&args[0]); |
| 173 | + |
| 174 | + // Check if the argument is a jsonb_build_object function |
| 175 | + if let Some(Expr::Function(inner_func)) = arg_expr { |
| 176 | + let inner_func_name = inner_func.name.to_string(); |
| 177 | + if is_json_build_function(inner_func_name.as_str()) { |
| 178 | + // Extract arguments from the inner function |
| 179 | + let inner_args = match &inner_func.args { |
| 180 | + FunctionArguments::List(arg_list) => &arg_list.args, |
| 181 | + _ => { |
| 182 | + return ctx |
| 183 | + .ts_query |
| 184 | + .insert_result(Some(ctx.alias), &[TsFieldType::Any], ctx.is_selection, false, expr_log); |
| 185 | + } |
| 186 | + }; |
| 187 | + |
| 188 | + // Process the inner jsonb_build_object |
| 189 | + if let Some(object_fields) = |
| 190 | + process_json_build_object_args(inner_args, ctx.single_table_name, ctx.table_with_joins, ctx.db_conn).await |
| 191 | + { |
| 192 | + let object_type = TsFieldType::StructuredObject(object_fields); |
| 193 | + let array_type = TsFieldType::Array(Box::new(object_type)); |
| 194 | + return ctx |
| 195 | + .ts_query |
| 196 | + .insert_result(Some(ctx.alias), &[array_type], ctx.is_selection, false, expr_log); |
| 197 | + } |
| 198 | + } |
| 199 | + } |
| 200 | + |
| 201 | + // If we can't infer the type, return Any |
| 202 | + ctx |
| 203 | + .ts_query |
| 204 | + .insert_result(Some(ctx.alias), &[TsFieldType::Any], ctx.is_selection, false, expr_log) |
| 205 | +} |
0 commit comments