Wrong IDENT returned

Issue #24 duplicate
Anonymous created an issue

Hello,

I have view like this: def myview(request): if request.FILES is None: raise Http404("No objects uploaded") f = request.FILES['file']

a = myFile()
a.file = f
a.save()

result = [{'name': f.name,
           'size': f.size,
           'url': a.file.url,
           'id': a.id,
        },]

response_data = simplejson.dumps(result)
if "application/json" in request.META['HTTP_ACCEPT_ENCODING']:
    mimetype = 'application/json'
else:
    mimetype = 'text/plain'
return HttpResponse(response_data, mimetype=mimetype)

The problem is, this is called by my concurrent uploader. And sometimes, I receive result like this:

[{"url": "/media/uploads/2012/12/tumblr_me1rlcLEth1rjchmeo1_1280.jpg", "id": 76, "name": "tumblr_me1rlcLEth1rjchmeo1_1280.jpg", "size": 129268}] [{"url": "/media/uploads/2012/12/tumblr_mdmwgzVYSn1r62m2no1_500.jpg", "id": 76, "name": "tumblr_mdmwgzVYSn1r62m2no1_500.jpg", "size": 65839}]

Please note, there are two same IDs, but that's impossible. In fact, the first ID is 75, but the a.id variable has wrong value.

I checked it using SQL Profiler and there are two INSERTS and two SELECT CAST(IDENT_CURRENT(@P1) as bigint). In this order. And this is why I think, I'm receiveng wrong ID for my rows.

I believe, I could fix this by switching this view to manual transaction management, but I'm worried this error could appear somewhere else in my app.

Please, isn't there any other solution? Is this bug, wrong settings on my server, or just some strange feature?

I'm running Django 1.4.2 and django-mssql 1.2rc2.

Thank you a lot.

Regards, Vlastik K.

Comments (3)

  1. Michael Manfre repo owner

    This is a known limitation of selecting the ID as a separate query. IDENT_CURRENT returns the last ID inserted to a table, regardless of scope. This was an intentional choice and the best scoping option due to the potential of the database table having a trigger.

    This shouldn't be a problem with django-mssql 1.3, which will return the id of the insert as part of the insert. Until that version is released, you'll need to rewrite your view to explicitly select a row to get the id of the record you inserted, instead of relying upon the inserted ID.

    Also, update to 1.2 final, instead of using rc2.

  2. Martijn Pieters

    So you are saying it is better to be wrong, guaranteed, for most people (e.g. when there is a concurrent request), than to be wrong for only some people? :)

    Now that 1.3 is out, the problem is moot, but for those not in a position to upgrade and without triggers that insert additional rows, pull request #8 contains a patch that fixes the issue.

  3. Log in to comment