def _dump_db(self, conn: sqlite3.Connection) -> StringIO: """dump sqlite db to a string buffer""" dbdump = StringIO() for line in conn.iterdump(): dbdump.write("%s\n" % line) dbdump.seek(0) return dbdump
def test_save_database(connect_memory_db: sqlite3.Connection, tmp_path: Path) -> None: """Save a database in an SQL text format.""" dump_path = tmp_path.joinpath("dump.sql") with open(dump_path, mode="w") as dump_file: for line in connect_memory_db.iterdump(): dump_file.write(f"{line}\n") with open(dump_path) as dump_read: assert ( dump_read.read() == """\ BEGIN TRANSACTION; DELETE FROM "sqlite_sequence"; INSERT INTO "sqlite_sequence" VALUES('tasks',2); CREATE TABLE tasks( id integer primary key autoincrement not null, priority integer default 1, details text, deadline date ); INSERT INTO "tasks" VALUES(1,2,'Task 1','2020-07-08'); INSERT INTO "tasks" VALUES(2,1,'Task 2','2020-07-11'); COMMIT; """ )
def fetch_schedules(self, db: sqlite3.Connection, path: str) -> List[sqlite3.Row]: with db: if self.dump_on_update: dump = [line for line in db.iterdump()] dump = "\n".join(dump) log.debug(f"db dump:\n{dump}") cur = db.execute(Schedule.EXEC_QUERY, (path,)) all_rows = cur.fetchall() rows = [r for r in all_rows if self._is_allowed_repeat(r, path)][0:1] return rows
def sqlite_backup(*, source: sqlite3.Connection, dest: sqlite3.Connection, **kwargs) -> None: if sys.version_info[:2] >= (3, 7): source.backup(dest, **kwargs) else: # https://stackoverflow.com/a/10856450/706389 import io tempfile = io.StringIO() for line in source.iterdump(): tempfile.write('%s\n' % line) tempfile.seek(0) dest.cursor().executescript(tempfile.read()) dest.commit()
def sql_from_sqlite_database(connection: sqlite3.Connection) -> str: """ Returns SQL to describe an SQLite database. Args: connection: connection to SQLite database via ``sqlite3`` module Returns: the SQL """ with StringIO() as f: # noinspection PyTypeChecker for line in connection.iterdump(): f.write(line + "\n") f.flush() return f.getvalue()
def dump_db(db: sqlite3.Connection): with open(DB_EXPORT, 'w') as f: for l in db.iterdump(): f.write(l) f.write('\n') pass