use ordermap::OrderMap;
use crate::TranslationRegistry;
use hamelin_lib::func::defs::{ParseJsonString, ParseJsonVariant, ToJsonString, Typeof};
use hamelin_lib::sql::expression::apply::FunctionCallApply;
use hamelin_lib::sql::expression::identifier::SimpleIdentifier;
use hamelin_lib::sql::expression::literal::{RowLiteral, StringLiteral};
use hamelin_lib::sql::expression::Cast;
use hamelin_lib::sql::types::{SQLBaseType, SQLRowType};
pub fn register(registry: &mut TranslationRegistry) {
registry.register::<ParseJsonString>(|_, mut bindings| {
let json = bindings.take()?;
Ok(
FunctionCallApply::with_two("json_extract", json.sql, StringLiteral::new("$").into())
.into(),
)
});
registry.register::<ParseJsonVariant>(|_, mut bindings| bindings.take().map(|t| t.sql));
registry.register::<ToJsonString>(|_, mut bindings| {
let json = bindings.take()?;
Ok(FunctionCallApply::with_one("json_format", json.sql).into())
});
registry.register::<Typeof>(|_, mut bindings| {
let expr = bindings.take()?;
let row_literal = RowLiteral::new(vec![
StringLiteral::new(&expr.typ.to_string()).into(),
FunctionCallApply::with_one("typeof", expr.sql).into(),
]);
let mut fields = OrderMap::new();
fields.insert(
SimpleIdentifier::new("hamelin_type"),
SQLBaseType::VarChar.into(),
);
fields.insert(
SimpleIdentifier::new("sql_type"),
SQLBaseType::VarChar.into(),
);
let row_type = SQLRowType::new(fields);
Ok(Cast::new(row_literal.into(), row_type.into()).into())
});
}