Flask migrate error target database is not up to date

I'd like to make a migration for a Flask app. I am using Alembic. However, I receive the following error. Target database is not up to date. Online, I read that it has something to do with this. h...

After creating a migration, either manually or as --autogenerate, you must apply it with alembic upgrade head. If you used db.create_all() from a shell, you can use alembic stamp head to indicate that the current state of the database represents the application of all migrations.

answered Jul 21, 2013 at 20:25

davidism's user avatar

0

This Worked For me

$ flask db stamp head
$ flask db migrate
$ flask db upgrade

answered Oct 28, 2019 at 5:43

XeusKing's user avatar

XeusKingXeusKing

1,5801 gold badge10 silver badges17 bronze badges

1

My stuation is like this question, When I execute «./manage.py db migrate -m ‘Add relationship'», the error occused like this »
alembic.util.exc.CommandError: Target database is not up to date.»

So I checked the status of my migrate:

(venv) ]#./manage.py db heads
d996b44eca57 (head)
(venv) ]#./manage.py db current
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
715f79abbd75

and found that the heads and the current are different!

I fixed it by doing this steps:

(venv)]#./manage.py db stamp heads
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running stamp_revision 715f79abbd75 -> d996b44eca57

And now the current is same to the head

(venv) ]#./manage.py db current
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
d996b44eca57 (head)

And now I can do the migrate again.

answered Dec 3, 2018 at 12:31

LittleLogic's user avatar

LittleLogicLittleLogic

4314 silver badges3 bronze badges

2

This can be solved bby many ways :

1 To fix this error, delete the latest migration file ( a python file) then try to perform a migration afresh.

If issue still persists try these commands :

$ flask db stamp head  # To set the revision in the database to the head, without performing any migrations. You can change head to the required change you want.
$ flask db migrate     # To detect automatically all the changes.
$ flask db upgrade     # To apply all the changes.

answered May 23, 2020 at 9:48

Anupam Haldkar's user avatar

1

$ flask db stamp head  # To set the revision in the database to the head, without performing any migrations. You can change head to the required change you want.
$ flask db migrate  # To detect automatically all the changes.
$ flask db upgrade  # To apply all the changes.

You can find more info at the documentation https://flask-migrate.readthedocs.io/en/latest/

answered Jan 6, 2020 at 12:02

Sergi Ramón's user avatar

I had to delete some of my migration files for some reason. Not sure why. But that fixed the problem, kind of.

One issue is that the database ends up getting updated properly, with all the new tables, etc, but the migration files themselves don’t show any changes when I use automigrate.

If someone has a better solution, please let me know, as right now my solution is kind of hacky.

answered Jul 21, 2013 at 4:56

GangstaGraham's user avatar

GangstaGrahamGangstaGraham

8,55512 gold badges41 silver badges60 bronze badges

1

I did too run into different heads and I wanted to change one of the fields from string to integer, so first run:

$ flask db stamp head # to make the current the same
$ flask db migrate
$ flask db upgrade

It’s solved now!

answered Nov 2, 2019 at 1:10

Serg's user avatar

SergSerg

1231 silver badge8 bronze badges

To fix this error, delete the latest migration file ( a python file) then try to perform a migration afresh.

answered Jun 24, 2018 at 19:00

Patrick Mutuku's user avatar

1

This can also happen if you, like myself, have just started a new project and you are using in-memory SQLite database (sqlite:///:memory:). If you apply a migration on such a database, obviously the next time you want to say auto-generate a revision, the database will still be in its original state (empty), so alembic will be complaining that the target database is not up to date. The solution is to switch to a persisted database.

answered Nov 13, 2019 at 16:00

jbasko's user avatar

jbaskojbasko

6,8781 gold badge38 silver badges51 bronze badges

I also had the same problem input with flask db migrate
I used
flask db stamp head
and then
flask db migrate

answered Sep 2, 2022 at 23:19

Vector's user avatar

Try to drop all tables before execute the db upgrade command.

answered Sep 19, 2018 at 16:45

Rafael Rotiroti's user avatar

To solve this, I drop(delete) the tables in migration and run these commands

flask db migrate

and

flask db upgrade

answered Feb 8, 2019 at 19:42

fill_J's user avatar

fill_Jfill_J

4295 silver badges13 bronze badges

I’d like to make a migration for a Flask app. I am using Alembic.

However, I receive the following error.

Target database is not up to date.

Online, I read that it has something to do with this.
http://alembic.zzzcomputing.com/en/latest/cookbook.html#building-an-up-to-date-database-from-scratch

Unfortunately, I don’t quite understand how to get the database up to date and where/how I should write the code given in the link.

1) Solution

After creating a migration, either manually or as --autogenerate, you must apply it with alembic upgrade head. If you used db.create_all() from a shell, you can use alembic stamp head to indicate that the current state of the database represents the application of all migrations.

2) Solution

This Worked For me

$ flask db stamp head
$ flask db migrate
$ flask db upgrade
3) Solution

My stuation is like this question, When I execute «./manage.py db migrate -m ‘Add relationship'», the error occused like this »
alembic.util.exc.CommandError: Target database is not up to date.»

So I checked the status of my migrate:

(venv) ]#./manage.py db heads
d996b44eca57 (head)
(venv) ]#./manage.py db current
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
715f79abbd75

and found that the heads and the current are different!

I fixed it by doing this steps:

(venv)]#./manage.py db stamp heads
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running stamp_revision 715f79abbd75 -> d996b44eca57

And now the current is same to the head

(venv) ]#./manage.py db current
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
d996b44eca57 (head)

And now I can do the migrate again.

4) Solution

This can be solved bby many ways :

1 To fix this error, delete the latest migration file ( a python file) then try to perform a migration afresh.

If issue still persists try these commands :

$ flask db stamp head  # To set the revision in the database to the head, without performing any migrations. You can change head to the required change you want.
$ flask db migrate     # To detect automatically all the changes.
$ flask db upgrade     # To apply all the changes.
5) Solution
$ flask db stamp head  # To set the revision in the database to the head, without performing any migrations. You can change head to the required change you want.
$ flask db migrate  # To detect automatically all the changes.
$ flask db upgrade  # To apply all the changes.

You can find more info at the documentation https://flask-migrate.readthedocs.io/en/latest/

6) Solution

I had to delete some of my migration files for some reason. Not sure why. But that fixed the problem, kind of.

One issue is that the database ends up getting updated properly, with all the new tables, etc, but the migration files themselves don’t show any changes when I use automigrate.

If someone has a better solution, please let me know, as right now my solution is kind of hacky.

7) Solution

I did too run into different heads and I wanted to change one of the fields from string to integer, so first run:

$ flask db stamp head # to make the current the same
$ flask db migrate
$ flask db upgrade

It’s solved now!

8) Solution

To fix this error, delete the latest migration file ( a python file) then try to perform a migration afresh.

9) Solution

This can also happen if you, like myself, have just started a new project and you are using in-memory SQLite database (sqlite:///:memory:). If you apply a migration on such a database, obviously the next time you want to say auto-generate a revision, the database will still be in its original state (empty), so alembic will be complaining that the target database is not up to date. The solution is to switch to a persisted database.

10) Solution

Try to drop all tables before execute the db upgrade command.

11) Solution

To solve this, I drop(delete) the tables in migration and run these commands

flask db migrate

and

flask db upgrade

Comments Section

I know it is a bit old now, but do your tables inherit from Base? I had the same issue and automigrate wasn’t picking up changes due to the fact that my new tables weren’t inheriting from Base where base is Base = declarative_base() and also remember from sqlalchemy.ext.declarative import declarative_base

Works like a charm ! I feel this is the best way to manage this issue !

Same here! Worked smooth. I knew it had do with db heads and current, but didn’t know there is «stamp» command. Thanks!

I deleted the latest migration file. Its works! thx

This worked for me when I wanted to regenerate a migration file because the first was incomplete.

Related Topics
alembic

Mentions
Braiam
Davidism
Jbasko
Patrick Mutuku
Serg
Gangsta Graham
Anupam Haldkar
Rafael Rotiroti
Xeus King
Little Logic

References
17768940/target-database-is-not-up-to-date

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

mattgathu opened this issue

Jan 26, 2015

· 12 comments

Comments

@mattgathu

I’m running a database migration, and Alembic complains with
alembic.util.CommandError: Target database is not up to date.

So and I then run a database upgrade
python manage.py db upgrade

Here is the output:
INFO [alembic.migration] Context impl PostgresqlImpl.
INFO [alembic.migration] Will assume transactional DDL.
INFO [alembic.migration] Running upgrade 604497a5e5 -> 431e33e6fce, empty message

The issue is that Alembic never finishes the upgrade (never quits the terminal) and it appears stuck on the third step, I have tried severally, even leaving it for several minutes but it never completes the upgrade.
I have tried running this locally and on the server and it doesn’t work (it’s not an issue with the connection).

@jwindridge

What was your fix? I’m having the same issue!

@mattgathu

I can’t quite remember, but I reckon you could squash the migration by deleting it (since it’s not committed) and redoing the migrate and upgrade steps again.

@jwindridge

Thanks for the reply — worked it out in the end:
I had a database session open in a flask shell, which was preventing alembic from obtaining a lock and therefore running the update — finished the session and then the migration worked fine.

dhhagan, gaotongfei, noisytoken, Toilal, kvudata, utsavtiwary04, pradeepb6, rns4731, tomsing1, SirNeuman, and 32 more reacted with thumbs up emoji
Mukhametvaleev, kiptoomm, precious, cyzanfar, AtaruOhto, AndreyS87, kuba1302, melisekm, fasiha, and felixminom reacted with hooray emoji
fasiha and felixminom reacted with rocket emoji

@samakshjain

@authentik8 Had the same problem, thanks ! 👍
P.S. I noticed that you found the fix after 2 days. Just wondering, did you let it be like that for two days ?

@jwindridge

No problem, put up an explanation for exactly that reason!

In reply to your PS, no (I was out for one of the middle days anyway!) — I got as far as working out that if I killed and recreated my tmux session whenever it hung then I could get it to work. Obviously the issue was intermittent as I only had a flask shell open some of the time, but it worked «well enough» for a while.

Eventually I got tired of having to reconfigure all of my panes after every time it hung, so I decided to stop developing more stuff until I resolved it. Took me about 15 minutes of playing around with different things until I could isolate the cause (which then made sense, reading the SQLAlchemy docs on how sessions work).

@samakshjain

Yep, this should have been obvious, ha!.
I had around 3 terminals open one for vim, one for the flask server and the other for the flask shell, still I didn’t notice. palm to the face.

@rnm-patel

This is happening also because of thread with an infinite loop (intentionally for checking some kind of event),

@Sparrow1029

@samakshjain Thank you for saying so. I use gnu screen as well, and that was the exact problem! Also facepalm

@reinoldus

Just adding this as a potential cause:
For me, it was a docker container running in the background that was locking the database…

@kangju1

For those who want to run alembic upgrade when app is running, add the following code in your project’s app file.

@app.teardown_appcontext
    def shutdown_session(exception=None):
        db.remove()

the variable db is the database session from your database setting file. so you should import it first.
you have to remove the session (return it to the pool) after each request.

When alembic runs, it uses flask’s app context, and the currently running app is holding all connections, which means there are no available connections for alembic to use.

https://flask.palletsprojects.com/en/1.0.x/appcontext/

@jabbawockeez

For me, it’s because the type tinyint and bool are the same thing in mysql but alembic sees them differently, so every time I upgrade it stuck. See here for more detail.

@edwardmoradian

Same issue — for me I had one of my tables misspelled such as in
tablename = ‘nlp_words_in_topics_t’
Check syntax, spelling errors

A question that I frequently get is how to start tracking database migrations with my Flask-Migrate extension when the project has an established database, making it impossible to delete everything and start over from scratch. In this article and companion video I’m going to show you how to set up Flask-Migrate with zero risk for your current database.

Installing and Configuring Flask-Migrate

This step is the same for new and existing projects. Assuming you have a project that uses Flask-SQLAlchemy to manage a database, you begin by installing the Flask-Migrate extension:

(venv) $ pip install flask-migrate

The extension then needs to be added to the project. This involves creating and initializing a Migrate instance. If you use the direct method of creating extensions:

from flask_migrate import Migrate

app = Flask(__name__)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

If you use an application factory function you very likely use the delayed method to create your extensions. In that case you would initialize Flask-Migrate as follows:

from flask_migrate import Migrate

db = SQLAlchemy()
migrate = Migrate()

def create_app():
    app = Flask(__name__)
    db.init_app(app)
    migrate.init_app(app, db)
    return app

Once the extension is added to the project you will have a flask db command available:

(venv) $ flask db
Usage: flask db [OPTIONS] COMMAND [ARGS]...

  Perform database migrations.

Options:
  --help  Show this message and exit.

Commands:
  branches   Show current branch points
  current    Display the current revision for each...
  downgrade  Revert to a previous version
  edit       Edit a revision file
  heads      Show current available heads in the script...
  history    List changeset scripts in chronological...
  init       Creates a new migration repository.
  merge      Merge two revisions together, creating a new...
  migrate    Autogenerate a new revision file (Alias for...
  revision   Create a new revision file.
  show       Show the revision denoted by the given...
  stamp      'stamp' the revision table with the given...
  upgrade    Upgrade to a later version

Creating the Migration Repository

The next step in the process is to create a database migration repository. This is a directory where all the migration scripts are going to be stored. The migration repository should be considered part of your source code, and should be added to your source control.

To create the repository you can use the init command:

(venv) $ flask db init
  Creating directory /Users/mgrinberg/microblog/migrations ... done
  Creating directory /Users/mgrinberg/microblog/migrations/versions ... done
  Generating /Users/mgrinberg/microblog/migrations/script.py.mako ... done
  Generating /Users/mgrinberg/microblog/migrations/env.py ... done
  Generating /Users/mgrinberg/microblog/migrations/README ... done
  Generating /Users/mgrinberg/microblog/migrations/alembic.ini ... done
  Please edit configuration/connection/logging settings in 'migrations/alembic.ini' before proceeding.

This command adds a migrations directory in the root of your project. Add the directory and all of its contents to source control.

Creating the Initial Migration

If you look at the documentation, the next step in the process is to create an initial migration for your project, using the migrate command:

(venv) $ flask db migrate

This step does not actually work if you have an existing project that has a populated database:

(venv) $ flask db migrate
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.env] No changes in schema detected.

The «No changes in schema detected» message indicates that there is no need to migrate the database. But how can that be if we are just getting started with migrations in this project?

To understand the problem you have to think about how Alembic (the migration engine used by Flask-Migrate) generates database migrations. The contents of a migration are obtained by running a comparison between the current model definitions and the current schema of your database.

In a new project the models are going to be compared against a brand new (empty) database, so the migration script will include all the model definitions. For an existing project the database is up to date and in sync with the models, so there are no differences, and thus, Alembic thinks that there is nothing to put in the database migration script.

The trick to generate this initial migration for a project that uses an up to date database is to temporarily switch to an empty database, just for the flask db migrate command. In my projects I use a DATABASE_URL environment variable to configure the location of the database. This is a good practice that I recommend you follow as well, because with this variable it is easy to redirect to another database.

In general you can replace your real database with an in-memory SQLite database, just for the migrate command:

(venv) $ DATABASE_URL=sqlite:/// flask db migrate
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.autogenerate.compare] Detected added table 'user'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_user_email' on '['email']'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_user_token' on '['token']'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_user_username' on '['username']'
INFO  [alembic.autogenerate.compare] Detected added table 'followers'
INFO  [alembic.autogenerate.compare] Detected added table 'message'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_message_timestamp' on '['timestamp']'
INFO  [alembic.autogenerate.compare] Detected added table 'notification'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_notification_name' on '['name']'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_notification_timestamp' on '['timestamp']'
INFO  [alembic.autogenerate.compare] Detected added table 'post'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_post_timestamp' on '['timestamp']'
INFO  [alembic.autogenerate.compare] Detected added table 'task'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_task_name' on '['name']'
  Generating migrations/versions/97180cecd04b_.py ... done

Using an in-memory SQLite database is very convenient, but will only work if you are in one of the two following situations:

  • You are also using SQLite for your real database
  • You are using another database engine (MySQL, Postgres, etc.), but your models are written generically, without using any constructs that are specific to your chosen engine.

If you cannot use an in-memory SQLite database, then go to your database server and create a new database there, and then set DATABASE_URL to it for the migrate command. Once you have generated the first migration you can delete the empty database from your server.

The next step according to the documentation is to run the upgrade command, which executes the migration script and applies the changes in it to your database. Obviously this is also going to fail, because the database does not need updating. Instead you have to tell Flask-Migrate and Alembic that the database is up to date. You can do this with the stamp command»

(venv) $ flask db stamp head

This command will add a alembic_version table to your database, and will store the initial migration generated above as the current migration. The head alias always points to the most recent migration, which in our case is the first and only one currently in the repository.

As I mentioned above, the contents of the migrations directory needs to be under source control. Remember to add the new migration script, which you will find in the migrations/versions directory.

Updating Additional Databases

You will likely have multiple databases for your application, at least one for development and one for production. You may be part of a team, so each team member will have their own development database in their local systems. Once you created the initial migration and added it to source control, you can just «stamp» all the additional databases. For each additional database make sure the code is refreshed from source control to include the migration repository and then just run the stamp command from above to «fix» the database:

(venv) $ flask db stamp head

Migration Workflow

From this point on you have a project that is fully enabled to use database migrations. The normal migration process goes as follows:

  • You will make some changes to your models in your Python source code.
  • You will then run flask db migrate to generate a new database migration for these changes.
  • You will finally apply the changes to the database by running flask db upgrade.

This cycle repeats every time new changes to the database schema are needed.

Conclusion

I hope this short tutorial clarifies how to add database migrations to your existing project. If you want to avoid the extra trouble required to get that first migration generated, in your next project consider adding Flask-Migrate from the start. It may seem unnecessary at first, but you’ll eventually want to have it.

Базовые сведения о работе SQLAlchemy в Flask.

Эта статья из цикла статей о создании сайта на Flask.

Для понимания этой статьи у вас должен быть создан каркас приложения. Если этого нет, прочитайте статью как сделать приложение на Flask.

Примеры запросов SQLAlchemy

Подготовка

В системе должен быть установлен python:
— как установить python на Mac OS
— как установить python на Ubuntu

Также должна быть создана виртуальная среда для работы команды pip. Если её еще нет:

Заходим внутрь виртуальной среды python:

Обновим pip:

pip install —upgrade pip

Установка

pip install Flask-SQLAlchemy
pip install Flask-Migrate
pip install psycopg2-binary

Основной синтаксис в файле __init__.py директории app:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config

def create_app():
    app = Flask(__name__)

    app.config.from_object(Config)
    app.config.from_pyfile(‘../config-extended.py’)

    return app

app = create_app()
db = SQLAlchemy(app)
migrate = Migrate(app, db)

Также должен быть создан файл конфигурации, в котором будут указаны данные для соединения с базой данных в различных средах. Об этом подробнее можно узнать в статье конфигурационные файлы Flask.

Миграция

Под миграцией подразумевается синхронизация классов модели с базой данных.

Перед миграцией должна быть создана база данных. Подробнее о создании бд есть в статье установки PostgreSQL.

При первой инициализации и создании таблиц в БД:

flask db init
flask db migrate -m «Initial migration.»
flask db upgrade

Справка:

Ошибки

1

Если при миграции возникнет ошибка:

ERROR [root] Error: Target database is not up to date.

Проделать следующее:

flask db stamp head
flask db migrate
flask db upgrade

2

FATAL: database «…» does not exist

Забыли создать базу данных или неправильно прописали подключение.

3

ERROR [root] Error: Multiple head revisions are present for given argument ‘head’; please specify a specific target revision, ‘

@head’ to narrow to a specific head, or ‘heads’ for all heads

Возникала при обновлении БД с локалки на лайве.

Для решения удаляем папку миграции с локалки и коммитим на сервер, там подтягиваем изменения. Вновь создаем эту директорию все теми же командами, что и раньше. Снова коммитим ее на сервер. Там обновляем БД:

Возможно понадобится предварительно заменить версию alembic в БД на ту же что и в локалке (если они не равны).

4

ERROR [root] Error: Can’t locate revision identified by ‘5e14ad967025’

а)

Удаляем таблицу алембик:

DROP TABLE alembic_version;

Затем обновляем БД из файлов миграции:

flask db init
flask db migrate -m «…»
flask db upgrade

б)

Пробуем поменять версию в таблице alembic_version на ту, которая уже есть в БД, которая работает нормально (если разработка ведется на нескольких компьютерах), затем:

flask db init
flask db upgrade

Прочие ошибки можно найти здесь.

Понравилась статья? Поделить с друзьями:
  • Flask json error
  • Flask internal server error render template
  • Flask error log
  • Fix win32bridge server exe startup error on windows 10
  • Fix video error