如何使用Python将内存中的SQLite数据库复制到另一个内存中的SQLite数据库? [英] How can I copy an in-memory SQLite database to another in-memory SQLite database in Python?

查看:319
本文介绍了如何使用Python将内存中的SQLite数据库复制到另一个内存中的SQLite数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Django开发一个测试套件,该套件以树状方式运行测试。例如,测试用例A可能有2个结果,测试用例B可能有1个结果,而测试用例C可能有3个结果。树看起来像这样

I'm writing a test suite for Django that runs tests in a tree-like fashion. For example, Testcase A might have 2 outcomes, and Testcase B might have 1, and Testcase C might have 3. The tree looks like this

      X
     /
A-B-C-X
 \   \
  B   X
   \   X
    \ /
     C-X
      \
       X

对于上面树中的每个路径,数据库内容可能不同。因此,在每个分支中,我都在考虑创建数据库当前状态的内存副本,然后将该参数提供给下一个测试。

For each path in the tree above, the database contents may be different. So at each fork, I'm thinking of creating an in-memory copy of the current state of the database, and then feeding that parameter into the next test.

任何人有一个关于如何从本质上将内存数据库复制到另一个数据库,然后获得将数据库传递给周围的引用的想法吗?

Anyone have an idea about how to essentially copy the in-memory database to another one, and then get a reference to pass that database around?

谢谢!

推荐答案

好吧,经过一次有趣的冒险,我发现了这个问题。

Alright, after a fun adventure I figured this one out.

from django.db import connections
import sqlite3

# Create a Django database connection for our test database
connections.databases['test'] = {'NAME': ":memory:", 'ENGINE': "django.db.backends.sqlite3"}

# We assume that the database under the source_wrapper hasn't been created
source_wrapper = connections['default']  # put alias of source db here
target_wrapper = connections['test'] 

# Create the tables for the source database
source_wrapper.creation.create_test_db()

# Dump the database into a single text query
query = "".join(line for line in source_wrapper.connection.iterdump())

# Generate an in-memory sqlite connection
target_wrapper.connection = sqlite3.connect(":memory:")
target_wrapper.connection.executescript(query)

现在名为 test 的数据库将成为默认值的副本。数据库。使用target_wrapper.connection作为对新创建数据库的引用。

And now the database called test will be a carbon copy of the default database. Use target_wrapper.connection as a reference to the newly created database.

这篇关于如何使用Python将内存中的SQLite数据库复制到另一个内存中的SQLite数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆