"ALTER TABLE" 使用 Pony ORM 添加数据库列

"ALTER TABLE" to add a database column with Pony ORM

我尝试使用 Pony ORM 更新 SQL 数据库,但我没有找到如何更改 SQL table 来添加列。

我想做的是:

ALTER TABLE USER ADD COLUMN sex char(1);

有人可以帮我吗?

您可以使用 orm-migrations 分支中的迁移工具。尚未正式发布。

或者,如果数据库还没有包含有用的数据,您可以删除所有表并从头开始重新创建它们:

db.drop_all_tables(with_all_data=True)
db.create_tables()

我已使用变通方法解决此问题,如果您不介意的话,需要直接使用 SQL。基本上,您可以使用 ALTER TABLE 命令添加该列,然后修改您的 Pony 实体 class 之后它应该可以正常加载。

我不知道此方法是否适用于这个非常基本的示例,或者这是否会破坏进一步的内容。或许知道的人可以评论一下。

无论如何,这是该过程的 MWE。

ponymwe.py
-----------
from pony import orm

db = orm.Database()

class Person(db.Entity):
    name = orm.Required(str)
    #age = orm.Required(int) # <-- this is the column we want to add

db.bind(provider='sqlite', filename='./tmp.sqlite', create_db=True)
db.generate_mapping(create_tables=True)

@orm.db_session
def init_populate():
    Person(name='nic cage')

@orm.db_session
def showall():
    orm.show(Person)        # see the schema
    Person.select().show()  # see the entries

运行 init_populate() 在数据库中放置一个条目。 然后 运行 以下 update_schema.pyage 列添加到您的数据库:

update_schema.py
----------------
import sqlite3

con = sqlite3.connect('./tmp.sqlite')
con.execute('ALTER TABLE person ADD COLUMN age INTEGER')
con.execute('UPDATE person SET age=? WHERE name=?', (57, 'nic cage'))
con.commit()

现在返回 ponymwe.py 并取消注释 age = orm.Required(int) 和 运行 showall() 以查看架构和条目确实已更新:

# output should be:
class Person(Entity):
    id = PrimaryKey(int, auto=True)
    name = Required(str)
    age = Required(int)
id|name    |age
--+--------+---
1 |nic cage|57