Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a column to typed table without altering type in PostgreSQL?

Tags:

postgresql

I am using PostgreSQL 9.5, I have a TYPE which discribes a collection of columns:

CREATE TYPE datastore.record AS
   (recordid bigint,
    ...
    tags text[]);

I have created many tables reliying on this TYPE:

CREATE TABLE datastore.events
OF datastore.record;

Now I would like to add a column to a table which rely on this TYPE without updating the TYPE. I think it is impossible as this, thus I am wondering if there is a way to unbind my table from this TYPE without losing any data or copying the table into a temporary table?

like image 907
jlandercy Avatar asked Dec 27 '16 09:12

jlandercy


2 Answers

There is a special option not of for this purpose. Per the documentation:

NOT OF - This form dissociates a typed table from its type.

So:

alter table my_table not of;
alter table my_table add new_column integer;
like image 153
klin Avatar answered Sep 19 '22 12:09

klin


If you don't want to break relations:

--drop table if exists t2;
--drop table if exists t1;
--drop type if exists tp_foo;

create type tp_foo as (i int, x int);

create table t1 of tp_foo;
create table t2 (y text) inherits(t1);

alter type tp_foo add attribute z date cascade;

select * from t2;
like image 38
Abelisto Avatar answered Sep 17 '22 12:09

Abelisto