|
| 1 | +""" |
| 2 | +notion_habits.py |
| 3 | +
|
| 4 | +DAG to load daily and weekly habits from Notion API into BigQuery. |
| 5 | +""" |
| 6 | + |
| 7 | +# Basic imports |
| 8 | +import datetime |
| 9 | +import pendulum |
| 10 | + |
| 11 | +# Standard airflow imports |
| 12 | +from airflow.decorators import dag, task |
| 13 | +from airflow.models.param import Param |
| 14 | +from airflow.operators.python import get_current_context |
| 15 | +from airflow.exceptions import AirflowSkipException |
| 16 | + |
| 17 | +# Airflow hooks and operators |
| 18 | +from airflow.hooks.base import BaseHook |
| 19 | +from airflow.providers.google.cloud.operators.bigquery import ( |
| 20 | + BigQueryCreateEmptyDatasetOperator, |
| 21 | + BigQueryCreateEmptyTableOperator, |
| 22 | + BigQueryInsertJobOperator, |
| 23 | +) |
| 24 | + |
| 25 | + |
| 26 | +@dag( |
| 27 | + schedule="@daily", |
| 28 | + catchup=True, |
| 29 | + start_date=pendulum.datetime(2024, 10, 1, tz="UTC"), |
| 30 | + dagrun_timeout=datetime.timedelta(minutes=20), |
| 31 | + tags=["habits", "notion", "staging"], |
| 32 | + # Provide tables via params to enable unit testing |
| 33 | + params={"daily_habit_table": Param("notion_habits_daily")}, |
| 34 | +) |
| 35 | +def NotionHabits(): |
| 36 | + |
| 37 | + # Notion package and details |
| 38 | + from notion_client import Client |
| 39 | + |
| 40 | + NOTION_CONN_ID = "notion_productivity" |
| 41 | + DAILY_HABIT_DB = "10140b50-0f0d-43d2-905a-7ed714ef7f2c" |
| 42 | + WEEKLY_HABIT_DB = "11e09eb8-3f76-80e7-8fac-e8d0bb538fb0" |
| 43 | + |
| 44 | + # BigQuery connection details |
| 45 | + BQ_CONN_ID = "bigquery_reporting" |
| 46 | + BQ_DATASET = "staging" |
| 47 | + BQ_LOCATION = "us-central1" |
| 48 | + |
| 49 | + # Create staging dataset if it doesn't exist |
| 50 | + create_staging_dataset = BigQueryCreateEmptyDatasetOperator( |
| 51 | + task_id="create_staging_dataset", |
| 52 | + gcp_conn_id=BQ_CONN_ID, |
| 53 | + dataset_id=BQ_DATASET, |
| 54 | + location=BQ_LOCATION, |
| 55 | + if_exists="ignore", |
| 56 | + ) |
| 57 | + |
| 58 | + # Create daily habits staging table if it doesn't exist |
| 59 | + create_daily_table = BigQueryCreateEmptyTableOperator( |
| 60 | + task_id="create_staging_notion_habits_daily_table", |
| 61 | + gcp_conn_id=BQ_CONN_ID, |
| 62 | + dataset_id=BQ_DATASET, |
| 63 | + table_id="{{ params.daily_habit_table }}", |
| 64 | + schema_fields=[ |
| 65 | + { |
| 66 | + "name": "bq_id", |
| 67 | + "type": "STRING", |
| 68 | + "mode": "REQUIRED", |
| 69 | + "defaultValueExpression": "GENERATE_UUID()", |
| 70 | + }, |
| 71 | + {"name": "page_id", "type": "STRING", "mode": "REQUIRED"}, |
| 72 | + {"name": "database_id", "type": "STRING", "mode": "REQUIRED"}, |
| 73 | + {"name": "date", "type": "DATE", "mode": "REQUIRED"}, |
| 74 | + {"name": "habit", "type": "STRING", "mode": "REQUIRED"}, |
| 75 | + {"name": "is_complete", "type": "BOOLEAN", "mode": "REQUIRED"}, |
| 76 | + {"name": "page_created", "type": "TIMESTAMP", "mode": "REQUIRED"}, |
| 77 | + {"name": "page_edited", "type": "TIMESTAMP", "mode": "REQUIRED"}, |
| 78 | + { |
| 79 | + "name": "bq_ts", |
| 80 | + "type": "TIMESTAMP", |
| 81 | + "mode": "REQUIRED", |
| 82 | + "defaultValueExpression": "CURRENT_TIMESTAMP()", |
| 83 | + }, |
| 84 | + ], |
| 85 | + if_exists="ignore", |
| 86 | + ) |
| 87 | + |
| 88 | + @task( |
| 89 | + task_id="load_notion_habits_daily_tasks", |
| 90 | + ) |
| 91 | + def get_daily_tasks(params: dict): |
| 92 | + # Get task context for data interval |
| 93 | + context = get_current_context() |
| 94 | + dag = context["dag"] |
| 95 | + # Connect to Notion API |
| 96 | + connection = BaseHook.get_connection(NOTION_CONN_ID) |
| 97 | + client = Client(auth=connection.password) |
| 98 | + |
| 99 | + notion_filters = { |
| 100 | + # Added formula property in database for last edited date to allow filter |
| 101 | + # Use data interval to get records edited within interval |
| 102 | + "and": [ |
| 103 | + { |
| 104 | + "property": "Last Edited", |
| 105 | + "date": {"after": context["data_interval_start"].isoformat()}, |
| 106 | + }, |
| 107 | + { |
| 108 | + "property": "Last Edited", |
| 109 | + "date": {"before": context["data_interval_end"].isoformat()}, |
| 110 | + }, |
| 111 | + ] |
| 112 | + } |
| 113 | + # Query the daily habits database |
| 114 | + query_rs = client.databases.query( |
| 115 | + database_id=DAILY_HABIT_DB, |
| 116 | + filter=notion_filters, |
| 117 | + ) |
| 118 | + |
| 119 | + # Pivot the results to a row per habit |
| 120 | + results = [ |
| 121 | + ( |
| 122 | + r["id"], # Notion page ID |
| 123 | + DAILY_HABIT_DB, |
| 124 | + r["properties"]["Date"]["date"]["start"][:10], # Notion task date |
| 125 | + p, # Notion habit name |
| 126 | + r["created_time"], # Notion page creation time |
| 127 | + r["last_edited_time"], # Notion page last edited time |
| 128 | + v["checkbox"], # Habit completion status |
| 129 | + ) |
| 130 | + for r in query_rs["results"] |
| 131 | + # Include only checkbox properties |
| 132 | + for p, v in r["properties"].items() |
| 133 | + if v["type"] == "checkbox" |
| 134 | + ] |
| 135 | + dag.log.info( |
| 136 | + f"{len(results)} daily habits updated for {context['execution_date']}" |
| 137 | + ) |
| 138 | + |
| 139 | + if not results: |
| 140 | + raise AirflowSkipException("No daily habits found for the interval.") |
| 141 | + else: |
| 142 | + # Structure row data for insert query |
| 143 | + data_rows = ", ".join( |
| 144 | + f"({', '.join([repr(v) for v in row])})" for row in results |
| 145 | + ) |
| 146 | + insert_rows_query = f""" |
| 147 | + INSERT INTO {BQ_DATASET}.{params["daily_habit_table"]} |
| 148 | + (page_id, database_id, date, habit, page_created, page_edited, is_complete) |
| 149 | + VALUES {data_rows}; |
| 150 | + """ |
| 151 | + |
| 152 | + # Insert daily habits into BigQuery |
| 153 | + # TODO: Break into separate task - how to pass data? |
| 154 | + insert_daily_job = BigQueryInsertJobOperator( |
| 155 | + gcp_conn_id=BQ_CONN_ID, |
| 156 | + task_id="insert_query_job", |
| 157 | + configuration={ |
| 158 | + "query": { |
| 159 | + "query": insert_rows_query, |
| 160 | + "useLegacySql": False, |
| 161 | + "priority": "BATCH", |
| 162 | + } |
| 163 | + }, |
| 164 | + location=BQ_LOCATION, |
| 165 | + ) |
| 166 | + insert_daily_job.execute(context=context) |
| 167 | + |
| 168 | + # Define task flow - task functions must be called () |
| 169 | + create_staging_dataset >> create_daily_table >> get_daily_tasks() |
| 170 | + |
| 171 | + |
| 172 | +# Assign the dag to global for execution |
| 173 | +dag = NotionHabits() |
0 commit comments