0

I have multiple database, each has table "authentication". In each table I want to drop a constraint and replace it with a new one. That would be great if I had not to do that manually.

ALTER TABLE authentication DROP CONSTRAINT  uk_authentication_01;
ALTER TABLE authentication ADD CONSTRAINT uk_authentication_01 UNIQUE (authenticator, method);

is there a way to do a bulk alter with a script?

2

2 Answers 2

2

You could iterate over your databases in a shell script:

for db in dbname1 dbname2 dbname3...
do
 psql -d $db -U username << EOF
ALTER TABLE authentication DROP CONSTRAINT  uk_authentication_01;
ALTER TABLE authentication ADD CONSTRAINT uk_authentication_01 UNIQUE (authenticator, method);
EOF
done
Sign up to request clarification or add additional context in comments.

Comments

0

I assume that all databases are on the same server? If that is true you can simply do the SELECT:

SELECT 'SELECT * FROM  dblink_exec(''dbname=' || datname 
         || '''::text, ''ALTER TABLE authentication 
         DROP CONSTRAINT  uk_authentication_01;
         ALTER TABLE authentication ADD CONSTRAINT uk_authentication_01 
         UNIQUE (authenticator, method);''::text);'
FROM pg_database WHERE datistemplate = false;

Then copy the result of this query and run it.

And you'll need for that dblink extension:

CREATE EXTENSION dblink;

6 Comments

yes, they are on the same servlet. Let me try it out, if works I'll be back to accept as the right answer.
Sadly, it does not seem to be working. Can we stick to the bare essentials? Let's say I just want to drop the first constraint and I want to perform it on only two databases baml1 and baml2. Those are on the same server.
Have you installed the extension first?
When you run just - SELECT datname FROM pg_database WHERE datistemplate = false; Do you get the list of dbs?
CREATE EXTENSION dblink; ERROR: could not open extension control file "/usr/pkg/share/postgresql/extension/dblink.control": No such file or directory
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.