如何在Python中将内存中的SQLite数据库复制到另一个内存中的SQLite数据库?

时间:2011-11-08 03:27:44

标签: python django sqlite

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

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

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

任何人都知道如何将内存数据库实质上复制到另一个数据库,然后获取传递该数据库的引用?

谢谢!

2 个答案:

答案 0 :(得分:4)

好吧,经过一次有趣的冒险之后,我想出了这个。

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的数据库将成为default数据库的副本。使用target_wrapper.connection作为对新创建的数据库的引用。

答案 1 :(得分:2)

这是一个复制数据库的功能。源和目标都可以是内存中或磁盘上(默认目标是内存中的副本):

import sqlite3

def copy_database(source_connection, dest_dbname=':memory:'):
    '''Return a connection to a new copy of an existing database.                        
       Raises an sqlite3.OperationalError if the destination already exists.             
    '''
    script = ''.join(source_connection.iterdump())
    dest_conn = sqlite3.connect(dest_dbname)
    dest_conn.executescript(script)
    return dest_conn

以下是一个如何应用于您的用例的示例:

from contextlib import closing

with closing(sqlite3.connect('root_physical.db')) as on_disk_start:
    in_mem_start = copy_database(on_disk_start)

a1 = testcase_a_outcome1(copy_database(in_mem_start))
a2 = testcase_a_outcome1(copy_database(in_mem_start))
a1b = test_case_b(a1)
a2b = test_case_b(a2)
a1bc1 = test_case_c_outcome1(copy_database(a1b))
a1bc2 = test_case_c_outcome2(copy_database(a1b))
a1bc3 = test_case_c_outcome3(copy_database(a1b))
a2bc1 = test_case_c_outcome1(copy_database(a2b))
a2bc2 = test_case_c_outcome2(copy_database(a2b))
a2bc3 = test_case_c_outcome3(copy_database(a2b))