Skip to content

DataError properties #374

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
yohanboniface opened this issue Oct 10, 2018 · 2 comments
Closed

DataError properties #374

yohanboniface opened this issue Oct 10, 2018 · 2 comments

Comments

@yohanboniface
Copy link

Hi,

Is there any way to access/populate the DataError properties (eg. column_name) as for other exceptions (eg. NotNullViolationError) ?

Here is a quick script to demonstrate my point:

import asyncio
import asyncpg
import datetime


async def main():
    conn = await asyncpg.connect("postgresql://postgres@localhost/test")
    await conn.execute(
        """
        CREATE TABLE IF NOT EXISTS users(
            id serial PRIMARY KEY,
            name text,
            dob date NOT NULL,
            foo integer
        )
    """
    )

   # With a NotNullViolationError
    try:
        await conn.execute(
            """
            INSERT INTO users(name, dob, foo) VALUES($1, $2, $3)
        """,
            "Bob",
            None,
            42
        )
    except asyncpg.NotNullViolationError as err:
        print(err.as_dict())
        # Will print:
        # {'severity': 'ERROR', 'severity_en': 'ERROR', 'sqlstate': '23502', 'message': 'null value in column "dob" violates not-null constraint', 
        # 'detail': 'Failing row contains (3, Bob, null, 12).', 'schema_name': 'public', 'table_name': 'users', 
        # 'column_name': 'dob', 'server_source_filename': 'execMain.c', 'server_source_line': '2008', 
        # 'server_source_function': 'ExecConstraints'}

    # With a DataError.
    try:
        await conn.execute(
            """
            INSERT INTO users(name, dob, foo) VALUES($1, $2, $3)
        """,
            "Bob",
            datetime.datetime(2018, 10, 10),
            "invalid"
        )
    except asyncpg.DataError as err:
        print(err.as_dict())
        # Will print, with no more details:
        # {'sqlstate': '22000'}

asyncio.get_event_loop().run_until_complete(main())

Thanks! :)

@elprans
Copy link
Member

elprans commented Oct 10, 2018

That DataError comes from asyncpg, not from postgres itself and is the result of invalid input representation of a data type. Short of parsing the input query, we cannot say that the input was actually destined to a specific column in an INSERT statement.

@yohanboniface
Copy link
Author

OK, thanks!

Maybe once #196 is out we can name the field attached to an error?

@elprans elprans closed this as completed Nov 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants