Pan Luo <luopa...@gmail.com> wrote:

> If someone new come to the project and they use  db.create_all() or some 
> script to create a fresh new database with declared models. There is no 
> alembic_version table and he/she will run into problems when doing the 
> upgrade. Is there something in alembic to support it? I have been poking 
> around and came up with the following:
> 
>  alembic_cfg = Config("alembic.ini")
>  context = MigrationContext.configure(db.engine.connect())
>  current_rev = context.get_current_revision()
>  context._ensure_version_table()
> 
>  script = ScriptDirectory.from_config(alembic_cfg)
>  head_revision = script.get_current_head()
>  context.stamp(script, head_revision)
> 
>  command.downgrade(alembic_cfg, "base")
> 
> However, it works with file based sqlite db but no in memory one: Error: 
> Destination base is not a valid downgrade target from current head(s)
> 
> It seems the migrationcontext use different from the one I generated and the 
> one used in the alembic, so the current revision was empty when I do the 
> downgrade (just for. Not sure why file based sqlite works.

A SQLite :memory: database only exists with the span of a single SQLite 
database connection.   You get that above when you call db.engine.connect().   
But then when you call command.downgrade(), you are not passing this connection 
to that command in any way; the connection is stuck inside your 
MigrationContext which isn’t present in command.downgrade(alembic_cfg).   
command.downgrade() then calls upon your env.py in order to get the database 
connection, and you probably have another engine.connect() in there using a 
different engine (and therefore connection pool).  This makes a brand new 
:memory: connection that has no state on it.

So you’d want to send an argument into the alembic_cfg in this case which 
refers to that connection from db.engine.connect(), which your env.py can pull 
out and make use of instead of connecting in some other way.  This requires 
modifications to your env.py to look for this connection and use it, instead of 
connecting again. Or you can set up this connection as a global variable 
somewhere.

This is a common issue so at some point I will add recipes to the documentation 
that show how to transfer a connection from the outside of command.xyz(), 
through the env.py and into the migration context.


-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy-alembic" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy-alembic+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to