Use PostgreSQL database in SQL script - postgresql

I'm creating 3 databases from a single file:
CREATE DATABASE "products"
WITH
OWNER = postgres
ENCODING = "UTF8"
CONNECTION LIMIT = -1
IS_TEMPLATE = False;
CREATE DATABASE "accounts"
WITH
OWNER = postgres
ENCODING = "UTF8"
CONNECTION LIMIT = -1
IS_TEMPLATE = False;
CREATE TYPE role as ENUM ('employee', 'admin', 'customer');
Now I would like the type role to be created in the accounts database. The current script just creates the role in the 'default' postgres DB. I am used to MySQL syntax where I could use the 'use ' command. Any idea how I can use a similar command for a PostgreSQL script?
For additional context: this SQL file is executed in a PostgreSQL docker container upon initialisation.
I tried the following:
use the 'use' command. -> not recognised.
use the 'select' command. -> invalid.

In PostgreSQL you have to specify the database when you open a connection to the server. You can not switch to a different database using SQL.
From the documentation of the low-level API for opening connections:
An application program can have several backend connections open at one time. (One reason to do that is to access more than one database.)
But as #a_horse_with_no_name already pointed out if you are using psql you can use the command \connect to open a new connection to a different database.

Related

How to DROP tables from specific database-schema in Postgresql?

I am new to Postgresql and so far I have not found a way to drop a table from specific database. To give some context:
We are doing a synchronization from Oracle to PostgreSQL of 5 tables. In postgres I have a database SoloCopy and the schema is the default public. In the Postgresql instance we have also 2 more databases SoloSynch and postgres (the default one).
What I want to do is to select SoloCopy database and:
DROP TABLE public.table1;
When I do the above DROP statement table1 is deleted only from the database that was selected when opening SQL Query. But I want to specify the database before that and to be irrelevant from where the SQL Query was open. How can I do that?
I found an answer on my own. Setup can be found here:
Psql in Task Scheduler does not run a file script
Basically I needed to use PSQL and with the connection string there I connect to a specific DB, which I can drop the tables from. The details for PGPASSWORD and the .bat file I ended up creating are in the link above. Had to start everything from CMD and switch to psql from there.

postgresql database creation script

Long time user of sql server, i'm migrating to postgresql.
In sql server, i was able to script the entire database (drop/create), table create (...) from a single file as the GO keyword is a batch separator.
In postgresql,
DROP DATABASE "appweb";
CREATE DATABASE "appweb"
WITH
OWNER = postgres
ENCODING = 'UTF8'
CONNECTION LIMIT = -1;
Result error database drop cannot run inside a transaction block
How i can do this in postgresql ?
Thanks

PostgreSQL 13: create empty copy of database

I have a AWS RDS PostgreSQL 13 server with some databases. I have to create an empty copy of one database (empty means schema (tables, views, functions) + security (users, roles)).
Is pg_dump -s what I am looking for?
Thanks!
pg_dump -d db_name -s. You will also need to do pg_dumpall -g to get the global data e.g. roles. This will get all global data for the Postgres cluster, so you may have more then you need for the particular database.
Postgres allows the use of any existing database on the server as a template when creating a new database. I'm not sure whether pgAdmin gives you the option on the create database dialog but you should be able to execute the following in a query window if it doesn't:
CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER dbuser;
Still, you may get:
ERROR: source database "originaldb" is being accessed by other users
To disconnect all other users from the database, you can use this query:
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'originaldb' AND pid <> pg_backend_pid();

How to move/switch one database to another database using shell script(psql)?

How can I move or switch one database to another database using PostgreSQL 9.3 version in shell script(psql)?
Example:
testdb=#
to
mydb=#
If you mean in a script sourced by psql via -f or \i, you can use the command \connect (shorthand \c).
It doesn't just switch databases, it actually disconnects and reconnects. Any SET commands, etc, are not preserved across reconnection.
Simply use below statement:
\c database name

Trying to rename a database in Redshift cluster

I'm trying to rename a database in my Redshift cluster.
You cannot rename the database when you're connected to it so I've created a temporary database, reconnected with SQL Workbench to the temporary db and issued:
ALTER DATABASE olddb RENAME to newdb;
I get an error stating ERROR: database "olddb" is being accessed by other users [SQL State=55006]
I've checked who is connected and there appear to be some connections from user rdsdb to the database. I assume this is a service account that AWS Redshift use to perform maintenance tasks etc.
How can I rename the database when this superuser is connected?
Many thanks.
You cannot alter the name of (or delete!) the database that is created during the initial cluster creation. I don't believe this is mentioned in the docs but I've confirmed it with them.
We can change the database name which is already created.
Detailed steps on how to do
Connect to the old database and create a new database if you do not have another one already.
create database databasebasename
In this example, I will call the databasename as 'newdb'.
Connect to newdb using connecting string as, jdbc:redshift://.us-east-1.redshift.amazonaws.com:8192/newdb, with the same password and username of your superuser (or the other eligible users as mentioned above).
Now you can alter the database name. Substitute 'database_name_new' with the desired databasename.
alter database old-db-name rename to database_name_new;
If there are any active sessions, you'll have to kill them. To find the pid of active sessions:
select * from STV_SESSIONS where user_name='rdsdb';
Then to kill a session:
SELECT
pg_terminate_backend(<pid>)
FROM
pg_stat_activity
WHERE
-- don't kill my own connection!
procpid <> pg_backend_pid()
-- don't kill the connections to other databases
AND datname = '<old-db-name>';
Once complete, you can connect back to that new database using the new name in the connection string as
jdbc:redshift://<cluser-id>.us-east-1.redshift.amazonaws.com:8192/database_name_new
You can delete the temporary 'newdb'.
drop database databasebasename
That's possible now -- I just renamed the database that was created during the initial cluster creation.
We had a similar situation.
Step 1: Connect to the database which is not the one you are trying to rename. Check the same by executing SELECT CURRENT_DATABASE();.
Step 2: Execute the query below -
SELECT
ss.*, 'select pg_terminate_backend('||process||');'
FROM
stv_sessions ss
ORDER BY
db_name;
The output of the query will have a column at the end with the select statements. Execute those to kill the sessions.
Step 3(Optional): If you are not the owner of the database try to modify the ownership of the database -
ALTER DATABASE <database to be renamed>
OWNER TO <user which is going to do the rename>;
Step 4: Rename the database