You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "mistercrunch (via GitHub)" <gi...@apache.org> on 2025/08/13 18:16:17 UTC
[PR] fix: Check migration status before initializing database-dependent features [superset]
mistercrunch opened a new pull request, #34679:
URL: https://github.com/apache/superset/pull/34679
This fixes a startup issue where SeedSystemThemesCommand tried to access theme columns (is_system, is_system_default, is_system_dark) before database migrations were applied, causing initialization failures.
The solution adds an Alembic-based migration check to ensure the database schema is up-to-date before running any database-dependent initialization.
Changes:
- Added _is_database_up_to_date() method that compares current DB revision with the head revision from migration files
- Simplified _init_database_dependent_features() by removing redundant table existence checks and consolidating all DB-dependent features under the migration check
- Removed unused sqlalchemy imports (inspect, OperationalError)
This prevents startup failures when:
1. The database hasn't been migrated yet
2. New columns are added but migrations haven't run
3. The app starts before 'superset db upgrade' is executed
The fix ensures theme seeding and other DB-dependent features only run when the database schema is fully up-to-date.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix: Check migration status before initializing database-dependent features [superset]
Posted by "mistercrunch (via GitHub)" <gi...@apache.org>.
mistercrunch merged PR #34679:
URL: https://github.com/apache/superset/pull/34679
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix: Check migration status before initializing database-dependent features [superset]
Posted by "korbit-ai[bot] (via GitHub)" <gi...@apache.org>.
korbit-ai[bot] commented on code in PR #34679:
URL: https://github.com/apache/superset/pull/34679#discussion_r2274269484
##########
superset/initialization/__init__.py:
##########
@@ -503,11 +504,40 @@ def init_views(self) -> None:
icon="fa-lock",
)
+ def _is_database_up_to_date(self) -> bool:
+ """
+ Check if database migrations are up to date.
+ Returns False if there are pending migrations or unable to determine.
+ """
+ try:
+ # Get current revision from database
+ with db.engine.connect() as connection:
+ context = MigrationContext.configure(connection)
+ current_rev = context.get_current_revision()
Review Comment:
### Uncached Database Migration Check <sub></sub>
<details>
<summary>Tell me more</summary>
###### What is the issue?
The database migration check creates a new connection for each verification without any caching mechanism, potentially causing unnecessary database connections on every app startup.
###### Why this matters
Multiple apps/workers starting simultaneously could create connection spikes to the database. For migration status that rarely changes, this is inefficient.
###### Suggested change ∙ *Feature Preview*
Implement caching of the migration status with a reasonable TTL (e.g. 5 minutes) to avoid repeated database connections:
```python
def _is_database_up_to_date(self) -> bool:
cache_key = 'db_migration_status'
if status := cache_manager.get(cache_key):
return status
try:
with db.engine.connect() as connection:
context = MigrationContext.configure(connection)
current_rev = context.get_current_revision()
alembic_cfg = Config()
alembic_cfg.set_main_option("script_location", "superset:migrations")
script = ScriptDirectory.from_config(alembic_cfg)
head_rev = script.get_current_head()
is_current = current_rev == head_rev
cache_manager.set(cache_key, is_current, timeout=300) # Cache for 5 minutes
return is_current
except Exception as e:
logger.debug("Could not check migration status: %s", e)
return False
```
###### Provide feedback to improve future suggestions
[](https://app.korbit.ai/feedback/aa91ff46-6083-4491-9416-b83dd1994b51/9a5e4c81-ba56-4641-bda9-c67fc604bb4a/upvote) [](https://app.korbit.ai/feedback/aa91ff46-6083-4491-9416-b83dd1994b51/9a5e4c81-ba56-4641-bda9-c67fc604bb4a?what_not_true=true) [](https://app.korbit.ai/feedback/aa91ff46-6083-4491-9416-b83dd1994b51/9a5e4c81-ba56-4641-bda9-c67fc604bb4a?what_out_of_scope=true) [](https://app.korbit.ai/feedback/aa91ff46-6083-4491-9416-b83dd1994b51/9a5e4c81-ba56-4641-bda9-c67fc604bb4a?what_not_in_standard=true) [](https://app.korbit.ai/feedback/aa91ff46-6083-4491-9416-b83dd1994b51/9a5e4c81-ba56-4641-bda9-c67fc604bb4a)
</details>
<sub>
💬 Looking for more details? Reply to this comment to chat with Korbit.
</sub>
<!--- korbi internal id:1319256c-6252-4a9a-a82a-9057953a878e -->
[](1319256c-6252-4a9a-a82a-9057953a878e)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix: Check migration status before initializing database-dependent features [superset]
Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #34679:
URL: https://github.com/apache/superset/pull/34679#discussion_r2281427594
##########
superset/initialization/__init__.py:
##########
@@ -503,11 +504,40 @@ def init_views(self) -> None:
icon="fa-lock",
)
+ def _is_database_up_to_date(self) -> bool:
Review Comment:
nit: we could move this to `utils` if you think it could be useful for other code paths in the future
##########
superset/initialization/__init__.py:
##########
@@ -517,39 +547,24 @@ def _init_database_dependent_features(self) -> None:
):
logger.warning(
"Database URI appears to be a fallback value. "
- "Skipping database-dependent initialization. "
- "This may indicate the workspace context is not ready yet."
+ "Skipping database-dependent initialization."
)
return
- try:
- inspector = inspect(db.engine)
-
- # Check if core tables exist (use 'dashboards' as proxy for Superset tables)
- if not inspector.has_table("dashboards"):
- logger.debug(
- "Superset tables not yet created. Skipping database-dependent "
- "initialization. These features will be initialized after "
- "migration."
- )
- return
- except OperationalError as e:
- logger.debug(
- "Error inspecting database tables. Skipping database-dependent "
- "initialization: %s",
- e,
- )
+ # Check if database is up-to-date with migrations
+ if not self._is_database_up_to_date():
+ logger.info("Pending database migrations: run 'superset db upgrade'")
return
+ # Initialize all database-dependent features
# Register SQLA event listeners for tagging system
if feature_flag_manager.is_feature_enabled("TAGGING_SYSTEM"):
register_sqla_event_listeners()
# Seed system themes from configuration
from superset.commands.theme.seed import SeedSystemThemesCommand
- if inspector.has_table("themes"):
- SeedSystemThemesCommand().run()
+ SeedSystemThemesCommand().run()
Review Comment:
We do `AppBuilder(update_perms=False)` to avoid needing the db on startup and use the cli to update permissions. We could also use `FAB_UPDATE_PERMS` to control this behaviour also.
Following the same pattern we could create a new config flag to avoid seeding the themes at app startup, and move this to `superset init` for example.
I'm also thinking about `register_sqla_event_listeners` that won't register any listeners if we don't have a request context, and having a request context is not expected on app initialization, so these listeners won't be registered if the db uri contains `["nouser", "nopassword", "nohost", "nodb"]` and `TAGGING_SYSTEM` is `True`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix: Check migration status before initializing database-dependent features [superset]
Posted by "mistercrunch (via GitHub)" <gi...@apache.org>.
mistercrunch commented on code in PR #34679:
URL: https://github.com/apache/superset/pull/34679#discussion_r2289583707
##########
superset/app.py:
##########
@@ -96,6 +100,90 @@ def send_static_file(self, filename: str) -> Response:
return Response("", status=204) # No Content
return super().send_static_file(filename)
+ def _is_database_up_to_date(self) -> bool:
+ """
+ Check if database migrations are up to date.
+ Returns False if there are pending migrations or unable to determine.
+ """
+ try:
+ # Import here to avoid circular import issues
+ from superset.extensions import db
+
+ # Get current revision from database
+ with db.engine.connect() as connection:
+ context = MigrationContext.configure(connection)
+ current_rev = context.get_current_revision()
+
+ # Get head revision from migration files
+ alembic_cfg = Config()
+ alembic_cfg.set_main_option("script_location", "superset:migrations")
+ script = ScriptDirectory.from_config(alembic_cfg)
+ head_rev = script.get_current_head()
+
+ # Database is up-to-date if current revision matches head
+ is_current = current_rev == head_rev
+ if not is_current:
+ logger.debug(
+ "Pending migrations. Current: %s, Head: %s",
+ current_rev,
+ head_rev,
+ )
+ return is_current
+ except Exception as e:
+ logger.debug("Could not check migration status: %s", e)
+ return False
+
+ def sync_config_to_db(self) -> None:
+ """
+ Synchronize configuration to database.
+ This method handles database-dependent features that need to be synced
+ after the app is initialized and database connection is available.
+
+ This is separated from app initialization to support multi-tenant
+ environments where database connection might not be available during
+ app startup.
+ """
+ try:
+ # Import here to avoid circular import issues
+ from superset.extensions import feature_flag_manager
+
+ # Check if database URI is a fallback value before trying to connect
+ db_uri = self.config.get("SQLALCHEMY_DATABASE_URI", "")
+ if not db_uri or any(
+ fallback in db_uri.lower()
+ for fallback in ["nouser", "nopassword", "nohost", "nodb"]
Review Comment:
Spoke with @eschutho and it's not needed anymore
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix: Check migration status before initializing database-dependent features [superset]
Posted by "mistercrunch (via GitHub)" <gi...@apache.org>.
mistercrunch commented on code in PR #34679:
URL: https://github.com/apache/superset/pull/34679#discussion_r2289422568
##########
superset/app.py:
##########
@@ -96,6 +100,90 @@ def send_static_file(self, filename: str) -> Response:
return Response("", status=204) # No Content
return super().send_static_file(filename)
+ def _is_database_up_to_date(self) -> bool:
+ """
+ Check if database migrations are up to date.
+ Returns False if there are pending migrations or unable to determine.
+ """
+ try:
+ # Import here to avoid circular import issues
+ from superset.extensions import db
+
+ # Get current revision from database
+ with db.engine.connect() as connection:
+ context = MigrationContext.configure(connection)
+ current_rev = context.get_current_revision()
+
+ # Get head revision from migration files
+ alembic_cfg = Config()
+ alembic_cfg.set_main_option("script_location", "superset:migrations")
+ script = ScriptDirectory.from_config(alembic_cfg)
+ head_rev = script.get_current_head()
+
+ # Database is up-to-date if current revision matches head
+ is_current = current_rev == head_rev
+ if not is_current:
+ logger.debug(
+ "Pending migrations. Current: %s, Head: %s",
+ current_rev,
+ head_rev,
+ )
+ return is_current
+ except Exception as e:
+ logger.debug("Could not check migration status: %s", e)
+ return False
+
+ def sync_config_to_db(self) -> None:
+ """
+ Synchronize configuration to database.
+ This method handles database-dependent features that need to be synced
+ after the app is initialized and database connection is available.
+
+ This is separated from app initialization to support multi-tenant
+ environments where database connection might not be available during
+ app startup.
+ """
+ try:
+ # Import here to avoid circular import issues
+ from superset.extensions import feature_flag_manager
+
+ # Check if database URI is a fallback value before trying to connect
+ db_uri = self.config.get("SQLALCHEMY_DATABASE_URI", "")
+ if not db_uri or any(
+ fallback in db_uri.lower()
+ for fallback in ["nouser", "nopassword", "nohost", "nodb"]
+ ):
+ logger.warning(
+ "Database URI appears to be a fallback value. "
+ "Skipping database-dependent sync."
+ )
+ return
+
+ # Check if database is up-to-date with migrations
+ if not self._is_database_up_to_date():
Review Comment:
I think it's necessary, the issue that prompted all this was that if you were on an old migration (pre Theme model creation), everything would fail, including `superset db upgrade` ...
In general, I think that `sync_config_to_db` requires a check to make sure that the db is up-to-date. If anything, maybe we should even fail harder and only allow you to run `superset db upgrade` or things that really don't depend on the database.
I think this check here makes things better, there's now a clear `sync_to_db()` step that requires an up-to-date database, pretty important assumption before syncing anything...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix: Check migration status before initializing database-dependent features [superset]
Posted by "mistercrunch (via GitHub)" <gi...@apache.org>.
mistercrunch commented on code in PR #34679:
URL: https://github.com/apache/superset/pull/34679#discussion_r2289417125
##########
superset/app.py:
##########
@@ -96,6 +100,90 @@ def send_static_file(self, filename: str) -> Response:
return Response("", status=204) # No Content
return super().send_static_file(filename)
+ def _is_database_up_to_date(self) -> bool:
+ """
+ Check if database migrations are up to date.
+ Returns False if there are pending migrations or unable to determine.
+ """
+ try:
+ # Import here to avoid circular import issues
+ from superset.extensions import db
+
+ # Get current revision from database
+ with db.engine.connect() as connection:
+ context = MigrationContext.configure(connection)
+ current_rev = context.get_current_revision()
+
+ # Get head revision from migration files
+ alembic_cfg = Config()
+ alembic_cfg.set_main_option("script_location", "superset:migrations")
+ script = ScriptDirectory.from_config(alembic_cfg)
+ head_rev = script.get_current_head()
+
+ # Database is up-to-date if current revision matches head
+ is_current = current_rev == head_rev
+ if not is_current:
+ logger.debug(
+ "Pending migrations. Current: %s, Head: %s",
+ current_rev,
+ head_rev,
+ )
+ return is_current
+ except Exception as e:
+ logger.debug("Could not check migration status: %s", e)
+ return False
+
+ def sync_config_to_db(self) -> None:
+ """
+ Synchronize configuration to database.
+ This method handles database-dependent features that need to be synced
+ after the app is initialized and database connection is available.
+
+ This is separated from app initialization to support multi-tenant
+ environments where database connection might not be available during
+ app startup.
+ """
+ try:
+ # Import here to avoid circular import issues
+ from superset.extensions import feature_flag_manager
+
+ # Check if database URI is a fallback value before trying to connect
+ db_uri = self.config.get("SQLALCHEMY_DATABASE_URI", "")
+ if not db_uri or any(
+ fallback in db_uri.lower()
+ for fallback in ["nouser", "nopassword", "nohost", "nodb"]
Review Comment:
idk! @eschutho I think you might have added this logic
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix: Check migration status before initializing database-dependent features [superset]
Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #34679:
URL: https://github.com/apache/superset/pull/34679#discussion_r2287456623
##########
superset/app.py:
##########
@@ -96,6 +100,90 @@ def send_static_file(self, filename: str) -> Response:
return Response("", status=204) # No Content
return super().send_static_file(filename)
+ def _is_database_up_to_date(self) -> bool:
+ """
+ Check if database migrations are up to date.
+ Returns False if there are pending migrations or unable to determine.
+ """
+ try:
+ # Import here to avoid circular import issues
+ from superset.extensions import db
+
+ # Get current revision from database
+ with db.engine.connect() as connection:
+ context = MigrationContext.configure(connection)
+ current_rev = context.get_current_revision()
+
+ # Get head revision from migration files
+ alembic_cfg = Config()
+ alembic_cfg.set_main_option("script_location", "superset:migrations")
+ script = ScriptDirectory.from_config(alembic_cfg)
+ head_rev = script.get_current_head()
+
+ # Database is up-to-date if current revision matches head
+ is_current = current_rev == head_rev
+ if not is_current:
+ logger.debug(
+ "Pending migrations. Current: %s, Head: %s",
+ current_rev,
+ head_rev,
+ )
+ return is_current
+ except Exception as e:
+ logger.debug("Could not check migration status: %s", e)
+ return False
+
+ def sync_config_to_db(self) -> None:
+ """
+ Synchronize configuration to database.
+ This method handles database-dependent features that need to be synced
+ after the app is initialized and database connection is available.
+
+ This is separated from app initialization to support multi-tenant
+ environments where database connection might not be available during
+ app startup.
+ """
+ try:
+ # Import here to avoid circular import issues
+ from superset.extensions import feature_flag_manager
+
+ # Check if database URI is a fallback value before trying to connect
+ db_uri = self.config.get("SQLALCHEMY_DATABASE_URI", "")
+ if not db_uri or any(
+ fallback in db_uri.lower()
+ for fallback in ["nouser", "nopassword", "nohost", "nodb"]
Review Comment:
do we still need this?
##########
superset/app.py:
##########
@@ -96,6 +100,90 @@ def send_static_file(self, filename: str) -> Response:
return Response("", status=204) # No Content
return super().send_static_file(filename)
+ def _is_database_up_to_date(self) -> bool:
+ """
+ Check if database migrations are up to date.
+ Returns False if there are pending migrations or unable to determine.
+ """
+ try:
+ # Import here to avoid circular import issues
+ from superset.extensions import db
+
+ # Get current revision from database
+ with db.engine.connect() as connection:
+ context = MigrationContext.configure(connection)
+ current_rev = context.get_current_revision()
+
+ # Get head revision from migration files
+ alembic_cfg = Config()
+ alembic_cfg.set_main_option("script_location", "superset:migrations")
+ script = ScriptDirectory.from_config(alembic_cfg)
+ head_rev = script.get_current_head()
+
+ # Database is up-to-date if current revision matches head
+ is_current = current_rev == head_rev
+ if not is_current:
+ logger.debug(
+ "Pending migrations. Current: %s, Head: %s",
+ current_rev,
+ head_rev,
+ )
+ return is_current
+ except Exception as e:
+ logger.debug("Could not check migration status: %s", e)
+ return False
+
+ def sync_config_to_db(self) -> None:
+ """
+ Synchronize configuration to database.
+ This method handles database-dependent features that need to be synced
+ after the app is initialized and database connection is available.
+
+ This is separated from app initialization to support multi-tenant
+ environments where database connection might not be available during
+ app startup.
+ """
+ try:
+ # Import here to avoid circular import issues
+ from superset.extensions import feature_flag_manager
+
+ # Check if database URI is a fallback value before trying to connect
+ db_uri = self.config.get("SQLALCHEMY_DATABASE_URI", "")
+ if not db_uri or any(
+ fallback in db_uri.lower()
+ for fallback in ["nouser", "nopassword", "nohost", "nodb"]
+ ):
+ logger.warning(
+ "Database URI appears to be a fallback value. "
+ "Skipping database-dependent sync."
+ )
+ return
+
+ # Check if database is up-to-date with migrations
+ if not self._is_database_up_to_date():
Review Comment:
is it still necessary? if superset init's without having the database up to date will it be silently in a broken state?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org