I am new to postgreSQL and I am trying to create a schema file which will contain all the scripts required to create the database and required tables. The way I used to do this for SQl server was to check if the database exists and then run the necessary scripts.
The following script in postgreSQL throws an error saying, "CREATE DATABASE cannot be executed from a function or multi-command string"
do $$
begin
If not exists (select 1 from pg_database where datname = 'TestDB')
Then
CREATE DATABASE "TestDB";
end if;
end
$$
I created a postgres database dump file by exporting a backup of the database but that contains,
Drop Database "TestDB"
Create Database "TestDB"
which means everytime I run the schema file, the database would be dropped and recreated and it would be a problem if there is data present in the database.
How do I check if the database exists in postgreSQL without having to drop the database and recreate it everytime I run the file please?
Thanks in Advance