簡體   English   中英

如何在Python中將內存中的SQLite數據庫復制到另一個內存中的SQLite數據庫?

[英]How can I copy an in-memory SQLite database to another in-memory SQLite database in Python?

我正在為Django編寫一個測試套件,它以樹狀方式運行測試。 例如,Testcase A可能有2個結果,Testcase B可能有1個,Testcase C可能有3個。樹看起來像這樣

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

對於上面樹中的每個路徑,數據庫內容可能不同。 所以在每個fork中,我正在考慮創建數據庫當前狀態的內存副本,然后將該參數提供給下一個測試。

任何人都知道如何將內存數據庫實質上復制到另一個數據庫,然后獲得傳遞該數據庫的引用?

謝謝!

好吧,經過一次有趣的冒險之后,我想出了這個。

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作為對新創建的數據庫的引用。

這是一個復制數據庫的函數。 源和目標都可以是內存中或磁盤上(默認目標是內存中的副本):

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM