2

I try to update an SQL database using Pony ORM, but I didn't found how to ALTER an SQL table to add a column.

What i want to do is:

ALTER TABLE USER ADD COLUMN sex char(1);

Could someone help me?

4

2 回答 2

3

您可以使用orm-migrations分支中的迁移工具。它还没有正式发布。

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

db.drop_all_tables(with_all_data=True)
db.create_tables()
于 2018-08-03T12:16:19.277 回答
0

如果您同意的话,我已经使用了一个需要直接使用 SQL 的解决方法来解决这个问题。基本上,您可以使用命令添加列ALTER TABLE,然后修改您的 Pony 实体类,之后它应该可以正常加载。

我不知道这种方法是否适用于这个非常基本的示例,或者这是否会进一步破坏某些东西。或许了解更多的人可以评论一下。

无论如何,这是该过程的 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.py命令将该age列添加到您的数据库中:

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 
于 2021-06-16T23:54:33.043 回答