Automatically point to PR preview database

PR previews create a preview database. How can we automatically point our app to that?

The render.yaml has:

    envVars:
      - key: DATABASE_URL
        fromDatabase:
          name: staging
          property: connectionString

but I can’t think of a way to use previewValue to automagically point to the preview database since it’s created with an incremental number (of the PR) for the name.

How would you go about it?

Hey Oleg,

Welcome to the Render community!

I think you may be using https://render.com/docs/pull-request-previews, however you might want give Preview Environments | Render · Cloud Hosting for Developers a try as these will create a full environment for you and achieve what you want I think

Hey Oleg,

I am not a render.com staff, just one of their users. So, with a configuration looking something like this:

# render.yaml
previewsEnabled: true # this is important

databases:
  - name: staging
    plan: standard

services:
  - name: api
    type: web
    env: elixir
    envVars:
      - key: DATABASE_URL
        fromDatabase:
          name: staging
          property: connectionString
  # ...and so on

Your api service will have DATABASE_URL environment variable pointing to a staging DB normally, but for a preview environment (for a pull request), it will point to a PR version of that database created specifically for that PR. It’s done automatically. There’s nothing more you have to do on your side.

So for example in my Elixir application, I just need something like this and that is it.

# config/releases.exs
config :my_app, MyApp.Repo,
  adapter: Ecto.Adapters.Postgres,
  url: System.fetch_env!("DATABASE_URL")

Hope this helps.

2 Likes

Thanks for the replies. Apologies for the lack of detail but I am using the previewsEnabled: true but that was master and hence this might have caused the misalignment. Just rebased my PR onto master and will keep you updated.

2 Likes

I am having other issues about the preview environment but this seems to be resolved as per @stefan.luptak reply, i.e. the preview environment automagically points to the preview database.

1 Like