├── .astro ├── config.yaml └── test_dag_integrity_default.py ├── .dockerignore ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── dags ├── .airflowignore ├── basic │ ├── simple_dag.py │ └── simple_task_group.py ├── filtering │ ├── customers_tag.py │ ├── only_models.py │ └── only_seeds.py └── profiles │ ├── dbt_profile.py │ └── overrides.py ├── dbt └── jaffle_shop │ ├── .user.yml │ ├── LICENSE │ ├── README.md │ ├── dbt_project.yml │ ├── models │ ├── customers │ │ └── customers.sql │ ├── docs.md │ ├── orders.sql │ ├── overview.md │ ├── schema.yml │ └── staging │ │ ├── schema.yml │ │ ├── stg_customers.sql │ │ ├── stg_orders.sql │ │ └── stg_payments.sql │ ├── profiles.yml │ └── seeds │ ├── raw_customers.csv │ ├── raw_orders.csv │ └── raw_payments.csv ├── docker-compose.override.yml ├── include ├── constants.py └── profiles.py ├── packages.txt ├── requirements.txt └── tests └── dags └── test_dag_integrity.py /.astro/config.yaml: -------------------------------------------------------------------------------- 1 | project: 2 | name: cosmos-demo 3 | -------------------------------------------------------------------------------- /.astro/test_dag_integrity_default.py: -------------------------------------------------------------------------------- 1 | """Test the validity of all DAGs. **USED BY DEV PARSE COMMAND DO NOT EDIT**""" 2 | from contextlib import contextmanager 3 | import logging 4 | import os 5 | 6 | import pytest 7 | 8 | from airflow.models import DagBag, Variable, Connection 9 | from airflow.hooks.base import BaseHook 10 | 11 | 12 | # The following code patches errors caused by missing OS Variables, Airflow Connections, and Airflow Variables 13 | 14 | # =========== MONKEYPATCH BaseHook.get_connection() =========== 15 | def basehook_get_connection_monkeypatch(key: str, *args, **kwargs): 16 | print( 17 | f"Attempted to fetch connection during parse returning an empty Connection object for {key}" 18 | ) 19 | return Connection(key) 20 | 21 | 22 | BaseHook.get_connection = basehook_get_connection_monkeypatch 23 | # # =========== /MONKEYPATCH BASEHOOK.GET_CONNECTION() =========== 24 | 25 | # =========== MONKEYPATCH OS.GETENV() =========== 26 | def os_getenv_monkeypatch(key: str, *args, default=None, **kwargs): 27 | print( 28 | f"Attempted to fetch os environment variable during parse, returning a mocked value for {key}" 29 | ) 30 | if ( 31 | key == "JENKINS_HOME" and default is None 32 | ): # fix https://github.com/astronomer/astro-cli/issues/601 33 | return None 34 | if default: 35 | return default 36 | return "NON_DEFAULT_OS_ENV_VALUE" 37 | 38 | 39 | os.getenv = os_getenv_monkeypatch 40 | # # =========== /MONKEYPATCH OS.GETENV() =========== 41 | 42 | # =========== MONKEYPATCH VARIABLE.GET() =========== 43 | 44 | 45 | class magic_dict(dict): 46 | def __init__(self, *args, **kwargs): 47 | self.update(*args, **kwargs) 48 | 49 | def __getitem__(self, key): 50 | return {}.get(key, "MOCKED_KEY_VALUE") 51 | 52 | 53 | def variable_get_monkeypatch(key: str, default_var=None, deserialize_json=False): 54 | print( 55 | f"Attempted to get Variable value during parse, returning a mocked value for {key}" 56 | ) 57 | 58 | if default_var: 59 | return default_var 60 | if deserialize_json: 61 | return magic_dict() 62 | return "NON_DEFAULT_MOCKED_VARIABLE_VALUE" 63 | 64 | 65 | Variable.get = variable_get_monkeypatch 66 | # # =========== /MONKEYPATCH VARIABLE.GET() =========== 67 | 68 | 69 | @contextmanager 70 | def suppress_logging(namespace): 71 | """ 72 | Suppress logging within a specific namespace to keep tests "clean" during build 73 | """ 74 | logger = logging.getLogger(namespace) 75 | old_value = logger.disabled 76 | logger.disabled = True 77 | try: 78 | yield 79 | finally: 80 | logger.disabled = old_value 81 | 82 | 83 | def get_import_errors(): 84 | """ 85 | Generate a tuple for import errors in the dag bag 86 | """ 87 | with suppress_logging("airflow"): 88 | dag_bag = DagBag(include_examples=False) 89 | 90 | def strip_path_prefix(path): 91 | return os.path.relpath(path, os.environ.get("AIRFLOW_HOME")) 92 | 93 | # we prepend "(None,None)" to ensure that a test object is always created even if its a no op. 94 | return [(None, None)] + [ 95 | (strip_path_prefix(k), v.strip()) for k, v in dag_bag.import_errors.items() 96 | ] 97 | 98 | 99 | @pytest.mark.parametrize( 100 | "rel_path,rv", get_import_errors(), ids=[x[0] for x in get_import_errors()] 101 | ) 102 | def test_file_imports(rel_path, rv): 103 | """Test for import errors on a file""" 104 | if rel_path and rv: # Make sure our no op test doesn't raise an error 105 | raise Exception(f"{rel_path} failed to import with message \n {rv}") 106 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | astro 2 | .git 3 | .env 4 | airflow_settings.yaml 5 | logs/ 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # dbt-specific 2 | dbt/jaffle_shop/logs/* 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | share/python-wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | cover/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | db.sqlite3-journal 66 | 67 | # Flask stuff: 68 | instance/ 69 | .webassets-cache 70 | 71 | # Scrapy stuff: 72 | .scrapy 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | .pybuilder/ 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | # For a library or package, you might want to ignore these files since the code is 90 | # intended to run in multiple environments; otherwise, check them in: 91 | # .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # poetry 101 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 102 | # This is especially recommended for binary packages to ensure reproducibility, and is more 103 | # commonly ignored for libraries. 104 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 105 | #poetry.lock 106 | 107 | # pdm 108 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 109 | #pdm.lock 110 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 111 | # in version control. 112 | # https://pdm.fming.dev/#use-with-ide 113 | .pdm.toml 114 | 115 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 116 | __pypackages__/ 117 | 118 | # Celery stuff 119 | celerybeat-schedule 120 | celerybeat.pid 121 | 122 | # SageMath parsed files 123 | *.sage.py 124 | 125 | # Environments 126 | .env 127 | .venv 128 | env/ 129 | venv/ 130 | ENV/ 131 | env.bak/ 132 | venv.bak/ 133 | 134 | # Spyder project settings 135 | .spyderproject 136 | .spyproject 137 | 138 | # Rope project settings 139 | .ropeproject 140 | 141 | # mkdocs documentation 142 | /site 143 | 144 | # mypy 145 | .mypy_cache/ 146 | .dmypy.json 147 | dmypy.json 148 | 149 | # Pyre type checker 150 | .pyre/ 151 | 152 | # pytype static type analyzer 153 | .pytype/ 154 | 155 | # Cython debug symbols 156 | cython_debug/ 157 | 158 | # PyCharm 159 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 160 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 161 | # and can be added to the global gitignore or merged into this file. For a more nuclear 162 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 163 | #.idea/ 164 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM quay.io/astronomer/astro-runtime:12.1.1 2 | 3 | # install dbt into a virtual environment 4 | RUN python -m venv dbt_venv && source dbt_venv/bin/activate && \ 5 | pip install --no-cache-dir dbt-postgres==1.8.2 && deactivate 6 | 7 | # set a connection to the airflow metadata db to use for testing 8 | ENV AIRFLOW_CONN_AIRFLOW_METADATA_DB=postgresql+psycopg2://postgres:postgres@postgres:5432/postgres 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cosmos-demo 2 | 3 | This repo contains a dbt project and a set of Airflow DAGs showing how to run dbt in Airflow using [Cosmos](https://github.com/astronomer/astronomer-cosmos). 4 | 5 | To run this, you'll need: 6 | 7 | - [The Astro CLI installed](https://docs.astronomer.io/astro/cli/overview) 8 | - Docker 9 | 10 | ## Setup 11 | 12 | 1. Clone this repo 13 | 2. Run `astro dev start` to start the Airflow instance 14 | 15 | ## The DAGs 16 | 17 | The DAGs in this repo are meant to illustrate how to run dbt in Airflow using Cosmos. They use dbt's jaffle_shop example project. 18 | 19 | The DAGs fall into three categories: 20 | 21 | - Basic: these are the simplest examples of Cosmos 22 | - Profiles: these show how to customize your dbt profiles using Cosmos 23 | - Filtering: these show how to use Cosmos to filter which models are run 24 | -------------------------------------------------------------------------------- /dags/.airflowignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/astronomer/cosmos-demo/896b7b0dfa5d04ae798df5e113c1f104e2760fe0/dags/.airflowignore -------------------------------------------------------------------------------- /dags/basic/simple_dag.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from cosmos import DbtDag, ProjectConfig 4 | 5 | from include.profiles import airflow_db 6 | from include.constants import jaffle_shop_path, venv_execution_config 7 | 8 | simple_dag = DbtDag( 9 | # dbt/cosmos-specific parameters 10 | project_config=ProjectConfig(jaffle_shop_path), 11 | profile_config=airflow_db, 12 | execution_config=venv_execution_config, 13 | # normal dag parameters 14 | schedule_interval="@daily", 15 | start_date=datetime(2023, 1, 1), 16 | catchup=False, 17 | dag_id="simple_dag", 18 | tags=["simple"], 19 | ) 20 | -------------------------------------------------------------------------------- /dags/basic/simple_task_group.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from airflow.decorators import dag 4 | from airflow.operators.empty import EmptyOperator 5 | 6 | 7 | from cosmos import DbtTaskGroup, ProjectConfig 8 | 9 | from include.profiles import airflow_db 10 | from include.constants import jaffle_shop_path, venv_execution_config 11 | 12 | 13 | @dag( 14 | schedule_interval="@daily", 15 | start_date=datetime(2023, 1, 1), 16 | catchup=False, 17 | tags=["simple"], 18 | ) 19 | def simple_task_group() -> None: 20 | """ 21 | The simplest example of using Cosmos to render a dbt project as a TaskGroup. 22 | """ 23 | pre_dbt = EmptyOperator(task_id="pre_dbt") 24 | 25 | jaffle_shop = DbtTaskGroup( 26 | group_id="my_jaffle_shop_project", 27 | project_config=ProjectConfig(jaffle_shop_path), 28 | profile_config=airflow_db, 29 | execution_config=venv_execution_config, 30 | ) 31 | 32 | post_dbt = EmptyOperator(task_id="post_dbt") 33 | 34 | pre_dbt >> jaffle_shop >> post_dbt 35 | 36 | 37 | simple_task_group() 38 | -------------------------------------------------------------------------------- /dags/filtering/customers_tag.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from cosmos import DbtDag, ProjectConfig, RenderConfig 4 | 5 | from include.profiles import airflow_db 6 | from include.constants import jaffle_shop_path, venv_execution_config 7 | 8 | customers_tag = DbtDag( 9 | project_config=ProjectConfig(jaffle_shop_path), 10 | profile_config=airflow_db, 11 | execution_config=venv_execution_config, 12 | # new render config 13 | render_config=RenderConfig( 14 | select=["tag:customers"], 15 | ), 16 | # normal dag parameters 17 | schedule_interval="@daily", 18 | start_date=datetime(2023, 1, 1), 19 | catchup=False, 20 | dag_id="customers_tag", 21 | tags=["filtering"], 22 | ) 23 | -------------------------------------------------------------------------------- /dags/filtering/only_models.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from cosmos import DbtDag, ProjectConfig, RenderConfig 4 | 5 | from include.profiles import airflow_db 6 | from include.constants import jaffle_shop_path, venv_execution_config 7 | 8 | only_models = DbtDag( 9 | project_config=ProjectConfig(jaffle_shop_path), 10 | profile_config=airflow_db, 11 | execution_config=venv_execution_config, 12 | # new render config 13 | render_config=RenderConfig( 14 | select=["path:models"], 15 | ), 16 | # normal dag parameters 17 | schedule_interval="@daily", 18 | start_date=datetime(2023, 1, 1), 19 | catchup=False, 20 | dag_id="only_models", 21 | tags=["filtering"], 22 | ) 23 | -------------------------------------------------------------------------------- /dags/filtering/only_seeds.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from cosmos import DbtDag, ProjectConfig, RenderConfig 4 | 5 | from include.profiles import airflow_db 6 | from include.constants import jaffle_shop_path, venv_execution_config 7 | 8 | only_seeds = DbtDag( 9 | project_config=ProjectConfig(jaffle_shop_path), 10 | profile_config=airflow_db, 11 | execution_config=venv_execution_config, 12 | # new render config 13 | render_config=RenderConfig( 14 | select=["path:seeds"], 15 | ), 16 | # normal dag parameters 17 | schedule_interval=None, 18 | start_date=datetime(2023, 1, 1), 19 | catchup=False, 20 | dag_id="only_seeds", 21 | tags=["filtering"], 22 | ) 23 | -------------------------------------------------------------------------------- /dags/profiles/dbt_profile.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from cosmos import DbtDag, ProjectConfig, ProfileConfig 4 | 5 | from include.constants import jaffle_shop_path, venv_execution_config 6 | 7 | dbt_profile_example = DbtDag( 8 | # dbt/cosmos-specific parameters 9 | project_config=ProjectConfig(jaffle_shop_path), 10 | profile_config=ProfileConfig( 11 | # these map to dbt/jaffle_shop/profiles.yml 12 | profile_name="airflow_db", 13 | target_name="dev", 14 | profiles_yml_filepath=jaffle_shop_path / "profiles.yml", 15 | ), 16 | execution_config=venv_execution_config, 17 | # normal dag parameters 18 | schedule_interval="@daily", 19 | start_date=datetime(2023, 1, 1), 20 | catchup=False, 21 | dag_id="dbt_profile_example", 22 | tags=["profiles"], 23 | ) 24 | -------------------------------------------------------------------------------- /dags/profiles/overrides.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | from cosmos import DbtDag, ProjectConfig, ProfileConfig 4 | from cosmos.profiles import PostgresUserPasswordProfileMapping 5 | 6 | from include.constants import jaffle_shop_path, venv_execution_config 7 | 8 | dbt_profile_overrides = DbtDag( 9 | # dbt/cosmos-specific parameters 10 | project_config=ProjectConfig(jaffle_shop_path), 11 | profile_config=ProfileConfig( 12 | # these map to dbt/jaffle_shop/profiles.yml 13 | profile_name="airflow_db", 14 | target_name="dev", 15 | profile_mapping=PostgresUserPasswordProfileMapping( 16 | conn_id="airflow_metadata_db", 17 | profile_args={"schema": "my_dbt_schema"}, 18 | ), 19 | ), 20 | execution_config=venv_execution_config, 21 | # normal dag parameters 22 | schedule_interval="@daily", 23 | start_date=datetime(2023, 1, 1), 24 | catchup=False, 25 | dag_id="dbt_profile_overrides", 26 | tags=["profiles"], 27 | ) 28 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/.user.yml: -------------------------------------------------------------------------------- 1 | id: 15f4b14a-123f-433a-bddc-864f00ab86fc 2 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/README.md: -------------------------------------------------------------------------------- 1 | ## `jaffle_shop` 2 | 3 | `jaffle_shop` is a fictional ecommerce store. This dbt project transforms raw data from an app database into a customers and orders model ready for analytics. 4 | 5 | See [dbt's documentation](https://github.com/dbt-labs/jaffle_shop) for more info. 6 | 7 | ### Modifications 8 | 9 | This project has been modified from the original to highlight some of the features of Cosmos. Namely: 10 | 11 | - tags have been added to the models 12 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/dbt_project.yml: -------------------------------------------------------------------------------- 1 | name: 'jaffle_shop' 2 | 3 | config-version: 2 4 | version: '0.1' 5 | 6 | profile: 'jaffle_shop' 7 | 8 | model-paths: ["models"] 9 | seed-paths: ["seeds"] 10 | test-paths: ["tests"] 11 | analysis-paths: ["analysis"] 12 | macro-paths: ["macros"] 13 | 14 | target-path: "target" 15 | clean-targets: 16 | - "target" 17 | - "dbt_modules" 18 | - "logs" 19 | 20 | require-dbt-version: [">=1.0.0", "<2.0.0"] 21 | 22 | models: 23 | jaffle_shop: 24 | materialized: table 25 | staging: 26 | materialized: view 27 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/models/customers/customers.sql: -------------------------------------------------------------------------------- 1 | {{ config(tags=['customers']) }} 2 | 3 | with customers as ( 4 | 5 | select * from {{ ref('stg_customers') }} 6 | 7 | ), 8 | 9 | orders as ( 10 | 11 | select * from {{ ref('stg_orders') }} 12 | 13 | ), 14 | 15 | payments as ( 16 | 17 | select * from {{ ref('stg_payments') }} 18 | 19 | ), 20 | 21 | customer_orders as ( 22 | 23 | select 24 | customer_id, 25 | 26 | min(order_date) as first_order, 27 | max(order_date) as most_recent_order, 28 | count(order_id) as number_of_orders 29 | from orders 30 | 31 | group by customer_id 32 | 33 | ), 34 | 35 | customer_payments as ( 36 | 37 | select 38 | orders.customer_id, 39 | sum(amount) as total_amount 40 | 41 | from payments 42 | 43 | left join orders on 44 | payments.order_id = orders.order_id 45 | 46 | group by orders.customer_id 47 | 48 | ), 49 | 50 | final as ( 51 | 52 | select 53 | customers.customer_id, 54 | customers.first_name, 55 | customers.last_name, 56 | customer_orders.first_order, 57 | customer_orders.most_recent_order, 58 | customer_orders.number_of_orders, 59 | customer_payments.total_amount as customer_lifetime_value 60 | 61 | from customers 62 | 63 | left join customer_orders 64 | on customers.customer_id = customer_orders.customer_id 65 | 66 | left join customer_payments 67 | on customers.customer_id = customer_payments.customer_id 68 | 69 | ) 70 | 71 | select * from final 72 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/models/docs.md: -------------------------------------------------------------------------------- 1 | {% docs orders_status %} 2 | 3 | Orders can be one of the following statuses: 4 | 5 | | status | description | 6 | |----------------|------------------------------------------------------------------------------------------------------------------------| 7 | | placed | The order has been placed but has not yet left the warehouse | 8 | | shipped | The order has ben shipped to the customer and is currently in transit | 9 | | completed | The order has been received by the customer | 10 | | return_pending | The customer has indicated that they would like to return the order, but it has not yet been received at the warehouse | 11 | | returned | The order has been returned by the customer and received at the warehouse | 12 | 13 | 14 | {% enddocs %} 15 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/models/orders.sql: -------------------------------------------------------------------------------- 1 | {% set payment_methods = ['credit_card', 'coupon', 'bank_transfer', 'gift_card'] %} 2 | 3 | with orders as ( 4 | 5 | select * from {{ ref('stg_orders') }} 6 | 7 | ), 8 | 9 | payments as ( 10 | 11 | select * from {{ ref('stg_payments') }} 12 | 13 | ), 14 | 15 | order_payments as ( 16 | 17 | select 18 | order_id, 19 | 20 | {% for payment_method in payment_methods -%} 21 | sum(case when payment_method = '{{ payment_method }}' then amount else 0 end) as {{ payment_method }}_amount, 22 | {% endfor -%} 23 | 24 | sum(amount) as total_amount 25 | 26 | from payments 27 | 28 | group by order_id 29 | 30 | ), 31 | 32 | final as ( 33 | 34 | select 35 | orders.order_id, 36 | orders.customer_id, 37 | orders.order_date, 38 | orders.status, 39 | 40 | {% for payment_method in payment_methods -%} 41 | 42 | order_payments.{{ payment_method }}_amount, 43 | 44 | {% endfor -%} 45 | 46 | order_payments.total_amount as amount 47 | 48 | from orders 49 | 50 | 51 | left join order_payments 52 | on orders.order_id = order_payments.order_id 53 | 54 | ) 55 | 56 | select * from final 57 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/models/overview.md: -------------------------------------------------------------------------------- 1 | {% docs __overview__ %} 2 | 3 | ## Data Documentation for Jaffle Shop 4 | 5 | `jaffle_shop` is a fictional ecommerce store. 6 | 7 | This [dbt](https://www.getdbt.com/) project is for testing out code. 8 | 9 | The source code can be found [here](https://github.com/clrcrl/jaffle_shop). 10 | 11 | {% enddocs %} 12 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/models/schema.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | models: 4 | - name: customers 5 | description: This table has basic information about a customer, as well as some derived facts based on a customer's orders 6 | 7 | columns: 8 | - name: customer_id 9 | description: This is a unique identifier for a customer 10 | tests: 11 | - unique 12 | - not_null 13 | 14 | - name: first_name 15 | description: Customer's first name. PII. 16 | 17 | - name: last_name 18 | description: Customer's last name. PII. 19 | 20 | - name: first_order 21 | description: Date (UTC) of a customer's first order 22 | 23 | - name: most_recent_order 24 | description: Date (UTC) of a customer's most recent order 25 | 26 | - name: number_of_orders 27 | description: Count of the number of orders a customer has placed 28 | 29 | - name: total_order_amount 30 | description: Total value (AUD) of a customer's orders 31 | 32 | - name: orders 33 | description: This table has basic information about orders, as well as some derived facts based on payments 34 | 35 | columns: 36 | - name: order_id 37 | tests: 38 | - unique 39 | - not_null 40 | description: This is a unique identifier for an order 41 | 42 | - name: customer_id 43 | description: Foreign key to the customers table 44 | tests: 45 | - not_null 46 | - relationships: 47 | to: ref('customers') 48 | field: customer_id 49 | 50 | - name: order_date 51 | description: Date (UTC) that the order was placed 52 | 53 | - name: status 54 | description: '{{ doc("orders_status") }}' 55 | tests: 56 | - accepted_values: 57 | values: ['placed', 'shipped', 'completed', 'return_pending', 'returned'] 58 | 59 | - name: amount 60 | description: Total amount (AUD) of the order 61 | tests: 62 | - not_null 63 | 64 | - name: credit_card_amount 65 | description: Amount of the order (AUD) paid for by credit card 66 | tests: 67 | - not_null 68 | 69 | - name: coupon_amount 70 | description: Amount of the order (AUD) paid for by coupon 71 | tests: 72 | - not_null 73 | 74 | - name: bank_transfer_amount 75 | description: Amount of the order (AUD) paid for by bank transfer 76 | tests: 77 | - not_null 78 | 79 | - name: gift_card_amount 80 | description: Amount of the order (AUD) paid for by gift card 81 | tests: 82 | - not_null 83 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/models/staging/schema.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | models: 4 | - name: stg_customers 5 | columns: 6 | - name: customer_id 7 | tests: 8 | - unique 9 | - not_null 10 | 11 | - name: stg_orders 12 | columns: 13 | - name: order_id 14 | tests: 15 | - unique 16 | - not_null 17 | - name: status 18 | tests: 19 | - accepted_values: 20 | values: ['placed', 'shipped', 'completed', 'return_pending', 'returned'] 21 | 22 | - name: stg_payments 23 | columns: 24 | - name: payment_id 25 | tests: 26 | - unique 27 | - not_null 28 | - name: payment_method 29 | tests: 30 | - accepted_values: 31 | values: ['credit_card', 'coupon', 'bank_transfer', 'gift_card'] 32 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/models/staging/stg_customers.sql: -------------------------------------------------------------------------------- 1 | {{ config(tags=['customers']) }} 2 | 3 | with source as ( 4 | 5 | {#- 6 | Normally we would select from the table here, but we are using seeds to load 7 | our data in this project 8 | #} 9 | select * from {{ ref('raw_customers') }} 10 | 11 | ), 12 | 13 | renamed as ( 14 | 15 | select 16 | id as customer_id, 17 | first_name, 18 | last_name 19 | 20 | from source 21 | 22 | ) 23 | 24 | select * from renamed 25 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/models/staging/stg_orders.sql: -------------------------------------------------------------------------------- 1 | {{ config(tags=['customers']) }} 2 | 3 | with source as ( 4 | 5 | {#- 6 | Normally we would select from the table here, but we are using seeds to load 7 | our data in this project 8 | #} 9 | select * from {{ ref('raw_orders') }} 10 | 11 | ), 12 | 13 | renamed as ( 14 | 15 | select 16 | id as order_id, 17 | user_id as customer_id, 18 | order_date, 19 | status 20 | 21 | from source 22 | 23 | ) 24 | 25 | select * from renamed 26 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/models/staging/stg_payments.sql: -------------------------------------------------------------------------------- 1 | {{ config(tags=['customers']) }} 2 | 3 | with source as ( 4 | 5 | {#- 6 | Normally we would select from the table here, but we are using seeds to load 7 | our data in this project 8 | #} 9 | select * from {{ ref('raw_payments') }} 10 | 11 | ), 12 | 13 | renamed as ( 14 | 15 | select 16 | id as payment_id, 17 | order_id, 18 | payment_method, 19 | 20 | -- `amount` is currently stored in cents, so we convert it to dollars 21 | amount / 100 as amount 22 | 23 | from source 24 | 25 | ) 26 | 27 | select * from renamed 28 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/profiles.yml: -------------------------------------------------------------------------------- 1 | airflow_db: 2 | target: dev 3 | outputs: 4 | dev: 5 | type: postgres 6 | host: postgres 7 | user: postgres 8 | password: postgres 9 | port: 5432 10 | dbname: postgres 11 | schema: dbt 12 | threads: 4 13 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/seeds/raw_customers.csv: -------------------------------------------------------------------------------- 1 | id,first_name,last_name 2 | 1,Michael,P. 3 | 2,Shawn,M. 4 | 3,Kathleen,P. 5 | 4,Jimmy,C. 6 | 5,Katherine,R. 7 | 6,Sarah,R. 8 | 7,Martin,M. 9 | 8,Frank,R. 10 | 9,Jennifer,F. 11 | 10,Henry,W. 12 | 11,Fred,S. 13 | 12,Amy,D. 14 | 13,Kathleen,M. 15 | 14,Steve,F. 16 | 15,Teresa,H. 17 | 16,Amanda,H. 18 | 17,Kimberly,R. 19 | 18,Johnny,K. 20 | 19,Virginia,F. 21 | 20,Anna,A. 22 | 21,Willie,H. 23 | 22,Sean,H. 24 | 23,Mildred,A. 25 | 24,David,G. 26 | 25,Victor,H. 27 | 26,Aaron,R. 28 | 27,Benjamin,B. 29 | 28,Lisa,W. 30 | 29,Benjamin,K. 31 | 30,Christina,W. 32 | 31,Jane,G. 33 | 32,Thomas,O. 34 | 33,Katherine,M. 35 | 34,Jennifer,S. 36 | 35,Sara,T. 37 | 36,Harold,O. 38 | 37,Shirley,J. 39 | 38,Dennis,J. 40 | 39,Louise,W. 41 | 40,Maria,A. 42 | 41,Gloria,C. 43 | 42,Diana,S. 44 | 43,Kelly,N. 45 | 44,Jane,R. 46 | 45,Scott,B. 47 | 46,Norma,C. 48 | 47,Marie,P. 49 | 48,Lillian,C. 50 | 49,Judy,N. 51 | 50,Billy,L. 52 | 51,Howard,R. 53 | 52,Laura,F. 54 | 53,Anne,B. 55 | 54,Rose,M. 56 | 55,Nicholas,R. 57 | 56,Joshua,K. 58 | 57,Paul,W. 59 | 58,Kathryn,K. 60 | 59,Adam,A. 61 | 60,Norma,W. 62 | 61,Timothy,R. 63 | 62,Elizabeth,P. 64 | 63,Edward,G. 65 | 64,David,C. 66 | 65,Brenda,W. 67 | 66,Adam,W. 68 | 67,Michael,H. 69 | 68,Jesse,E. 70 | 69,Janet,P. 71 | 70,Helen,F. 72 | 71,Gerald,C. 73 | 72,Kathryn,O. 74 | 73,Alan,B. 75 | 74,Harry,A. 76 | 75,Andrea,H. 77 | 76,Barbara,W. 78 | 77,Anne,W. 79 | 78,Harry,H. 80 | 79,Jack,R. 81 | 80,Phillip,H. 82 | 81,Shirley,H. 83 | 82,Arthur,D. 84 | 83,Virginia,R. 85 | 84,Christina,R. 86 | 85,Theresa,M. 87 | 86,Jason,C. 88 | 87,Phillip,B. 89 | 88,Adam,T. 90 | 89,Margaret,J. 91 | 90,Paul,P. 92 | 91,Todd,W. 93 | 92,Willie,O. 94 | 93,Frances,R. 95 | 94,Gregory,H. 96 | 95,Lisa,P. 97 | 96,Jacqueline,A. 98 | 97,Shirley,D. 99 | 98,Nicole,M. 100 | 99,Mary,G. 101 | 100,Jean,M. 102 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/seeds/raw_orders.csv: -------------------------------------------------------------------------------- 1 | id,user_id,order_date,status 2 | 1,1,2018-01-01,returned 3 | 2,3,2018-01-02,completed 4 | 3,94,2018-01-04,completed 5 | 4,50,2018-01-05,completed 6 | 5,64,2018-01-05,completed 7 | 6,54,2018-01-07,completed 8 | 7,88,2018-01-09,completed 9 | 8,2,2018-01-11,returned 10 | 9,53,2018-01-12,completed 11 | 10,7,2018-01-14,completed 12 | 11,99,2018-01-14,completed 13 | 12,59,2018-01-15,completed 14 | 13,84,2018-01-17,completed 15 | 14,40,2018-01-17,returned 16 | 15,25,2018-01-17,completed 17 | 16,39,2018-01-18,completed 18 | 17,71,2018-01-18,completed 19 | 18,64,2018-01-20,returned 20 | 19,54,2018-01-22,completed 21 | 20,20,2018-01-23,completed 22 | 21,71,2018-01-23,completed 23 | 22,86,2018-01-24,completed 24 | 23,22,2018-01-26,return_pending 25 | 24,3,2018-01-27,completed 26 | 25,51,2018-01-28,completed 27 | 26,32,2018-01-28,completed 28 | 27,94,2018-01-29,completed 29 | 28,8,2018-01-29,completed 30 | 29,57,2018-01-31,completed 31 | 30,69,2018-02-02,completed 32 | 31,16,2018-02-02,completed 33 | 32,28,2018-02-04,completed 34 | 33,42,2018-02-04,completed 35 | 34,38,2018-02-06,completed 36 | 35,80,2018-02-08,completed 37 | 36,85,2018-02-10,completed 38 | 37,1,2018-02-10,completed 39 | 38,51,2018-02-10,completed 40 | 39,26,2018-02-11,completed 41 | 40,33,2018-02-13,completed 42 | 41,99,2018-02-14,completed 43 | 42,92,2018-02-16,completed 44 | 43,31,2018-02-17,completed 45 | 44,66,2018-02-17,completed 46 | 45,22,2018-02-17,completed 47 | 46,6,2018-02-19,completed 48 | 47,50,2018-02-20,completed 49 | 48,27,2018-02-21,completed 50 | 49,35,2018-02-21,completed 51 | 50,51,2018-02-23,completed 52 | 51,71,2018-02-24,completed 53 | 52,54,2018-02-25,return_pending 54 | 53,34,2018-02-26,completed 55 | 54,54,2018-02-26,completed 56 | 55,18,2018-02-27,completed 57 | 56,79,2018-02-28,completed 58 | 57,93,2018-03-01,completed 59 | 58,22,2018-03-01,completed 60 | 59,30,2018-03-02,completed 61 | 60,12,2018-03-03,completed 62 | 61,63,2018-03-03,completed 63 | 62,57,2018-03-05,completed 64 | 63,70,2018-03-06,completed 65 | 64,13,2018-03-07,completed 66 | 65,26,2018-03-08,completed 67 | 66,36,2018-03-10,completed 68 | 67,79,2018-03-11,completed 69 | 68,53,2018-03-11,completed 70 | 69,3,2018-03-11,completed 71 | 70,8,2018-03-12,completed 72 | 71,42,2018-03-12,shipped 73 | 72,30,2018-03-14,shipped 74 | 73,19,2018-03-16,completed 75 | 74,9,2018-03-17,shipped 76 | 75,69,2018-03-18,completed 77 | 76,25,2018-03-20,completed 78 | 77,35,2018-03-21,shipped 79 | 78,90,2018-03-23,shipped 80 | 79,52,2018-03-23,shipped 81 | 80,11,2018-03-23,shipped 82 | 81,76,2018-03-23,shipped 83 | 82,46,2018-03-24,shipped 84 | 83,54,2018-03-24,shipped 85 | 84,70,2018-03-26,placed 86 | 85,47,2018-03-26,shipped 87 | 86,68,2018-03-26,placed 88 | 87,46,2018-03-27,placed 89 | 88,91,2018-03-27,shipped 90 | 89,21,2018-03-28,placed 91 | 90,66,2018-03-30,shipped 92 | 91,47,2018-03-31,placed 93 | 92,84,2018-04-02,placed 94 | 93,66,2018-04-03,placed 95 | 94,63,2018-04-03,placed 96 | 95,27,2018-04-04,placed 97 | 96,90,2018-04-06,placed 98 | 97,89,2018-04-07,placed 99 | 98,41,2018-04-07,placed 100 | 99,85,2018-04-09,placed 101 | -------------------------------------------------------------------------------- /dbt/jaffle_shop/seeds/raw_payments.csv: -------------------------------------------------------------------------------- 1 | id,order_id,payment_method,amount 2 | 1,1,credit_card,1000 3 | 2,2,credit_card,2000 4 | 3,3,coupon,100 5 | 4,4,coupon,2500 6 | 5,5,bank_transfer,1700 7 | 6,6,credit_card,600 8 | 7,7,credit_card,1600 9 | 8,8,credit_card,2300 10 | 9,9,gift_card,2300 11 | 10,9,bank_transfer,0 12 | 11,10,bank_transfer,2600 13 | 12,11,credit_card,2700 14 | 13,12,credit_card,100 15 | 14,13,credit_card,500 16 | 15,13,bank_transfer,1400 17 | 16,14,bank_transfer,300 18 | 17,15,coupon,2200 19 | 18,16,credit_card,1000 20 | 19,17,bank_transfer,200 21 | 20,18,credit_card,500 22 | 21,18,credit_card,800 23 | 22,19,gift_card,600 24 | 23,20,bank_transfer,1500 25 | 24,21,credit_card,1200 26 | 25,22,bank_transfer,800 27 | 26,23,gift_card,2300 28 | 27,24,coupon,2600 29 | 28,25,bank_transfer,2000 30 | 29,25,credit_card,2200 31 | 30,25,coupon,1600 32 | 31,26,credit_card,3000 33 | 32,27,credit_card,2300 34 | 33,28,bank_transfer,1900 35 | 34,29,bank_transfer,1200 36 | 35,30,credit_card,1300 37 | 36,31,credit_card,1200 38 | 37,32,credit_card,300 39 | 38,33,credit_card,2200 40 | 39,34,bank_transfer,1500 41 | 40,35,credit_card,2900 42 | 41,36,bank_transfer,900 43 | 42,37,credit_card,2300 44 | 43,38,credit_card,1500 45 | 44,39,bank_transfer,800 46 | 45,40,credit_card,1400 47 | 46,41,credit_card,1700 48 | 47,42,coupon,1700 49 | 48,43,gift_card,1800 50 | 49,44,gift_card,1100 51 | 50,45,bank_transfer,500 52 | 51,46,bank_transfer,800 53 | 52,47,credit_card,2200 54 | 53,48,bank_transfer,300 55 | 54,49,credit_card,600 56 | 55,49,credit_card,900 57 | 56,50,credit_card,2600 58 | 57,51,credit_card,2900 59 | 58,51,credit_card,100 60 | 59,52,bank_transfer,1500 61 | 60,53,credit_card,300 62 | 61,54,credit_card,1800 63 | 62,54,bank_transfer,1100 64 | 63,55,credit_card,2900 65 | 64,56,credit_card,400 66 | 65,57,bank_transfer,200 67 | 66,58,coupon,1800 68 | 67,58,gift_card,600 69 | 68,59,gift_card,2800 70 | 69,60,credit_card,400 71 | 70,61,bank_transfer,1600 72 | 71,62,gift_card,1400 73 | 72,63,credit_card,2900 74 | 73,64,bank_transfer,2600 75 | 74,65,credit_card,0 76 | 75,66,credit_card,2800 77 | 76,67,bank_transfer,400 78 | 77,67,credit_card,1900 79 | 78,68,credit_card,1600 80 | 79,69,credit_card,1900 81 | 80,70,credit_card,2600 82 | 81,71,credit_card,500 83 | 82,72,credit_card,2900 84 | 83,73,bank_transfer,300 85 | 84,74,credit_card,3000 86 | 85,75,credit_card,1900 87 | 86,76,coupon,200 88 | 87,77,credit_card,0 89 | 88,77,bank_transfer,1900 90 | 89,78,bank_transfer,2600 91 | 90,79,credit_card,1800 92 | 91,79,credit_card,900 93 | 92,80,gift_card,300 94 | 93,81,coupon,200 95 | 94,82,credit_card,800 96 | 95,83,credit_card,100 97 | 96,84,bank_transfer,2500 98 | 97,85,bank_transfer,1700 99 | 98,86,coupon,2300 100 | 99,87,gift_card,3000 101 | 100,87,credit_card,2600 102 | 101,88,credit_card,2900 103 | 102,89,bank_transfer,2200 104 | 103,90,bank_transfer,200 105 | 104,91,credit_card,1900 106 | 105,92,bank_transfer,1500 107 | 106,92,coupon,200 108 | 107,93,gift_card,2600 109 | 108,94,coupon,700 110 | 109,95,coupon,2400 111 | 110,96,gift_card,1700 112 | 111,97,bank_transfer,1400 113 | 112,98,bank_transfer,1000 114 | 113,99,credit_card,2400 115 | -------------------------------------------------------------------------------- /docker-compose.override.yml: -------------------------------------------------------------------------------- 1 | version: "3.1" 2 | 3 | # mount the dbt directory as a volume 4 | services: 5 | scheduler: 6 | volumes: 7 | - ./dbt:/usr/local/airflow/dbt -------------------------------------------------------------------------------- /include/constants.py: -------------------------------------------------------------------------------- 1 | "Contains constants used in the DAGs" 2 | 3 | from pathlib import Path 4 | from cosmos import ExecutionConfig 5 | 6 | jaffle_shop_path = Path("/usr/local/airflow/dbt/jaffle_shop") 7 | dbt_executable = Path("/usr/local/airflow/dbt_venv/bin/dbt") 8 | 9 | venv_execution_config = ExecutionConfig( 10 | dbt_executable_path=str(dbt_executable), 11 | ) 12 | -------------------------------------------------------------------------------- /include/profiles.py: -------------------------------------------------------------------------------- 1 | "Contains profile mappings used in the project" 2 | 3 | from cosmos import ProfileConfig 4 | from cosmos.profiles import PostgresUserPasswordProfileMapping 5 | 6 | 7 | airflow_db = ProfileConfig( 8 | profile_name="airflow_db", 9 | target_name="dev", 10 | profile_mapping=PostgresUserPasswordProfileMapping( 11 | conn_id="airflow_metadata_db", 12 | profile_args={"schema": "dbt"}, 13 | ), 14 | ) 15 | -------------------------------------------------------------------------------- /packages.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/astronomer/cosmos-demo/896b7b0dfa5d04ae798df5e113c1f104e2760fe0/packages.txt -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | astronomer-cosmos>=1.0.2 -------------------------------------------------------------------------------- /tests/dags/test_dag_integrity.py: -------------------------------------------------------------------------------- 1 | """Test the validity of all DAGs. This test ensures that all Dags have tags, retries set to two, and no import errors. Feel free to add and remove tests.""" 2 | 3 | import os 4 | import logging 5 | from contextlib import contextmanager 6 | import pytest 7 | from airflow.models import DagBag 8 | 9 | 10 | @contextmanager 11 | def suppress_logging(namespace): 12 | logger = logging.getLogger(namespace) 13 | old_value = logger.disabled 14 | logger.disabled = True 15 | try: 16 | yield 17 | finally: 18 | logger.disabled = old_value 19 | 20 | 21 | def get_import_errors(): 22 | """ 23 | Generate a tuple for import errors in the dag bag 24 | """ 25 | with suppress_logging("airflow"): 26 | dag_bag = DagBag(include_examples=False) 27 | 28 | def strip_path_prefix(path): 29 | return os.path.relpath(path, os.environ.get("AIRFLOW_HOME")) 30 | 31 | # we prepend "(None,None)" to ensure that a test object is always created even if its a no op. 32 | return [(None, None)] + [ 33 | (strip_path_prefix(k), v.strip()) for k, v in dag_bag.import_errors.items() 34 | ] 35 | 36 | 37 | def get_dags(): 38 | """ 39 | Generate a tuple of dag_id, in the DagBag 40 | """ 41 | with suppress_logging("airflow"): 42 | dag_bag = DagBag(include_examples=False) 43 | 44 | def strip_path_prefix(path): 45 | return os.path.relpath(path, os.environ.get("AIRFLOW_HOME")) 46 | 47 | return [(k, v, strip_path_prefix(v.fileloc)) for k, v in dag_bag.dags.items()] 48 | 49 | 50 | @pytest.mark.parametrize( 51 | "rel_path,rv", get_import_errors(), ids=[x[0] for x in get_import_errors()] 52 | ) 53 | def test_file_imports(rel_path, rv): 54 | """Test for import errors on a file""" 55 | if rel_path and rv: 56 | raise Exception(f"{rel_path} failed to import with message \n {rv}") 57 | 58 | 59 | APPROVED_TAGS = {} 60 | 61 | 62 | @pytest.mark.parametrize( 63 | "dag_id,dag,fileloc", get_dags(), ids=[x[2] for x in get_dags()] 64 | ) 65 | def test_dag_tags(dag_id, dag, fileloc): 66 | """ 67 | test if a DAG is tagged and if those TAGs are in the approved list 68 | """ 69 | assert dag.tags, f"{dag_id} in {fileloc} has no tags" 70 | if APPROVED_TAGS: 71 | assert not set(dag.tags) - APPROVED_TAGS 72 | 73 | 74 | @pytest.mark.parametrize( 75 | "dag_id,dag, fileloc", get_dags(), ids=[x[2] for x in get_dags()] 76 | ) 77 | def test_dag_retries(dag_id, dag, fileloc): 78 | """ 79 | test if a DAG has retries set 80 | """ 81 | assert ( 82 | dag.default_args.get("retries", None) >= 2 83 | ), f"{dag_id} in {fileloc} does not have retries not set to 2." 84 | --------------------------------------------------------------------------------