You should take a look at <https://sqlite.org/c3ref/progress_handler.html> which you can use to have the database engine callback your code periodically while executing a VDBE program. If it finds that the execution has taken too long it can issue an sqlite3_interrupt on the connection.