Skip to content

Second transaction in bulk_create_with_history results in n+1 query #974

@twolfson

Description

@twolfson

Describe the bug
Running bulk_create_with_history on a database that doesn't support returning ids from bulk_create results in an n+1 query due to all the additional one-off .filter() calls it's making

https://github.com/jazzband/django-simple-history/blob/3.1.0/simple_history/utils.py#L113-L131

I believe this was originally needed to maintain the order from the original list, but it should be possible to use the same CASE/WHEN trick that Django uses for bulk_update to bulk resolve ids in the same order as our original list

https://github.com/django/django/blob/4.0.4/django/db/models/query.py#L624-L638

https://stackoverflow.com/a/19196522/1960509

To Reproduce
Steps to reproduce the behavior:

  1. Create a model
  2. Run a script with --print-sql on and bulk create with more than 1 model on a database that lacks support for returning multiple ids from bulk_create
  3. See more queries than expected

Expected behavior

1 query for bulk creation (INSERT INTO normal table) + 1 query for retrieving ids (SELECT WHERE) + 1 query for bulk history creation (INSERT INTO)

Actual behavior

1 query for bulk creation (INSERT INTO normal table) + n query for retrieving ids (SELECT WHERE * n) + 1 query for bulk history creation (INSERT INTO history table)

Environment (please complete the following information):

Not willing to share at this time, I'll file iterate within django-simple-history test environment instead

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