python内存数据库触发器,如何使用Python将内存中的SQLite数据库复制到另一个内存中的SQLite数据库?...

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?

Thanks!

解决方案

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)

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值