1//===----------------------------------------------------------------------===//
2// DuckDB
3//
4// duckdb/planner/expression/bound_cast_expression.hpp
5//
6//
7//===----------------------------------------------------------------------===//
8
9#pragma once
10
11#include "duckdb/planner/expression.hpp"
12#include "duckdb/function/cast/default_casts.hpp"
13
14namespace duckdb {
15
16class BoundCastExpression : public Expression {
17public:
18 static constexpr const ExpressionClass TYPE = ExpressionClass::BOUND_CAST;
19
20public:
21 BoundCastExpression(unique_ptr<Expression> child, LogicalType target_type, BoundCastInfo bound_cast,
22 bool try_cast = false);
23
24 //! The child type
25 unique_ptr<Expression> child;
26 //! Whether to use try_cast or not. try_cast converts cast failures into NULLs instead of throwing an error.
27 bool try_cast;
28 //! The bound cast info
29 BoundCastInfo bound_cast;
30
31public:
32 LogicalType source_type() {
33 D_ASSERT(child->return_type.IsValid());
34 return child->return_type;
35 }
36
37 //! Cast an expression to the specified SQL type, using only the built-in SQL casts
38 static unique_ptr<Expression> AddDefaultCastToType(unique_ptr<Expression> expr, const LogicalType &target_type,
39 bool try_cast = false);
40 //! Cast an expression to the specified SQL type if required
41 DUCKDB_API static unique_ptr<Expression> AddCastToType(ClientContext &context, unique_ptr<Expression> expr,
42 const LogicalType &target_type, bool try_cast = false);
43 //! Returns true if a cast is invertible (i.e. CAST(s -> t -> s) = s for all values of s). This is not true for e.g.
44 //! boolean casts, because that can be e.g. -1 -> TRUE -> 1. This is necessary to prevent some optimizer bugs.
45 static bool CastIsInvertible(const LogicalType &source_type, const LogicalType &target_type);
46
47 string ToString() const override;
48
49 bool Equals(const BaseExpression &other) const override;
50
51 unique_ptr<Expression> Copy() override;
52
53 void Serialize(FieldWriter &writer) const override;
54 static unique_ptr<Expression> Deserialize(ExpressionDeserializationState &state, FieldReader &reader);
55};
56} // namespace duckdb
57