64
64
# Create config object - this is the standard way in Alembic
65
65
config = getattr (context , "config" , None ) or Config ()
66
66
67
+
67
68
def _inside_alembic () -> bool :
68
- """Return True only when this file is running under Alembic CLI."""
69
+ """Detect if this module is being executed by the Alembic CLI.
70
+
71
+ This function checks whether the current execution context is within
72
+ an Alembic migration environment. It's used to prevent migration code
73
+ from running when this module is imported for other purposes (e.g.,
74
+ during testing or when importing models).
75
+
76
+ The detection works by checking for the presence of the '_proxy' attribute
77
+ on the alembic.context object. This attribute is set internally by Alembic
78
+ when it loads and executes the env.py file during migration operations.
79
+
80
+ Returns:
81
+ bool: True if running under Alembic CLI (e.g., during 'alembic upgrade',
82
+ 'alembic downgrade', etc.), False if imported normally by Python
83
+ code or during testing.
84
+
85
+ Examples:
86
+ When running migrations::
87
+
88
+ $ alembic upgrade head
89
+ # _inside_alembic() returns True
90
+
91
+ When importing in tests or application code::
92
+
93
+ from mcpgateway.alembic.env import target_metadata
94
+ # _inside_alembic() returns False
95
+
96
+ Note:
97
+ This guard is crucial to prevent the migration execution code at the
98
+ bottom of this module from running during normal imports. Without it,
99
+ importing this module would attempt to run migrations every time.
100
+ """
69
101
return getattr (context , "_proxy" , None ) is not None
70
102
103
+
71
104
config .set_main_option ("script_location" , str (files ("mcpgateway" ).joinpath ("alembic" )))
72
105
73
106
# Interpret the config file for Python logging.
@@ -146,8 +179,9 @@ def run_migrations_online() -> None:
146
179
with context .begin_transaction ():
147
180
context .run_migrations ()
148
181
182
+
149
183
if _inside_alembic ():
150
184
if context .is_offline_mode ():
151
185
run_migrations_offline ()
152
186
else :
153
- run_migrations_online ()
187
+ run_migrations_online ()
0 commit comments