jedcunningham commented on code in PR #41437:
URL: https://github.com/apache/airflow/pull/41437#discussion_r1724399931


##########
airflow/providers/fab/migrations/env.py:
##########
@@ -0,0 +1,125 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import contextlib
+from logging.config import fileConfig
+
+from alembic import context
+
+from airflow import settings
+from airflow.providers.fab.auth_manager.models.db import FABDBManager
+
+# this is the Alembic Config object, which provides
+# access to the values within the .ini file in use.
+config = context.config
+
+version_table = FABDBManager.version_table_name
+
+# Interpret the config file for Python logging.
+# This line sets up loggers basically.
+if config.config_file_name is not None:
+    fileConfig(config.config_file_name)

Review Comment:
   @ephraimbuddy this is the line that causes the caplog failures! Not exactly 
sure why, but if I comment this out they go away.



##########
airflow/utils/db_manager.py:
##########
@@ -0,0 +1,176 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import os
+from typing import TYPE_CHECKING
+
+from airflow.configuration import conf
+from airflow.exceptions import AirflowException
+from airflow.utils.log.logging_mixin import LoggingMixin
+from airflow.utils.module_loading import import_string
+
+if TYPE_CHECKING:
+    from sqlalchemy import MetaData
+
+
+class AttributeCheckerMeta(type):
+    """Metaclass to check attributes of subclasses."""
+
+    def __new__(cls, name, bases, dct):
+        """Check that subclasses are setting the required attributes."""
+        required_attrs = ["metadata", "migration_dir", "alembic_file", 
"version_table_name"]
+        for attr in required_attrs:
+            if attr not in dct:
+                raise AttributeError(f"{name} is missing required attribute: 
{attr}")
+        return super().__new__(cls, name, bases, dct)
+
+
+class BaseDBManager(LoggingMixin, metaclass=AttributeCheckerMeta):

Review Comment:
   Can this be an AbstractBaseClass instead of rolling our own 
AttributeCheckMeta?



##########
airflow/utils/db_manager.py:
##########
@@ -0,0 +1,176 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import os
+from typing import TYPE_CHECKING
+
+from airflow.configuration import conf
+from airflow.exceptions import AirflowException
+from airflow.utils.log.logging_mixin import LoggingMixin
+from airflow.utils.module_loading import import_string
+
+if TYPE_CHECKING:
+    from sqlalchemy import MetaData
+
+
+class AttributeCheckerMeta(type):
+    """Metaclass to check attributes of subclasses."""
+
+    def __new__(cls, name, bases, dct):
+        """Check that subclasses are setting the required attributes."""
+        required_attrs = ["metadata", "migration_dir", "alembic_file", 
"version_table_name"]
+        for attr in required_attrs:
+            if attr not in dct:
+                raise AttributeError(f"{name} is missing required attribute: 
{attr}")
+        return super().__new__(cls, name, bases, dct)
+
+
+class BaseDBManager(LoggingMixin, metaclass=AttributeCheckerMeta):
+    """Base DB manager for external DBs."""
+
+    metadata: MetaData = None
+    migration_dir: str = ""
+    alembic_file: str = ""
+    version_table_name: str = ""
+    # Whether the database supports dropping tables when airflow tables are 
dropped
+    supports_table_dropping: bool = False
+
+    def __init__(self, session):
+        super().__init__()
+        self.session = session
+
+    def get_alembic_config(self):
+        from alembic.config import Config
+
+        from airflow import settings
+
+        config = Config(self.alembic_file)
+        config.set_main_option("script_location", 
self.migration_dir.replace("%", "%%"))
+        config.set_main_option("sqlalchemy.url", 
settings.SQL_ALCHEMY_CONN.replace("%", "%%"))
+        return config
+
+    def get_current_revision(self):
+        from alembic.migration import MigrationContext
+
+        conn = self.session.connection()
+
+        migration_ctx = MigrationContext.configure(conn, 
opts={"version_table": self.version_table_name})
+
+        return migration_ctx.get_current_revision()
+
+    def _create_db_from_orm(self):
+        """Create database from ORM."""
+        from alembic import command
+
+        engine = self.session.get_bind().engine
+        self.metadata.create_all(engine)
+        config = self.get_alembic_config()
+        command.stamp(config, "head")
+
+    def initdb(self):
+        """Initialize the database."""
+        db_exists = self.get_current_revision()
+        if db_exists:
+            self.upgradedb()
+        else:
+            self._create_db_from_orm()
+
+    def upgradedb(self, to_version=None, from_version=None, 
show_sql_only=False):
+        """Upgrade the database."""
+        from alembic import command
+
+        config = self.get_alembic_config()
+        command.upgrade(config, revision=to_version or "heads", 
sql=show_sql_only)
+
+    def downgradedb(self, to_version, from_version=None, show_sql_only=False):
+        """Downgrade the database."""

Review Comment:
   Was the downgrade skipped intentionally?



##########
airflow/config_templates/config.yml:
##########
@@ -720,6 +720,14 @@ database:
       type: string
       example: ~
       default: "True"
+    external_db_managers:
+      description: |
+        List of DB managers to use to migrate external tables in airflow 
database. The managers must inherit
+        from BaseDBManager
+      version_added: 3.0.0
+      type: string
+      example: ~
+      default: "airflow.providers.fab.auth_manager.models.db.FABDBManager"

Review Comment:
   The default should be null I think. We don't want things to blow up if you 
don't have the FAB provider installed.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to