微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PostgreSQL中的派生类型

是否可以从类型中创建“派生类型”?就像在 Java中扩展一样.

例如,我需要这些类型:

create type mytype as (
    f1 int,--many other fields...
    fn varchar(10)
);

create type mytype_extended as (
    f1 int,--many other fields...
    fn varchar(10),fx int --one field more
);

你可以看到这是多余的.如果将来我改变了mytype,我也需要更改mytype_extended.

我试过这个:

create type mytype as (
    f1 int,--many other fields...
    fn varchar(10)
);

create type mytype_extended as (
    mt mytype,fx int --one field more
);

但这导致mytype_extended只有2个字段,mt(我认为是复杂类型)和fx,而不是f1,f2 … fn,fx.

有没有办法实现这个目标?

解决方法

在Postgresql中,没有直接的类型继承,但是你有几个选择:

1. Table inheritance

您可以创建继承表来创建继承类型(Postgresql将始终为每个表创建一个具有相同名称的复合类型):

create table supertable (
  foo   int,bar   text
);

create table subtable (
  baz   int
) inherits (supertable);

2. Construct views using each other

因为视图(实际上)是表(使用rules),所以也为每个表创建一个类型:

create view superview
  as select null::int  foo,null::text bar;

create view subview
  as select superview.*,null::int  baz
     from   superview;

3. Type composition

这就是你尝试过的.一般来说,你对这个有更多的控制权:

create type supertype as (
  foo   int,bar   text
);

create type subtype as (
  super supertype,baz   int
);

-- resolve composition manually
select get_foo(v),-- this will call get_foo(subtype)
       get_foo((v).super) -- this will call get_foo(supertype)
from   (values (((1,'2'),3)::subtype)) v(v);

 1真正的类型继承?

PostgreSQL’s documentation explicitly says,表继承不是标准的类型继承:

sql:1999 and later define a type inheritance feature,which differs in many respects from the features described here.

尽管如此,继承表的自动创建类型确实像真正的继承类型一样工作(可以使用它们,可以使用超类型):

-- if there is a get_foo(supertable) function,-- but there is no get_foo(subtable) function:

select get_foo((1,'2')::supertable);  -- will call get_foo(supertable)
select get_foo((1,'2',3)::subtable); -- will also call get_foo(supertable)

SQLFiddle

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐