Search code examples
python-3.xpostgresqlsqlalchemy

SQLAlchemy always fails with `invalid connection option` error


I am trying to connect with CockroachDB from Python using SQLAlchemy with SSL.
In the below code I have shown various combinations I tried.
I am getting error for all the combinations.

Program
import sqlalchemy as sa

cert_path = "/tmp/mountedcerts"

# https://stackoverflow.com/a/48851490/2243490
ssl_args1 = {
    'sslmode': 'REQUIRED',
    'ssl_ca': f"{cert_path}/ca.crt",
    'ssl_cert': f"{cert_path}/client.root.crt",
    'ssl_key': f"{cert_path}/client.root.key"
}

# https://stackoverflow.com/a/14992181/2243490
ssl_args2 = {
    'sslmode': 'REQUIRED',
    'ssl': {
        'cert': f"{cert_path}/client.root.crt",
        'key': f"{cert_path}/client.root.key",
        'ca': f"{cert_path}/ca.crt",
    }
}

conn_strs = [
    "postgresql://root@cockroachdb:26257/sample",
    "postgresql://root@cockroachdb:26257/sample?ssl=True",
    "postgresql+psycopg2://root@cockroachdb:26257/sample?sslmode=require"
]

ssl_args = [ssl_args1, ssl_args2]

def get_engine():
    for cs in conn_strs:
        for arg in ssl_args:
            yield sa.create_engine(cs, connect_args=arg)

def get_list_of_table():
    for engine in get_engine():
        try:
            with engine.connect() as conn:
                result = conn.execute("SHOW TABLES")
                return [row[0] for row in result]
        except Exception as ex:
            print(ex)

if __name__ == "__main__":
    get_list_of_table()
Error Messages
(psycopg2.ProgrammingError) invalid dsn: invalid connection option "ssl_ca"
(psycopg2.ProgrammingError) invalid dsn: invalid connection option "ssl"
(psycopg2.ProgrammingError) invalid dsn: invalid connection option "ssl"
(psycopg2.ProgrammingError) invalid dsn: invalid connection option "ssl"
(psycopg2.ProgrammingError) invalid dsn: invalid connection option "ssl_ca"
(psycopg2.ProgrammingError) invalid dsn: invalid connection option "ssl"

Solution

  • Change ssl parameters in the ssl_args1 definition to

    ssl_args1 = {
        'sslmode': 'verify-full',
        'sslrootcert': f"{cert_path}/ca.crt",
        'sslcert': f"{cert_path}/client.root.crt",
        'sslkey': f"{cert_path}/client.root.key"
    }