databases icon indicating copy to clipboard operation
databases copied to clipboard

NotNullViolationError when inserting a row with all default values

Open ghost opened this issue 2 years ago • 1 comments

  • OS: Windows 11
  • Python version: 3.11.0
  • Databases version: 0.7.0
  • Database backend: PostgreSQL
  • Database driver: asyncpg

I have an SQLAlchemy table with one primary key column and one column with a default value (sqlalchemy.sql.functions.now()).

Because both columns in the table have a default value (from a sequence or the PostgreSQL now() function), I should be able to insert a row without a values argument, or with an empty mapping, e.g. database.execute(table.insert()) or database.execute(table.insert(), values={}). But inserting a row either way raises a NotNullViolationError:

asyncpg.exceptions.NotNullViolationError: null value in column "id" of relation "post" violates not-null constraint
DETAIL:  Failing row contains (null, null).

It seems that a default value isn't being generated for the ID column, which is violating its not-null constraint.

The exception isn't raised and the row is inserted if I pass a value, e.g. database.execute(table.insert(), values={"posted_at": datetime.datetime.now()}), but that defeats the purpose of defining a default value in the database schema.

ghost avatar Jan 19 '23 11:01 ghost

Duplicate of #72?

mathause avatar Mar 13 '23 08:03 mathause