static void deparseTypeCast()

in ext/pg_query/pg_query_deparse.c [3184:3249]


static void deparseTypeCast(StringInfo str, TypeCast *type_cast)
{
	bool need_parens = false;

	Assert(type_cast->typeName != NULL);

	if (IsA(type_cast->arg, A_Expr))
	{
		appendStringInfoString(str, "CAST(");
		deparseExpr(str, type_cast->arg);
		appendStringInfoString(str, " AS ");
		deparseTypeName(str, type_cast->typeName);
		appendStringInfoChar(str, ')');
		return;
	}

	if (IsA(type_cast->arg, A_Const))
	{
		A_Const *a_const = castNode(A_Const, type_cast->arg);

		if (list_length(type_cast->typeName->names) == 2 &&
			strcmp(strVal(linitial(type_cast->typeName->names)), "pg_catalog") == 0)
		{
			char *typename = strVal(lsecond(type_cast->typeName->names));
			if (strcmp(typename, "bpchar") == 0 && type_cast->typeName->typmods == NULL)
			{
				appendStringInfoString(str, "char ");
				deparseAConst(str, a_const);
				return;
			}
			else if (strcmp(typename, "bool") == 0 && IsA(&a_const->val, String))
			{
				/*
				* Handle "bool" or "false" in the statement, which is represented as a typecast
				* (other boolean casts should be represented as a cast, i.e. don't need special handling)
				*/
				char *const_val = strVal(&a_const->val);
				if (strcmp(const_val, "t") == 0)
				{
					appendStringInfoString(str, "true");
					return;
				}
				if (strcmp(const_val, "f") == 0)
				{
					appendStringInfoString(str, "false");
					return;
				}
			}
		}

		// Ensure negative values have wrapping parentheses
		if (IsA(&a_const->val, Float) || (IsA(&a_const->val, Integer) && intVal(&a_const->val) < 0))
		{
			need_parens = true;
		}
	}

	if (need_parens)
		appendStringInfoChar(str, '(');
	deparseExpr(str, type_cast->arg);
	if (need_parens)
		appendStringInfoChar(str, ')');

	appendStringInfoString(str, "::");
	deparseTypeName(str, type_cast->typeName);
}