473,410 Members | 1,946 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,410 software developers and data experts.

create database test if not exists

9
create database test if not exists. Someone know how to do this in postgreSQL?
Dec 15 '06 #1
7 58477
michaelb
534 Expert 512MB
I think the least known part here is finding out whether database exists.
Here you can try something like this:

Expand|Select|Wrap|Line Numbers
  1. select count(*) from pg_catalog.pg_database where datname = 'test' ;
To create database you'll use the CREATE DATABASE command:
Expand|Select|Wrap|Line Numbers
  1. CREATE DATABASE name
  2.     [ [ WITH ] [ OWNER [=] dbowner ]
  3.            [ LOCATION [=] 'dbpath' ]
  4.            [ TEMPLATE [=] template ]
  5.            [ ENCODING [=] encoding ] ]
  6.  
(this part is well documented in Postgres manual)
Let me know if you have more questions.
Dec 17 '06 #2
olav78
9
Thank you. The problem is how to use "if" or "case" before create database... i've created a plpgsql function, but this seems to only work from the command prompt and not trough jdbc...

Expand|Select|Wrap|Line Numbers
  1. CREATE OR REPLACE FUNCTION createdbtest() RETURNS void AS $t$
  2. BEGIN
  3.     SELECT datname FROM pg_database WHERE datname='test'';
  4.     IF datname='test' 
  5.         THEN CREATE DATABASE test PASSWORD 'test';
  6.     END IF;
  7. END;
  8. $t$ LANGUAGE plpgsql;
  9.  
is it possible to do this without using a pl-function?
Dec 18 '06 #3
olav78
9
forget the last post. I almost found a solution using a pl/pgsql function. but i get this error: "ERROR: CREATE DATABASE
cannot be executed from a function"...

It works fine when i try to create a new role (only when it does not exists) though.

here is the code:
Expand|Select|Wrap|Line Numbers
  1. CREATE OR REPLACE FUNCTION createusertest() RETURNS void AS '
  2. DECLARE user_rec RECORD;
  3. BEGIN
  4. select into user_rec * FROM pg_user WHERE usename=''test''; 
  5. IF user_rec.usename IS NULL THEN CREATE USER test PASSWORD ''test'';
  6. END IF;
  7. END;
  8. ' LANGUAGE plpgsql;
  9.  
the big question is: how can i create a new database when it does not exists and at the same time not getting an error when it exists?
Dec 18 '06 #4
michaelb
534 Expert 512MB
Do you really have to employ the function here, or to be more to the point do you HAVE to run it all in a single shot?

I assume you have some backend process, which gets the database name from GUI, or some other source. At this point you can run the SQL I posted earlier to find out whether the database with given name exists.
If it does, issue the appropriate warning, or error message.
If not run the sql to create database.

The only possible catch here ir a race condition which may take place when different processes would attempt to check on the same name and create database at the same time... but this can (probably) happen even if you pack your code in a single module.

Am I missing something?
Dec 18 '06 #5
olav78
9
Sorry for not being very specific. We have a sql ant task, only used in development, where we set up the database. This task shall run both when the database does exist and when it does not. So we can’t do something like if(not exists){ create database}, because we call a “pure” sql script from the ant task. We have to do this in sql or pl/pgsql or something I guess. But it seems like I can’t create a database from inside a function, and I can’t use (sql) CASE either, so I’m kind of lost…

It was so easy in MySQL :(, but anyway I still like postgres better ;)
Dec 18 '06 #6
olav78
9
well, i found a not very elegant solution. Set onerror="continue" in the ant sql-task. it still generates error when the database exists offcourse, but it works ok i guess...
Dec 19 '06 #7
michaelb
534 Expert 512MB
Optionally you can try to run a shell script in this task.
This is not a very elegant solution either :(
I don't really like it, but perhaps its worth trying.
Here's the basic idea
Expand|Select|Wrap|Line Numbers
  1. #!/bin/sh
  2. ########################################################
  3. # - create a test database if it does not exist.
  4. # if necessary some variables may be passed
  5. # with arguments; db password, path to psql,
  6. # name of the database, db owner... anything else
  7. #-----------------------------------------------------
  8.  
  9. # if we get the db password, we put it in our temp
  10. # env., otherwise psql may pause and prompt for it.
  11. if [ "$1" ] ; then
  12.    export PGPASSWORD="$1"
  13. fi
  14.  
  15. # may check the args to see if dbname
  16. # was provided
  17. dbname=test
  18.  
  19. # sql to check whether given database exist
  20. sql1="select count(1) from pg_catalog.pg_database where datname = '$dbname'"
  21.  
  22. # sql to create database (add other params as needed)
  23. sql2="create database $dbname"
  24.  
  25. # depending on how PATH is set psql may require a fully qualified path
  26. cmd="psql -t -c \"$sql1\""
  27.  
  28. db_exists=`eval $cmd`
  29.  
  30. if [ $db_exists -eq 0 ] ; then
  31.    # create the database, discard the output
  32.    cmd="psql -t -c \"$sql2\" > /dev/null 2>&1"
  33.    eval $cmd
  34. fi
  35.  
  36. # exit with success status
  37. exit 0
  38.  
  39.  
Dec 19 '06 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Frank | last post by:
I can use mysqldump to create a .sql file backup of my data.. For importing how can I test to see if the DB exists, if it does import the .sql If not create the DB then import the .sql ! ...
4
by: Phil Powell | last post by:
create table if not exists nnet_produkt_varegruppe ( nnet_produkt_varegruppe_id int not null auto_increment, primary key(nnet_produkt_varegruppe_id), nnet_produkt_varegruppe_navn varchar(255) not...
3
by: geoff | last post by:
Is there a stored procedure installed by sql server 2000 that I can call and just pass in the name of a new database and have it create the database for me? If not, how do I do it in sql? Thanks.
6
by: news.dsl.pipex.com | last post by:
Hi I have a front/back end scenario for my access app. I need to allow user to connect the front end to one of two back ends at start time. Presumably this needs linking to the relevant back end...
9
by: Peter | last post by:
Hello£¬everyone, My program will collect a testing machine's data ,save the data and deal with the data everyday. I want to use vb.net to create database, add and delete tables or modify the...
17
by: Chris Podmore | last post by:
When I perform: EventLog.WriteEntry(strSource, strEntry, EventLogEntryType.Error, intEventID) The event viewer reports The description for Event ID ( 234 ) in Source ( Siclops_WS_Mobile )...
4
by: M Bourgon | last post by:
I have two SPs, call them Daily and Weekly. Weekly will always call Daily, but Daily can run on its own. I currently use a global temp table because certain things I do with it won't work with a...
3
by: teddysnips | last post by:
I have a need to create a database, and then populate it. However, the code below doesn't work as I hoped it might (it creates the table in the "master" database, which is Not A Good Thing). I...
10
by: AAaron123 | last post by:
I want to create a database with one table on the host. I can't user SQL Server Management Studio to do it so I guess I have to do it programmatically. I have in mind that in the session start...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.