Exemple #1
0
 def _check_if_db_exists(self, db_name, hook: CloudSqlHook):
     try:
         return hook.get_database(
             project_id=self.project_id,
             instance=self.instance,
             database=db_name)
     except HttpError as e:
         status = e.resp.status
         if status == 404:
             return False
         raise e
Exemple #2
0
class CloudSqlBaseOperator(BaseOperator):
    """
    Abstract base operator for Google Cloud SQL operators to inherit from.

    :param instance: Cloud SQL instance ID. This does not include the project ID.
    :type instance: str
    :param project_id: Optional, Google Cloud Platform Project ID.  f set to None or missing,
            the default project_id from the GCP connection is used.
    :type project_id: str
    :param gcp_conn_id: The connection ID used to connect to Google Cloud Platform.
    :type gcp_conn_id: str
    :param api_version: API version used (e.g. v1beta4).
    :type api_version: str
    """
    @apply_defaults
    def __init__(self,
                 instance: str,
                 project_id: Optional[str] = None,
                 gcp_conn_id: str = 'google_cloud_default',
                 api_version: str = 'v1beta4',
                 *args,
                 **kwargs) -> None:
        self.project_id = project_id
        self.instance = instance
        self.gcp_conn_id = gcp_conn_id
        self.api_version = api_version
        self._validate_inputs()
        self._hook = CloudSqlHook(
            gcp_conn_id=self.gcp_conn_id,
            api_version=self.api_version)  # type: CloudSqlHook
        super().__init__(*args, **kwargs)

    def _validate_inputs(self):
        if self.project_id == '':
            raise AirflowException(
                "The required parameter 'project_id' is empty")
        if not self.instance:
            raise AirflowException(
                "The required parameter 'instance' is empty or None")

    def _check_if_instance_exists(self, instance):
        try:
            return self._hook.get_instance(project_id=self.project_id,
                                           instance=instance)
        except HttpError as e:
            status = e.resp.status
            if status == 404:
                return False
            raise e

    def _check_if_db_exists(self, db_name):
        try:
            return self._hook.get_database(project_id=self.project_id,
                                           instance=self.instance,
                                           database=db_name)
        except HttpError as e:
            status = e.resp.status
            if status == 404:
                return False
            raise e

    def execute(self, context):
        pass

    @staticmethod
    def _get_settings_version(instance):
        return instance.get(SETTINGS).get(SETTINGS_VERSION)