PostgreSQL自定义类型转换

示例以如下两个自定义类型转换:

drop table if exists test;
drop cast if exists (__hoperate as __operate);
drop cast if exists (__operate as __hoperate);
drop function if exists conv_hoperate_to_operate(__hoperate);
drop function if exists conv_hoperate_from_operate(__operate);
drop type if exists __hoperate;
drop type if exists __operate;

create type __operate as (
	uid bigint,
	gen timestamptz
);

create type __hoperate as (
	uid bigint,
	gen timestamptz,
	action integer
);

1 创建转换函数

drop cast if exists (__hoperate as __operate);
drop cast if exists (__operate as __hoperate);
drop function if exists conv_hoperate_to_operate(__hoperate);
drop function if exists conv_hoperate_from_operate(__operate);


create function conv_hoperate_to_operate(
	iparam __hoperate
) returns __operate
as $$
	select ((iparam).uid,(iparam).gen)::__operate;
$$ language sql immutable strict;

create function conv_hoperate_from_operate(
	iparam __operate
) returns __hoperate
as $$
	select ((iparam).uid,(iparam).gen,0)::__hoperate;
$$ language sql immutable strict;

2 创建转换

create cast (__hoperate as __operate) with function conv_hoperate_to_operate(__hoperate) as assignment;
create cast (__operate as __hoperate) with function conv_hoperate_from_operate(__operate) as assignment;

3 转换测试

with cte as(
	select (1::bigint,now())::__operate as x1,(1::bigint,now(),1)::__hoperate as x2
)select 
	x1::__hoperate,cast(x1 as __hoperate),
	x2::__operate,cast(x2 as __operate) 
from cte;

4 表字段使用自定义并且要转换为其它自类型

如果没有定义转换函数,会报以下错误

create table test(
	id bigint,
	ope __hoperate
);

--删除转换修改表类型报错
drop cast if exists (__hoperate as __operate);
drop cast if exists (__operate as __hoperate);
drop function if exists conv_hoperate_to_operate(__hoperate);
drop function if exists conv_hoperate_from_operate(__operate);

alter table test alter column ope type __operate using cast(ope as __operate);
ERROR:  cannot cast type __hoperate to __operate
第1行... table test alter column ope type __operate using cast(ope a...

如果我们按1、2步骤创建了转换,那么执行表类型转换就没有问题了。
再次执行字段类型转换成功。

alter table test alter column ope type __operate using cast(ope as __operate);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kmblack1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值