postgresqlinsertcross-database

INSERT across Databases in PostgreSQL


I'm trying to do an INSERT from one database to another, eg:

//called in database 'model'
INSERT INTO login.Hospital (name, phonenumber) --EDIT, now Hospital
VALUES ('Foo Bar', '555-555-5555');

I get this error:

"null value in column "id" violates not-null constraint"

Where column id is a primary key on table People that auto-increments.

Is there a reason PG won't auto-increment id when doing an insert cross-database? Is there a 'recommended' way around this?

Thank you.

--EDIT-- For clarification: I have 2 databases, model and login each with a schema of dbo. Login has a schema called login which is for a Foreign Data Wrapper. The goal is from my database: model, call a Login database table using the schema login for tables we've imported (eg INSERT INTO login.hospitals... etc)

For all intents and purposes this Hospital table is created like this:

CREATE TABLE People(ID SERIAL NOT NULL, name TEXT, phonenumber TEXT);

I hope this clarifies any issues.


Solution

  • While searching I discovered these solutions:

    https://www.postgresql.org/message-id/26654.1380145647%40sss.pgh.pa.us http://www.slideshare.net/jkatz05/developing-and-deploying-apps-with-the-postgres-fdw

    These essentially involve creating a foreign table and maintaining two tables, something I wanted to avoid.

    So, my solution was to create a trigger on the source DB (eg Login) for each table that is called from the calling DB (eg Model). This trigger would be fired before an INSERT and call a trigger function. The trigger function looks like this:

    CREATE OR REPLACE FUNCTION dbo.tf_insert_cross_schema()
    RETURNS TRIGGER AS
    $$
    DECLARE
        sequenceName TEXT = 'dbo.' || TG_TABLE_NAME || '_id_seq';
    
    BEGIN
        IF (NEW.id IS NULL) THEN
            NEW.id = (SELECT nextval(sequenceName));
        END IF;
    
        RETURN NEW;
    END;
    $$
    LANGUAGE PLPGSQL VOLATILE;
    

    Thanks!