How to catch sqlite database locked errors

Viewed 404

Edit: the linked "duplicate" answer does not address my concerns. I know why the error is happening and do not wish to change the timeout length. I want to know how to properly detect a locked Sqlite DB so that I can react accordingly. That is to say, if the file is locked, I do not want to wait or try again; I want to signal that it is locked.

I have code right now in a Django framework that needs to access a data stored in an Sqlite file and return it as JSON (GeoJSON specifically). This works, but I have a specific case where the database can be accessed in a locked state.

I know why the problem is happening, but I'd like to know how to detect when it is happening, and return an appropriate response. My naive guess was to try to catch an Sqlite OperationalError, but this is non-effectual.

The problem code:

class GetVectorLayer(APIView):
   def post(self, request):
   ...
   ...

        import sqlite3
        try:
            cache.write_layers(VectorLayer.objects.filter(pk=layer.pk), Formats.GeoJSON, file_path, epsg, bbox)
        except sqlite3.OperationalError as e:
            return Response("Cache Locked", status=status.HTTP_423_LOCKED)
        import json

When this executes I get the same error as before I added the try:

ERROR 1: sqlite3_step() failed: database is locked (5)

The error happens in lower level code that is accessing the DB. That code throws whatever error that is printing to my console, but it doesn't seem to be actually raising an exception fortunately.

The error happens when the cache is still being populated from an external source while someone tries to access data from it. I don't know how to properly check for this state and return a response.

0 Answers
Related