Skip to content

Configuration

mongrator can be configured via a TOML file or environment variables.

TOML file

mongrator init creates a mongrator.toml stub:

[mongrator]
uri = "mongodb://localhost:27017"
database = "mydb"
migrations_dir = "migrations"
collection = "mongrator_migrations"

Use --config PATH to specify an alternate config file location.

Environment variables

Variable Description Required
MONGRATOR_URI MongoDB connection URI yes
MONGRATOR_DB Database name yes
MONGRATOR_MIGRATIONS_DIR Path to migrations directory no (default: migrations)
MONGRATOR_COLLECTION Tracking collection name no (default: mongrator_migrations)

Environment variables are used when no config file is found at the expected path.

Programmatic configuration

mongrator.config.MigratorConfig dataclass

Immutable configuration for a migrator instance.

Source code in src/mongrator/config.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
@dataclass(frozen=True)
class MigratorConfig:
    """Immutable configuration for a migrator instance."""

    uri: str
    database: str
    migrations_dir: Path
    collection: str = _DEFAULT_COLLECTION

    @classmethod
    def from_toml(cls, path: Path) -> Self:
        """Load configuration from a TOML file (e.g. mongrator.toml)."""
        try:
            with open(path, "rb") as f:
                data = tomllib.load(f)
        except FileNotFoundError:
            raise ConfigurationError(f"Config file not found: {path}")
        except tomllib.TOMLDecodeError as e:
            raise ConfigurationError(f"Invalid TOML in {path}: {e}")

        cfg = data.get("mongrator", data)

        try:
            uri: str = cfg["uri"]
            database: str = cfg["database"]
        except KeyError as e:
            raise ConfigurationError(f"Missing required config key: {e}")

        migrations_dir = Path(cfg.get("migrations_dir", str(_DEFAULT_MIGRATIONS_DIR)))
        collection: str = cfg.get("collection", _DEFAULT_COLLECTION)
        return cls(uri=uri, database=database, migrations_dir=migrations_dir, collection=collection)

    @classmethod
    def from_env(cls, dotenv_path: Path | None = None) -> Self:
        """Load configuration from environment variables.

        If *dotenv_path* is given and the file exists, its values are used as
        defaults — real environment variables always take precedence.

        Variables:
            MONGRATOR_URI         — MongoDB connection URI (required)
            MONGRATOR_DB          — database name (required)
            MONGRATOR_MIGRATIONS_DIR — path to migrations directory (default: migrations)
            MONGRATOR_COLLECTION  — tracking collection name (default: mongrator_migrations)
        """
        dotenv: dict[str, str] = {}
        if dotenv_path is not None:
            dotenv = _load_dotenv(dotenv_path)

        def _get(key: str, default: str | None = None) -> str | None:
            if key in os.environ:
                return os.environ[key]
            if key in dotenv:
                return dotenv[key]
            return default

        uri = _get("MONGRATOR_URI")
        database = _get("MONGRATOR_DB")
        if not uri:
            raise ConfigurationError("MONGRATOR_URI environment variable is not set")
        if not database:
            raise ConfigurationError("MONGRATOR_DB environment variable is not set")
        migrations_dir = Path(_get("MONGRATOR_MIGRATIONS_DIR") or str(_DEFAULT_MIGRATIONS_DIR))
        collection = _get("MONGRATOR_COLLECTION") or _DEFAULT_COLLECTION
        return cls(uri=uri, database=database, migrations_dir=migrations_dir, collection=collection)

from_toml(path) classmethod

Load configuration from a TOML file (e.g. mongrator.toml).

Source code in src/mongrator/config.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
@classmethod
def from_toml(cls, path: Path) -> Self:
    """Load configuration from a TOML file (e.g. mongrator.toml)."""
    try:
        with open(path, "rb") as f:
            data = tomllib.load(f)
    except FileNotFoundError:
        raise ConfigurationError(f"Config file not found: {path}")
    except tomllib.TOMLDecodeError as e:
        raise ConfigurationError(f"Invalid TOML in {path}: {e}")

    cfg = data.get("mongrator", data)

    try:
        uri: str = cfg["uri"]
        database: str = cfg["database"]
    except KeyError as e:
        raise ConfigurationError(f"Missing required config key: {e}")

    migrations_dir = Path(cfg.get("migrations_dir", str(_DEFAULT_MIGRATIONS_DIR)))
    collection: str = cfg.get("collection", _DEFAULT_COLLECTION)
    return cls(uri=uri, database=database, migrations_dir=migrations_dir, collection=collection)

from_env(dotenv_path=None) classmethod

Load configuration from environment variables.

If dotenv_path is given and the file exists, its values are used as defaults — real environment variables always take precedence.

Variables

MONGRATOR_URI — MongoDB connection URI (required) MONGRATOR_DB — database name (required) MONGRATOR_MIGRATIONS_DIR — path to migrations directory (default: migrations) MONGRATOR_COLLECTION — tracking collection name (default: mongrator_migrations)

Source code in src/mongrator/config.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
@classmethod
def from_env(cls, dotenv_path: Path | None = None) -> Self:
    """Load configuration from environment variables.

    If *dotenv_path* is given and the file exists, its values are used as
    defaults — real environment variables always take precedence.

    Variables:
        MONGRATOR_URI         — MongoDB connection URI (required)
        MONGRATOR_DB          — database name (required)
        MONGRATOR_MIGRATIONS_DIR — path to migrations directory (default: migrations)
        MONGRATOR_COLLECTION  — tracking collection name (default: mongrator_migrations)
    """
    dotenv: dict[str, str] = {}
    if dotenv_path is not None:
        dotenv = _load_dotenv(dotenv_path)

    def _get(key: str, default: str | None = None) -> str | None:
        if key in os.environ:
            return os.environ[key]
        if key in dotenv:
            return dotenv[key]
        return default

    uri = _get("MONGRATOR_URI")
    database = _get("MONGRATOR_DB")
    if not uri:
        raise ConfigurationError("MONGRATOR_URI environment variable is not set")
    if not database:
        raise ConfigurationError("MONGRATOR_DB environment variable is not set")
    migrations_dir = Path(_get("MONGRATOR_MIGRATIONS_DIR") or str(_DEFAULT_MIGRATIONS_DIR))
    collection = _get("MONGRATOR_COLLECTION") or _DEFAULT_COLLECTION
    return cls(uri=uri, database=database, migrations_dir=migrations_dir, collection=collection)