迁移后如何修复错误的SQLAlchemy元数据

时间:2019-06-05 18:13:53

标签: python sqlite sqlalchemy

我已经使用SQLAlchemy定义并创建了SQLite数据库,并添加了一些数据。该数据库运行良好。但是,我对其中一个模型(“用户”)的列名进行了更改,并使用alembic迁移了此更改。当前模型如下所示,其中旧名称“ analogy”更改为“ metaphor”:

class User(Base):
    __tablename__ = "user"
    id = Column(Integer, primary_key=True)
    username = Column(String(32), nullable=False, index=True, unique=True)
    registered_on = Column(DateTime, index=True, default=datetime.now())
    metaphor = Column(String(16))

迁移似乎进行得很顺利,我还使用SQLite命令行进行了仔细检查,以确认该模式确实发生了变化。

sqlite > .schema
CREATE TABLE "user" (
    id INTEGER NOT NULL, 
    username VARCHAR(32) NOT NULL, 
    registered_on DATETIME,  
    metaphor VARCHAR(16), 
    PRIMARY KEY (id), 
    UNIQUE (wc_id)
);
CREATE UNIQUE INDEX ix_user_username ON user (username);
CREATE INDEX ix_user_registered_on ON user (registered_on);

但是现在当我尝试在Python中查询表时,出现以下错误,引用了旧的列名并说没有这样的列

>>> from background.database import db_session
>>> from data.models import User
>>> users = db_session.query(User).all()
Traceback (most recent call last):
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
    context)
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/engine/default.py", line 509, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: no such column: user.analogy

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/orm/query.py", line 2843, in all
    return list(self)
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/orm/query.py", line 2995, in __iter__
    return self._execute_and_instances(context)
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/orm/query.py", line 3018, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 948, in execute
    return meth(self, multiparams, params)
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/sql/elements.py", line 269, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1060, in _execute_clauseelement
    compiled_sql, distilled_params
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1200, in _execute_context
    context)
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1413, in _handle_dbapi_exception
    exc_info
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/util/compat.py", line 265, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/util/compat.py", line 248, in reraise
    raise value.with_traceback(tb)
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
    context)
  File "/export/scratch/pt/power/lib/python3.5/site-packages/sqlalchemy/engine/default.py", line 509, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: user.goal_period [SQL: 'SELECT user.id AS user_id, user.username AS user_username, user.registered_on AS user_registered_on, user.analogy AS user_analogy \nFROM user'] (Background on this error at: http://sqlalche.me/e/e3q8)

跟踪此错误后,看起来对模型的名称更改未反映在从SQLAlchemy导入的元数据中。因此,SQLAlchemy仍在使用该表的先前版本中的元数据,而实际的数据库模式和定义的模型具有不同的列名。

我尝试删除所有缓存(.pyc,py_cache)以查看是否是问题的根源。 但是,这样做之后,元数据仍然没有任何更改。 当我打开一个新的Interprer会话并查询元数据时,它显示的是旧模式,而不是新模式。

>>> from SQLAlchemy import MetaData
>>> metadata= MetaData()
>>> metadata.tables['user']
Table('user', MetaData(bind=None), Column('id', Integer(), table=<user>, primary_key=True, nullable=False), Column('username', String(length=32), table=<user>, nullable=False), Column('registered_on', DateTime(), table=<user>, default=ColumnDefault(datetime.datetime(2019, 6, 5, 12, 33, 57, 11763))), Column('goal_period', String(length=16), table=<user>, default=ColumnDefault('daily'))), schema=None)

为什么不更新元数据,以及如何解决此问题?

0 个答案:

没有答案