You should pragna optimize before TX end, not at tx start.
Except for long lived connections where you do it periodically.
https://www.sqlite.org/lang_analyze.html#periodically_run_pr...
Also foreign_keys has to be set per connection but journal_mode is sticky (it changes the database itself).
Also foreign_keys has to be set per connection but journal_mode is sticky (it changes the database itself).