Skip to content
Advertisement

Create new PostgresSQL schema

What’s the easiest way to create a new Postgres scheme inside the database on the runtime and also, create the tables written inside a SQL file?

This is a Spring boot application and the method receives the schema name that needs to be created for the db.

Advertisement

Answer

Although it sounds like this would be a case for using Liquibase or Flyway or any other tool, here is a simple (but very hacky) solution/starting point:

(rough) Steps:

  • create the whole ddl query, which consists of the “create and use schema part” and the content of your SQL file
  • inject the entity manager
  • run the whole ddl query as a native query

Example/(hacky) Code:

Here a simple controller class defining a GET method that takes a parameter called “schema”:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement