当前位置: 首页 > news >正文

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);

http://www.mrgr.cn/news/11482.html

相关文章:

  • 前端宝典十四:Node缓存、安全与鉴权
  • vue之函数式组件
  • 溺水检测数据集 代码在博客
  • 在野漏洞的应急响应流程
  • 国产数据库对比与分析
  • tornado一个请求对应一个实例
  • 基于图神经网络的EEG分类
  • 实用攻略:亲身试用,高效数据恢复软件推荐!
  • qt在ui上面给QWidget设置布局
  • 1. Java集合框架的主要接口有哪些?它们之间的关系是什么?
  • 数据结构-KMP算法
  • 团队管理之敏捷开发
  • 新零售社交电商系统案例分析
  • 数学建模学习(126):基于Python的最优最劣法(BWM)在多标准决策中的应用
  • RIP路由信息协议
  • Linux磁盘管理
  • 区块链应用,密码学会议书籍推荐以及隐私保护知识整理
  • 主流的工厂仓库管理系统 ERP 有哪些值得推荐?
  • 鸿蒙项目目录
  • C++ 设计模式——单例模式