How do I get a postgres connection string for prisma2 framework

Goal

To create a postgresql connection string from the PLATFORM_RELATIONSHIPS environment variable.

Assumptions

  • You have nodejs installed in your container.
  • You have postgresql
  • You know how to work with prisma2

Problem

You can get database credentials using the $PLATFORM_RELATIONSHIPS variable
echo $PLATFORM_RELATIONSHIPS | base64 --decode | json_pp

See our documentation

But… the prisma2 framework assumes you have a postgresql connection string See prisma2 documentation.

Proposed solution

We can make a simple nodejs script that takes the base64 decoded string from PLATFORM_RELATIONSHIPS, and converts it into a postgresql connection string.

In a bash script, that would look like this:

$ DECODED_RELATIONSHIPS=$(echo $PLATFORM_RELATIONSHIPS | base64 --decode)
$ nodejs get_postgres_querystring.js $DECODED_RELATIONSHIPS postgresdatabase

postgres://main:main@postgresdatabase.internal:5432/main

Where the last variable, postgresdatabase, is the name of the relationship.
And get_postgres_querystring.js looks like this:

var myArgs = process.argv.slice(2);
var relationships = myArgs[0];
var db = myArgs[1];

var json_rel = JSON.parse(relationships);
var json_db = json_rel[db][0];
var url = "postgres://"+json_db["username"]+":"+json_db["password"]+"@"+json_db["host"]+":"+json_db["port"]+"/"+json_db["path"];

console.log(url);

Integrate into your environment

Create a .environment file

According to the documentation we can create an .environment file that allows us to set environment variables.

Create a .environment file and put what we have learned above in it, but add the output to an environment variable using export

$ DECODED_RELATIONSHIPS=$(echo $PLATFORM_RELATIONSHIPS | base64 --decode)
$ connect_string=$(nodejs qs.js $DECODED_RELATIONSHIPS postgresdatabase)
$ export PS_CON_STRING="$connect_string"

Using the environment variable

You can now use env("PS_CON_STRING") in your prisma2 configuration.

1 Like