psycopg2 has results from invalid connection

Question:

I was using psycopg2 to connect to my local instance of postgres but didn’t realize I never set the env vars. I decided to do a select on a sys table (information_schema.tables) to check if I had connected and it came back with results. I was confused for a long time trying to figure out why i wasn’t getting the desired results back.

What is going on under the hood to cause this and why didn’t psycopg2 just error out and say it was an invalid connection?

import psycopg2


conn = psycopg2.connect(
                host=None,
                port=None,
                dbname=None,
                user=None,
                password=None,
            )

cur = conn.cursor()

cur.execute("""SELECT table_name 
FROM information_schema.tables
limit 3 """)

print(cur.fetchall())

results:

[(‘pg_statistic’,), (‘pg_foreign_table’,), (‘pg_authid’,)]

Asked By: Jimmy

||

Answers:

Surely, the connection is valid. When you pass null arguments to psycopg2.connect() like you have done then the program gets Postgres environment variables which are apparently set up properly. Note that this is not true in the case you pass a DSN string to the function:

conn = psycopg2.connect("host=None") # this defines an invalid connection

Per the documentation:

The PostgreSQL documentation contains the complete list of the supported parameters. Also note that the same parameters can be passed to the client library using environment variables.

Answered By: klin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.