我注意到,当我使用add-migration
创建代码首次数据库迁移时,它会生成Down()
方法以及Up()
方法。
如何告知我的数据库降级?
答案 0 :(得分:41)
几乎放弃了对Google的研究后,我设法从这里找到了这个引用:
其中指定:
假设我们想要在运行AddBlogUrl迁移后将数据库迁移到它所处的状态。我们可以使用
–TargetMigration
开关降级到此迁移。在程序包管理器控制台中运行
Update-Database –TargetMigration: AddBlogUrl
命令。 此命令将为AddBlogAbstract和AddPostClass迁移运行Down脚本。如果要一直回滚到空数据库,则可以使用
Update-Database –TargetMigration: $InitialDatabase
命令。
答案 1 :(得分:13)
首先通过发出Get-Migrations命令获取要在降级之前应用的迁移的名称。
Update-Database –TargetMigration: "<the migration applied before it>"
此列表显示首先列出最近应用的迁移的迁移。选择要降级的列表之后发生的迁移,即在您要降级的应用之前应用的迁移。
#!/usr/bin/env python2
import sqlite3
import csv
def quotify(s):
return '"' + s.strip().replace('"', '""') + '"'
con = sqlite3.connect("pets.db")
# Examle contents of pets.csv:
# person_name, person_age, pet_name
# Lisa, 8, Snowball I
# Lisa, 8, Snowball II
# Bart, 10, Santa's Little Helper
with open("pets.csv") as pets:
pets = csv.reader(pets)
with con:
names = next(pets)
names = [name.decode('utf-8') for name in names]
for name in names:
con.execute('drop table if exists %s;' % quotify(name))
con.execute('create table %s (value unique on conflict ignore);'
% quotify(name))
con.execute("drop table if exists master")
st = "create table master(%s);" % (
','.join("%s" % quotify(name) for name in names))
con.execute(st)
for row in pets:
row = [item.decode('utf-8') for item in row]
rowids = []
for name, value in zip(names, row):
rowids.append(
con.execute("insert into %s (value) values(?)"
% quotify(name),
(value.strip(),)).lastrowid)
st = 'insert into master values(%s)' % (
','.join('?' for rowid in rowids))
con.execute(st, rowids)
# Demonstration, using Simpon's example from question:
from pprint import pprint
st = '''select person_name.value, person_age.value, pet_name.value
from person_name, person_age, pet_name, master
where master.person_name = person_name.rowid
and master.person_age = person_age.rowid
and master.pet_name = pet_name.rowid;'''
pprint(con.execute(st).fetchall())
在指定的迁移之后应用的所有迁移将按照从最先应用的最新迁移开始的顺序进行降级。