Skip to content

Error.sqlstate not available for unknown error codes #225

@dvarrazzo

Description

@dvarrazzo

From the ML

This SQL code inside a function:

RAISE EXCEPTION 'Error wrong database' USING HINT = 'You need to use a 
different database', ERRCODE = 'PA002';

is catched in python code with:

try:
    <execute sql function>
except psycopg.Error as er:
     raise PyAppDBError(er.sqlstate, er)

With psycopg2 er.sqlstate is set to 'PA002' in psycopg3 is set to None

Is this an expected behavour ? Is there a way to get the error code in
psycopg3 like it is available in psycopg2 ?

A quick solution here is to use er.diag.sqlstate, because er.sqlstate is a class attribute only knwon for the known values, and PA002 is not a known one. However it the result is inconsistent and I think should be improved. At the moment this test fails and it's probably worth fixing it.

def test_unknown_sqlstate(conn):
    with pytest.raises(e.ProgrammingError) as excinfo:
        conn.execute("""
            do $$begin
            raise exception 'made up code' using errcode = 'PXX99';
            end$$ language plpgsql
            """)
    exc = excinfo.value
    assert exc.diag.sqlstate == "PXX99"
    assert exc.sqlstate == "PXX99"  # <<< this assert fails in 3.0.8

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions