Skip to content

Commit

Permalink
fix relative ids for downgrade/upgrade (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidism authored Feb 22, 2024
2 parents e13ced3 + 2803324 commit 311d1bc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

Unlreleased

- Fix handling of relative ids (`+1`, `-1`) passed to `downgrade` and `upgrade`.

## Version 3.0.0

Released 2024-02-08
Expand Down
17 changes: 12 additions & 5 deletions src/flask_alembic/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ def _simplify_rev(
return [r.revision for r in self.current()]
elif handle_int:
try:
return [str(int(rev))]
return [f"{int(rev):+d}"]
except ValueError:
return [rev]
else:
Expand All @@ -341,7 +341,8 @@ def _simplify_rev(
return [rev.revision]

if isinstance(rev, int):
return [str(rev)]
# Positive relative ids must have + prefix.
return [f"{rev:+d}"]

return [r.revision if isinstance(r, Script) else r for r in rev]

Expand Down Expand Up @@ -377,7 +378,12 @@ def upgrade(self, target: int | str | Script = "heads") -> None:
:param target: Revision to go up to.
"""
target_arg = self._simplify_rev(target, handle_int=True)
target_arg: list[str] | str = self._simplify_rev(target, handle_int=True)

if len(target_arg) == 1:
# Despite its signature, _upgrade_revs can take a list of ids. But
# if it's a relative id (+1), it must be a single value.
target_arg = target_arg[0]

def do_upgrade(
revision: str | list[str] | tuple[str, ...], context: MigrationContext
Expand All @@ -394,13 +400,14 @@ def downgrade(self, target: int | str | Script = -1) -> None:
:param target: Revision to go down to.
"""
target_arg = self._simplify_rev(target, handle_int=True)
# Unlike upgrade, downgrade always requires a single id.
target_arg = self._simplify_rev(target, handle_int=True)[0]

def do_downgrade(
revision: str | list[str] | tuple[str, ...], context: MigrationContext
) -> list[MigrationStep]:
return self.script_directory._downgrade_revs( # type: ignore[return-value]
target_arg, # type: ignore[arg-type]
target_arg,
revision, # type: ignore[arg-type]
)

Expand Down

0 comments on commit 311d1bc

Please sign in to comment.