我正在尝试使用以下SQL炼金术脚本在表中创建一个新的布尔值,不可为空的列(默认值为True):
from sqlalchemy import MetaData, Table, Boolean, Column
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
message_table = Table('message', meta, autoload=True)
col = Column('include_signature', Boolean(), default=True, nullable=False)
col.create(message_table)
这导致了一个相当令人费解的错误:
File "src/adhocracy/migration/versions/061_optional_massmessage_signature.py", line 7, in upgrade
col.create(message_table)
File "eggs/sqlalchemy_migrate-0.7.2-py2.6.egg/migrate/changeset/schema.py", line 528, in create
engine._run_visitor(visitorcallable, self, connection, **kwargs)
File "eggs/SQLAlchemy-0.7.10-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 2302, in _run_visitor
conn._run_visitor(visitorcallable, element, **kwargs)
File "eggs/SQLAlchemy-0.7.10-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1972, in _run_visitor
**kwargs).traverse_single(element)
File "eggs/sqlalchemy_migrate-0.7.2-py2.6.egg/migrate/changeset/ansisql.py", line 53, in traverse_single
ret = super(AlterTableVisitor, self).traverse_single(elem)
File "eggs/SQLAlchemy-0.7.10-py2.6-linux-x86_64.egg/sqlalchemy/sql/visitors.py", line 106, in traverse_single
return meth(obj, **kw)
File "eggs/sqlalchemy_migrate-0.7.2-py2.6.egg/migrate/changeset/databases/sqlite.py", line 75, in visit_column
super(SQLiteColumnGenerator,self).visit_column(column)
File "eggs/sqlalchemy_migrate-0.7.2-py2.6.egg/migrate/changeset/ansisql.py", line 101, in visit_column
self.execute()
File "eggs/sqlalchemy_migrate-0.7.2-py2.6.egg/migrate/changeset/ansisql.py", line 42, in execute
return self.connection.execute(self.buffer.getvalue())
File "eggs/SQLAlchemy-0.7.10-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1449, in execute
params)
File "eggs/SQLAlchemy-0.7.10-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1628, in _execute_text
statement, parameters
File "eggs/SQLAlchemy-0.7.10-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1698, in _execute_context
context)
File "eggs/SQLAlchemy-0.7.10-py2.6-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1691, in _execute_context
context)
File "eggs/SQLAlchemy-0.7.10-py2.6-linux-x86_64.egg/sqlalchemy/engine/default.py", line 331, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (OperationalError) Cannot add a NOT NULL column
with default value NULL '\nALTER TABLE message ADD include_signature BOOLEAN NOT NULL' ()
据我所知,sqlalchemy缺少一个默认值,但我确实包含了default=True
!这有什么不对?
答案 0 :(得分:21)
使用server_default="true"
,就像那样:
col = Column('include_signature', Boolean(), default=True,
server_default="true", nullable=False)
其中default
用于类实例,server_default
用于数据库列定义。