├── .github └── workflows │ ├── build_and_deploy.yaml │ └── delete_branch.yaml ├── .gitignore ├── .python-version ├── LICENSE ├── README.md ├── config.py.sample ├── docs └── manual_run.png ├── procedure ├── __init__.py └── process.py ├── requirements.other.txt ├── requirements.txt ├── scratch.ipynb ├── setup ├── 00_init_schema.sql └── 01_run_procedures.sql ├── tests ├── __init__.py ├── e2e_tests.json └── procedure_test.py └── utils ├── __init__.py ├── get_session.py └── snowflake_connection.py /.github/workflows/build_and_deploy.yaml: -------------------------------------------------------------------------------- 1 | # This is a basic workflow to help you get started with Actions 2 | 3 | name: Build, Deploy, Validate 4 | 5 | # Controls when the workflow will run 6 | on: 7 | # Triggers the workflow on push or pull request events but only for the main branch 8 | push: 9 | branches: 10 | - "*" 11 | tags: 12 | - "v*" 13 | 14 | # Allows you to run this workflow manually from the Actions tab 15 | workflow_dispatch: 16 | 17 | env: 18 | SNOWSQL_PWD: ${{ secrets.SNOWSQL_PWD }} 19 | SNOWSQL_ACCOUNT: ${{ secrets.SNOWSQL_ACCOUNT }} 20 | SNOWSQL_USER: ${{ secrets.SNOWSQL_USER }} 21 | SNOWSQL_DATABASE: ${{ secrets.SNOWSQL_DATABASE }} 22 | SNOWSQL_SCHEMA: ${{ github.ref_name }} 23 | SNOWSQL_ROLE: ${{ secrets.SNOWSQL_ROLE }} 24 | SNOWSQL_WAREHOUSE: ${{ secrets.SNOWSQL_WAREHOUSE }} 25 | 26 | jobs: 27 | build: 28 | runs-on: ubuntu-latest 29 | outputs: 30 | matrix: ${{ steps.matrix.outputs.assertions }} 31 | steps: 32 | - uses: actions/checkout@v3 33 | - name: Install SnowSQL 34 | run: | 35 | curl -O https://sfc-repo.snowflakecomputing.com/snowsql/bootstrap/1.2/linux_x86_64/snowsql-1.2.23-linux_x86_64.bash 36 | SNOWSQL_DEST=~/bin SNOWSQL_LOGIN_SHELL=~/.profile bash snowsql-1.2.23-linux_x86_64.bash 37 | - uses: actions/setup-python@v4 38 | with: 39 | python-version: "3.8" 40 | - name: Install python packages 41 | run: pip install -r requirements.txt 42 | - name: Create schema for branch if not exists 43 | run: | 44 | ~/bin/snowsql -q 'create schema if not exists ${{ github.ref_name }}' -o friendly=false 45 | - name: Run unit tests 46 | run: python -m pytest 47 | - name: Installing manually managed packages for deployment 48 | run: | 49 | echo 'Installing packages that require manual installation....' 50 | pip install -t .packages -r requirements.other.txt 51 | - name: Create zip package 52 | run: | 53 | echo 'Creating zip package...' 54 | if [ -d "build" ] ; then 55 | cd .packages 56 | zip -r ../app.zip . 57 | cd .. 58 | fi 59 | zip -g -x .\* -r app.zip . 60 | - name: Archive python artifact 61 | uses: actions/upload-artifact@v3 62 | with: 63 | name: app 64 | path: app.zip 65 | retention-days: 7 66 | - name: Parse test plan 67 | id: matrix 68 | run: | 69 | assertions=$(cat ./tests/e2e_tests.json | jq -c '.assertions' | sed 's/{{schema}}/${{ github.ref_name }}/g') 70 | echo "::set-output name=assertions::$assertions" 71 | 72 | deploy: 73 | needs: build 74 | runs-on: ubuntu-latest 75 | steps: 76 | - uses: actions/checkout@v3 77 | - uses: actions/download-artifact@v3 78 | with: 79 | name: app 80 | - name: Install SnowSQL 81 | run: | 82 | curl -O https://sfc-repo.snowflakecomputing.com/snowsql/bootstrap/1.2/linux_x86_64/snowsql-1.2.23-linux_x86_64.bash 83 | SNOWSQL_DEST=~/bin SNOWSQL_LOGIN_SHELL=~/.profile bash snowsql-1.2.23-linux_x86_64.bash 84 | - name: Upload artifact to SnowSQL 85 | run: | 86 | ~/bin/snowsql -s ${{ github.ref_name }} -q 'create stage if not exists deploy' -o friendly=false -o exit_on_error=true 87 | ~/bin/snowsql -s ${{ github.ref_name }} -q 'put file://'$(pwd)'/app.zip @deploy overwrite=true auto_compress=false' -o friendly=false -o exit_on_error=true 88 | - name: Create resources and seed database 89 | run: | 90 | ~/bin/snowsql -s ${{ github.ref_name }} -f ./setup/00_init_schema.sql -o friendly=false -o exit_on_error=true 91 | 92 | run_procedures: 93 | needs: [deploy, build] 94 | runs-on: ubuntu-latest 95 | steps: 96 | - uses: actions/checkout@v3 97 | - name: Install SnowSQL 98 | run: | 99 | curl -O https://sfc-repo.snowflakecomputing.com/snowsql/bootstrap/1.2/linux_x86_64/snowsql-1.2.23-linux_x86_64.bash 100 | SNOWSQL_DEST=~/bin SNOWSQL_LOGIN_SHELL=~/.profile bash snowsql-1.2.23-linux_x86_64.bash 101 | - name: Run any procedures 102 | run: | 103 | ~/bin/snowsql -s ${{ github.ref_name }} -f ./setup/01_run_procedures.sql -o friendly=false -o exit_on_error=true 104 | 105 | e2etest: 106 | needs: [deploy, build, run_procedures] 107 | runs-on: ubuntu-latest 108 | strategy: 109 | matrix: 110 | tests: ${{fromJson(needs.build.outputs.matrix)}} 111 | steps: 112 | - uses: actions/checkout@v3 113 | - name: Install SnowSQL 114 | run: | 115 | curl -O https://sfc-repo.snowflakecomputing.com/snowsql/bootstrap/1.2/linux_x86_64/snowsql-1.2.23-linux_x86_64.bash 116 | SNOWSQL_DEST=~/bin SNOWSQL_LOGIN_SHELL=~/.profile bash snowsql-1.2.23-linux_x86_64.bash 117 | - name: Run test - ${{ matrix.tests.name }} 118 | run: | 119 | rowCount=$(~/bin/snowsql -s ${{ github.ref_name }} -q $'${{ matrix.tests.value }}' -o friendly=false -o exit_on_error=true -o output_format=json -o timing=false | jq '. | length') 120 | if [[ $rowCount -ne 0 ]]; then 121 | echo "Test failed! $rowCount rows returned" 1>&2 122 | exit 1 123 | else 124 | echo "Test Passed! $rowCount rows returned" 125 | fi 126 | -------------------------------------------------------------------------------- /.github/workflows/delete_branch.yaml: -------------------------------------------------------------------------------- 1 | name: Branch Deleted 2 | on: delete 3 | 4 | env: 5 | SNOWSQL_PWD: ${{ secrets.SNOWSQL_PWD }} 6 | SNOWSQL_ACCOUNT: ${{ secrets.SNOWSQL_ACCOUNT }} 7 | SNOWSQL_USER: ${{ secrets.SNOWSQL_USER }} 8 | SNOWSQL_DATABASE: ${{ secrets.SNOWSQL_DATABASE }} 9 | SNOWSQL_ROLE: ${{ secrets.SNOWSQL_ROLE }} 10 | SNOWSQL_WAREHOUSE: ${{ secrets.SNOWSQL_WAREHOUSE }} 11 | 12 | jobs: 13 | delete: 14 | if: github.event.ref_type == 'branch' 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Install SnowSQL 18 | run: | 19 | curl -O https://sfc-repo.snowflakecomputing.com/snowsql/bootstrap/1.2/linux_x86_64/snowsql-1.2.23-linux_x86_64.bash 20 | SNOWSQL_DEST=~/bin SNOWSQL_LOGIN_SHELL=~/.profile bash snowsql-1.2.23-linux_x86_64.bash 21 | - name: Upload artifact to SnowSQL 22 | run: | 23 | ~/bin/snowsql -q 'drop schema ${{ github.event.ref }}' -o friendly=false -o exit_on_error=true 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | config.py 2 | .venv 3 | __pycache__ 4 | .pytest_cache 5 | app.zip 6 | .packages 7 | .ipynb_checkpoints 8 | *_converted.py -------------------------------------------------------------------------------- /.python-version: -------------------------------------------------------------------------------- 1 | 3.8.13 2 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Snowpark DevOps Template 2 | 3 | This repo is a sample project for a stored procedure (that created / depends on a user defined function) which is configured for CI/CD via pytest and GitHub Actions. 4 | 5 | View the session from [Snowflake BUILD '22 here](https://www.snowflake.com/build/agenda?agendaPath=session/1005370). 6 | 7 | ## Prerequisites 8 | 9 | * Snowflake account 10 | * Python 3.8 11 | * Git 12 | 13 | ## Setup 14 | 15 | ### Database Setup 16 | 17 | #### 1. Get the economy dataset 18 | Log into Snowflake, browse to the marketplace, and get the **Knoema Economy Data Atlas** dataset. Leave the database name as the default `Economy_Data_Atlas` and feel free to select any roles for access. 19 | 20 | #### 2. Create a database, schema, and warehouse for development 21 | If you already have a database / schema you'd like to use, feel free to skip this step. Otherwise, we'll create a new one. Open a worksheet in Snowflake and run the following: 22 | 23 | ```sql 24 | create database if not exists snowpark_devops; 25 | use database snowpark_devops; 26 | create schema if not exists dev; 27 | use schema dev; 28 | create warehouse if not exists dev_wh warehouse_size='small'; 29 | ``` 30 | 31 | #### 3. Create a view on the marketplace data to use for development 32 | Run the following command on the database created in the previous step (you can just add to the same worksheet) 33 | ```sql 34 | CREATE VIEW IF NOT EXISTS BEANIPA ("Table", Table_Name, Table_Description, Table_Full_Name, Table_Unit, Indicator, Indicator_Name, Indicator_Description, Indicator_Full_Name, Units, Scale, Frequency, Date, Value) 35 | as 36 | SELECT * FROM ECONOMY_DATA_ATLAS.ECONOMY.BEANIPA; 37 | ``` 38 | 39 | You should see `View BEANIPA successfully created.` letting you know this schema is ready for use. 40 | 41 | ### Development Setup 42 | 43 | #### 1. Clone this repo 44 | 45 | Select to **Use this Template** on the repo. Then clone the repo in your acount: 46 | 47 | ```bash 48 | git clone 49 | ``` 50 | 51 | #### 2. Configure connection to Snowflake 52 | Navigate to the project and open in your favorite code editor like VS Code. 53 | 54 | Rename the `config.py.sample` file to `config.py` and update the values to match your environment. 55 | 56 | If unsure of what your account name is, you can view in a SQL worksheet with `select current_account()`. 57 | 58 | If using the values from the previous Snowflake setup steps, your `config.py` should look something like: 59 | ```python 60 | snowpark_config = { 61 | 'account': 'CIB54868', 62 | 'user': 'jeffhollan', 63 | 'password': 'secretpassword', 64 | 'role': 'ACCOUNTADMIN', 65 | 'warehouse': 'dev_wh', 66 | 'database': 'snowpark_devops', 67 | 'schema': 'dev' 68 | } 69 | ``` 70 | 71 | #### 4. Install python packages for project 72 | 73 | > NOTE: We recommend you activate a conda or venv environment for the project 74 | 75 | ```bash 76 | pip install -r requirements.txt 77 | ``` 78 | 79 | #### 5. Verify environment is configured correctly 80 | Verify packages, python, and connection is setup correctly by running the tests for the project: 81 | 82 | ```python 83 | python -m pytest 84 | ``` 85 | 86 | If everything is configured correctly you should see **2 passed** in the output. 87 | 88 | ### GitHub Actions DevOps Setup 89 | 90 | #### 1. Create the secrets to use in automation 91 | 92 | In the settings of the repo, navigate to **Secrets** and **Actions** for the project and create the following secrets. Values should match configuration from the `config.py` file. 93 | 94 | | Name | Description | 95 | | --- | --- | 96 | | SNOWFLAKE_ACCOUNT | Snowflake account name | 97 | | SNOWFLAKE_USERNAME | Snowflake user name | 98 | | SNOWFLAKE_PASSWORD | Snowflake password | 99 | | SNOWFLAKE_ROLE | Snowflake role to execute the GitHub actions | 100 | | SNOWFLAKE_WAREHOUSE | Snowflake warehouse to execute the GitHub actions | 101 | | SNOWFLAKE_DATABASE | Snowflake database to execute the GitHub actions | 102 | 103 | #### 2. Enable the actions on the repo 104 | Verify actions are enabled in the settings of the repo in **Actions** and **General** and confirm are enabled. 105 | 106 | #### 3. Manually run the deploy action 107 | We now want to configure our "production" branch, which will map to the `main` branch of the repo. Now that the connection and configuration is applied, manually run the Action on the `main` branch which will create the schemas, views, and run this Snowpark pipeline on your Snowflake account. This includes some Python dataframe operations to train and publish a UDF for predict consumer spend. 108 | 109 | Open the **Actions** tab on the repo and manually run the Build and Deploy action: 110 | 111 | ![screenshot](./docs/manual_run.png) 112 | 113 | ## Adding a new feature 114 | 115 | The template includes a branch for a new feature. Normally you'd manually create a branch, and when pushed to the repo would automatically create a schema. 116 | 117 | You can navigate to this branch locally by running `git checkout forecast`. 118 | 119 | Any changes made to this branch that are pushed up will automatically kick off actions that will create the artifacts in the `forecast` schema. 120 | 121 | If you open a pull request and merge it to main, you will see these features now promoted to the `main` environment. -------------------------------------------------------------------------------- /config.py.sample: -------------------------------------------------------------------------------- 1 | # This file can be used to store credentials for local dev / testing 2 | # Rename to `config.py` and replace the values below with your own 3 | 4 | snowpark_config = { 5 | 'account': 'acme', 6 | 'user': 'johndoe', 7 | 'password': 'hunter2', 8 | 'role': 'ACCOUNTADMIN', 9 | 'warehouse': 'mywarehouse', 10 | 'database': 'mydatabase', 11 | 'schema': 'PUBLIC' 12 | } -------------------------------------------------------------------------------- /docs/manual_run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Snowflake-Labs/snowpark-devops/51e194afb3dfabba9fcf47862e37a89c48ffcd46/docs/manual_run.png -------------------------------------------------------------------------------- /procedure/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Snowflake-Labs/snowpark-devops/51e194afb3dfabba9fcf47862e37a89c48ffcd46/procedure/__init__.py -------------------------------------------------------------------------------- /procedure/process.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | from snowflake.snowpark import Session, DataFrame 5 | from snowflake.snowpark.types import PandasSeriesType, PandasDataFrameType, IntegerType, FloatType 6 | from snowflake.snowpark.functions import col, year 7 | from sklearn.linear_model import LinearRegression 8 | import pandas as pd 9 | 10 | OUTPUTS = [] 11 | 12 | def run(session: Session) -> str: 13 | pce_df = session.table('BEANIPA') 14 | filtered_df = filter_personal_consumption_expenditures(pce_df) 15 | pce_pred = train_linear_regression_model(filtered_df.to_pandas()) # type: ignore 16 | register_udf(pce_pred, session) 17 | return str(OUTPUTS) 18 | 19 | # get PCE data 20 | def filter_personal_consumption_expenditures(input_df: DataFrame) -> DataFrame: 21 | df_pce = (input_df 22 | .filter(col("Table_Name") == 'Price Indexes For Personal Consumption Expenditures By Major Type Of Product') 23 | .filter(col('Indicator_Name') == 'Personal consumption expenditures (PCE)') 24 | .filter(col('Frequency') == 'A') 25 | .filter(col('Date') >= '1972-01-01')) 26 | df_pce_year = df_pce.select(year(col('Date')).alias('Year'), col('Value').alias('PCE') ) 27 | return df_pce_year 28 | 29 | def train_linear_regression_model(input_pd: pd.DataFrame) -> LinearRegression: 30 | x = input_pd["YEAR"].to_numpy().reshape(-1,1) 31 | y = input_pd["PCE"].to_numpy() 32 | 33 | model = LinearRegression().fit(x, y) 34 | 35 | # test model for 2023 36 | predictYear = 2023 37 | pce_pred = model.predict([[predictYear]]) 38 | OUTPUTS.append(input_pd.tail()) 39 | OUTPUTS.append('Prediction for '+str(predictYear)+': '+ str(round(pce_pred[0],2))) 40 | return model 41 | 42 | def register_udf(model, session): 43 | def predict_pce(ps: pd.Series) -> pd.Series: 44 | return ps.transform(lambda x: model.predict([[x]])[0].round(2).astype(float)) 45 | session.udf.register(predict_pce, 46 | return_type=PandasSeriesType(FloatType()), 47 | input_types=[PandasSeriesType(IntegerType())], 48 | packages= ["pandas","scikit-learn"], 49 | is_permanent=True, 50 | name="predict_pce_udf", 51 | replace=True, 52 | stage_location="@deploy") 53 | OUTPUTS.append('UDF registered') 54 | 55 | if __name__ == "__main__": 56 | from utils import get_session 57 | session = get_session.session() 58 | run(session) 59 | -------------------------------------------------------------------------------- /requirements.other.txt: -------------------------------------------------------------------------------- 1 | # text file to store requirements that need to be manually installed 2 | # NOTE: Can not include native libraries as those can only be included via Anaconda 3 | # 4 | # holidays>0.14 5 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | snowflake-snowpark-python[pandas] 2 | sklearn 3 | pandas 4 | pytest -------------------------------------------------------------------------------- /scratch.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "# If you want to use a notebook to expirement, I often keep one in my project here.\n", 10 | "from snowflake.snowpark.session import Session\n", 11 | "from snowflake.snowpark.functions import *\n", 12 | "from snowflake.snowpark.types import *\n", 13 | "from config import snowpark_config\n", 14 | "\n", 15 | "session = Session.builder.configs(snowpark_config).create()" 16 | ] 17 | } 18 | ], 19 | "metadata": { 20 | "kernelspec": { 21 | "display_name": "Python 3.8.13 ('x86_p38')", 22 | "language": "python", 23 | "name": "python3" 24 | }, 25 | "language_info": { 26 | "codemirror_mode": { 27 | "name": "ipython", 28 | "version": 3 29 | }, 30 | "file_extension": ".py", 31 | "mimetype": "text/x-python", 32 | "name": "python", 33 | "nbconvert_exporter": "python", 34 | "pygments_lexer": "ipython3", 35 | "version": "3.8.13 (default, Mar 28 2022, 06:16:26) \n[Clang 12.0.0 ]" 36 | }, 37 | "vscode": { 38 | "interpreter": { 39 | "hash": "6c310b686aade603b7b6d1b84b2526a1fe60e588546e8258abd036f8ed7a0730" 40 | } 41 | } 42 | }, 43 | "nbformat": 4, 44 | "nbformat_minor": 2 45 | } 46 | -------------------------------------------------------------------------------- /setup/00_init_schema.sql: -------------------------------------------------------------------------------- 1 | -- First create database using the Knoema Economical Data Atlas 2 | -- Go to Marketplace to get database 3 | 4 | CREATE VIEW IF NOT EXISTS BEANIPA ("Table", Table_Name, Table_Description, Table_Full_Name, Table_Unit, Indicator, Indicator_Name, Indicator_Description, Indicator_Full_Name, Units, Scale, Frequency, Date, Value) 5 | as 6 | SELECT * FROM ECONOMY_DATA_ATLAS.ECONOMY.BEANIPA; 7 | 8 | create or replace procedure my_procedure() 9 | returns string 10 | language python 11 | runtime_version = '3.8' 12 | PACKAGES = ('snowflake-snowpark-python', 'scikit-learn', 'pandas') 13 | handler = 'procedure.process.run' 14 | imports = ('@deploy/app.zip'); -------------------------------------------------------------------------------- /setup/01_run_procedures.sql: -------------------------------------------------------------------------------- 1 | call my_procedure(); -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Snowflake-Labs/snowpark-devops/51e194afb3dfabba9fcf47862e37a89c48ffcd46/tests/__init__.py -------------------------------------------------------------------------------- /tests/e2e_tests.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "PCE Forecast tests", 3 | "assertions": [ 4 | { 5 | "name": "Prediction returns positive int", 6 | "value": "SELECT predict_pce_udf(2023) WHERE predict_pce_udf(2023) < 0" 7 | } 8 | ] 9 | } -------------------------------------------------------------------------------- /tests/procedure_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from snowflake.snowpark import Session 3 | from snowflake.snowpark.types import LongType, DateType, StringType, StructType, StructField, DoubleType, IntegerType 4 | import pandas as pd 5 | from utils import get_session 6 | get_session.session() 7 | from procedure import process 8 | 9 | @pytest.fixture 10 | def session() -> Session: 11 | return get_session.session() 12 | 13 | def test_filter(session: Session): 14 | source_data = [ 15 | ("T10109", "Implicit Price Deflators For Gross Domestic Product", None, "Table 1.1.9. Implicit Price Deflators For Gross Domestic Product (A) (Q)", "Index, 2012=100", "DPCERD-2", "Personal consumption expenditures", None, None, "Index, 2012=100", 1, "Q", "1976-01-01", 29.437), 16 | ("T20304", "Price Indexes For Personal Consumption Expenditures By Major Type Of Product", None, "Table 2.3.4. Price Indexes For Personal Consumption Expenditures By Major Type Of Product (A) (Q)", "Index, 2012=100", "DPCERG-1", "Personal consumption expenditures (PCE)", None, None, "Index, 2012=100", 1, "A", "2021-01-01", 115.53), 17 | ("T20304", "Price Indexes For Personal Consumption Expenditures By Major Type Of Product", None, "Table 2.3.4. Price Indexes For Personal Consumption Expenditures By Major Type Of Product (A) (Q)", "Index, 2012=100", "DPCERG-1", "Personal consumption expenditures (PCE)", None, None, "Index, 2012=100", 1, "A", "1929-01-01", 9.296) 18 | ] 19 | schema=StructType([StructField('Table', StringType(), nullable=True), StructField('Table_Name', StringType(), nullable=True), StructField('Table_Description', StringType(), nullable=True), StructField('Table_Full_Name', StringType(), nullable=True), StructField('Table_Unit', StringType(), nullable=True), StructField('Indicator', StringType(), nullable=True), StructField('Indicator_Name', StringType(), nullable=True), StructField('Indicator_Description', StringType(), nullable=True), StructField('Indicator_Full_Name', StringType(), nullable=True), StructField('Units', StringType(), nullable=True), StructField('Scale', LongType(), nullable=True), StructField('Frequency', StringType(), nullable=True), StructField('Date', DateType(), nullable=True), StructField('Value', DoubleType(), nullable=True)]) 20 | source_df = session.create_dataframe( 21 | source_data, 22 | schema=schema 23 | ) 24 | actual_df = process.filter_personal_consumption_expenditures(source_df) 25 | expected_data = [ 26 | (2021, 115.53) 27 | ] 28 | expected_df = session.create_dataframe(expected_data, 29 | schema=StructType([StructField('Year', IntegerType(), nullable=True), StructField('PCE', DoubleType(), nullable=True)]) 30 | ) 31 | assert (actual_df.collect() == expected_df.collect()) 32 | 33 | def test_linear_regression(): 34 | source_data = [ 35 | (2017, 106.051), 36 | (2018, 108.318), 37 | (2019, 109.922), 38 | (2020, 111.225) 39 | ] 40 | source_pd = pd.DataFrame(source_data, columns=['YEAR', 'PCE']) 41 | actual_model = process.train_linear_regression_model(source_pd) 42 | assert (actual_model.predict([[2021]])[0] == pytest.approx(113.1605, 0.01)) -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Snowflake-Labs/snowpark-devops/51e194afb3dfabba9fcf47862e37a89c48ffcd46/utils/__init__.py -------------------------------------------------------------------------------- /utils/get_session.py: -------------------------------------------------------------------------------- 1 | from utils.snowflake_connection import SnowflakeConnection 2 | from snowflake.snowpark import Session 3 | import os 4 | from typing import Optional 5 | 6 | 7 | def session() -> Session: 8 | 9 | # if running in snowflake 10 | if SnowflakeConnection().connection: 11 | session = SnowflakeConnection().connection 12 | # if running locally with a config file 13 | elif os.path.exists('../config.py') or os.path.exists('config.py'): 14 | from config import snowpark_config 15 | SnowflakeConnection().connection = Session.builder.configs(snowpark_config).create() 16 | else: 17 | connection_parameters = { 18 | "account": os.environ["SNOWSQL_ACCOUNT"], 19 | "user": os.environ["SNOWSQL_USER"], 20 | "password": os.environ["SNOWSQL_PWD"], 21 | "role": os.environ["SNOWSQL_ROLE"], 22 | "warehouse": os.environ["SNOWSQL_WAREHOUSE"], 23 | "database": os.environ["SNOWSQL_DATABASE"], 24 | "schema": os.environ["SNOWSQL_SCHEMA"] 25 | } 26 | SnowflakeConnection().connection = Session.builder.configs(connection_parameters).create() 27 | if SnowflakeConnection().connection: 28 | return SnowflakeConnection().connection # type: ignore 29 | else: 30 | raise Exception("Unable to create a session") 31 | -------------------------------------------------------------------------------- /utils/snowflake_connection.py: -------------------------------------------------------------------------------- 1 | # Class to store a singleton connection option 2 | # Used to pass the connection from a stored procedure to a script 3 | from snowflake.snowpark import Session 4 | from typing import Optional 5 | 6 | class SnowflakeConnection(object): 7 | 8 | _connection = None 9 | 10 | @property 11 | def connection(self) -> Optional[Session]: 12 | return type(self)._connection 13 | 14 | @connection.setter 15 | def connection(self, val): 16 | type(self)._connection = val 17 | --------------------------------------------------------------------------------