sqlpostgresqlpostgresql-9.1

how to move tables from public to other schema in Postgres


Postgres 9.1 database contains tables yksus1 .. ykssu9 in public schema. pgAdmin shows those definitions as in code below. How to move those tables to firma1 schema ?

Other tables in firma1 schema have foreign key references to those table primay keys. Foreign key references to those tables are only from tables in firma1 schema.

Some of those tables contain data. If tables is moved to firma1 schema, foreign key references shouuld also be updated to firma1.yksusn tables. Table structures cannot changed.

It looks like primary key sequences are already in firma1 schema so those should not moved. Version string PostgreSQL 9.1.2 on x86_64-unknown-linux-gnu, compiled by gcc-4.4.real (Debian 4.4.5-8) 4.4.5, 64-bit

CREATE TABLE yksus1
(
  yksus character(10) NOT NULL DEFAULT ((nextval('firma1.yksus1_yksus_seq'::regclass))::text || '_'::text),
  veebis ebool,
  nimetus character(70),
  "timestamp" character(14) DEFAULT to_char(now(), 'YYYYMMDDHH24MISS'::text),
  username character(10) DEFAULT "current_user"(),
  klient character(40),
  superinden character(20),
  telefon character(10),
  aadress character(50),
  tlnr character(15),
  rus character(60),
  CONSTRAINT yksus1_pkey PRIMARY KEY (yksus)
);
ALTER TABLE yksus1
  OWNER TO mydb_owner;

CREATE TRIGGER yksus1_trig
  BEFORE INSERT OR UPDATE OR DELETE
  ON yksus1
  FOR EACH STATEMENT
  EXECUTE PROCEDURE setlastchange();

other tables are similar:

CREATE TABLE yksus2
(
  yksus character(10) NOT NULL DEFAULT ((nextval('firma1.yksus2_yksus_seq'::regclass))::text || '_'::text),
  nimetus character(70),
  "timestamp" character(14) DEFAULT to_char(now(), 'YYYYMMDDHH24MISS'::text),
  osakond character(10),
  username character(10) DEFAULT "current_user"(),
  klient character(40),
  superinden character(20),
  telefon character(10),
  aadress character(50),
  tlnr character(15),
  rus character(60),
  CONSTRAINT yksus2_pkey PRIMARY KEY (yksus),
  CONSTRAINT yksus2_osakond_fkey FOREIGN KEY (osakond)
      REFERENCES yksus2 (yksus) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE NO ACTION DEFERRABLE INITIALLY IMMEDIATE
);
ALTER TABLE yksus2
  OWNER TO mydb_owner;

CREATE TRIGGER yksus2_trig
  BEFORE INSERT OR UPDATE OR DELETE
  ON yksus2
  FOR EACH STATEMENT
  EXECUTE PROCEDURE setlastchange();

Solution

  • ALTER TABLE yksus1
        SET SCHEMA firma1;
    

    More details in the manual: http://www.postgresql.org/docs/current/static/sql-altertable.html

    Associated indexes, constraints, and sequences owned by table columns are moved as well.

    Not sure about the trigger function though, but there is an equivalent ALTER FUNCTION .. SET SCHEMA ... as well.