postgresql database creation script - postgresql

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

Related

Use PostgreSQL database in SQL script

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.

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.

Convert dbeaver create table script into sql server script

I have to migrate some table from Database informix (i'm using dbeaver for it) to Sql server.
When i click on table to create DDL script , it's different script than sql server create table script.
Does anyone know the hack that how we can generate sql server create table script from dbeaver tables.
Thanks

Drop DB2 database if exist

I would like to write db2 command which find out first database exist or not and if exist that data base then drop this database and create a new updated database .
Please help for same
There is not a command or language in DB2 that support that instruction. You have to define what to do when the given name exist as an alias of a database (not the real name of the database), drop the alias? rename it?
The script will look like:
List the database directory and filter the name and the alias (db2 list db directory). Filtering can be done in linux with Awk or Grep, in Windows with Filter.
If there is a database alias with that name, then YOU decide what to do.
Instead if there is a database name with that name, then drop it (db2 drop db xxx)
Create the database.
If there is an error of existent database in the system (SQL1005N), then catalog it and drop it (db2 catalog db xxx, db2 drop db xxx)
Retry the database creation.
First query system table, in db2 for zos table SYSIBM.SYSDATABASE or SYSIBM.SYSTABLES, in db2 LUW version table SYSCAT.tables . If there are rows in query, database exists.
In LUW, you can do:
--#SET TERMINATOR #
BEGIN
DECLARE TABLE_NOT_FOUND CONDITION FOR SQLSTATE '42704';
DECLARE CONTINUE HANDLER FOR TABLE_NOT_FOUND;
EXECUTE IMMEDIATE 'DROP TABLE myschema.mytable';
END #
You can convert this snippet into a function that receives the schema name and table name.
calling this function will let you drop the table if exist:
CALL FNC.DROP_IF_EXISTS('TABLENAME')!

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