aaossa
aaossa

Reputation: 3852

How to backup Peewee database (SqliteQueueDatabase) programatically?

I'm using Peewee in one of my projecs. Specifically, I'm using SqliteQueueDatabase and I need to create a backup (i.e. another *.db file) without stopping my application. I saw that there are two methods that could work for me (backup and backup_to_file) but they're methods from CSqliteExtDatabase, and SqliteQueueDatabase is subclass of SqliteExtDatabase. I've found solutions to manually create a dump of the file, but I need a *.db file (not a *.csv file, for example). Couldn't find any similar question or relevant answer.

Thanks!

Upvotes: 0

Views: 689

Answers (2)

gil9red
gil9red

Reputation: 1020

Implementation via backup:

import sqlite3
from pathlib import Path

from peewee import SqliteDatabase


# db = SqliteDatabase("db.sqlite")
# ...
# Models
# ...
# db.connect()
# db.create_tables...


def backup(db: SqliteDatabase, file_name: Path | str):
    dst = sqlite3.connect(file_name)
    db.connection().backup(dst)
    dst.close()


file_name_backup = Path(__file__).resolve().name + ".db"
backup(db, file_name_backup)

Upvotes: 0

coleifer
coleifer

Reputation: 26235

You can just import the backup_to_file() helper from playhouse._sqlite_ext and pass it your connection and a filename:

db = SqliteQueueDatabase('...')

from playhouse._sqlite_ext import backup_to_file
conn = db.connection()  # get the underlying pysqlite conn
backup_to_file(conn, 'dest.db')

Also, if you're using pysqlite3, then there are also backup methods available on the connection itself.

Upvotes: 4

Related Questions