Question

Searching the web for a solution to create a database for my spring project when it doesn't exist, I found this topic here in stackoverflow:

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

with this stored procedure to acomplish that:

DO
$do$
BEGIN

IF EXISTS (SELECT 1 FROM pg_database WHERE datname = 'mydb') THEN
   RAISE NOTICE 'Database already exists'; 
ELSE
   PERFORM dblink_exec('dbname=' || current_database() -- current db
                      , $$CREATE DATABASE mydb$$);
END IF;

END
$do$

I want run this procedure from my Java code. My initial idea was include this code as a String atribute in this Service class:

@Service
public class InstallService {

    private String query = "";

    public boolean create_database(String maquina, String usuario, String senha) {
        return false;
    }

    public boolean create_user(String usuario, String senha, String email) {
        return false;
    }
}

But I just find out this can't be done. Anyone have any sugestion of how to do that inside this class?

Was it helpful?

Solution

I would recommend calling the stored procedure via whatever method you're currently using to connect to Postgres from Spring. (i.e. Spring JDBC: http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html; or perhaps MyBatis, etc.)

You could define the stored procedure in, say, the template database, and then connect to it via Spring JDBC or whatever method you're employing, with a query of the form:

SELECT stored_proc_name(dbname)

(You would need to have the stored procedure take the DB name as an argument, also.)

Edit: In response to the comment below, inquiring if this can be done without adding anything to a database, the answer is yes:

You could connect to the template1 DB, run the SELECT query against pg_catalog to see if the DB exists (you'll get an empty set back if it doesn't), and if it doesn't exist, run another query on the connection to the template1 db to create the DB.

Basically, it'd be deconstructing the stored procedure into its constituent parts and calling them directly from Java using JDBC or similar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top