Skip to content

Commit b26a2c2

Browse files
committed
database migrate
1 parent c7bbd36 commit b26a2c2

7 files changed

Lines changed: 258 additions & 2 deletions

File tree

.gitignore

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,4 @@
77
# python
88
__pycache__
99

10-
# database
11-
migrations
10+
# database

migrations/README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.

migrations/alembic.ini

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# template used to generate migration files
5+
# file_template = %%(rev)s_%%(slug)s
6+
7+
# set to 'true' to run the environment during
8+
# the 'revision' command, regardless of autogenerate
9+
# revision_environment = false
10+
11+
12+
# Logging configuration
13+
[loggers]
14+
keys = root,sqlalchemy,alembic
15+
16+
[handlers]
17+
keys = console
18+
19+
[formatters]
20+
keys = generic
21+
22+
[logger_root]
23+
level = WARN
24+
handlers = console
25+
qualname =
26+
27+
[logger_sqlalchemy]
28+
level = WARN
29+
handlers =
30+
qualname = sqlalchemy.engine
31+
32+
[logger_alembic]
33+
level = INFO
34+
handlers =
35+
qualname = alembic
36+
37+
[handler_console]
38+
class = StreamHandler
39+
args = (sys.stderr,)
40+
level = NOTSET
41+
formatter = generic
42+
43+
[formatter_generic]
44+
format = %(levelname)-5.5s [%(name)s] %(message)s
45+
datefmt = %H:%M:%S

migrations/env.py

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
from __future__ import with_statement
2+
3+
import logging
4+
from logging.config import fileConfig
5+
6+
from sqlalchemy import engine_from_config
7+
from sqlalchemy import pool
8+
9+
from alembic import context
10+
11+
# this is the Alembic Config object, which provides
12+
# access to the values within the .ini file in use.
13+
config = context.config
14+
15+
# Interpret the config file for Python logging.
16+
# This line sets up loggers basically.
17+
fileConfig(config.config_file_name)
18+
logger = logging.getLogger('alembic.env')
19+
20+
# add your model's MetaData object here
21+
# for 'autogenerate' support
22+
# from myapp import mymodel
23+
# target_metadata = mymodel.Base.metadata
24+
from flask import current_app
25+
config.set_main_option(
26+
'sqlalchemy.url', current_app.config.get(
27+
'SQLALCHEMY_DATABASE_URI').replace('%', '%%'))
28+
target_metadata = current_app.extensions['migrate'].db.metadata
29+
30+
# other values from the config, defined by the needs of env.py,
31+
# can be acquired:
32+
# my_important_option = config.get_main_option("my_important_option")
33+
# ... etc.
34+
35+
36+
def run_migrations_offline():
37+
"""Run migrations in 'offline' mode.
38+
39+
This configures the context with just a URL
40+
and not an Engine, though an Engine is acceptable
41+
here as well. By skipping the Engine creation
42+
we don't even need a DBAPI to be available.
43+
44+
Calls to context.execute() here emit the given string to the
45+
script output.
46+
47+
"""
48+
url = config.get_main_option("sqlalchemy.url")
49+
context.configure(
50+
url=url, target_metadata=target_metadata, literal_binds=True
51+
)
52+
53+
with context.begin_transaction():
54+
context.run_migrations()
55+
56+
57+
def run_migrations_online():
58+
"""Run migrations in 'online' mode.
59+
60+
In this scenario we need to create an Engine
61+
and associate a connection with the context.
62+
63+
"""
64+
65+
# this callback is used to prevent an auto-migration from being generated
66+
# when there are no changes to the schema
67+
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
68+
def process_revision_directives(context, revision, directives):
69+
if getattr(config.cmd_opts, 'autogenerate', False):
70+
script = directives[0]
71+
if script.upgrade_ops.is_empty():
72+
directives[:] = []
73+
logger.info('No changes in schema detected.')
74+
75+
connectable = engine_from_config(
76+
config.get_section(config.config_ini_section),
77+
prefix='sqlalchemy.',
78+
poolclass=pool.NullPool,
79+
)
80+
81+
with connectable.connect() as connection:
82+
context.configure(
83+
connection=connection,
84+
target_metadata=target_metadata,
85+
process_revision_directives=process_revision_directives,
86+
**current_app.extensions['migrate'].configure_args
87+
)
88+
89+
with context.begin_transaction():
90+
context.run_migrations()
91+
92+
93+
if context.is_offline_mode():
94+
run_migrations_offline()
95+
else:
96+
run_migrations_online()

migrations/script.py.mako

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
${imports if imports else ""}
11+
12+
# revision identifiers, used by Alembic.
13+
revision = ${repr(up_revision)}
14+
down_revision = ${repr(down_revision)}
15+
branch_labels = ${repr(branch_labels)}
16+
depends_on = ${repr(depends_on)}
17+
18+
19+
def upgrade():
20+
${upgrades if upgrades else "pass"}
21+
22+
23+
def downgrade():
24+
${downgrades if downgrades else "pass"}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""empty message
2+
3+
Revision ID: b25fcdb3cfcc
4+
Revises:
5+
Create Date: 2019-07-19 21:28:12.190440
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
11+
12+
# revision identifiers, used by Alembic.
13+
revision = 'b25fcdb3cfcc'
14+
down_revision = None
15+
branch_labels = None
16+
depends_on = None
17+
18+
19+
def upgrade():
20+
# ### commands auto generated by Alembic - please adjust! ###
21+
op.create_table('users',
22+
sa.Column('id', sa.Integer(), nullable=False),
23+
sa.Column('name', sa.String(length=255), nullable=False),
24+
sa.Column('email', sa.String(length=50), nullable=False),
25+
sa.Column('password', sa.String(length=255), nullable=False),
26+
sa.Column('created', sa.TIMESTAMP(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
27+
sa.PrimaryKeyConstraint('id'),
28+
sa.UniqueConstraint('email'),
29+
mysql_collate='utf8_general_ci'
30+
)
31+
op.create_table('teams',
32+
sa.Column('id', sa.Integer(), nullable=False),
33+
sa.Column('name', sa.String(length=255), nullable=False),
34+
sa.Column('author_id', sa.Integer(), nullable=True),
35+
sa.ForeignKeyConstraint(['author_id'], ['users.id'], ),
36+
sa.PrimaryKeyConstraint('id'),
37+
mysql_collate='utf8_general_ci'
38+
)
39+
# ### end Alembic commands ###
40+
41+
42+
def downgrade():
43+
# ### commands auto generated by Alembic - please adjust! ###
44+
op.drop_table('teams')
45+
op.drop_table('users')
46+
# ### end Alembic commands ###
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""empty message
2+
3+
Revision ID: d6202514e0b0
4+
Revises: b25fcdb3cfcc
5+
Create Date: 2019-07-19 22:03:10.439818
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
from sqlalchemy.dialects import mysql
11+
12+
# revision identifiers, used by Alembic.
13+
revision = 'd6202514e0b0'
14+
down_revision = 'b25fcdb3cfcc'
15+
branch_labels = None
16+
depends_on = None
17+
18+
19+
def upgrade():
20+
# ### commands auto generated by Alembic - please adjust! ###
21+
op.create_table('posts',
22+
sa.Column('id', sa.Integer(), nullable=False),
23+
sa.Column('name', sa.String(length=255), nullable=False),
24+
sa.Column('author_id', sa.Integer(), nullable=True),
25+
sa.ForeignKeyConstraint(['author_id'], ['users.id'], ),
26+
sa.PrimaryKeyConstraint('id'),
27+
mysql_collate='utf8_general_ci'
28+
)
29+
op.drop_table('teams')
30+
# ### end Alembic commands ###
31+
32+
33+
def downgrade():
34+
# ### commands auto generated by Alembic - please adjust! ###
35+
op.create_table('teams',
36+
sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
37+
sa.Column('name', mysql.VARCHAR(length=255), nullable=False),
38+
sa.Column('author_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
39+
sa.ForeignKeyConstraint(['author_id'], ['users.id'], name='teams_ibfk_1'),
40+
sa.PrimaryKeyConstraint('id'),
41+
mysql_default_charset='utf8',
42+
mysql_engine='InnoDB'
43+
)
44+
op.drop_table('posts')
45+
# ### end Alembic commands ###

0 commit comments

Comments
 (0)