Heroku DATABASE_URL as a JDBC Url for Maven

≯℡__Kan透↙ 提交于 2019-12-04 16:54:04

I have solved this thanks to heroku support. Lukas and Axel you may want to document this for any of your users that are using heroku, want to run your tools in their build (vs code startup), and do not want to hand maintain different environment variables.

We will be using the GMavin Plus Plugin to run some code to parse the DATABASE_URL environment variable into properties prior to running the flyway migration or jOOQ code generation.

First off you need to add Groovy as a dependency:

<dependency>
  <groupId>org.codehaus.groovy</groupId>
  <artifactId>groovy-all</artifactId>
  <version>2.3.9</version>
  <scope>compile</scope>
</dependency>

Then the GMaven plus plugin:

<plugin>
  <groupId>org.codehaus.gmavenplus</groupId>
  <artifactId>gmavenplus-plugin</artifactId>
  <version>1.2</version>
  <executions>
    <execution>
      <phase>initialize</phase>
      <goals>
        <goal>execute</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <scripts>
      <script><![CDATA[
        URI dbUri = new URI(System.getenv("DATABASE_URL"));

        String username = dbUri.getUserInfo().split(":")[0];
        String password = dbUri.getUserInfo().split(":")[1];
        int port = dbUri.getPort();

        String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ":" + port + dbUri.getPath();

        project.properties['database.jdbcUrl']=dbUrl
        project.properties['database.username']=username
        project.properties['database.password']=password
        ]]></script>
      </scripts>
    </configuration>
</plugin>

Now you can use ${database.jdbcUrl}, ${database.username}, and ${database.password} in your flyway, jOOQ, or whatever else configurations.

There are probably myriad ways to solve this with Maven, but one option is to keep a single properties file in your /src/main/resources path, load it using the properties-maven-plugin (an example can be seen in the jOOQ-Spring example), and then compose URLs using the individual parts, e.g. jOOQ and Flyway:

<url>jdbc:postgresql://${db.host}:${db.port}/${db.database}</url>
<user>${db.username}</user>
<password>${db.password}</password>

Heroku:

<database_url>postgres://${db.username}:${db.password}@${db.host}:${db.port}/${db.database}</database_url>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!