我从我的ubuntu安装了alembic 0.3.4,sqlalchemy,SQLite版本3.7.4,并将SQLAlchemy 0.6.4升级到SQLAlchemy 0.7或更高版本.我按照说明操作:http://alembic.readthedocs.org/en/latest/tutorial.html
现在我正在测试:自动生成迁移我创建了一个包:schemas和一个包标记下的模式:init .py,其中定义了一行:
__all__ = ["teacher"]
Run Code Online (Sandbox Code Playgroud)
我还在schemas目录中创建了一个模块文件:dbmodel.py,其中包含以下内容
Base = declarative_base()
class teacher(Base):
__tablename__ = 'teacher'
id = Column(Integer, primary_key=True)
name = Column(String)
department = Column(String)
Run Code Online (Sandbox Code Playgroud)
顺便说一下,我创建了一个sqlite数据库,并且在自动生成迁移之前进行一些测试它运行正常.我配置了env.py文件.添加了两行:
from schemas.dbmodel import Base
target_metadata = Base.metadata
Run Code Online (Sandbox Code Playgroud)
然后我跑:
alembic revision --autogenerate -m "Added teacher table"
Run Code Online (Sandbox Code Playgroud)
但仍然得到错误:
Traceback (most recent call last):
File "/usr/local/bin/alembic", line 9, in <module>
load_entry_point('alembic==0.3.4', 'console_scripts', 'alembic')()
File "/usr/local/lib/python2.7/dist-packages/alembic-0.3.4-py2.7.egg/alembic/config.py", line 229, in main
**dict((k, getattr(options, k)) for k in kwarg)
File "/usr/local/lib/python2.7/dist-packages/alembic-0.3.4-py2.7.egg/alembic/command.py", line 93, …Run Code Online (Sandbox Code Playgroud) 我目前有一个包含HTML标记的列.在该标记内,有一个我想要存储在新列中的时间戳(因此我可以查询它).我的想法是在一次迁移中执行以下操作:
但是当我尝试运行迁移时,它似乎陷入无限循环.这是我到目前为止所得到的:
def _extract_publication_date(html):
root = html5lib.parse(html, treebuilder='lxml', namespaceHTMLElements=False)
publication_date_string = root.xpath("//a/@data-datetime")[0]
return parse_date(publication_date)
def _update_tip(tip):
tip.publication_date = _extract_publication_date(tip.rendered_html)
tip.save()
def upgrade():
op.add_column('tip', sa.Column('publication_date', sa.DateTime(timezone=True)))
tips = Tip.query.all()
map(tips, _update_tip)
def downgrade():
op.drop_column('tip', 'publication_date')
Run Code Online (Sandbox Code Playgroud) 我想使用Alembic将数据库的列类型从字符串更改为整数.如果我使用纯SQL,它实现了目标:
alter table statistic_ticket alter column tags type bigint using tags::bigint;
Run Code Online (Sandbox Code Playgroud)
但是当我使用Alembic时:
import sqlalchemy as sa
def upgrade():
op.alter_column('statistic_ticket', 'tags', nullable = True, existing_type=sa.String(length=255), type_=sa.Integer, existing_nullable=True)
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
HINT: Please use USING clause for carrying out the conversion
Run Code Online (Sandbox Code Playgroud)
SQLAlchemy生成的SQL语句是:
ALTER TABLE statistic_ticket ALTER COLUMN tags TYPE INTEGER' {}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我怎么做alembic或SQLAlchemy中的SQL op.execute(SQL)吗?
我编写了一个在sqlite上工作正常的迁移脚本,但如果我尝试将其应用于postgres,它将永远停留.通过一个简单的ps我可以看到postres卡在"创建表等待".有什么最好的做法?
我正在使用PostgreSQL和Alembic进行迁移.当我向User表添加新列时,Alembic使用以下脚本生成了迁移:
revision = '4824acf75bf3'
down_revision = '2f0fbdd56de1'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
'user',
sa.Column(
'username',
sa.Unicode(length=255),
nullable=False
)
)
def downgrade():
op.drop_column('user', 'username')
Run Code Online (Sandbox Code Playgroud)
我真正想要做的是在升级生产版本时自动生成用户名的值.换句话说,我的生产版本中有很多用户,如果我在其上运行上述升级,则会出现错误,指出用户名不能为NULL,因此我必须删除所有用户,升级用户表和再次添加用户后,这很痛苦.因此,我想用以下内容更改上述脚本:
revision = '4824acf75bf3'
down_revision = '2f0fbdd56de1'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
'user',
sa.Column(
'username',
sa.Unicode(length=255)
)
)
op.execute(
'UPDATE "user" set username = <email address with no '@'
and everything comes after '@' sign should be removed>
WHERE email is not null'
)
<only …Run Code Online (Sandbox Code Playgroud) 我试图改变Alembic但是当我尝试运行Alembic时我得到了错误.我是alembic的新手,请告诉我为什么我会收到此错误,我该如何解决?
我可以alembic.ini在迁移文件夹和Alembic使用的修订标识符中看到,一切似乎都很好.
$alembic current
No handlers could be found for logger "alembic.util"
FAILED: No config file 'alembic.ini' found, or file has no '[alembic]' section
Run Code Online (Sandbox Code Playgroud)
20c921506336_.py:
"""empty message
Revision ID: 20c921506336
Revises: None
Create Date: 2015-01-30 16:28:38.981023
"""
# revision identifiers, used by Alembic.
revision = '20c921506336'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=True),
sa.Column('email', …Run Code Online (Sandbox Code Playgroud) 我正在尝试为我的Pyramid项目配置SQLAlchemy Alembic,我想使用我的developement.ini(或production.ini)进行Alembic的配置设置.是否可以在Alembic中的任何地方指定我想使用的.ini文件?
我有几个我想在create table之后运行的自定义DDL语句:
update_function = DDL("""
CREATE OR REPLACE FUNCTION update_timestamp()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ language 'pgplsql';
""")
update_trigger = DDL("""
CREATE TRIGGER update %(table)s_timestamp BEFORE UPDATE
ON %(table)s FOR EACH ROW EXECUTE PROCEDURE update_timestamp();
""")
Run Code Online (Sandbox Code Playgroud)
而且我像这样附上他们:
event.listen(Session.__table__, 'after_create', update_function)
event.listen(Session.__table__, 'after_create', update_trigger)
Run Code Online (Sandbox Code Playgroud)
当我这样做时create_all,我得到了我期望的SQL:
CREATE OR REPLACE FUNCTION update_timestamp()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ language 'pgplsql';
CREATE TRIGGER update session_timestamp BEFORE UPDATE
ON session …Run Code Online (Sandbox Code Playgroud) 我试图首次对预先存在的数据库自动生成一个alembic修订版,但是当我运行以下命令时
alembic revision --autogenerate
Run Code Online (Sandbox Code Playgroud)
它会生成一个迁移,尝试在我的数据库中创建每个表和索引.与此类似:
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('table1',
sa.Column('id', sa.SmallInteger(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=True),
sa.Column('desc', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name'),
schema='schema1'
)
op.create_index(op.f('ix_index1'), 'table1', ['name'], unique=False, schema='schema1')
... all my other tables/indexes ..
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_index1'), table_name='table1', schema='schema1')
op.drop_table('table1', schema='schema1')
... all my other tables/indexes ..
Run Code Online (Sandbox Code Playgroud)
然后,如果我尝试运行迁移,它将失败,因为对象已经存在:
sqlalchemy.exc.ProgrammingError: (ProgrammingError) relation "table1" already exists
Run Code Online (Sandbox Code Playgroud)
所以在我看来,像alembic认为我的数据库不包含任何表,但确实如此.
任何想法为什么会这样?
我一直在使用Flask-Migrate(Alembic)来更新我的数据库.我更新了我的models.py文件,但是我犯了一个错误.我运行了迁移并去升级数据库,但是我收到了这个错误:
sqlalchemy.exc.IntegrityError: (_mysql_exceptions.IntegrityError) (1215, 'Cannot add foreign key constraint') [SQL: u'\nCREATE TABLE topics (\n\tid INTEGER NOT NULL AUTO_INCREMENT, \n\t`subjectID` INTEGER, \n\ttopic VARCHAR(150) NOT NULL, \n\tPRIMARY KEY (id), \n\tFOREIGN KEY(`subjectID`) REFERENCES subjects (id)\n)\n\n']
Run Code Online (Sandbox Code Playgroud)
我所做的是db.Text取而代之的db.Integer是外键.
当我尝试运行新的迁移时,我得到了这个:
alembic.util.CommandError: Target database is not up to date.
Run Code Online (Sandbox Code Playgroud)
所以现在我被卡住了.我无法升级数据库,也无法运行迁移.我尝试使用以下内容降级到较旧的数据库版本:
python manage.py db downgrade --sql b877018671c:36949b1cca31
Run Code Online (Sandbox Code Playgroud)
但是当我运行时,python manage.py db current我得到了最新的数据库版本,我被困在其中.
有没有解决这个问题?谢谢.
alembic ×10
python ×8
sqlalchemy ×5
postgresql ×4
database ×1
ddl ×1
flask ×1
orm ×1
pyramid ×1
upgrade ×1