Skip to main content
`Ctrl`+`K`

# Script Directory

The `ScriptDirectory` object provides programmatic access to the Alembic version files present in the filesystem.

class alembic.script.Script(module: ModuleType, rev_id: str, path: str | PathLike[str])

  Represent a single revision file in a `versions/` directory.

  The `Script` instance is returned by methods such as `ScriptDirectory.iterate_revisions()`.

  property doc: str

    Return the docstring given in the script.

  property longdoc: str

    Return the docstring given in the script.

  module: ModuleType

    The Python module representing the actual script itself.

  path: str

    Filesystem path of the script.

class alembic.script.ScriptDirectory(dir: str | os.PathLike[str], file_template: str = '%(rev)s_%(slug)s', truncate_slug_length: int | None = 40, version_locations: Sequence[str | os.PathLike[str]] | None = None, sourceless: bool = False, output_encoding: str = 'utf-8', timezone: str | None = None, hooks: list[PostWriteHookConfig] = [], recursive_version_locations: bool = False, messaging_opts: MessagingOptions = {})

  Provides operations upon an Alembic script directory.

  This object is useful to get information as to current revisions, most notably being able to get at the “head” revision, for schemes that want to test if the current revision in the database is the most recent:

      from alembic.script import ScriptDirectory
      from alembic.config import Config
      config = Config()
      config.set_main_option("script_location", "myapp:migrations")
      script = ScriptDirectory.from_config(config)

      head_revision = script.get_current_head()

  as_revision_number(id_: str | None) → str | Tuple[str, ...] | None

    Convert a symbolic revision, i.e. ‘head’ or ‘base’, into an actual revision number.

  classmethod from_config(config: Config) → ScriptDirectory

    Produce a new `ScriptDirectory` given a `Config` instance.

    The `Config` need only have the `script_location` key present.

  generate_revision(revid: str, message: str | None, head: _RevIdType | None = None, splice: bool | None = False, branch_labels: _RevIdType | None = None, version_path: str | os.PathLike[str] | None = None, file_template: str | None = None, depends_on: _RevIdType | None = None, **kw: Any) → Script | None

    Generate a new revision file.

    This runs the `script.py.mako` template, given template arguments, and creates a new file.

    Parameters:

      - revid – String revision id. Typically this comes from `alembic.util.rev_id()`.

      - message – the revision message, the one passed by the -m argument to the `revision` command.

      - head – the head revision to generate against. Defaults to the current “head” if no branches are present, else raises an exception.

      - splice – if True, allow the “head” version to not be an actual head; otherwise, the selected head must be a head (e.g. endpoint) revision.

  get_base() → str | None

    Return the “base” revision as a string.

    This is the revision number of the script that has a `down_revision` of None.

    If the script directory has multiple bases, an error is raised; `ScriptDirectory.get_bases()` should be preferred.

  get_bases() → List[str]

    return all “base” revisions as strings.

    This is the revision number of all scripts that have a `down_revision` of None.

  get_current_head() → str | None

    Return the current head revision.

    If the script directory has multiple heads due to branching, an error is raised; `ScriptDirectory.get_heads()` should be preferred.

    Returns:

      a string revision number.

    See also

    `ScriptDirectory.get_heads()`

  get_heads() → List[str]

    Return all “versioned head” revisions as strings.

    This is normally a list of length one, unless branches are present. The `ScriptDirectory.get_current_head()` method can be used normally when a script directory has only one head.

    Returns:

      a tuple of string revision numbers.

  get_revision(id_: str) → Script

    Return the `Script` instance with the given rev id.

    See also

    `ScriptDirectory.get_revisions()`

  get_revisions(id_: _GetRevArg) → Tuple[Script, ...]

    Return the `Script` instance with the given rev identifier, symbolic name, or sequence of identifiers.

  iterate_revisions(upper: str | Tuple[str, ...] | None, lower: str | Tuple[str, ...] | None, **kw: Any) → Iterator[Script]

    Iterate through script revisions, starting at the given upper revision identifier and ending at the lower.

    The traversal uses strictly the down_revision marker inside each migration script, so it is a requirement that upper >= lower, else you’ll get nothing back.

    The iterator yields `Script` objects.

    See also

    `RevisionMap.iterate_revisions()`

  run_env() → None

    Run the script environment.

    This basically runs the `env.py` script present in the migration environment. It is called exclusively by the command functions in `alembic.command`.

  property versions: str

    return a single version location based on the sole path passed within version_locations.

    If multiple version locations are configured, an error is raised.

  walk_revisions(base: str = 'base', head: str = 'heads') → Iterator[Script]

    Iterate through all revisions.

    Parameters:

      - base – the base revision, or “base” to start from the empty revision.

      - head – the head revision; defaults to “heads” to indicate all head revisions. May also be “head” to indicate a single head revision.

## Revision

The `RevisionMap` object serves as the basis for revision management, used exclusively by `ScriptDirectory`.

exception alembic.script.revision.CycleDetected(revisions: Sequence[str])

exception alembic.script.revision.DependencyCycleDetected(revisions: Sequence[str])

exception alembic.script.revision.DependencyLoopDetected(revision: Sequence[str])

exception alembic.script.revision.LoopDetected(revision: str)

exception alembic.script.revision.MultipleHeads(heads: Sequence[str], argument: str | None)

exception alembic.script.revision.RangeNotAncestorError(lower: str | Tuple[str, ...] | None, upper: str | Tuple[str, ...] | None)

exception alembic.script.revision.ResolutionError(message: str, argument: str)

class alembic.script.revision.Revision(revision: str, down_revision: str | Tuple[str, ...] | None, dependencies: str | Tuple[str, ...] | None = None, branch_labels: str | Tuple[str, ...] | None = None)

  Base class for revisioned objects.

  The `Revision` class is the base of the more public-facing `Script` object, which represents a migration script. The mechanics of revision management and traversal are encapsulated within `Revision`, while `Script` applies this logic to Python files in a version directory.

  branch_labels: Set[str] = None

    Optional string/tuple of symbolic names to apply to this revision’s branch

  dependencies: str | List[str] | Tuple[str, ...] | None = None

    Additional revisions which this revision is dependent on.

    From a migration standpoint, these dependencies are added to the down_revision to form the full iteration. However, the separation of down_revision from “dependencies” is to assist in navigating a history that contains many branches, typically a multi-root scenario.

  down_revision: str | List[str] | Tuple[str, ...] | None = None

    The `down_revision` identifier(s) within the migration script.

    Note that the total set of “down” revisions is down_revision + dependencies.

  property is_base: bool

    Return True if this `Revision` is a ‘base’ revision.

  property is_branch_point: bool

    Return True if this `Script` is a branch point.

    A branchpoint is defined as a `Script` which is referred to by more than one succeeding `Script`, that is more than one `Script` has a down_revision identifier pointing here.

  property is_head: bool

    Return True if this `Revision` is a ‘head’ revision.

    This is determined based on whether any other `Script` within the `ScriptDirectory` refers to this `Script`. Multiple heads can be present.

  property is_merge_point: bool

    Return True if this `Script` is a merge point.

  nextrev: FrozenSet[str] = frozenset({})

    following revisions, based on down_revision only.

  revision: str = None

    The string revision number.

exception alembic.script.revision.RevisionError

class alembic.script.revision.RevisionMap(generator: Callable[[], Iterable[Revision]])

  Maintains a map of `Revision` objects.

  `RevisionMap` is used by `ScriptDirectory` to maintain and traverse the collection of `Script` objects, which are themselves instances of `Revision`.

  Construct a new `RevisionMap`.

  Parameters:

    generator – a zero-arg callable that will generate an iterable of `Revision` instances to be used. These are typically `Script` subclasses within regular Alembic use.

  add_revision(revision: Revision, _replace: bool = False) → None

    add a single revision to an existing map.

    This method is for single-revision use cases, it’s not appropriate for fully populating an entire revision map.

  bases

    All “base” revisions as strings.

    These are revisions that have a `down_revision` of None, or empty tuple.

    Returns:

      a tuple of string revision numbers.

  get_current_head(branch_label: str | None = None) → str | None

    Return the current head revision.

    If the script directory has multiple heads due to branching, an error is raised; `ScriptDirectory.get_heads()` should be preferred.

    Parameters:

      branch_label – optional branch name which will limit the heads considered to those which include that branch_label.

    Returns:

      a string revision number.

    See also

    `ScriptDirectory.get_heads()`

  get_revision(id_: str | None) → Revision | None

    Return the `Revision` instance with the given rev id.

    If a symbolic name such as “head” or “base” is given, resolves the identifier into the current head or base revision. If the symbolic name refers to multiples, `MultipleHeads` is raised.

    Supports partial identifiers, where the given identifier is matched against all identifiers that start with the given characters; if there is exactly one match, that determines the full revision.

  get_revisions(id_: _GetRevArg | None) → Tuple[_RevisionOrBase | None, ...]

    Return the `Revision` instances with the given rev id or identifiers.

    May be given a single identifier, a sequence of identifiers, or the special symbols “head” or “base”. The result is a tuple of one or more identifiers, or an empty tuple in the case of “base”.

    In the cases where ‘head’, ‘heads’ is requested and the revision map is empty, returns an empty tuple.

    Supports partial identifiers, where the given identifier is matched against all identifiers that start with the given characters; if there is exactly one match, that determines the full revision.

  heads

    All “head” revisions as strings.

    This is normally a tuple of length one, unless unmerged branches are present.

    Returns:

      a tuple of string revision numbers.

  iterate_revisions(upper: str | Tuple[str, ...] | None, lower: str | Tuple[str, ...] | None, implicit_base: bool = False, inclusive: bool = False, assert_relative_length: bool = True, select_for_downgrade: bool = False) → Iterator[Revision]

    Iterate through script revisions, starting at the given upper revision identifier and ending at the lower.

    The traversal uses strictly the down_revision marker inside each migration script, so it is a requirement that upper >= lower, else you’ll get nothing back.

    The iterator yields `Revision` objects.

## Write Hooks

alembic.script.write_hooks.register(name: str) → Callable

  A function decorator that will register that function as a write hook.

  See the documentation linked below for an example.

  See also

  Writing Custom Hooks as Python Functions