SQLite only allows one connection to write to the database at any given time. As a result, if you have a multi-threaded application (like a web-server, for example) that needs to write to the database, you may see occasional errors when one or more of the threads attempting to write cannot acquire the lock.

    SqliteQueueDatabase is designed to simplify things by sending all write queries through a single, long-lived connection. The benefit is that you get the appearance of multiple threads writing to the database without conflicts or timeouts. The downside, however, is that you cannot issue write transactions that encompass multiple queries – all writes run in autocommit mode, essentially.

    Note

    The module gets its name from the fact that all write queries get put into a thread-safe queue. A single worker thread listens to the queue and executes all queries that are sent to it.

    • Thread A: UPDATE transplants SET organ=’liver’, …;
    • Thread B: UPDATE life_support_system SET timer += 60 …;

    Since there is a potential for queries from separate transactions to be interleaved, the transaction() and atomic() methods are disabled on .

    For cases when you wish to temporarily write to the database from a different thread, you can use the pause() and unpause() methods. These methods block the caller until the writer thread is finished with its current workload. The writer then disconnects and the caller takes over until unpause is called.

    The stop(), start(), and is_stopped() methods can also be used to control the writer thread.

    Note

    Code sample

    Creating a database instance does not require any special handling. The accepts some special parameters which you should be aware of, though. If you are using gevent, you must specify use_gevent=True when instantiating your database – this way Peewee will know to use the appropriate objects for handling queueing, thread creation, and locking.

    If autostart=False, as in the above example, you will need to call start() to bring up the worker threads that will do the actual write query execution.

    If you plan on performing SELECT queries or generally wanting to access the database, you will need to call and close() as you would with any other database instance.

    When your application is ready to terminate, use the stop() method to shut down the worker thread. If there was a backlog of work, then this method will block until all pending work is finished (though no new work is allowed).