@@ -136,38 +136,42 @@ async def run_migration(
136136 if toversion is None :
137137 toversion = version
138138 files = []
139+
139140 conn = await asyncpg .connect (dsn = dsn )
140141 oldversion = await get_version (conn )
141-
142- if oldversion == toversion :
143- typer .echo (f"Target database already at version: { toversion } " )
144- return toversion
145- if oldversion is None :
146- typer .echo (f"No pgstac version set, installing { toversion } from scratch." )
147- files .append (os .path .join (migrations_dir , f"pgstac.{ toversion } .sql" ))
148- else :
149- typer .echo (f"Migrating from { oldversion } to { toversion } ." )
150- m = MigrationPath (migrations_dir , oldversion , toversion )
151- files = m .migrations ()
152-
153- if len (files ) < 1 :
154- raise Exception ("Could not find migration files" )
155-
156- typer .echo (f"Running migrations for { files } ." )
157-
158- for file in files :
159- migration_sql = get_sql (file )
160- async with conn .transaction ():
161- await conn .execute (migration_sql )
162- await conn .execute (
163- """
164- INSERT INTO pgstac.migrations (version)
165- VALUES ($1);
166- """ ,
167- toversion ,
168- )
169-
170- newversion = await get_version (conn )
171- await conn .close ()
172-
173- return newversion
142+ try :
143+ if oldversion == toversion :
144+ typer .echo (f"Target database already at version: { toversion } " )
145+ await conn .close ()
146+ return toversion
147+ if oldversion is None :
148+ typer .echo (f"No pgstac version set, installing { toversion } from scratch." )
149+ files .append (os .path .join (migrations_dir , f"pgstac.{ toversion } .sql" ))
150+ else :
151+ typer .echo (f"Migrating from { oldversion } to { toversion } ." )
152+ m = MigrationPath (migrations_dir , oldversion , toversion )
153+ files = m .migrations ()
154+
155+ if len (files ) < 1 :
156+ raise Exception ("Could not find migration files" )
157+
158+ typer .echo (f"Running migrations for { files } ." )
159+
160+ for file in files :
161+ migration_sql = get_sql (file )
162+ async with conn .transaction ():
163+ await conn .execute (migration_sql )
164+ await conn .execute (
165+ """
166+ INSERT INTO pgstac.migrations (version)
167+ VALUES ($1);
168+ """ ,
169+ toversion ,
170+ )
171+
172+ newversion = await get_version (conn )
173+ await conn .close ()
174+
175+ return newversion
176+ finally :
177+ await conn .close ()
0 commit comments