SectorLabs / django-postgres-extra

Bringing all of PostgreSQL's awesomeness to Django.
MIT License
695 stars 96 forks source link

feat: Add Operation Type support #215

Open rmanganiello opened 1 year ago

rmanganiello commented 1 year ago

Problem

Currently, there's no way to determine if after an UPSERT operation in the database a row was inserted or updated.

This functionality can be handy in different use cases. i.e.:

  1. Exposing this to clients through an API (200 or 201 status codes).
  2. Deciding how to notify this event in an Event-based driven system.

Solution

This PR intends to add this functionality by adding a new flag called return_operation_type.

When the client specifies this flag, a new key _operation_type will be returned for each row setting the corresponding operation ("INSERT" or "UPDATE") that was performed for it.

This new flag will be available in the bulk_upsert and bulk_insert methods of the PostgresQuerySet class, and, only if the return_model flag is off.

Caveats

  1. This flag is only available if the return_model flag is off to avoid breaking the current contracts since injecting this data into a Django Model is hacky.
  2. The decision on having this flag off by default, is to avoid breaking any implementation where clients are building their own Django models by hand after calling the bulk_upsert/bulk_insert methods.

Related Issue: #100

Photonios commented 3 months ago

Nice trick! I am not a fan of the API for this. We already have dynamic return types in bulk_upsert and adding yet another variation does not make for a predictable API.

Could we maybe abstract this in a separate method?