Coverage for /pythoncovmergedfiles/medio/medio/src/airflow/airflow/providers/microsoft/azure/operators/cosmos.py: 0%
22 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
1#
2# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18from __future__ import annotations
20from typing import TYPE_CHECKING, Sequence
22from airflow.models import BaseOperator
23from airflow.providers.microsoft.azure.hooks.cosmos import AzureCosmosDBHook
25if TYPE_CHECKING:
26 from airflow.utils.context import Context
29class AzureCosmosInsertDocumentOperator(BaseOperator):
30 """
31 Inserts a new document into the specified Cosmos database and collection
32 It will create both the database and collection if they do not already exist.
34 :param database_name: The name of the database. (templated)
35 :param collection_name: The name of the collection. (templated)
36 :param document: The document to insert
37 :param azure_cosmos_conn_id: Reference to the
38 :ref:`Azure CosmosDB connection<howto/connection:azure_cosmos>`.
39 """
41 template_fields: Sequence[str] = ("database_name", "collection_name")
42 ui_color = "#e4f0e8"
44 def __init__(
45 self,
46 *,
47 database_name: str,
48 collection_name: str,
49 document: dict,
50 azure_cosmos_conn_id: str = "azure_cosmos_default",
51 **kwargs,
52 ) -> None:
53 super().__init__(**kwargs)
54 self.database_name = database_name
55 self.collection_name = collection_name
56 self.document = document
57 self.azure_cosmos_conn_id = azure_cosmos_conn_id
59 def execute(self, context: Context) -> None:
60 # Create the hook
61 hook = AzureCosmosDBHook(azure_cosmos_conn_id=self.azure_cosmos_conn_id)
63 # Create the DB if it doesn't already exist
64 if not hook.does_database_exist(self.database_name):
65 hook.create_database(self.database_name)
67 # Create the collection as well
68 if not hook.does_collection_exist(self.collection_name, self.database_name):
69 hook.create_collection(self.collection_name, self.database_name)
71 # finally insert the document
72 hook.upsert_document(self.document, self.database_name, self.collection_name)