| 1 | //===----------------------------------------------------------------------===// |
|---|---|
| 2 | // DuckDB |
| 3 | // |
| 4 | // duckdb/function/scalar_macro_function.hpp |
| 5 | // |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "duckdb/function/scalar_macro_function.hpp" |
| 10 | |
| 11 | #include "duckdb/function/macro_function.hpp" |
| 12 | #include "duckdb/parser/expression/constant_expression.hpp" |
| 13 | #include "duckdb/parser/parsed_expression_iterator.hpp" |
| 14 | |
| 15 | namespace duckdb { |
| 16 | |
| 17 | ScalarMacroFunction::ScalarMacroFunction(unique_ptr<ParsedExpression> expression) |
| 18 | : MacroFunction(MacroType::SCALAR_MACRO), expression(std::move(expression)) { |
| 19 | } |
| 20 | |
| 21 | ScalarMacroFunction::ScalarMacroFunction(void) : MacroFunction(MacroType::SCALAR_MACRO) { |
| 22 | } |
| 23 | |
| 24 | unique_ptr<MacroFunction> ScalarMacroFunction::Copy() const { |
| 25 | auto result = make_uniq<ScalarMacroFunction>(); |
| 26 | result->expression = expression->Copy(); |
| 27 | CopyProperties(other&: *result); |
| 28 | |
| 29 | return std::move(result); |
| 30 | } |
| 31 | |
| 32 | void RemoveQualificationRecursive(unique_ptr<ParsedExpression> &expr) { |
| 33 | if (expr->GetExpressionType() == ExpressionType::COLUMN_REF) { |
| 34 | auto &col_ref = expr->Cast<ColumnRefExpression>(); |
| 35 | auto &col_names = col_ref.column_names; |
| 36 | if (col_names.size() == 2 && col_names[0].find(s: DummyBinding::DUMMY_NAME) != string::npos) { |
| 37 | col_names.erase(position: col_names.begin()); |
| 38 | } |
| 39 | } else { |
| 40 | ParsedExpressionIterator::EnumerateChildren( |
| 41 | expr&: *expr, callback: [](unique_ptr<ParsedExpression> &child) { RemoveQualificationRecursive(expr&: child); }); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | string ScalarMacroFunction::ToSQL(const string &schema, const string &name) const { |
| 46 | // In case of nested macro's we need to fix it a bit |
| 47 | auto expression_copy = expression->Copy(); |
| 48 | RemoveQualificationRecursive(expr&: expression_copy); |
| 49 | return MacroFunction::ToSQL(schema, name) + StringUtil::Format(fmt_str: "(%s);", params: expression_copy->ToString()); |
| 50 | } |
| 51 | |
| 52 | void ScalarMacroFunction::SerializeInternal(FieldWriter &writer) const { |
| 53 | writer.WriteSerializable(element: *expression); |
| 54 | } |
| 55 | |
| 56 | unique_ptr<MacroFunction> ScalarMacroFunction::Deserialize(FieldReader &reader) { |
| 57 | auto result = make_uniq<ScalarMacroFunction>(); |
| 58 | result->expression = reader.ReadRequiredSerializable<ParsedExpression>(); |
| 59 | return std::move(result); |
| 60 | } |
| 61 | |
| 62 | } // namespace duckdb |
| 63 |