Mysterious Postgres connection bug

2 min read Original article ↗

Aviraj Khare

Press enter or click to view image in full size

Postgres image

This wierd thing happened with me today where I was unable to run some migrations of my Django app.

So I created new database, filled up correct environment variables and again, same issue was happening.

Here is screenshot of the issue.

Press enter or click to view image in full size

issue with migration

Since I created a new container for postgres. It shouldn’t happen. I started to dig deep.

First step was to check all my enviroment variables that looks like this.

PGDATABASE="pillow"
PGPASSWORD="pillowconnect"
PGUSER="pillow"
PGHOST="localhost"
PGPORT="5431"
DATABASE_NAME="pillow"

And here is my database settings in my settings.py page

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ.get('PGDATABASE'),
'USER': os.environ.get('PGUSER'),
'PASSWORD': os.environ.get('PGPASSWORD'),
'HOST': os.environ.get('PGHOST'),
'PORT': os.environ.get('PGPORT'),
}
}

I echoed all environment variables in my shell to double check if all are correct.

THEY WERE!!!

Then I typed the command: python manage.py dbshell and below is the output.

Press enter or click to view image in full size

dbshell command output

There was one small issue with it. I was inside postgres database, instead I should be inside pillowdatabase.

I became suspecious and started to dig little further. I stopped my system’s postgres and removed socket file which is usually located inside /tmp directory.

Still, same issue persisted.

I wanted to check the directory from which data was being read, so I ran the following command:

show data_directory;

Below is the output:

Press enter or click to view image in full size

show data_directory output

This is the root cause for all. Postgres is not getting connected to my container.

Then I typed python manage.py migrate command in my iTerm terminal instead of Cursor Terminal.

Press enter or click to view image in full size

in iTerm terminal

It ran perfectly. In order to verify, I ran python manage.py dbshell from my iTerm terminal. Below is the output:

Press enter or click to view image in full size

iTerm show data_directory

My hypothesis is there might be a bug inside Cursor’s terminal that caused above issue. Although I am not sure how it happened.

Please comment if you know what might have happened.

Update

Running command: set -a; source .env.local; set +a; worked.

By sandwiching source .env.local between set -a and set +a:

  • Temporarily enable automatic exporting.
  • Load environment variables from .env.local.
  • Disable automatic exporting to prevent polluting the environment.

Thankfully, it is not a bug. Just an issue with environment variables not being exported correctly.