├── .cruft.json ├── .env ├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ ├── auto-merge.yml │ ├── ci.yml │ ├── release-please.yml │ └── release.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .python-version ├── .release-please-manifest.json ├── .typos.toml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── Makefile-common.mk ├── README.md ├── fakesnow ├── __init__.py ├── __main__.py ├── arrow.py ├── checks.py ├── cli.py ├── conn.py ├── converter.py ├── copy_into.py ├── cursor.py ├── expr.py ├── fakes.py ├── fixtures.py ├── info_schema.py ├── instance.py ├── logger.py ├── macros.py ├── pandas_tools.py ├── py.typed ├── rowtype.py ├── server.py ├── transforms │ ├── __init__.py │ ├── merge.py │ ├── show.py │ ├── stage.py │ └── transforms.py └── variables.py ├── notebooks ├── README.md ├── duckdb.ipynb ├── fakesnow.ipynb ├── snowflake.ipynb ├── sqlglot.ipynb └── timezones.md ├── package.json ├── pyproject.toml ├── release-please-config.json ├── tests ├── __init__.py ├── conftest.py ├── fixtures │ └── moto.py ├── hello.py ├── matchers.py ├── patch_other.py ├── test_arrow.py ├── test_checks.py ├── test_cli.py ├── test_connect.py ├── test_converter.py ├── test_copy_into.py ├── test_cursor.py ├── test_describe.py ├── test_expr.py ├── test_fakes.py ├── test_flatten.py ├── test_info_schema.py ├── test_matchers.py ├── test_merge.py ├── test_patch.py ├── test_semis.py ├── test_server.py ├── test_show.py ├── test_sqlalchemy.py ├── test_stage.py ├── test_transforms.py ├── test_users.py ├── test_write_pandas.py └── utils.py ├── toast.yml └── tools └── decode.py /.cruft.json: -------------------------------------------------------------------------------- 1 | { 2 | "template": "git@github.com:tekumara/python-typed-template.git", 3 | "commit": "0cecf703ec6c45f0b7173fe8d8804e3c29e6921f", 4 | "checkout": null, 5 | "context": { 6 | "cookiecutter": { 7 | "repo_name": "fakesnow", 8 | "package_name": "fakesnow", 9 | "project_name": "fakesnow", 10 | "description": "Fake Snowflake Connector for Python. Run Snowflake DB locally.", 11 | "_copy_without_render": [ 12 | ".github" 13 | ], 14 | "_template": "git@github.com:tekumara/python-typed-template.git", 15 | "_commit": "0cecf703ec6c45f0b7173fe8d8804e3c29e6921f" 16 | } 17 | }, 18 | "directory": null 19 | } 20 | -------------------------------------------------------------------------------- /.env: -------------------------------------------------------------------------------- 1 | FAKESNOW_DEBUG=1 # show transformed sql, to see original sql set the value to snowflake 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [tekumara] 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "pip" 4 | directory: "/" 5 | schedule: 6 | interval: "monthly" 7 | groups: 8 | pip: 9 | applies-to: version-updates 10 | dependency-type: development 11 | # use increase otherwise widen is chosen 12 | versioning-strategy: increase 13 | - package-ecosystem: "npm" 14 | directory: "/" 15 | schedule: 16 | interval: "monthly" 17 | -------------------------------------------------------------------------------- /.github/workflows/auto-merge.yml: -------------------------------------------------------------------------------- 1 | name: Dependabot Auto-merge 2 | on: 3 | pull_request: 4 | types: [opened] 5 | 6 | permissions: 7 | contents: write 8 | pull-requests: write 9 | 10 | jobs: 11 | dependabot: 12 | runs-on: ubuntu-latest 13 | if: github.event.pull_request.user.login == 'dependabot[bot]' 14 | steps: 15 | - name: Enable auto-merge for Dependabot PRs 16 | # don't include verbose dependabot PR description as body when merging 17 | run: gh pr merge --auto --squash "$PR_URL" --body "" 18 | env: 19 | PR_URL: ${{github.event.pull_request.html_url}} 20 | GH_TOKEN: ${{secrets.GITHUB_TOKEN}} 21 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | - name: Set up Python 13 | id: setup-python 14 | uses: actions/setup-python@v5 15 | - name: Install uv 16 | uses: astral-sh/setup-uv@v3 17 | - name: Cache virtualenv 18 | id: cache-venv 19 | uses: actions/cache@v4 20 | with: 21 | path: .venv 22 | key: ${{ runner.os }}-py${{ steps.setup-python.outputs.python-version }}-venv-${{ hashFiles('pyproject.toml') }} 23 | - name: Cache pre-commit 24 | id: cache-pre-commit 25 | uses: actions/cache@v4 26 | with: 27 | path: ~/.cache/pre-commit 28 | key: ${{ runner.os }}-py${{ steps.setup-python.outputs.python-version }}-pre-commit-${{ hashFiles('.pre-commit-config.yaml') }} 29 | - name: make install 30 | if: steps.cache-venv.outputs.cache-hit != 'true' 31 | run: make install 32 | - name: make hooks 33 | run: make hooks 34 | -------------------------------------------------------------------------------- /.github/workflows/release-please.yml: -------------------------------------------------------------------------------- 1 | name: release-please 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | workflow_dispatch: 8 | 9 | permissions: 10 | contents: write 11 | pull-requests: write 12 | 13 | jobs: 14 | release-please: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Generate app token for release-please 18 | uses: actions/create-github-app-token@v1 19 | id: app-token 20 | with: 21 | # https://github.com/apps/potatobot-prime 22 | app-id: ${{ secrets.APP_ID }} 23 | private-key: ${{ secrets.APP_PRIVATE_KEY }} 24 | - uses: googleapis/release-please-action@v4 25 | with: 26 | # use app token so that PRs and releases created by release-please trigger 27 | # additional workflows. They'll also be authored by the app. 28 | # see https://github.com/googleapis/release-please-action#github-credentials 29 | token: ${{ steps.app-token.outputs.token }} 30 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release 2 | 3 | on: 4 | release: 5 | types: [published] 6 | workflow_dispatch: 7 | 8 | jobs: 9 | publish: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Wait for checks to succeed 13 | uses: poseidon/wait-for-status-checks@v0.6.0 14 | with: 15 | token: ${{ secrets.GITHUB_TOKEN }} 16 | interval: 5 17 | - uses: actions/checkout@v4 18 | - name: Set up Python 19 | id: setup-python 20 | uses: actions/setup-python@v5 21 | - name: Install uv 22 | uses: astral-sh/setup-uv@v3 23 | - name: Cache virtualenv 24 | id: cache-venv 25 | uses: actions/cache@v4 26 | with: 27 | path: .venv 28 | # same as used in the ci workflow for reuse across workflows 29 | key: ${{ runner.os }}-py${{ steps.setup-python.outputs.python-version }}-venv-${{ hashFiles('pyproject.toml') }} 30 | - if: steps.cache-venv.outputs.cache-hit != 'true' 31 | run: make install 32 | - run: make dist 33 | - name: Publish to pypi 34 | env: 35 | TWINE_USERNAME: __token__ 36 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 37 | run: make publish 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .eggs/ 2 | .idea/ 3 | .vscode/ 4 | *.code-workspace 5 | *.iml 6 | .pytest_cache/ 7 | __pycache__/ 8 | .mypy_cache/ 9 | *.egg-info 10 | build/ 11 | dist/ 12 | .DS_Store 13 | typings/ 14 | .tox/ 15 | pip-wheel-metadata/ 16 | .venv/ 17 | duckdb 18 | notebooks/.ipynb_checkpoints 19 | tests/vcr 20 | # ignore uv.lock so we are always testing with the latest versions 21 | uv.lock 22 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # unless otherwise specified, hooks run on push only 2 | default_stages: [pre-push] 3 | repos: 4 | - repo: https://github.com/crate-ci/typos 5 | rev: v1.31.1 6 | hooks: 7 | - id: typos 8 | # formatters and linters are available in the virtualenv so they can be run from the makefile & vscode 9 | - repo: local 10 | hooks: 11 | - id: ruff 12 | name: ruff 13 | entry: uv run ruff check --force-exclude 14 | language: system 15 | types: [python] 16 | require_serial: true 17 | - id: ruff-format 18 | name: ruff-format 19 | entry: uv run ruff format 20 | language: system 21 | types: [python] 22 | require_serial: true 23 | - id: pyright 24 | name: pyright 25 | entry: uv run pyright 26 | # run on all files to catch type errors that affect unchanged files 27 | pass_filenames: false 28 | language: system 29 | types: [python] 30 | - id: test 31 | name: test 32 | entry: uv run pytest 33 | # run on all files 34 | pass_filenames: false 35 | language: system 36 | types: [python] 37 | -------------------------------------------------------------------------------- /.python-version: -------------------------------------------------------------------------------- 1 | 3.9 2 | -------------------------------------------------------------------------------- /.release-please-manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | ".": "0.9.39" 3 | } 4 | -------------------------------------------------------------------------------- /.typos.toml: -------------------------------------------------------------------------------- 1 | [files] 2 | # ignore CHANGELOG because it contains commit SHAs 3 | extend-exclude = ["CHANGELOG.md", "notebooks/*"] 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 🌳 2 | 3 | ## Prerequisites 4 | 5 | - make 6 | - python >= 3.9 7 | - uv >= 0.5.0 8 | 9 | ## Getting started 10 | 11 | `make install` creates the dev environment with: 12 | 13 | - a virtualenv in _.venv/_ 14 | - git hooks for formatting & linting on git push (these also run in CI) 15 | 16 | `. .venv/bin/activate` activates the virtualenv. 17 | 18 | The make targets will update the virtualenv when _pyproject.toml_ changes. 19 | 20 | ## Usage 21 | 22 | Run `make` to see the options for running tests, linting, formatting etc. 23 | 24 | ## Raising a PR 25 | 26 | PR titles use [conventional commit](https://www.conventionalcommits.org/en/v1.0.0/) prefixes where: 27 | 28 | - `feat` adding an unimplemented feature 29 | - `fix` fixing an already implemented feature 30 | 31 | Changes to behaviour covered by a test is considered a breaking change. Breaking changes are indicated with an exclamation mark in the title. 32 | 33 | New features and bug fixes require a minimal test case that mimics the behaviour of Snowflake and passes if run against a real Snowflake instance, or documents clearly where it deviates. 34 | -------------------------------------------------------------------------------- /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 2023 Oliver Mannion 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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | include *.mk 2 | 3 | # add additional targets here 4 | -------------------------------------------------------------------------------- /Makefile-common.mk: -------------------------------------------------------------------------------- 1 | MAKEFLAGS += --warn-undefined-variables 2 | SHELL = /bin/bash -o pipefail 3 | .DEFAULT_GOAL := help 4 | .PHONY: help .uv .sync clean install check format pyright test dist hooks install-hooks 5 | 6 | ## display help message 7 | help: 8 | @awk '/^##.*$$/,/^[~\/\.0-9a-zA-Z_-]+:/' $(MAKEFILE_LIST) | awk '!(NR%2){print $$0p}{p=$$0}' | awk 'BEGIN {FS = ":.*?##"}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' | sort 9 | 10 | ## check that uv is installed 11 | .uv: 12 | @uv --version || { echo 'Please install uv: https://docs.astral.sh/uv/getting-started/installation/' && exit 13 ;} 13 | 14 | .sync: 15 | uv sync --extra server $(if $(value CI),,--group notebook) 16 | 17 | # delete the venv 18 | clean: 19 | rm -rf .venv 20 | 21 | ## create venv and install this package and hooks 22 | install: .uv .sync $(if $(value CI),,install-hooks) 23 | 24 | ## format, lint and type check 25 | check: export SKIP=test 26 | check: hooks 27 | 28 | ## format and lint 29 | format: export SKIP=pyright,test 30 | format: hooks 31 | 32 | ## pyright type check 33 | pyright: 34 | PYRIGHT_PYTHON_IGNORE_WARNINGS=1 uv run pyright 35 | 36 | ## run tests 37 | test: 38 | uv run pytest 39 | 40 | ## build python distribution 41 | dist: 42 | # start with a clean slate (see setuptools/#2347) 43 | rm -rf build dist *.egg-info 44 | uv run -m build --wheel 45 | 46 | ## publish to pypi 47 | publish: 48 | uv run twine upload dist/* 49 | 50 | ## run pre-commit git hooks on all files 51 | hooks: 52 | uv run pre-commit run --color=always --all-files --hook-stage push 53 | 54 | install-hooks: .git/hooks/pre-push 55 | 56 | .git/hooks/pre-push: 57 | uv run pre-commit install --install-hooks -t pre-push 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fakesnow ❄️ 2 | 3 | [![ci](https://github.com/tekumara/fakesnow/actions/workflows/ci.yml/badge.svg)](https://github.com/tekumara/fakesnow/actions/workflows/ci.yml) 4 | [![release](https://github.com/tekumara/fakesnow/actions/workflows/release.yml/badge.svg)](https://github.com/tekumara/fakesnow/actions/workflows/release.yml) 5 | [![PyPI](https://img.shields.io/pypi/v/fakesnow?color=violet)](https://pypi.org/project/fakesnow/) 6 | [![PyPI - Downloads](https://img.shields.io/pypi/dm/fakesnow?color=violet)](https://pypi.org/project/fakesnow/) 7 | 8 | Run, mock and test fake Snowflake databases locally. 9 | 10 | ## Install 11 | 12 | ``` 13 | pip install fakesnow 14 | ``` 15 | 16 | Or to install with the server: 17 | 18 | ``` 19 | pip install fakesnow[server] 20 | ``` 21 | 22 | ## Usage 23 | 24 | fakesnow offers two main approaches for faking Snowflake: [in-process patching](#in-process-patching) of the Snowflake Connector for Python or a [standalone HTTP server](#run-fakesnow-as-a-server). 25 | 26 | Patching only applies to the current Python process. If a subprocess is spawned it won't be patched. For subprocesses, or for non-Python clients, use the server instead. 27 | 28 | ### In-process patching 29 | 30 | To run script.py with patching: 31 | 32 | ```shell 33 | fakesnow script.py 34 | ``` 35 | 36 | Or a module, eg: pytest 37 | 38 | ```shell 39 | fakesnow -m pytest 40 | ``` 41 | 42 | `fakesnow` executes `fakesnow.patch` before running the script or module. 43 | 44 | #### Use fakesnow.patch in your code 45 | 46 | Alternatively, use fakesnow.patch in your code: 47 | 48 | ```python 49 | import fakesnow 50 | import snowflake.connector 51 | 52 | with fakesnow.patch(): 53 | conn = snowflake.connector.connect() 54 | 55 | print(conn.cursor().execute("SELECT 'Hello fake world!'").fetchone()) 56 | ``` 57 | 58 | #### What gets patched 59 | 60 | The following standard imports are automatically patched: 61 | 62 | - `import snowflake.connector.connect` 63 | - `import snowflake.connector.pandas_tools.write_pandas` 64 | 65 | #### Handling "from ... import" Statements 66 | 67 | To patch modules that use the `from ... import` syntax, you need to manually specify them, eg: if _mymodule.py_ contains: 68 | 69 | ```python 70 | from snowflake.connector.pandas_tools import write_pandas 71 | ``` 72 | 73 | Then patch it using: 74 | 75 | ```python 76 | with fakesnow.patch("mymodule.write_pandas"): 77 | ... 78 | ``` 79 | 80 | #### Database Persistence 81 | 82 | By default, databases are in-memory and will be lost when the process ends. To persist databases between processes, specify a databases path: 83 | 84 | ```python 85 | with fakesnow.patch(db_path="databases/"): 86 | ... 87 | ``` 88 | 89 | ### Run fakesnow as a server 90 | 91 | For scenarios where patching won't work (like subprocesses or non-Python clients), you can run fakesnow as an HTTP server: 92 | 93 | ```python 94 | import fakesnow 95 | import snowflake.connector 96 | 97 | # Start the fakesnow server in a context manager 98 | # This yields connection kwargs (host, port, etc.) 99 | with fakesnow.server() as conn_kwargs: 100 | # Connect to the fakesnow server using the yielded kwargs 101 | with snowflake.connector.connect(**conn_kwargs) as conn: 102 | print(conn.cursor().execute("SELECT 'Hello fake server!'").fetchone()) 103 | 104 | # The server is automatically stopped when exiting the context manager 105 | ``` 106 | 107 | This starts an HTTP server in its own thread listening for requests on localhost on an available random port. 108 | The server accepts any username/password combination. 109 | 110 | #### Server Configuration Options 111 | 112 | By default, the server uses a single in-memory database for its lifetime. To configure database persistence or isolation: 113 | 114 | ```python 115 | # Databases will be saved to the "databases/" directory 116 | with fakesnow.server(session_parameters={"FAKESNOW_DB_PATH": "databases/"}): 117 | ... 118 | 119 | # Each connection gets its own isolated in-memory database 120 | with fakesnow.server(session_parameters={"FAKESNOW_DB_PATH": ":isolated:"}): 121 | ... 122 | ``` 123 | 124 | To specify a port for the server: 125 | 126 | ```python 127 | with fakesnow.server(port=12345) as conn_kwargs: 128 | ... 129 | ``` 130 | 131 | ### pytest fixtures 132 | 133 | fakesnow provides [fixtures](fakesnow/fixtures.py) for easier test integration. Add them in _conftest.py_: 134 | 135 | ```python 136 | pytest_plugins = "fakesnow.fixtures" 137 | ``` 138 | 139 | To autouse the fixture you can wrap it like this in _conftest.py_: 140 | 141 | ```python 142 | from typing import Iterator 143 | 144 | import pytest 145 | 146 | pytest_plugins = "fakesnow.fixtures" 147 | 148 | @pytest.fixture(scope="session", autouse=True) 149 | def setup(_fakesnow_session: None) -> Iterator[None]: 150 | # the standard imports are now patched 151 | # Add any additional setup here 152 | yield 153 | # Add any teardown here 154 | ``` 155 | 156 | For code that uses `from ... import` statements: 157 | 158 | ```python 159 | from typing import Iterator 160 | 161 | import fakesnow 162 | import pytest 163 | 164 | pytest_plugins = "fakesnow.fixtures" 165 | 166 | @pytest.fixture(scope="session", autouse=True) 167 | def _fakesnow_session() -> Iterator[None]: 168 | with fakesnow.patch("mymodule.write_pandas"): 169 | yield 170 | ``` 171 | 172 | #### server fixture 173 | 174 | To start a fakesnow server instance, enable the plugin in _conftest.py_: 175 | 176 | ```python 177 | pytest_plugins = "fakesnow.fixtures" 178 | ``` 179 | 180 | And then use the `fakesnow_server` session fixture like this: 181 | 182 | ```python 183 | import snowflake.connector 184 | 185 | def test_with_server(fakesnow_server: dict): 186 | # fakesnow_server contains connection kwargs (host, port, etc.) 187 | with snowflake.connector.connect(**fakesnow_server) as conn: 188 | conn.cursor().execute("SELECT 1") 189 | assert conn.cursor().fetchone() == (1,) 190 | ``` 191 | 192 | ## Implementation coverage 193 | 194 | Fully supported: 195 | 196 | - Standard SQL operations and cursors 197 | - Information schema queries 198 | - Multiple databases 199 | - [Parameter binding](https://docs.snowflake.com/en/user-guide/python-connector-example#binding-data) in queries 200 | - Table comments 201 | - Pandas integration including [write_pandas(..)](https://docs.snowflake.com/en/user-guide/python-connector-api#write_pandas) (not available via the server yet) 202 | - Result batch retrieval via [get_result_batches()](https://docs.snowflake.com/en/user-guide/python-connector-api#get_result_batches) 203 | - HTTP server for non-Python connectors 204 | 205 | Partially supported: 206 | 207 | - Date functions 208 | - Regular expression functions 209 | - Semi-structured data operations 210 | - Tags 211 | - User management 212 | - `COPY INTO` from S3 sources, see [COPY INTO](#copy-into) 213 | 214 | Not yet implemented: 215 | 216 | - [Access control](https://docs.snowflake.com/en/user-guide/security-access-control-overview) 217 | - [Stored procedures](https://docs.snowflake.com/en/sql-reference/stored-procedures) 218 | 219 | For more detail see the [test suite](tests/). 220 | 221 | ## Caveats 222 | 223 | - Row ordering is non-deterministic and may differ from Snowflake unless you fully specify the ORDER BY clause. 224 | - fakesnow supports a more liberal SQL dialect than actual Snowflake. This means some queries that work with fakesnow might not work with a real Snowflake instance. 225 | 226 | ## COPY INTO 227 | 228 | `COPY INTO` can be used from S3 sources. By default the standard AWS credential chain will be used. If you are getting an HTTP 403 or need to provide alternative S3 credentials you can use the duckdb [CREATE SECRET](https://duckdb.org/docs/stable/extensions/httpfs/s3api) statement. For an example of creating a secret to use a moto S3 endpoint see `s3_client` in [conftest.py](tests/conftest.py#L80) 229 | 230 | ## Contributing 231 | 232 | See [CONTRIBUTING.md](CONTRIBUTING.md) for instructions on getting started with development and contributing to this project. 233 | -------------------------------------------------------------------------------- /fakesnow/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import contextlib 4 | import importlib 5 | import os 6 | import sys 7 | import unittest.mock as mock 8 | from collections.abc import Iterator, Sequence 9 | from contextlib import contextmanager 10 | 11 | import snowflake.connector 12 | import snowflake.connector.pandas_tools 13 | 14 | import fakesnow.fakes as fakes 15 | from fakesnow.instance import FakeSnow 16 | 17 | 18 | @contextmanager 19 | def patch( 20 | extra_targets: str | Sequence[str] = [], 21 | create_database_on_connect: bool = True, 22 | create_schema_on_connect: bool = True, 23 | db_path: str | os.PathLike | None = None, 24 | nop_regexes: list[str] | None = None, 25 | ) -> Iterator[None]: 26 | """Patch snowflake targets with fakes. 27 | 28 | The standard targets are: 29 | - snowflake.connector.connect 30 | - snowflake.connector.pandas_tools.write_pandas 31 | 32 | Args: 33 | extra_targets (str | Sequence[str], optional): Extra targets to patch. Defaults to []. 34 | 35 | Allows extra targets beyond the standard snowflake.connector targets to be patched. Needed because we cannot 36 | patch definitions, only usages, see https://docs.python.org/3/library/unittest.mock.html#where-to-patch 37 | 38 | create_database_on_connect (bool, optional): Create database if provided in connection. Defaults to True. 39 | create_schema_on_connect (bool, optional): Create schema if provided in connection. Defaults to True. 40 | db_path (str | os.PathLike | None, optional): Use existing database files from this path 41 | or create them here if they don't already exist. If None databases are in-memory. Defaults to None. 42 | nop_regexes (list[str] | None, optional): SQL statements matching these regexes (case-insensitive) will return 43 | the success response without being run. Useful to skip over SQL commands that aren't implemented yet. 44 | Defaults to None. 45 | 46 | Yields: 47 | Iterator[None]: None. 48 | """ 49 | 50 | # don't allow re-patching because the keys in the fake_fns dict will point to the fakes, and so we 51 | # won't be able to patch extra targets 52 | assert not isinstance(snowflake.connector.connect, mock.MagicMock), "Snowflake connector is already patched" 53 | 54 | fs = FakeSnow( 55 | create_database_on_connect=create_database_on_connect, 56 | create_schema_on_connect=create_schema_on_connect, 57 | db_path=db_path, 58 | nop_regexes=nop_regexes, 59 | ) 60 | 61 | fake_fns = { 62 | snowflake.connector.connect: fs.connect, 63 | snowflake.connector.pandas_tools.write_pandas: fakes.write_pandas, 64 | } 65 | 66 | std_targets = ["snowflake.connector.connect", "snowflake.connector.pandas_tools.write_pandas"] 67 | 68 | stack = contextlib.ExitStack() 69 | 70 | for im in std_targets + list([extra_targets] if isinstance(extra_targets, str) else extra_targets): 71 | module_name = ".".join(im.split(".")[:-1]) 72 | fn_name = im.split(".")[-1] 73 | # get module or try to import it if not loaded yet 74 | module = sys.modules.get(module_name) or importlib.import_module(module_name) 75 | fn = module.__dict__.get(fn_name) 76 | assert fn, f"No module var {im}" 77 | 78 | # if we imported the module above, it'll already be mocked because 79 | # it'll reference the standard targets which are mocked first 80 | if isinstance(fn, mock.MagicMock): 81 | continue 82 | 83 | fake = fake_fns.get(fn) 84 | assert fake, f"Module var {im} is {fn} and not one of {fake_fns.keys()}" 85 | 86 | p = mock.patch(im, side_effect=fake) 87 | stack.enter_context(p) 88 | 89 | try: 90 | yield None 91 | finally: 92 | stack.close() 93 | fs.duck_conn.close() 94 | 95 | 96 | @contextmanager 97 | def server(port: int | None = None, session_parameters: dict[str, str | int | bool] | None = None) -> Iterator[dict]: 98 | """Start a fake snowflake server in a separate thread and yield connection kwargs. 99 | 100 | Args: 101 | port (int | None, optional): Port to run the server on. If None, an available port is chosen. Defaults to None. 102 | 103 | Yields: 104 | Iterator[dict]: Connection parameters for the fake snowflake server. 105 | """ 106 | import socket 107 | import threading 108 | from time import sleep 109 | 110 | import uvicorn 111 | 112 | import fakesnow.server 113 | 114 | # find an unused TCP port between 1024-65535 115 | if not port: 116 | with contextlib.closing(socket.socket(type=socket.SOCK_STREAM)) as sock: 117 | sock.bind(("127.0.0.1", 0)) 118 | port = sock.getsockname()[1] 119 | 120 | assert port 121 | server = uvicorn.Server(uvicorn.Config(fakesnow.server.app, port=port, log_level="info")) 122 | thread = threading.Thread(target=server.run, name="fakesnow server", daemon=True) 123 | thread.start() 124 | 125 | while not server.started: 126 | sleep(0.1) 127 | 128 | try: 129 | yield dict( 130 | user="fake", 131 | password="snow", 132 | account="fakesnow", 133 | host="localhost", 134 | port=port, 135 | protocol="http", 136 | # disable telemetry 137 | session_parameters={"CLIENT_OUT_OF_BAND_TELEMETRY_ENABLED": False} | (session_parameters or {}), 138 | # disable retries on error 139 | network_timeout=1, 140 | ) 141 | finally: 142 | server.should_exit = True 143 | # wait for server thread to end 144 | thread.join() 145 | -------------------------------------------------------------------------------- /fakesnow/__main__.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | import fakesnow.cli 3 | 4 | fakesnow.cli.main() 5 | -------------------------------------------------------------------------------- /fakesnow/arrow.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import cast 4 | 5 | import pyarrow as pa 6 | import pyarrow.compute as pc 7 | 8 | from fakesnow.rowtype import ColumnInfo 9 | 10 | 11 | def to_sf_schema(schema: pa.Schema, rowtype: list[ColumnInfo]) -> pa.Schema: 12 | # expected by the snowflake connector 13 | # uses rowtype to populate metadata, rather than the arrow schema type, for consistency with 14 | # rowtype returned in the response 15 | 16 | assert len(schema) == len(rowtype), f"schema and rowtype must be same length but f{len(schema)=} f{len(rowtype)=}" 17 | 18 | # see https://github.com/snowflakedb/snowflake-connector-python/blob/e9393a6/src/snowflake/connector/nanoarrow_cpp/ArrowIterator/CArrowTableIterator.cpp#L32 19 | # and https://github.com/snowflakedb/snowflake-connector-python/blob/e9393a6/src/snowflake/connector/nanoarrow_cpp/ArrowIterator/SnowflakeType.cpp#L10 20 | 21 | def sf_field(field: pa.Field, c: ColumnInfo) -> pa.Field: 22 | if isinstance(field.type, pa.TimestampType): 23 | # snowflake uses a struct to represent timestamps, see timestamp_to_sf_struct 24 | fields = [pa.field("epoch", pa.int64(), nullable=False), pa.field("fraction", pa.int32(), nullable=False)] 25 | if field.type.tz: 26 | fields.append(pa.field("timezone", nullable=False, type=pa.int32())) 27 | field = field.with_type(pa.struct(fields)) 28 | elif isinstance(field.type, pa.Time64Type): 29 | field = field.with_type(pa.int64()) 30 | elif pa.types.is_uint64(field.type): 31 | # snowflake-python-connector expects signed ints 32 | # see https://github.com/snowflakedb/snowflake-connector-python/blob/5d7064c7f3f756792c1f6252bf5c9d807e4307e8/src/snowflake/connector/nanoarrow_cpp/ArrowIterator/CArrowChunkIterator.cpp#L187 33 | field = field.with_type(pa.int64()) 34 | 35 | return field.with_metadata( 36 | { 37 | "logicalType": c["type"].upper(), 38 | # required for FIXED type see 39 | # https://github.com/snowflakedb/snowflake-connector-python/blob/416ff57/src/snowflake/connector/nanoarrow_cpp/ArrowIterator/CArrowChunkIterator.cpp#L147 40 | "precision": str(c["precision"] or 38), 41 | "scale": str(c["scale"] or 0), 42 | "charLength": str(c["length"] or 0), 43 | } 44 | ) 45 | 46 | fms = [sf_field(schema.field(i), c) for i, c in enumerate(rowtype)] 47 | return pa.schema(fms) 48 | 49 | 50 | def to_ipc(table: pa.Table) -> pa.Buffer: 51 | batches = table.to_batches() 52 | if len(batches) != 1: 53 | raise NotImplementedError(f"{len(batches)} batches") 54 | batch = batches[0] 55 | 56 | sink = pa.BufferOutputStream() 57 | 58 | with pa.ipc.new_stream(sink, table.schema) as writer: 59 | writer.write_batch(batch) 60 | 61 | return sink.getvalue() 62 | 63 | 64 | def to_sf(table: pa.Table, rowtype: list[ColumnInfo]) -> pa.Table: 65 | def to_sf_col(col: pa.ChunkedArray) -> pa.Array | pa.ChunkedArray: 66 | if pa.types.is_timestamp(col.type): 67 | return timestamp_to_sf_struct(col) 68 | elif pa.types.is_time(col.type): 69 | # as nanoseconds 70 | return pc.multiply(col.cast(pa.int64()), 1000) # type: ignore https://github.com/zen-xu/pyarrow-stubs/issues/44 71 | return col 72 | 73 | return pa.Table.from_arrays([to_sf_col(c) for c in table.columns], schema=to_sf_schema(table.schema, rowtype)) 74 | 75 | 76 | def timestamp_to_sf_struct(ts: pa.Array | pa.ChunkedArray) -> pa.Array: 77 | if isinstance(ts, pa.ChunkedArray): 78 | # combine because pa.StructArray.from_arrays doesn't support ChunkedArray 79 | ts = cast(pa.Array, ts.combine_chunks()) # see https://github.com/zen-xu/pyarrow-stubs/issues/46 80 | 81 | if not isinstance(ts.type, pa.TimestampType): 82 | raise ValueError(f"Expected TimestampArray, got {type(ts)}") 83 | 84 | # Round to seconds, ie: strip subseconds 85 | tsa_without_us = pc.floor_temporal(ts, unit="second") # type: ignore https://github.com/zen-xu/pyarrow-stubs/issues/45 86 | epoch = pc.divide(tsa_without_us.cast(pa.int64()), 1_000_000) 87 | 88 | # Calculate fractional part as nanoseconds 89 | fraction = pc.multiply(pc.subsecond(ts), 1_000_000_000).cast(pa.int32()) # type: ignore 90 | 91 | if ts.type.tz: 92 | assert ts.type.tz == "UTC", f"Timezone {ts.type.tz} not yet supported" 93 | timezone = pa.array([1440] * len(ts), type=pa.int32()) 94 | 95 | return pa.StructArray.from_arrays( 96 | arrays=[epoch, fraction, timezone], 97 | fields=[ 98 | pa.field("epoch", nullable=False, type=pa.int64()), 99 | pa.field("fraction", nullable=False, type=pa.int32()), 100 | pa.field("timezone", nullable=False, type=pa.int32()), 101 | ], 102 | ) 103 | else: 104 | return pa.StructArray.from_arrays( 105 | arrays=[epoch, fraction], 106 | fields=[ 107 | pa.field("epoch", nullable=False, type=pa.int64()), 108 | pa.field("fraction", nullable=False, type=pa.int32()), 109 | ], 110 | ) 111 | -------------------------------------------------------------------------------- /fakesnow/checks.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from sqlglot import exp 4 | 5 | 6 | def is_unqualified_table_expression(expression: exp.Expression) -> tuple[bool, bool]: 7 | """Checks if the table expression is unqualified, eg: no database or schema. 8 | 9 | NB: sqlglot treats the identifier in "CREATE SCHEMA schema1" as a table expression. 10 | 11 | Example: 12 | >>> import sqlglot 13 | >>> is_unqualified_table_expression("SELECT * FROM customers") 14 | (True, True) 15 | >>> is_unqualified_table_expression("CREATE SCHEMA schema1") 16 | (True, False) 17 | >>> is_unqualified_table_expression("USE DATABASE db1") 18 | (False, False) 19 | 20 | See tests for more examples. 21 | Args: 22 | expression (exp.Expression): the expression that will be transformed. 23 | 24 | Returns: 25 | exp.Expression: The transformed expression. 26 | """ 27 | 28 | if not (node := expression.find(exp.Table)): 29 | return False, False 30 | 31 | assert node.parent, f"No parent for table expression {node.sql()}" 32 | 33 | if (parent_kind := node.parent.args.get("kind")) and isinstance(parent_kind, str): 34 | if parent_kind.upper() == "DATABASE": 35 | # "CREATE/DROP DATABASE" 36 | no_database = False 37 | no_schema = False 38 | elif parent_kind.upper() == "SCHEMA": 39 | # "CREATE/DROP SCHEMA" 40 | no_database = not node.args.get("catalog") 41 | no_schema = False 42 | elif parent_kind.upper() in {"TABLE", "VIEW", "STAGE"}: 43 | # "CREATE/DROP TABLE/VIEW/STAGE" 44 | no_database = not node.args.get("catalog") 45 | no_schema = not node.args.get("db") 46 | else: 47 | raise AssertionError(f"Unexpected parent kind: {parent_kind}") 48 | 49 | elif ( 50 | node.parent.key == "use" 51 | and (parent_kind := node.parent.args.get("kind")) 52 | and isinstance(parent_kind, exp.Var) 53 | and parent_kind.name 54 | ): 55 | if parent_kind.name.upper() == "DATABASE": 56 | # "USE DATABASE" 57 | no_database = False 58 | no_schema = False 59 | elif parent_kind.name.upper() == "SCHEMA": 60 | # "USE SCHEMA" 61 | no_database = not node.args.get("db") 62 | no_schema = False 63 | else: 64 | raise AssertionError(f"Unexpected parent kind: {parent_kind.name}") 65 | 66 | elif node.parent.key == "show": 67 | # don't require a database or schema for SHOW 68 | # TODO: make this more nuanced 69 | no_database = False 70 | no_schema = False 71 | else: 72 | no_database = not node.args.get("catalog") 73 | no_schema = not node.args.get("db") 74 | 75 | return no_database, no_schema 76 | 77 | 78 | def equal(left: exp.Identifier, right: exp.Identifier) -> bool: 79 | # as per https://docs.snowflake.com/en/sql-reference/identifiers-syntax#label-identifier-casing 80 | lid = left.this if left.quoted else left.this.upper() 81 | rid = right.this if right.quoted else right.this.upper() 82 | 83 | return lid == rid 84 | -------------------------------------------------------------------------------- /fakesnow/cli.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import runpy 3 | import sys 4 | from collections.abc import Sequence 5 | 6 | import fakesnow 7 | 8 | 9 | def arg_parser() -> argparse.ArgumentParser: 10 | parser = argparse.ArgumentParser( 11 | description="""eg: fakesnow script.py OR fakesnow -m pytest""", 12 | formatter_class=argparse.ArgumentDefaultsHelpFormatter, 13 | ) 14 | parser.add_argument( 15 | "-d", 16 | "--db_path", 17 | help="databases path. Use existing database files from this path or create them here if they don't already " 18 | "exist. If None databases are in-memory.", 19 | ) 20 | parser.add_argument("-m", "--module", help="target module") 21 | parser.add_argument("path", type=str, nargs="?", help="target path") 22 | parser.add_argument("targs", nargs="*", help="target args") 23 | return parser 24 | 25 | 26 | def split(args: Sequence[str]) -> tuple[Sequence[str], Sequence[str]]: 27 | # split the arguments into two lists either: 28 | # 1) after the first -m flag, or 29 | # 2) after the first positional arg 30 | in_flag = False 31 | i = 0 32 | for i in range(len(args)): 33 | a = args[i] 34 | if a in ["-m", "--module"]: 35 | i = min(i + 1, len(args) - 1) 36 | break 37 | elif a.startswith("-"): 38 | in_flag = True 39 | elif not in_flag: 40 | break 41 | else: 42 | in_flag = False 43 | 44 | return args[: i + 1], args[i + 1 :] 45 | 46 | 47 | def main(args: Sequence[str] = sys.argv[1:]) -> int: 48 | parser = arg_parser() 49 | # split args so the fakesnow cli doesn't consume from the target's args (eg: -m and -d) 50 | fsargs, targs = split(args) 51 | pargs = parser.parse_args(fsargs) 52 | 53 | with fakesnow.patch(db_path=pargs.db_path): 54 | if module := pargs.module: 55 | # NB: pargs.path and pargs.args are consumed by targs 56 | sys.argv = [module, *targs] 57 | 58 | # add current directory to path to mimic python -m 59 | sys.path.insert(0, "") 60 | runpy.run_module(module, run_name="__main__", alter_sys=True) 61 | elif path := pargs.path: 62 | # NB: pargs.args is consumed by targs 63 | sys.argv = [path, *targs] 64 | 65 | runpy.run_path(path, run_name="__main__") 66 | else: 67 | parser.print_usage() 68 | return 42 69 | 70 | return 0 71 | -------------------------------------------------------------------------------- /fakesnow/conn.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | from collections.abc import Iterable 5 | from pathlib import Path 6 | from types import TracebackType 7 | from typing import Any 8 | 9 | import snowflake.connector 10 | import sqlglot 11 | from duckdb import DuckDBPyConnection 12 | from snowflake.connector.cursor import DictCursor, SnowflakeCursor 13 | from sqlglot import exp 14 | from typing_extensions import Self 15 | 16 | import fakesnow.info_schema as info_schema 17 | import fakesnow.macros as macros 18 | from fakesnow.cursor import FakeSnowflakeCursor 19 | from fakesnow.variables import Variables 20 | 21 | 22 | class FakeSnowflakeConnection: 23 | def __init__( 24 | self, 25 | duck_conn: DuckDBPyConnection, 26 | database: str | None = None, 27 | schema: str | None = None, 28 | create_database: bool = True, 29 | create_schema: bool = True, 30 | db_path: str | os.PathLike | None = None, 31 | nop_regexes: list[str] | None = None, 32 | *args: Any, 33 | **kwargs: Any, 34 | ): 35 | self._duck_conn = duck_conn 36 | self._is_closed = False 37 | # upper case database and schema like snowflake unquoted identifiers 38 | # so they appear as upper-cased in information_schema 39 | # catalog and schema names are not actually case-sensitive in duckdb even though 40 | # they are as cased in information_schema.schemata, so when selecting from 41 | # information_schema.schemata below we use upper-case to match any existing duckdb 42 | # catalog or schemas like "information_schema" 43 | self.database = database and database.upper() 44 | self._schema = schema and ( 45 | "_FS_INFORMATION_SCHEMA" if schema.upper() == "INFORMATION_SCHEMA" else schema.upper() 46 | ) 47 | 48 | self.database_set = False 49 | self.schema_set = False 50 | self.db_path = Path(db_path) if db_path else None 51 | self.nop_regexes = nop_regexes 52 | self._paramstyle = kwargs.get("paramstyle", snowflake.connector.paramstyle) 53 | self.variables = Variables() 54 | 55 | # create database if needed 56 | if ( 57 | create_database 58 | and self.database 59 | and not duck_conn.execute( 60 | f"""select * from information_schema.schemata 61 | where upper(catalog_name) = '{self.database}'""" 62 | ).fetchone() 63 | ): 64 | if self.db_path: 65 | # raise a helpful error message when directory doesn't exist so users don't think 66 | # they have to create the database themselves 67 | if not os.path.isdir(self.db_path): 68 | raise NotADirectoryError(f"No such directory: '{self.db_path}'. Please ensure db_path exists.") 69 | db_file = f"{self.db_path / self.database}.db" 70 | else: 71 | db_file = ":memory:" 72 | 73 | # creates db file if it doesn't exist 74 | duck_conn.execute(f"ATTACH DATABASE '{db_file}' AS {self.database}") 75 | duck_conn.execute(info_schema.per_db_creation_sql(self.database)) 76 | duck_conn.execute(macros.creation_sql(self.database)) 77 | 78 | # create schema if needed 79 | if ( 80 | create_schema 81 | and self.database 82 | and self._schema 83 | and not duck_conn.execute( 84 | f"""select * from information_schema.schemata 85 | where upper(catalog_name) = '{self.database}' and upper(schema_name) = '{self._schema}'""" 86 | ).fetchone() 87 | ): 88 | duck_conn.execute(f"CREATE SCHEMA {self.database}.{self._schema}") 89 | 90 | # set database and schema if both exist 91 | if ( 92 | self.database 93 | and self._schema 94 | and duck_conn.execute( 95 | f"""select * from information_schema.schemata 96 | where upper(catalog_name) = '{self.database}' and upper(schema_name) = '{self._schema}'""" 97 | ).fetchone() 98 | ): 99 | duck_conn.execute(f"SET schema='{self.database}.{self._schema}'") 100 | self.database_set = True 101 | self.schema_set = True 102 | # set database if only that exists 103 | elif ( 104 | self.database 105 | and duck_conn.execute( 106 | f"""select * from information_schema.schemata 107 | where upper(catalog_name) = '{self.database}'""" 108 | ).fetchone() 109 | ): 110 | duck_conn.execute(f"SET schema='{self.database}.main'") 111 | self.database_set = True 112 | 113 | def __enter__(self) -> Self: 114 | return self 115 | 116 | def __exit__( 117 | self, 118 | exc_type: type[BaseException] | None, 119 | exc_value: BaseException | None, 120 | traceback: TracebackType | None, 121 | ) -> None: 122 | pass 123 | 124 | def autocommit(self, _mode: bool) -> None: 125 | # autcommit is always on in duckdb 126 | pass 127 | 128 | def close(self, retry: bool = True) -> None: 129 | self._duck_conn.close() 130 | self._is_closed = True 131 | 132 | def commit(self) -> None: 133 | self.cursor().execute("COMMIT") 134 | 135 | def cursor(self, cursor_class: type[SnowflakeCursor] = SnowflakeCursor) -> FakeSnowflakeCursor: 136 | # TODO: use duck_conn cursor for thread-safety 137 | return FakeSnowflakeCursor(conn=self, duck_conn=self._duck_conn, use_dict_result=cursor_class == DictCursor) 138 | 139 | def execute_string( 140 | self, 141 | sql_text: str, 142 | remove_comments: bool = False, 143 | return_cursors: bool = True, 144 | cursor_class: type[SnowflakeCursor] = SnowflakeCursor, 145 | **kwargs: dict[str, Any], 146 | ) -> Iterable[FakeSnowflakeCursor]: 147 | cursors = [ 148 | self.cursor(cursor_class).execute(e.sql(dialect="snowflake")) 149 | for e in sqlglot.parse(sql_text, read="snowflake") 150 | if e and not isinstance(e, exp.Semicolon) # ignore comments 151 | ] 152 | return cursors if return_cursors else [] 153 | 154 | def is_closed(self) -> bool: 155 | return self._is_closed 156 | 157 | def rollback(self) -> None: 158 | self.cursor().execute("ROLLBACK") 159 | 160 | @property 161 | def schema(self) -> str | None: 162 | return "INFORMATION_SCHEMA" if self._schema == "_FS_INFORMATION_SCHEMA" else self._schema 163 | -------------------------------------------------------------------------------- /fakesnow/converter.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import binascii 4 | import datetime 5 | from datetime import date, time, timezone 6 | 7 | # convert server bindings from strings into python types 8 | 9 | 10 | def from_binding(binding: dict[str, str]) -> int | bytes | bool | date | time | datetime.datetime | str: 11 | type_ = binding["type"] 12 | value = binding["value"] 13 | if type_ == "FIXED": 14 | return int(value) 15 | elif type_ == "BINARY": 16 | return from_binary(value) 17 | # TODO: not strictly needed 18 | elif type_ == "BOOLEAN": 19 | return value.lower() == "true" 20 | elif type_ == "DATE": 21 | return from_date(value) 22 | elif type_ == "TIME": 23 | return from_time(value) 24 | elif type_ == "TIMESTAMP_NTZ": 25 | return from_datetime(value) 26 | else: 27 | # For other types, return str 28 | return value 29 | 30 | 31 | def from_binary(s: str) -> bytes: 32 | return binascii.unhexlify(s) 33 | 34 | 35 | def from_boolean(s: str) -> bool: 36 | return s.lower() == "true" 37 | 38 | 39 | def from_date(s: str) -> date: 40 | milliseconds = int(s) 41 | seconds = milliseconds / 1000 42 | return datetime.datetime.fromtimestamp(seconds, timezone.utc).date() 43 | 44 | 45 | def from_time(s: str) -> time: 46 | nanoseconds = int(s) 47 | microseconds = nanoseconds / 1000 48 | return ( 49 | datetime.datetime.fromtimestamp(microseconds / 1_000_000, timezone.utc) 50 | .replace(microsecond=int(microseconds % 1_000_000)) 51 | .time() 52 | ) 53 | 54 | 55 | def from_datetime(s: str) -> datetime.datetime: 56 | nanoseconds = int(s) 57 | microseconds = nanoseconds / 1000 58 | return datetime.datetime.fromtimestamp(microseconds / 1_000_000, timezone.utc).replace( 59 | microsecond=int(microseconds % 1_000_000) 60 | ) 61 | -------------------------------------------------------------------------------- /fakesnow/expr.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from sqlglot import exp 4 | 5 | 6 | def key_command(expression: exp.Expression) -> str: 7 | """Identifies the key SQL command in an expression. 8 | 9 | Useful for conditional logic that acts on specific commands. 10 | 11 | Args: 12 | expression (exp.Expression): Expression to check. 13 | 14 | Returns: 15 | str: Command, eg: "CREATE SCHEMA", "SELECT", "SET" etc. 16 | """ 17 | 18 | kind = expression.args.get("kind") 19 | 20 | if isinstance(kind, str): 21 | # eg: "DROP/CREATE SCHEMA" 22 | key = f"{expression.key.upper()} {kind.upper()}" 23 | elif isinstance(kind, exp.Var): 24 | # eg: "USE DATABASE/SCHEMA" 25 | key = f"{expression.key.upper()} {kind.name.upper()}" 26 | elif isinstance(expression, exp.Command) and isinstance(expression.this, str): 27 | # eg: "SET" 28 | key = expression.this.upper() 29 | else: 30 | key = expression.key.upper() 31 | 32 | return key 33 | -------------------------------------------------------------------------------- /fakesnow/fakes.py: -------------------------------------------------------------------------------- 1 | from .conn import FakeSnowflakeConnection as FakeSnowflakeConnection 2 | from .cursor import FakeSnowflakeCursor as FakeSnowflakeCursor 3 | from .pandas_tools import write_pandas as write_pandas 4 | -------------------------------------------------------------------------------- /fakesnow/fixtures.py: -------------------------------------------------------------------------------- 1 | from collections.abc import Iterator 2 | from typing import Any 3 | 4 | import pytest 5 | 6 | import fakesnow 7 | 8 | 9 | @pytest.fixture 10 | def _fakesnow() -> Iterator[None]: 11 | with fakesnow.patch(): 12 | yield 13 | 14 | 15 | @pytest.fixture(scope="session") 16 | def fakesnow_server() -> Iterator[dict[str, Any]]: 17 | with fakesnow.server() as conn_kwargs: 18 | yield conn_kwargs 19 | 20 | 21 | @pytest.fixture 22 | def _fakesnow_no_auto_create() -> Iterator[None]: 23 | with fakesnow.patch(create_database_on_connect=False, create_schema_on_connect=False): 24 | yield 25 | 26 | 27 | @pytest.fixture(scope="session") 28 | def _fakesnow_session() -> Iterator[None]: 29 | with fakesnow.patch(): 30 | yield 31 | -------------------------------------------------------------------------------- /fakesnow/info_schema.py: -------------------------------------------------------------------------------- 1 | """Info schema extension tables/views used for storing snowflake metadata not captured by duckdb.""" 2 | 3 | from __future__ import annotations 4 | 5 | from string import Template 6 | 7 | SQL_CREATE_GLOBAL_FS_INFORMATION_SCHEMA = """ 8 | create schema if not exists _fs_global._fs_information_schema 9 | """ 10 | 11 | 12 | # use ext prefix in columns to disambiguate when joining with information_schema.tables 13 | SQL_CREATE_GLOBAL_INFORMATION_SCHEMA_TABLES_EXT = """ 14 | create table if not exists _fs_global._fs_information_schema._fs_tables_ext ( 15 | ext_table_catalog varchar, 16 | ext_table_schema varchar, 17 | ext_table_name varchar, 18 | comment varchar, 19 | PRIMARY KEY(ext_table_catalog, ext_table_schema, ext_table_name) 20 | ) 21 | """ 22 | 23 | 24 | SQL_CREATE_GLOBAL_INFORMATION_SCHEMA_COLUMNS_EXT = """ 25 | create table if not exists _fs_global._fs_information_schema._fs_columns_ext ( 26 | ext_table_catalog varchar, 27 | ext_table_schema varchar, 28 | ext_table_name varchar, 29 | ext_column_name varchar, 30 | ext_character_maximum_length integer, 31 | ext_character_octet_length integer, 32 | PRIMARY KEY(ext_table_catalog, ext_table_schema, ext_table_name, ext_column_name) 33 | ) 34 | """ 35 | 36 | # replicates the output structure of https://docs.snowflake.com/en/sql-reference/sql/show-users 37 | SQL_CREATE_GLOBAL_INFORMATION_SCHEMA_USERS_TABLE = """ 38 | create table if not exists _fs_global._fs_information_schema._fs_users ( 39 | name varchar, 40 | created_on TIMESTAMPTZ, 41 | login_name varchar, 42 | display_name varchar, 43 | first_name varchar, 44 | last_name varchar, 45 | email varchar, 46 | mins_to_unlock varchar, 47 | days_to_expiry varchar, 48 | comment varchar, 49 | disabled varchar, 50 | must_change_password varchar, 51 | snowflake_lock varchar, 52 | default_warehouse varchar, 53 | default_namespace varchar, 54 | default_role varchar, 55 | default_secondary_roles varchar, 56 | ext_authn_duo varchar, 57 | ext_authn_uid varchar, 58 | mins_to_bypass_mfa varchar, 59 | owner varchar, 60 | last_success_login TIMESTAMPTZ, 61 | expires_at_time TIMESTAMPTZ, 62 | locked_until_time TIMESTAMPTZ, 63 | has_password varchar, 64 | has_rsa_public_key varchar, 65 | ) 66 | """ 67 | 68 | 69 | SQL_CREATE_FS_INFORMATION_SCHEMA = Template( 70 | """ 71 | create schema if not exists ${catalog}._fs_information_schema 72 | """ 73 | ) 74 | 75 | SQL_CREATE_INFORMATION_SCHEMA_COLUMNS_VIEW = Template( 76 | """ 77 | create view if not exists ${catalog}._fs_information_schema._fs_columns AS 78 | select * from _fs_global._fs_information_schema._fs_columns where table_catalog = '${catalog}' 79 | """ 80 | ) 81 | 82 | # only include fields applicable to snowflake (as mentioned by describe table information_schema.columns) 83 | # snowflake integers are 38 digits, base 10, See https://docs.snowflake.com/en/sql-reference/data-types-numeric 84 | SQL_CREATE_GLOBAL_INFORMATION_SCHEMA_COLUMNS_VIEW = """ 85 | create view if not exists _fs_global._fs_information_schema._fs_columns AS 86 | select 87 | columns.table_catalog AS table_catalog, 88 | columns.table_schema AS table_schema, 89 | columns.table_name AS table_name, 90 | columns.column_name AS column_name, 91 | columns.ordinal_position AS ordinal_position, 92 | columns.column_default AS column_default, 93 | columns.is_nullable AS is_nullable, 94 | case when starts_with(columns.data_type, 'DECIMAL') or columns.data_type='BIGINT' then 'NUMBER' 95 | when columns.data_type='VARCHAR' then 'TEXT' 96 | when columns.data_type='DOUBLE' then 'FLOAT' 97 | when columns.data_type='BLOB' then 'BINARY' 98 | when columns.data_type='TIMESTAMP' then 'TIMESTAMP_NTZ' 99 | when columns.data_type='TIMESTAMP WITH TIME ZONE' then 'TIMESTAMP_TZ' 100 | when columns.data_type='JSON' then 'VARIANT' 101 | else columns.data_type end as data_type, 102 | ext_character_maximum_length as character_maximum_length, ext_character_octet_length as character_octet_length, 103 | case when columns.data_type='BIGINT' then 38 104 | when columns.data_type='DOUBLE' then NULL 105 | else columns.numeric_precision end as numeric_precision, 106 | case when columns.data_type='BIGINT' then 10 107 | when columns.data_type='DOUBLE' then NULL 108 | else columns.numeric_precision_radix end as numeric_precision_radix, 109 | case when columns.data_type='DOUBLE' then NULL else columns.numeric_scale end as numeric_scale, 110 | collation_name, is_identity, identity_generation, identity_cycle, 111 | ddb_columns.comment as comment, 112 | null::VARCHAR as identity_start, 113 | null::VARCHAR as identity_increment, 114 | from system.information_schema.columns columns 115 | left join _fs_global._fs_information_schema._fs_columns_ext ext 116 | on ext_table_catalog = columns.table_catalog 117 | AND ext_table_schema = columns.table_schema 118 | AND ext_table_name = columns.table_name 119 | AND ext_column_name = columns.column_name 120 | LEFT JOIN duckdb_columns ddb_columns 121 | ON ddb_columns.database_name = columns.table_catalog 122 | AND ddb_columns.schema_name = columns.table_schema 123 | AND ddb_columns.table_name = columns.table_name 124 | AND ddb_columns.column_name = columns.column_name 125 | where schema_name != '_fs_information_schema' 126 | """ 127 | 128 | 129 | # replicates https://docs.snowflake.com/sql-reference/info-schema/databases 130 | SQL_CREATE_INFORMATION_SCHEMA_DATABASES_VIEW = Template( 131 | """ 132 | create view if not exists ${catalog}._fs_information_schema.databases AS 133 | select 134 | catalog_name as database_name, 135 | 'SYSADMIN' as database_owner, 136 | 'NO' as is_transient, 137 | null::VARCHAR as comment, 138 | to_timestamp(0)::timestamptz as created, 139 | to_timestamp(0)::timestamptz as last_altered, 140 | 1 as retention_time, 141 | 'STANDARD' as type 142 | from system.information_schema.schemata 143 | where catalog_name not in ('memory', 'system', 'temp', '_fs_global') 144 | and schema_name = 'main' 145 | """ 146 | ) 147 | 148 | # replicates https://docs.snowflake.com/sql-reference/info-schema/tables 149 | SQL_CREATE_INFORMATION_SCHEMA_TABLES_VIEW = Template( 150 | """ 151 | create view if not exists ${catalog}._fs_information_schema._fs_tables AS 152 | select * 153 | from system.information_schema.tables tables 154 | left join _fs_global._fs_information_schema._fs_tables_ext on 155 | tables.table_catalog = _fs_tables_ext.ext_table_catalog AND 156 | tables.table_schema = _fs_tables_ext.ext_table_schema AND 157 | tables.table_name = _fs_tables_ext.ext_table_name 158 | where table_catalog = '${catalog}' 159 | and table_schema != '_fs_information_schema' 160 | """ 161 | ) 162 | 163 | # replicates https://docs.snowflake.com/sql-reference/info-schema/views 164 | SQL_CREATE_INFORMATION_SCHEMA_VIEWS_VIEW = Template( 165 | """ 166 | create view if not exists ${catalog}._fs_information_schema._fs_views AS 167 | select 168 | database_name as table_catalog, 169 | schema_name as table_schema, 170 | view_name as table_name, 171 | 'SYSADMIN' as table_owner, 172 | sql as view_definition, 173 | 'NONE' as check_option, 174 | 'NO' as is_updatable, 175 | 'NO' as insertable_into, 176 | 'NO' as is_secure, 177 | to_timestamp(0)::timestamptz as created, 178 | to_timestamp(0)::timestamptz as last_altered, 179 | to_timestamp(0)::timestamptz as last_ddl, 180 | 'SYSADMIN' as last_ddl_by, 181 | null::VARCHAR as comment 182 | from duckdb_views 183 | where database_name = '${catalog}' 184 | and schema_name != '_fs_information_schema' 185 | """ 186 | ) 187 | 188 | SQL_CREATE_LOAD_HISTORY_TABLE = Template( 189 | """ 190 | create table if not exists ${catalog}._fs_information_schema._fs_load_history ( 191 | SCHEMA_NAME VARCHAR, 192 | FILE_NAME VARCHAR, 193 | TABLE_NAME VARCHAR, 194 | LAST_LOAD_TIME TIMESTAMPTZ, 195 | STATUS VARCHAR, 196 | ROW_COUNT INTEGER, 197 | ROW_PARSED INTEGER, 198 | FIRST_ERROR_MESSAGE VARCHAR, 199 | FIRST_ERROR_LINE_NUMBER INTEGER, 200 | FIRST_ERROR_CHARACTER_POSITION INTEGER, 201 | FIRST_ERROR_COL_NAME VARCHAR, 202 | ERROR_COUNT INTEGER, 203 | ERROR_LIMIT INTEGER 204 | ) 205 | """ 206 | ) 207 | 208 | 209 | SQL_CREATE_GLOBAL_INFORMATION_SCHEMA_STAGES_TABLE = """ 210 | CREATE TABLE IF NOT EXISTS _fs_global._fs_information_schema._fs_stages ( 211 | created_on TIMESTAMPTZ, 212 | name TEXT, 213 | database_name TEXT, 214 | schema_name TEXT, 215 | url TEXT, 216 | has_credentials TEXT, 217 | has_encryption_key TEXT, 218 | owner TEXT, 219 | comment TEXT, 220 | region TEXT, 221 | type TEXT, 222 | cloud TEXT, 223 | notification_channel TEXT, 224 | storage_integration TEXT, 225 | endpoint TEXT, 226 | owner_role_type TEXT, 227 | directory_enabled TEXT 228 | ); 229 | """ 230 | 231 | 232 | def per_db_creation_sql(catalog: str) -> str: 233 | return f""" 234 | {SQL_CREATE_FS_INFORMATION_SCHEMA.substitute(catalog=catalog)}; 235 | {SQL_CREATE_INFORMATION_SCHEMA_COLUMNS_VIEW.substitute(catalog=catalog)}; 236 | {SQL_CREATE_INFORMATION_SCHEMA_DATABASES_VIEW.substitute(catalog=catalog)}; 237 | {SQL_CREATE_INFORMATION_SCHEMA_TABLES_VIEW.substitute(catalog=catalog)}; 238 | {SQL_CREATE_INFORMATION_SCHEMA_VIEWS_VIEW.substitute(catalog=catalog)}; 239 | {SQL_CREATE_LOAD_HISTORY_TABLE.substitute(catalog=catalog)}; 240 | """ 241 | 242 | 243 | def fs_global_creation_sql() -> str: 244 | return f""" 245 | {SQL_CREATE_GLOBAL_FS_INFORMATION_SCHEMA}; 246 | {SQL_CREATE_GLOBAL_INFORMATION_SCHEMA_TABLES_EXT}; 247 | {SQL_CREATE_GLOBAL_INFORMATION_SCHEMA_COLUMNS_EXT}; 248 | {SQL_CREATE_GLOBAL_INFORMATION_SCHEMA_COLUMNS_VIEW}; 249 | {SQL_CREATE_GLOBAL_INFORMATION_SCHEMA_USERS_TABLE}; 250 | {SQL_CREATE_GLOBAL_INFORMATION_SCHEMA_STAGES_TABLE} 251 | """ 252 | 253 | 254 | def insert_table_comment_sql(catalog: str, schema: str, table: str, comment: str) -> str: 255 | return f""" 256 | INSERT INTO _fs_global._fs_information_schema._fs_tables_ext 257 | values ('{catalog}', '{schema}', '{table}', '{comment}') 258 | ON CONFLICT (ext_table_catalog, ext_table_schema, ext_table_name) 259 | DO UPDATE SET comment = excluded.comment 260 | """ 261 | 262 | 263 | def insert_text_lengths_sql(catalog: str, schema: str, table: str, text_lengths: list[tuple[str, int]]) -> str: 264 | values = ", ".join( 265 | f"('{catalog}', '{schema}', '{table}', '{col_name}', {size}, {min(size * 4, 16777216)})" 266 | for (col_name, size) in text_lengths 267 | ) 268 | 269 | return f""" 270 | INSERT INTO _fs_global._fs_information_schema._fs_columns_ext 271 | values {values} 272 | ON CONFLICT (ext_table_catalog, ext_table_schema, ext_table_name, ext_column_name) 273 | DO UPDATE SET ext_character_maximum_length = excluded.ext_character_maximum_length, 274 | ext_character_octet_length = excluded.ext_character_octet_length 275 | """ 276 | -------------------------------------------------------------------------------- /fakesnow/instance.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | from typing import Any 5 | 6 | import duckdb 7 | 8 | import fakesnow.fakes as fakes 9 | from fakesnow import info_schema 10 | from fakesnow.transforms import show 11 | 12 | GLOBAL_DATABASE_NAME = "_fs_global" 13 | 14 | 15 | class FakeSnow: 16 | def __init__( 17 | self, 18 | create_database_on_connect: bool = True, 19 | create_schema_on_connect: bool = True, 20 | db_path: str | os.PathLike | None = None, 21 | nop_regexes: list[str] | None = None, 22 | ): 23 | self.create_database_on_connect = create_database_on_connect 24 | self.create_schema_on_connect = create_schema_on_connect 25 | self.db_path = db_path 26 | self.nop_regexes = nop_regexes 27 | 28 | self.duck_conn = duckdb.connect(database=":memory:") 29 | 30 | # create a "global" database for storing objects which span databases. 31 | self.duck_conn.execute(f"ATTACH IF NOT EXISTS ':memory:' AS {GLOBAL_DATABASE_NAME}") 32 | # create the info schema extensions and show views 33 | self.duck_conn.execute(info_schema.fs_global_creation_sql()) 34 | self.duck_conn.execute(show.fs_global_creation_sql()) 35 | 36 | # use UTC instead of local time zone for consistent testing 37 | self.duck_conn.execute("SET GLOBAL TimeZone = 'UTC'") 38 | 39 | def connect( 40 | self, database: str | None = None, schema: str | None = None, **kwargs: Any 41 | ) -> fakes.FakeSnowflakeConnection: 42 | # every time we connect, create a new cursor (ie: connection) so we can isolate each connection's 43 | # schema setting see 44 | # https://github.com/duckdb/duckdb/blob/18254ec/tools/pythonpkg/src/pyconnection.cpp#L1440 45 | # and to make connections thread-safe see 46 | # https://duckdb.org/docs/api/python/overview.html#using-connections-in-parallel-python-programs 47 | return fakes.FakeSnowflakeConnection( 48 | self.duck_conn.cursor(), 49 | database, 50 | schema, 51 | create_database=self.create_database_on_connect, 52 | create_schema=self.create_schema_on_connect, 53 | db_path=self.db_path, 54 | nop_regexes=self.nop_regexes, 55 | **kwargs, 56 | ) 57 | -------------------------------------------------------------------------------- /fakesnow/logger.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import sys 5 | from collections.abc import Sequence 6 | from typing import Any 7 | 8 | 9 | def log_sql(sql: str, params: Sequence[Any] | dict[Any, Any] | None = None) -> None: 10 | if (fs_debug := os.environ.get("FAKESNOW_DEBUG")) and fs_debug != "snowflake": 11 | print(f"{sql};{params=}" if params else f"{sql};", file=sys.stderr) 12 | -------------------------------------------------------------------------------- /fakesnow/macros.py: -------------------------------------------------------------------------------- 1 | from string import Template 2 | 3 | EQUAL_NULL = Template( 4 | """ 5 | CREATE MACRO IF NOT EXISTS ${catalog}.equal_null(a, b) AS a IS NOT DISTINCT FROM b; 6 | """ 7 | ) 8 | 9 | # emulate the Snowflake FLATTEN function for ARRAYs 10 | # see https://docs.snowflake.com/en/sql-reference/functions/flatten.html 11 | FS_FLATTEN = Template( 12 | """ 13 | CREATE OR REPLACE MACRO ${catalog}._fs_flatten(input) AS TABLE 14 | SELECT 15 | NULL AS SEQ, -- TODO use a sequence and nextval 16 | CAST(NULL AS VARCHAR) AS KEY, 17 | '[' || GENERATE_SUBSCRIPTS( 18 | CAST(TO_JSON(input) AS JSON []), 19 | 1 20 | ) - 1 || ']' AS PATH, 21 | GENERATE_SUBSCRIPTS( 22 | CAST(TO_JSON(input) AS JSON []), 23 | 1 24 | ) - 1 AS INDEX, 25 | UNNEST( 26 | CAST(TO_JSON(input) AS JSON []) 27 | ) AS VALUE, 28 | TO_JSON(input) AS THIS; 29 | """ 30 | ) 31 | 32 | 33 | def creation_sql(catalog: str) -> str: 34 | return f""" 35 | {EQUAL_NULL.substitute(catalog=catalog)}; 36 | {FS_FLATTEN.substitute(catalog=catalog)}; 37 | """ 38 | -------------------------------------------------------------------------------- /fakesnow/pandas_tools.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import json 4 | from collections.abc import Sequence 5 | from typing import TYPE_CHECKING, Any, Literal, Optional 6 | 7 | from duckdb import DuckDBPyConnection 8 | 9 | from fakesnow.conn import FakeSnowflakeConnection 10 | 11 | if TYPE_CHECKING: 12 | # don't require pandas or numpy at import time 13 | import numpy as np 14 | import pandas as pd 15 | 16 | 17 | CopyResult = tuple[ 18 | str, 19 | str, 20 | int, 21 | int, 22 | int, 23 | int, 24 | Optional[str], 25 | Optional[int], 26 | Optional[int], 27 | Optional[str], 28 | ] 29 | 30 | WritePandasResult = tuple[ 31 | bool, 32 | int, 33 | int, 34 | Sequence[CopyResult], 35 | ] 36 | 37 | 38 | def sql_type(dtype: np.dtype) -> str: 39 | if str(dtype) == "int64": 40 | return "NUMBER" 41 | elif str(dtype) == "object": 42 | return "VARCHAR" 43 | else: 44 | raise NotImplementedError(f"sql_type {dtype=}") 45 | 46 | 47 | def write_pandas( 48 | conn: FakeSnowflakeConnection, 49 | df: pd.DataFrame, 50 | table_name: str, 51 | database: str | None = None, 52 | schema: str | None = None, 53 | chunk_size: int | None = None, 54 | compression: str = "gzip", 55 | on_error: str = "abort_statement", 56 | parallel: int = 4, 57 | quote_identifiers: bool = True, 58 | auto_create_table: bool = False, 59 | create_temp_table: bool = False, 60 | overwrite: bool = False, 61 | table_type: Literal["", "temp", "temporary", "transient"] = "", 62 | **kwargs: Any, 63 | ) -> WritePandasResult: 64 | name = table_name 65 | if schema: 66 | name = f"{schema}.{name}" 67 | if database: 68 | name = f"{database}.{name}" 69 | 70 | if auto_create_table: 71 | cols = [f"{c} {sql_type(t)}" for c, t in df.dtypes.to_dict().items()] 72 | 73 | conn.cursor().execute(f"CREATE TABLE IF NOT EXISTS {name} ({','.join(cols)})") 74 | 75 | count = _insert_df(conn._duck_conn, df, name) # noqa: SLF001 76 | 77 | # mocks https://docs.snowflake.com/en/sql-reference/sql/copy-into-table.html#output 78 | mock_copy_results = [("fakesnow/file0.txt", "LOADED", count, count, 1, 0, None, None, None, None)] 79 | 80 | # return success 81 | return (True, len(mock_copy_results), count, mock_copy_results) 82 | 83 | 84 | def _insert_df(duck_conn: DuckDBPyConnection, df: pd.DataFrame, table_name: str) -> int: 85 | # Objects in dataframes are written as parquet structs, and snowflake loads parquet structs as json strings. 86 | # Whereas duckdb analyses a dataframe see https://duckdb.org/docs/api/python/data_ingestion.html#pandas-dataframes--object-columns 87 | # and converts a object to the most specific type possible, eg: dict -> STRUCT, MAP or varchar, and list -> LIST 88 | # For dicts see https://github.com/duckdb/duckdb/pull/3985 and https://github.com/duckdb/duckdb/issues/9510 89 | # 90 | # When the rows have dicts with different keys there isn't a single STRUCT that can cover them, so the type is 91 | # varchar and value a string containing a struct representation. In order to support dicts with different keys 92 | # we first convert the dicts to json strings. A pity we can't do something inside duckdb and avoid the dataframe 93 | # copy and transform in python. 94 | 95 | df = df.copy() 96 | 97 | # Identify columns of type object 98 | object_cols = df.select_dtypes(include=["object"]).columns 99 | 100 | # Apply json.dumps to these columns 101 | for col in object_cols: 102 | # don't jsonify string 103 | df[col] = df[col].apply(lambda x: json.dumps(x) if isinstance(x, (dict, list)) else x) 104 | 105 | escaped_cols = ",".join(f'"{col}"' for col in df.columns.to_list()) 106 | duck_conn.execute(f"INSERT INTO {table_name}({escaped_cols}) SELECT * FROM df") 107 | 108 | return duck_conn.fetchall()[0][0] 109 | -------------------------------------------------------------------------------- /fakesnow/py.typed: -------------------------------------------------------------------------------- 1 | # when type checking dependents, tell type checkers to use this package's types 2 | -------------------------------------------------------------------------------- /fakesnow/rowtype.py: -------------------------------------------------------------------------------- 1 | import re 2 | from typing import Optional, TypedDict 3 | 4 | from snowflake.connector.cursor import ResultMetadata 5 | 6 | 7 | class ColumnInfo(TypedDict): 8 | name: str 9 | database: str 10 | schema: str 11 | table: str 12 | nullable: bool 13 | type: str 14 | byteLength: Optional[int] 15 | length: Optional[int] 16 | scale: Optional[int] 17 | precision: Optional[int] 18 | collation: Optional[str] 19 | 20 | 21 | duckdb_to_sf_type = { 22 | "BIGINT": "fixed", 23 | "BLOB": "binary", 24 | "BOOLEAN": "boolean", 25 | "DATE": "date", 26 | "DECIMAL": "fixed", 27 | "DOUBLE": "real", 28 | "HUGEINT": "fixed", 29 | "INTEGER": "fixed", 30 | "JSON": "variant", 31 | "TIME": "time", 32 | "TIMESTAMP WITH TIME ZONE": "timestamp_tz", 33 | "TIMESTAMP_NS": "timestamp_ntz", 34 | "TIMESTAMP": "timestamp_ntz", 35 | "UBIGINT": "fixed", 36 | "VARCHAR": "text", 37 | } 38 | 39 | 40 | def describe_as_rowtype(describe_results: list) -> list[ColumnInfo]: 41 | """Convert duckdb column type to snowflake rowtype returned by the API.""" 42 | 43 | def as_column_info(column_name: str, column_type: str) -> ColumnInfo: 44 | if not (sf_type := duckdb_to_sf_type.get("DECIMAL" if column_type.startswith("DECIMAL") else column_type)): 45 | raise NotImplementedError(f"for column type {column_type}") 46 | 47 | info: ColumnInfo = { 48 | "name": column_name, 49 | # TODO 50 | "database": "", 51 | "schema": "", 52 | "table": "", 53 | # TODO 54 | "nullable": True, 55 | "type": sf_type, 56 | "byteLength": None, 57 | "length": None, 58 | "scale": None, 59 | "precision": None, 60 | "collation": None, 61 | } 62 | 63 | if column_type.startswith("DECIMAL"): 64 | match = re.search(r"\((\d+),(\d+)\)", column_type) 65 | info["precision"] = int(match[1]) if match else 38 66 | info["scale"] = int(match[2]) if match else 0 67 | elif sf_type == "fixed": 68 | info["precision"] = 38 69 | info["scale"] = 0 70 | elif sf_type == "text": 71 | # TODO: fetch actual varchar size 72 | info["byteLength"] = 16777216 73 | info["length"] = 16777216 74 | elif sf_type.startswith("time"): 75 | info["precision"] = 0 76 | info["scale"] = 9 77 | elif sf_type == "binary": 78 | info["byteLength"] = 8388608 79 | info["length"] = 8388608 80 | 81 | return info 82 | 83 | column_infos = [ 84 | as_column_info(column_name, column_type) 85 | for (column_name, column_type, _null, _key, _default, _extra) in describe_results 86 | ] 87 | return column_infos 88 | 89 | 90 | def describe_as_result_metadata(describe_results: list) -> list[ResultMetadata]: 91 | return [ResultMetadata.from_column(c) for c in describe_as_rowtype(describe_results)] # pyright: ignore[reportArgumentType] 92 | -------------------------------------------------------------------------------- /fakesnow/server.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import gzip 4 | import json 5 | import logging 6 | import secrets 7 | from base64 import b64encode 8 | from dataclasses import dataclass 9 | from typing import Any 10 | from urllib.parse import urlparse 11 | from urllib.request import url2pathname 12 | 13 | import snowflake.connector.errors 14 | from sqlglot import exp, parse_one 15 | from starlette.applications import Starlette 16 | from starlette.concurrency import run_in_threadpool 17 | from starlette.requests import Request 18 | from starlette.responses import JSONResponse 19 | from starlette.routing import Route 20 | 21 | from fakesnow.arrow import to_ipc, to_sf 22 | from fakesnow.converter import from_binding 23 | from fakesnow.fakes import FakeSnowflakeConnection 24 | from fakesnow.instance import FakeSnow 25 | from fakesnow.rowtype import describe_as_rowtype 26 | 27 | logger = logging.getLogger("fakesnow.server") 28 | # use same format as uvicorn 29 | logger.handlers = logging.getLogger("uvicorn").handlers 30 | logger.setLevel(logging.INFO) 31 | 32 | shared_fs = FakeSnow() 33 | sessions: dict[str, FakeSnowflakeConnection] = {} 34 | 35 | 36 | @dataclass 37 | class ServerError(Exception): 38 | status_code: int 39 | code: str 40 | message: str 41 | 42 | 43 | async def login_request(request: Request) -> JSONResponse: 44 | database = request.query_params.get("databaseName") 45 | schema = request.query_params.get("schemaName") 46 | body = await request.body() 47 | if request.headers.get("Content-Encoding") == "gzip": 48 | body = gzip.decompress(body) 49 | body_json = json.loads(body) 50 | session_params: dict[str, Any] = body_json["data"]["SESSION_PARAMETERS"] 51 | if db_path := session_params.get("FAKESNOW_DB_PATH"): 52 | # isolated creates a new in-memory database, rather than using the shared in-memory database 53 | # so this connection won't share any tables with other connections 54 | fs = FakeSnow() if db_path == ":isolated:" else FakeSnow(db_path=db_path) 55 | else: 56 | # share the in-memory database across connections 57 | fs = shared_fs 58 | token = secrets.token_urlsafe(32) 59 | logger.info(f"Session login {database=} {schema=}") 60 | sessions[token] = fs.connect(database, schema) 61 | return JSONResponse( 62 | { 63 | "data": { 64 | "token": token, 65 | "parameters": [ 66 | {"name": "AUTOCOMMIT", "value": True}, 67 | {"name": "CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY", "value": 3600}, 68 | ], 69 | "sessionInfo": {}, 70 | }, 71 | "success": True, 72 | } 73 | ) 74 | 75 | 76 | async def query_request(request: Request) -> JSONResponse: 77 | try: 78 | conn = to_conn(to_token(request)) 79 | 80 | body = await request.body() 81 | if request.headers.get("Content-Encoding") == "gzip": 82 | body = gzip.decompress(body) 83 | 84 | body_json = json.loads(body) 85 | 86 | sql_text = body_json["sqlText"] 87 | 88 | if bindings := body_json.get("bindings"): 89 | # Convert parameters like {'1': {'type': 'FIXED', 'value': '10'}, ...} to tuple (10, ...) 90 | params = tuple(from_binding(bindings[str(pos)]) for pos in range(1, len(bindings) + 1)) 91 | logger.debug(f"Bindings: {params}") 92 | else: 93 | params = None 94 | 95 | expr = parse_one(sql_text, read="snowflake") 96 | if isinstance(expr, exp.Put): 97 | # see https://docs.snowflake.com/en/sql-reference/sql/put 98 | assert isinstance(expr.this, exp.Literal), "PUT command requires a file path as a literal" 99 | src_url = urlparse(expr.this.this) 100 | src_path = url2pathname(src_url.path) 101 | stage_name = expr.args["target"].this 102 | stage_info = { 103 | "locationType": "LOCAL_FS", 104 | "location": f"/tmp/fakesnow_bucket/{stage_name}/", 105 | "creds": {}, 106 | } 107 | return JSONResponse( 108 | { 109 | "data": { 110 | "stageInfo": stage_info, 111 | "src_locations": [src_path], 112 | # defaults as per https://docs.snowflake.com/en/sql-reference/sql/put 113 | "parallel": 4, 114 | "autoCompress": True, 115 | "sourceCompression": "auto_detect", 116 | "overwrite": False, 117 | "command": "UPLOAD", 118 | }, 119 | "success": True, 120 | } 121 | ) 122 | elif isinstance(expr, exp.List): 123 | pass 124 | 125 | try: 126 | # only a single sql statement is sent at a time by the python snowflake connector 127 | cur = await run_in_threadpool(conn.cursor().execute, sql_text, binding_params=params) 128 | rowtype = describe_as_rowtype(cur._describe_last_sql()) # noqa: SLF001 129 | 130 | except snowflake.connector.errors.ProgrammingError as e: 131 | logger.info(f"{sql_text=} ProgrammingError {e}") 132 | code = f"{e.errno:06d}" 133 | return JSONResponse( 134 | { 135 | "data": { 136 | "errorCode": code, 137 | "sqlState": e.sqlstate, 138 | }, 139 | "code": code, 140 | "message": e.msg, 141 | "success": False, 142 | } 143 | ) 144 | except Exception as e: 145 | # we have a bug or use of an unsupported feature 146 | msg = f"{sql_text=} Unhandled exception" 147 | logger.error(msg, exc_info=e) 148 | # my guess at mimicking a 500 error as per https://docs.snowflake.com/en/developer-guide/sql-api/reference 149 | # and https://github.com/snowflakedb/gosnowflake/blob/8ed4c75ffd707dd712ad843f40189843ace683c4/restful.go#L318 150 | raise ServerError(status_code=500, code="261000", message=msg) from None 151 | 152 | if cur._arrow_table: # noqa: SLF001 153 | batch_bytes = to_ipc(to_sf(cur._arrow_table, rowtype)) # noqa: SLF001 154 | rowset_b64 = b64encode(batch_bytes).decode("utf-8") 155 | else: 156 | rowset_b64 = "" 157 | 158 | return JSONResponse( 159 | { 160 | "data": { 161 | "parameters": [ 162 | {"name": "TIMEZONE", "value": "Etc/UTC"}, 163 | ], 164 | "rowtype": rowtype, 165 | "rowsetBase64": rowset_b64, 166 | "total": cur._rowcount, # noqa: SLF001 167 | "queryId": cur.sfqid, 168 | "queryResultFormat": "arrow", 169 | }, 170 | "success": True, 171 | } 172 | ) 173 | 174 | except ServerError as e: 175 | return JSONResponse( 176 | {"data": None, "code": e.code, "message": e.message, "success": False, "headers": None}, 177 | status_code=e.status_code, 178 | ) 179 | 180 | 181 | def to_token(request: Request) -> str: 182 | if not (auth := request.headers.get("Authorization")): 183 | raise ServerError(status_code=401, code="390101", message="Authorization header not found in the request data.") 184 | 185 | return auth[17:-1] 186 | 187 | 188 | def to_conn(token: str) -> FakeSnowflakeConnection: 189 | if not (conn := sessions.get(token)): 190 | raise ServerError(status_code=401, code="390104", message="User must login again to access the service.") 191 | 192 | return conn 193 | 194 | 195 | async def session(request: Request) -> JSONResponse: 196 | try: 197 | token = to_token(request) 198 | _ = to_conn(token) 199 | 200 | if bool(request.query_params.get("delete")): 201 | del sessions[token] 202 | 203 | return JSONResponse( 204 | {"data": None, "code": None, "message": None, "success": True}, 205 | ) 206 | 207 | except ServerError as e: 208 | return JSONResponse( 209 | {"data": None, "code": e.code, "message": e.message, "success": False, "headers": None}, 210 | status_code=e.status_code, 211 | ) 212 | 213 | 214 | routes = [ 215 | Route( 216 | "/session/v1/login-request", 217 | login_request, 218 | methods=["POST"], 219 | ), 220 | Route("/session", session, methods=["POST"]), 221 | Route( 222 | "/queries/v1/query-request", 223 | query_request, 224 | methods=["POST"], 225 | ), 226 | Route("/queries/v1/abort-request", lambda _: JSONResponse({"success": True}), methods=["POST"]), 227 | ] 228 | 229 | app = Starlette(debug=True, routes=routes) 230 | -------------------------------------------------------------------------------- /fakesnow/transforms/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from fakesnow.transforms.merge import merge as merge 4 | from fakesnow.transforms.show import ( 5 | show_columns as show_columns, 6 | show_databases as show_databases, 7 | show_functions as show_functions, 8 | show_keys as show_keys, 9 | show_procedures as show_procedures, 10 | show_schemas as show_schemas, 11 | show_stages as show_stages, 12 | show_tables_etc as show_tables_etc, 13 | show_users as show_users, 14 | show_warehouses as show_warehouses, 15 | ) 16 | from fakesnow.transforms.stage import create_stage as create_stage 17 | from fakesnow.transforms.transforms import ( 18 | SUCCESS_NOP as SUCCESS_NOP, 19 | alias_in_join as alias_in_join, 20 | alter_table_strip_cluster_by as alter_table_strip_cluster_by, 21 | array_agg as array_agg, 22 | array_agg_within_group as array_agg_within_group, 23 | array_size as array_size, 24 | create_clone as create_clone, 25 | create_database as create_database, 26 | create_user as create_user, 27 | dateadd_date_cast as dateadd_date_cast, 28 | dateadd_string_literal_timestamp_cast as dateadd_string_literal_timestamp_cast, 29 | datediff_string_literal_timestamp_cast as datediff_string_literal_timestamp_cast, 30 | describe_table as describe_table, 31 | drop_schema_cascade as drop_schema_cascade, 32 | extract_comment_on_columns as extract_comment_on_columns, 33 | extract_comment_on_table as extract_comment_on_table, 34 | extract_text_length as extract_text_length, 35 | flatten as flatten, 36 | flatten_value_cast_as_varchar as flatten_value_cast_as_varchar, 37 | float_to_double as float_to_double, 38 | identifier as identifier, 39 | indices_to_json_extract as indices_to_json_extract, 40 | information_schema_databases as information_schema_databases, 41 | information_schema_fs as information_schema_fs, 42 | integer_precision as integer_precision, 43 | json_extract_cased_as_varchar as json_extract_cased_as_varchar, 44 | json_extract_cast_as_varchar as json_extract_cast_as_varchar, 45 | json_extract_precedence as json_extract_precedence, 46 | object_construct as object_construct, 47 | random as random, 48 | regex_replace as regex_replace, 49 | regex_substr as regex_substr, 50 | sample as sample, 51 | semi_structured_types as semi_structured_types, 52 | set_schema as set_schema, 53 | sha256 as sha256, 54 | split as split, 55 | tag as tag, 56 | timestamp_ntz as timestamp_ntz, 57 | to_date as to_date, 58 | to_decimal as to_decimal, 59 | to_timestamp as to_timestamp, 60 | to_timestamp_ntz as to_timestamp_ntz, 61 | trim_cast_varchar as trim_cast_varchar, 62 | try_parse_json as try_parse_json, 63 | try_to_decimal as try_to_decimal, 64 | update_variables as update_variables, 65 | upper_case_unquoted_identifiers as upper_case_unquoted_identifiers, 66 | values_columns as values_columns, 67 | ) 68 | -------------------------------------------------------------------------------- /fakesnow/transforms/merge.py: -------------------------------------------------------------------------------- 1 | import sqlglot 2 | from sqlglot import exp 3 | 4 | from fakesnow import checks 5 | 6 | # Implements snowflake's MERGE INTO functionality in duckdb (https://docs.snowflake.com/en/sql-reference/sql/merge). 7 | 8 | 9 | def merge(merge_expr: exp.Expression) -> list[exp.Expression]: 10 | if not isinstance(merge_expr, exp.Merge): 11 | return [merge_expr] 12 | 13 | return [_create_merge_candidates(merge_expr), *_mutations(merge_expr), _counts(merge_expr)] 14 | 15 | 16 | def _create_merge_candidates(merge_expr: exp.Merge) -> exp.Expression: 17 | """ 18 | Given a merge statement, produce a temporary table that joins together the target and source tables. 19 | The merge_op column identifies which merge clause applies to the row. 20 | """ 21 | target_tbl = merge_expr.this 22 | 23 | source = merge_expr.args.get("using") 24 | assert isinstance(source, exp.Expression) 25 | source_id = (alias := source.args.get("alias")) and alias.this if isinstance(source, exp.Subquery) else source.this 26 | assert isinstance(source_id, exp.Identifier) 27 | 28 | join_expr = merge_expr.args.get("on") 29 | assert isinstance(join_expr, exp.Binary) 30 | 31 | case_when_clauses: list[str] = [] 32 | values: set[str] = set() 33 | 34 | # extract keys that reference the source table from the join expression 35 | # so they can be used by the mutation statements for joining 36 | # will include the source table identifier 37 | values.update( 38 | map( 39 | str, 40 | { 41 | c 42 | for c in join_expr.find_all(exp.Column) 43 | if (table := c.args.get("table")) 44 | and isinstance(table, exp.Identifier) 45 | and checks.equal(table, source_id) 46 | }, 47 | ) 48 | ) 49 | 50 | # Iterate through the WHEN clauses to build up the CASE WHEN clauses 51 | for w_idx, w in enumerate(merge_expr.args["whens"]): 52 | assert isinstance(w, exp.When), f"Expected When expression, got {w}" 53 | 54 | predicate = join_expr.copy() 55 | matched = w.args.get("matched") 56 | then = w.args.get("then") 57 | condition = w.args.get("condition") 58 | 59 | if matched: 60 | # matchedClause see https://docs.snowflake.com/en/sql-reference/sql/merge#matchedclause-for-updates-or-deletes 61 | if condition: 62 | # Combine the top level ON expression with the AND condition 63 | # from this specific WHEN into a subquery, we use to target rows. 64 | # Eg. MERGE INTO t1 USING t2 ON t1.t1Key = t2.t2Key 65 | # WHEN MATCHED AND t2.marked = 1 THEN DELETE 66 | predicate = exp.And(this=predicate, expression=condition) 67 | 68 | if isinstance(then, exp.Update): 69 | case_when_clauses.append(f"WHEN {predicate} THEN {w_idx}") 70 | values.update([str(c.expression) for c in then.expressions if isinstance(c.expression, exp.Column)]) 71 | elif isinstance(then, exp.Var) and then.args.get("this") == "DELETE": 72 | case_when_clauses.append(f"WHEN {predicate} THEN {w_idx}") 73 | else: 74 | raise AssertionError(f"Expected 'Update' or 'Delete', got {then}") 75 | else: 76 | # notMatchedClause see https://docs.snowflake.com/en/sql-reference/sql/merge#notmatchedclause-for-inserts 77 | assert isinstance(then, exp.Insert), f"Expected 'Insert', got {then}" 78 | insert_values = then.expression.expressions 79 | values.update([str(c) for c in insert_values if isinstance(c, exp.Column)]) 80 | predicate = f"AND {condition}" if condition else "" 81 | case_when_clauses.append(f"WHEN {target_tbl}.rowid is NULL {predicate} THEN {w_idx}") 82 | 83 | sql = f""" 84 | CREATE OR REPLACE TEMPORARY TABLE merge_candidates AS 85 | SELECT 86 | {", ".join(sorted(values))}, 87 | CASE 88 | {" ".join(case_when_clauses)} 89 | ELSE NULL 90 | END AS MERGE_OP 91 | FROM {target_tbl} 92 | FULL OUTER JOIN {source} ON {join_expr.sql()} 93 | WHERE MERGE_OP IS NOT NULL 94 | """ 95 | 96 | return sqlglot.parse_one(sql) 97 | 98 | 99 | def _mutations(merge_expr: exp.Merge) -> list[exp.Expression]: 100 | """ 101 | Given a merge statement, produce a list of delete, update and insert statements that use the 102 | merge_candidates and source table to update the target target. 103 | """ 104 | target_tbl = merge_expr.this 105 | source = merge_expr.args.get("using") 106 | source_tbl = source.alias if isinstance(source, exp.Subquery) else source 107 | join_expr = merge_expr.args.get("on") 108 | 109 | statements: list[exp.Expression] = [] 110 | 111 | # Iterate through the WHEN clauses to generate delete/update/insert statements 112 | for w_idx, w in enumerate(merge_expr.args["whens"]): 113 | assert isinstance(w, exp.When), f"Expected When expression, got {w}" 114 | 115 | matched = w.args.get("matched") 116 | then = w.args.get("then") 117 | 118 | if matched: 119 | if isinstance(then, exp.Var) and then.args.get("this") == "DELETE": 120 | delete_sql = f""" 121 | DELETE FROM {target_tbl} 122 | USING merge_candidates AS {source_tbl} 123 | WHERE {join_expr} 124 | AND {source_tbl}.merge_op = {w_idx} 125 | """ 126 | statements.append(sqlglot.parse_one(delete_sql)) 127 | elif isinstance(then, exp.Update): 128 | # when the update statement has a table alias, duckdb doesn't support the alias in the set 129 | # column name, so we use e.this.this to get just the column name without its table prefix 130 | set_clauses = ", ".join( 131 | [f"{e.this.this} = {e.expression.sql()}" for e in then.args.get("expressions", [])] 132 | ) 133 | update_sql = f""" 134 | UPDATE {target_tbl} 135 | SET {set_clauses} 136 | FROM merge_candidates AS {source_tbl} 137 | WHERE {join_expr} 138 | AND {source_tbl}.merge_op = {w_idx} 139 | """ 140 | statements.append(sqlglot.parse_one(update_sql)) 141 | else: 142 | raise AssertionError(f"Expected 'Update' or 'Delete', got {then}") 143 | else: 144 | assert isinstance(then, exp.Insert), f"Expected 'Insert', got {then}" 145 | cols = [str(c) for c in then.this.expressions] if then.this else [] 146 | columns = f"({', '.join(cols)})" if cols else "" 147 | values = ", ".join(map(str, then.expression.expressions)) 148 | insert_sql = f""" 149 | INSERT INTO {target_tbl} {columns} 150 | SELECT {values} 151 | FROM merge_candidates AS {source_tbl} 152 | WHERE {source_tbl}.merge_op = {w_idx} 153 | """ 154 | statements.append(sqlglot.parse_one(insert_sql)) 155 | 156 | return statements 157 | 158 | 159 | def _counts(merge_expr: exp.Merge) -> exp.Expression: 160 | """ 161 | Given a merge statement, derive the a SQL statement which produces the following columns using the merge_candidates 162 | table: 163 | 164 | - "number of rows inserted" 165 | - "number of rows updated" 166 | - "number of rows deleted" 167 | 168 | Only columns relevant to the merge operation are included, eg: if no rows are deleted, the "number of rows deleted" 169 | column is not included. 170 | """ 171 | 172 | # Initialize dictionaries to store operation types and their corresponding indices 173 | operations = {"inserted": [], "updated": [], "deleted": []} 174 | 175 | # Iterate through the WHEN clauses to categorize operations 176 | for w_idx, w in enumerate(merge_expr.args["whens"]): 177 | assert isinstance(w, exp.When), f"Expected When expression, got {w}" 178 | 179 | matched = w.args.get("matched") 180 | then = w.args.get("then") 181 | 182 | if matched: 183 | if isinstance(then, exp.Update): 184 | operations["updated"].append(w_idx) 185 | elif isinstance(then, exp.Var) and then.args.get("this") == "DELETE": 186 | operations["deleted"].append(w_idx) 187 | else: 188 | raise AssertionError(f"Expected 'Update' or 'Delete', got {then}") 189 | else: 190 | assert isinstance(then, exp.Insert), f"Expected 'Insert', got {then}" 191 | operations["inserted"].append(w_idx) 192 | 193 | count_statements = [ 194 | f"""COUNT_IF(merge_op in ({",".join(map(str, indices))})) as \"number of rows {op}\"""" 195 | for op, indices in operations.items() 196 | if indices 197 | ] 198 | sql = f""" 199 | SELECT {", ".join(count_statements)} 200 | FROM merge_candidates 201 | """ 202 | 203 | return sqlglot.parse_one(sql) 204 | -------------------------------------------------------------------------------- /fakesnow/transforms/stage.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import datetime 4 | 5 | import sqlglot 6 | from sqlglot import exp 7 | 8 | 9 | def create_stage( 10 | expression: exp.Expression, current_database: str | None = None, current_schema: str | None = None 11 | ) -> exp.Expression: 12 | """Transform CREATE STAGE to an INSERT statement for the fake stages table.""" 13 | if not ( 14 | isinstance(expression, exp.Create) 15 | and (kind := expression.args.get("kind")) 16 | and isinstance(kind, str) 17 | and kind.upper() == "STAGE" 18 | and (table := expression.find(exp.Table)) 19 | ): 20 | return expression 21 | 22 | catalog = table.catalog or current_database 23 | schema = table.db or current_schema 24 | ident = table.this 25 | if isinstance(ident, exp.Placeholder): 26 | stage_name = "?" 27 | elif isinstance(ident, exp.Identifier): 28 | stage_name = ident.this if ident.quoted else ident.this.upper() 29 | else: 30 | raise ValueError(f"Invalid identifier type {ident.__class__.__name__} for stage name") 31 | now = datetime.datetime.now(datetime.timezone.utc).isoformat() 32 | 33 | is_temp = False 34 | url = "" 35 | properties = expression.args.get("properties") or [] 36 | for prop in properties: 37 | if isinstance(prop, exp.TemporaryProperty): 38 | is_temp = True 39 | elif ( 40 | isinstance(prop, exp.Property) 41 | and isinstance(prop.this, exp.Var) 42 | and isinstance(prop.this.this, str) 43 | and prop.this.this.upper() == "URL" 44 | ): 45 | value = prop.args.get("value") 46 | if isinstance(value, exp.Literal): 47 | url = value.this 48 | 49 | # Determine cloud provider based on url 50 | cloud = "AWS" if url.startswith("s3://") else None 51 | 52 | stage_type = ("EXTERNAL" if url else "INTERNAL") + (" TEMPORARY" if is_temp else "") 53 | stage_name_value = stage_name if stage_name == "?" else repr(stage_name) 54 | 55 | insert_sql = f""" 56 | INSERT INTO _fs_global._fs_information_schema._fs_stages 57 | (created_on, name, database_name, schema_name, url, has_credentials, has_encryption_key, owner, 58 | comment, region, type, cloud, notification_channel, storage_integration, endpoint, owner_role_type, 59 | directory_enabled) 60 | VALUES ( 61 | '{now}', {stage_name_value}, '{catalog}', '{schema}', '{url}', 'N', 'N', 'SYSADMIN', 62 | '', NULL, '{stage_type}', {f"'{cloud}'" if cloud else "NULL"}, NULL, NULL, NULL, 'ROLE', 63 | 'N' 64 | ) 65 | """ 66 | transformed = sqlglot.parse_one(insert_sql, read="duckdb") 67 | transformed.args["stage_name"] = stage_name 68 | return transformed 69 | -------------------------------------------------------------------------------- /fakesnow/variables.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | import snowflake.connector.errors 4 | from sqlglot import exp 5 | 6 | 7 | # Implements snowflake variables: https://docs.snowflake.com/en/sql-reference/session-variables#using-variables-in-sql 8 | # [ ] Add support for setting multiple variables in a single statement 9 | class Variables: 10 | @classmethod 11 | def is_variable_modifier(cls, expr: exp.Expression) -> bool: 12 | return cls._is_set_expression(expr) or cls._is_unset_expression(expr) 13 | 14 | @classmethod 15 | def _is_set_expression(cls, expr: exp.Expression) -> bool: 16 | if isinstance(expr, exp.Set): 17 | is_set = not expr.args.get("unset") 18 | if is_set: # SET varname = value; 19 | set_expressions = expr.args.get("expressions") 20 | assert set_expressions, "SET without values in expression(s) is unexpected." 21 | # Avoids mistakenly setting variables for statements that use SET in a different context. 22 | # (eg. WHEN MATCHED THEN UPDATE SET x=7) 23 | return isinstance(set_expressions[0], exp.SetItem) 24 | return False 25 | 26 | @classmethod 27 | def _is_unset_expression(cls, expr: exp.Expression) -> bool: 28 | if isinstance(expr, exp.Alias): 29 | this_expr = expr.this.args.get("this") 30 | return isinstance(this_expr, exp.Expression) and this_expr.this == "UNSET" 31 | return False 32 | 33 | def __init__(self) -> None: 34 | self._variables = {} 35 | 36 | def update_variables(self, expr: exp.Expression) -> None: 37 | if isinstance(expr, exp.Set): 38 | is_set = not expr.args.get("unset") 39 | if is_set: # SET varname = value; 40 | set_expressions = expr.args.get("expressions") 41 | assert set_expressions, "SET without values in expression(s) is unexpected." 42 | eq = set_expressions[0].this 43 | name = eq.this.sql() 44 | value = eq.args.get("expression").sql() 45 | self._set(name, value) 46 | else: 47 | # Haven't been able to produce this in tests yet due to UNSET being parsed as an Alias expression. 48 | raise NotImplementedError("UNSET") 49 | elif self._is_unset_expression(expr): # Unfortunately UNSET varname; is parsed as an Alias expression :( 50 | alias = expr.args.get("alias") 51 | assert alias, "UNSET without value in alias attribute is unexpected." 52 | name = alias.this 53 | self._unset(name) 54 | 55 | def _set(self, name: str, value: str) -> None: 56 | self._variables[name] = value 57 | 58 | def _unset(self, name: str) -> None: 59 | self._variables.pop(name) 60 | 61 | def inline_variables(self, sql: str) -> str: 62 | for name, value in self._variables.items(): 63 | sql = re.sub(rf"\${name}", value, sql, flags=re.IGNORECASE) 64 | 65 | # Only treat $ (not $) as session variables, 66 | # ignore identifiers containing $ 67 | if remaining_variables := re.search(r"(?The 'toml' package isn't installed. To load settings from pyproject.toml or ~/.jupysql/config, install with: pip install toml" 12 | ], 13 | "text/plain": [ 14 | "The 'toml' package isn't installed. To load settings from pyproject.toml or ~/.jupysql/config, install with: pip install toml" 15 | ] 16 | }, 17 | "metadata": {}, 18 | "output_type": "display_data" 19 | } 20 | ], 21 | "source": [ 22 | "import duckdb\n", 23 | "\n", 24 | "duck_conn = duckdb.connect(database=\":memory:\")\n", 25 | "\n", 26 | "%load_ext sql\n", 27 | "%config SqlMagic.feedback = False\n", 28 | "%config SqlMagic.displaycon = False\n", 29 | "%config SqlMagic.autopandas = True\n", 30 | "%sql duckdb:///:memory:" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 5, 36 | "metadata": {}, 37 | "outputs": [ 38 | { 39 | "data": { 40 | "text/plain": [ 41 | "[('[\"A\",\"B\"]',)]" 42 | ] 43 | }, 44 | "execution_count": 5, 45 | "metadata": {}, 46 | "output_type": "execute_result" 47 | } 48 | ], 49 | "source": [ 50 | "duck_conn.execute(\"select json(['A', 'B'])\").fetchall()" 51 | ] 52 | } 53 | ], 54 | "metadata": { 55 | "kernelspec": { 56 | "display_name": ".venv", 57 | "language": "python", 58 | "name": "python3" 59 | }, 60 | "language_info": { 61 | "codemirror_mode": { 62 | "name": "ipython", 63 | "version": 3 64 | }, 65 | "file_extension": ".py", 66 | "mimetype": "text/x-python", 67 | "name": "python", 68 | "nbconvert_exporter": "python", 69 | "pygments_lexer": "ipython3", 70 | "version": "3.9.18" 71 | }, 72 | "orig_nbformat": 4, 73 | "vscode": { 74 | "interpreter": { 75 | "hash": "f59249d332647baa27896e48b602655774b2ab27cda0296fe135a6398572f9c3" 76 | } 77 | } 78 | }, 79 | "nbformat": 4, 80 | "nbformat_minor": 2 81 | } 82 | -------------------------------------------------------------------------------- /notebooks/fakesnow.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "('Hello fake world!',)\n" 13 | ] 14 | }, 15 | { 16 | "name": "stderr", 17 | "output_type": "stream", 18 | "text": [ 19 | "SELECT 'Hello fake world!';\n" 20 | ] 21 | } 22 | ], 23 | "source": [ 24 | "import snowflake.connector\n", 25 | "\n", 26 | "import fakesnow\n", 27 | "\n", 28 | "p = fakesnow.patch()\n", 29 | "p.__enter__()\n", 30 | "conn = snowflake.connector.connect(database='db1', schema='schema1')\n", 31 | "cur = conn.cursor()\n", 32 | "print(cur.execute(\"SELECT 'Hello fake world!'\").fetchone())\n" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 2, 38 | "metadata": {}, 39 | "outputs": [ 40 | { 41 | "data": { 42 | "text/html": [ 43 | "The 'toml' package isn't installed. To load settings from pyproject.toml or ~/.jupysql/config, install with: pip install toml" 44 | ], 45 | "text/plain": [ 46 | "The 'toml' package isn't installed. To load settings from pyproject.toml or ~/.jupysql/config, install with: pip install toml" 47 | ] 48 | }, 49 | "metadata": {}, 50 | "output_type": "display_data" 51 | }, 52 | { 53 | "name": "stderr", 54 | "output_type": "stream", 55 | "text": [ 56 | "SELECT CURRENT_DATABASE(), CURRENT_SCHEMA();\n", 57 | "ROLLBACK;\n" 58 | ] 59 | } 60 | ], 61 | "source": [ 62 | "from snowflake.sqlalchemy import URL\n", 63 | "from sqlalchemy import create_engine\n", 64 | "\n", 65 | "url = URL(account=\"fakesnow\",database=\"db1\",schema=\"schema1\")\n", 66 | "engine = create_engine(url)\n", 67 | "\n", 68 | "%reload_ext sql\n", 69 | "\n", 70 | "%config SqlMagic.feedback = False\n", 71 | "%config SqlMagic.displaycon = False\n", 72 | "%config SqlMagic.autopandas = True\n", 73 | "%sql engine" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": 6, 79 | "metadata": {}, 80 | "outputs": [ 81 | { 82 | "name": "stderr", 83 | "output_type": "stream", 84 | "text": [ 85 | "SELECT 'Hello fake world!';\n", 86 | "COMMIT;\n" 87 | ] 88 | }, 89 | { 90 | "data": { 91 | "text/html": [ 92 | "
\n", 93 | "\n", 106 | "\n", 107 | " \n", 108 | " \n", 109 | " \n", 110 | " \n", 111 | " \n", 112 | " \n", 113 | " \n", 114 | " \n", 115 | " \n", 116 | " \n", 117 | " \n", 118 | " \n", 119 | "
'Hello fake world!'
0Statement executed successfully.
\n", 120 | "
" 121 | ], 122 | "text/plain": [ 123 | " 'Hello fake world!'\n", 124 | "0 Statement executed successfully." 125 | ] 126 | }, 127 | "execution_count": 6, 128 | "metadata": {}, 129 | "output_type": "execute_result" 130 | } 131 | ], 132 | "source": [ 133 | "%%sql\n", 134 | "SELECT 'Hello fake world!'" 135 | ] 136 | } 137 | ], 138 | "metadata": { 139 | "kernelspec": { 140 | "display_name": ".venv", 141 | "language": "python", 142 | "name": "python3" 143 | }, 144 | "language_info": { 145 | "codemirror_mode": { 146 | "name": "ipython", 147 | "version": 3 148 | }, 149 | "file_extension": ".py", 150 | "mimetype": "text/x-python", 151 | "name": "python", 152 | "nbconvert_exporter": "python", 153 | "pygments_lexer": "ipython3", 154 | "version": "3.9.18" 155 | }, 156 | "orig_nbformat": 4, 157 | "vscode": { 158 | "interpreter": { 159 | "hash": "f59249d332647baa27896e48b602655774b2ab27cda0296fe135a6398572f9c3" 160 | } 161 | } 162 | }, 163 | "nbformat": 4, 164 | "nbformat_minor": 2 165 | } 166 | -------------------------------------------------------------------------------- /notebooks/snowflake.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import snowflake.connector\n", 10 | "\n", 11 | "conn_info = dict(\n", 12 | " user = ...,\n", 13 | " role = ...,\n", 14 | " account = ...,\n", 15 | " authenticator=...,\n", 16 | " database=...,\n", 17 | " schema=...,\n", 18 | ")\n", 19 | "conn = snowflake.connector.connect(**conn_info)\n", 20 | "cur = conn.cursor()\n" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": { 27 | "tags": [ 28 | "foo" 29 | ] 30 | }, 31 | "outputs": [], 32 | "source": [ 33 | "from snowflake.sqlalchemy import URL\n", 34 | "from sqlalchemy import create_engine\n", 35 | "\n", 36 | "url = URL(**conn_info)\n", 37 | "\n", 38 | "engine = create_engine(url)\n", 39 | "\n", 40 | "%reload_ext sql\n", 41 | "\n", 42 | "%config SqlMagic.feedback = False\n", 43 | "%config SqlMagic.displaycon = False\n", 44 | "%config SqlMagic.autopandas = True\n", 45 | "%sql engine\n", 46 | "%sql select current_warehouse(), current_database(), current_schema()" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 66, 52 | "metadata": {}, 53 | "outputs": [ 54 | { 55 | "data": { 56 | "text/plain": [ 57 | "[(datetime.datetime(2020, 12, 31, 0, 1, 2, 345678),\n", 58 | " datetime.datetime(2020, 12, 31, 0, 1, 2, 345678, tzinfo=),\n", 59 | " datetime.datetime(2020, 12, 31, 0, 1, 2, 345678, tzinfo=pytz.FixedOffset(600)),\n", 60 | " datetime.datetime(2020, 12, 31, 0, 1, 2, 345678))]" 61 | ] 62 | }, 63 | "execution_count": 66, 64 | "metadata": {}, 65 | "output_type": "execute_result" 66 | } 67 | ], 68 | "source": [ 69 | "cur.execute(\n", 70 | " \"select '2020-12-31 00:01:02.345678 +0000'::timestamp_tz::timestamp, '2020-12-31 00:01:02.345678+00:00'::timestamp_tz, '2020-12-31 00:01:02.345678+10:00'::timestamp_tz, '2020-12-31 00:01:02.345678+10:00'::timestamp_tz::timestamp\"\n", 71 | ").fetchall()" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 72, 77 | "metadata": {}, 78 | "outputs": [ 79 | { 80 | "data": { 81 | "text/html": [ 82 | "
\n", 83 | "\n", 96 | "\n", 97 | " \n", 98 | " \n", 99 | " \n", 100 | " \n", 101 | " \n", 102 | " \n", 103 | " \n", 104 | " \n", 105 | " \n", 106 | " \n", 107 | " \n", 108 | " \n", 109 | " \n", 110 | " \n", 111 | " \n", 112 | " \n", 113 | " \n", 114 | " \n", 115 | "
'2020-12-31 00:01:02.345678+00:00' ::TIMESTAMP_TZ::TIMESTAMP'2020-12-31 00:01:02.345678+00:00' ::TIMESTAMP_TZ'2020-12-31 00:01:02.345678+10:00' ::TIMESTAMP_TZ'2020-12-31 00:01:02.345678 +1000' ::TIMESTAMP_TZ
02020-12-31 00:01:02.3456782020-12-31 00:01:02.345678+00:002020-12-31 00:01:02.345678+10:002020-12-31 00:01:02.345678+10:00
\n", 116 | "
" 117 | ], 118 | "text/plain": [ 119 | " '2020-12-31 00:01:02.345678+00:00' ::TIMESTAMP_TZ::TIMESTAMP \\\n", 120 | "0 2020-12-31 00:01:02.345678 \n", 121 | "\n", 122 | " '2020-12-31 00:01:02.345678+00:00' ::TIMESTAMP_TZ \\\n", 123 | "0 2020-12-31 00:01:02.345678+00:00 \n", 124 | "\n", 125 | " '2020-12-31 00:01:02.345678+10:00' ::TIMESTAMP_TZ \\\n", 126 | "0 2020-12-31 00:01:02.345678+10:00 \n", 127 | "\n", 128 | " '2020-12-31 00:01:02.345678 +1000' ::TIMESTAMP_TZ \n", 129 | "0 2020-12-31 00:01:02.345678+10:00 " 130 | ] 131 | }, 132 | "execution_count": 72, 133 | "metadata": {}, 134 | "output_type": "execute_result" 135 | } 136 | ], 137 | "source": [ 138 | "%sql select '2020-12-31 00:01:02.345678+00:00'::timestamp_tz::timestamp, '2020-12-31 00:01:02.345678+00:00'::timestamp_tz, '2020-12-31 00:01:02.345678+10:00'::timestamp_tz, '2020-12-31 00:01:02.345678 +1000'::timestamp_tz" 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": 76, 144 | "metadata": {}, 145 | "outputs": [ 146 | { 147 | "data": { 148 | "text/plain": [ 149 | "[(datetime.datetime(2020, 12, 31, 0, 1, 2, 345678),\n", 150 | " datetime.datetime(2020, 12, 31, 0, 1, 2, 345678))]" 151 | ] 152 | }, 153 | "execution_count": 76, 154 | "metadata": {}, 155 | "output_type": "execute_result" 156 | } 157 | ], 158 | "source": [ 159 | "cur.execute(\n", 160 | " \"select '2020-12-31 00:01:02.345678+10:00'::timestamp_tz::timestamp, '2020-12-31 00:01:02.345678'::timestamp_tz::timestamp\"\n", 161 | ").fetchall()" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": 80, 167 | "metadata": {}, 168 | "outputs": [], 169 | "source": [ 170 | "import datetime\n", 171 | "\n", 172 | "import pandas as pd\n", 173 | "import pytz\n", 174 | "import snowflake.connector.pandas_tools\n", 175 | "\n", 176 | "cur.execute(\"create or replace table example (UPDATE_AT_NTZ timestamp_ntz(9))\")\n", 177 | "# cur.execute(\"create table example (UPDATE_AT_NTZ timestamp)\")\n", 178 | "\n", 179 | "now_utc = datetime.datetime.now(pytz.utc)\n", 180 | "df = pd.DataFrame([(now_utc,)], columns=[\"UPDATE_AT_NTZ\"])\n", 181 | "snowflake.connector.pandas_tools.write_pandas(conn, df, \"EXAMPLE\")\n", 182 | "\n", 183 | "cur.execute(\"select * from example\")\n", 184 | "\n", 185 | "assert cur.fetchall() == [(now_utc.replace(tzinfo=None),)]" 186 | ] 187 | }, 188 | { 189 | "cell_type": "code", 190 | "execution_count": 57, 191 | "metadata": {}, 192 | "outputs": [ 193 | { 194 | "name": "stderr", 195 | "output_type": "stream", 196 | "text": [ 197 | "INFO:backoff:Backing off send_request(...) for 0.8s (requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='app.posthog.com', port=443): Read timed out. (read timeout=15))\n" 198 | ] 199 | }, 200 | { 201 | "data": { 202 | "text/html": [ 203 | "
\n", 204 | "\n", 217 | "\n", 218 | " \n", 219 | " \n", 220 | " \n", 221 | " \n", 222 | " \n", 223 | " \n", 224 | " \n", 225 | " \n", 226 | " \n", 227 | " \n", 228 | " \n", 229 | " \n", 230 | " \n", 231 | " \n", 232 | "
'2020-12-31 00:01:02.345678 +0000' ::TIMESTAMP_TZ::TIMESTAMP'2020-12-31 00:01:02.345678 +0000' ::TIMESTAMP_TZ
02020-12-31 00:01:02.3456782020-12-31 00:01:02.345678+00:00
\n", 233 | "
" 234 | ], 235 | "text/plain": [ 236 | " '2020-12-31 00:01:02.345678 +0000' ::TIMESTAMP_TZ::TIMESTAMP \\\n", 237 | "0 2020-12-31 00:01:02.345678 \n", 238 | "\n", 239 | " '2020-12-31 00:01:02.345678 +0000' ::TIMESTAMP_TZ \n", 240 | "0 2020-12-31 00:01:02.345678+00:00 " 241 | ] 242 | }, 243 | "execution_count": 57, 244 | "metadata": {}, 245 | "output_type": "execute_result" 246 | } 247 | ], 248 | "source": [ 249 | "%sql select '2020-12-31 00:01:02.345678 +0000'::timestamp_tz::timestamp, '2020-12-31 00:01:02.345678 +0000'::timestamp_tz" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": 22, 255 | "metadata": {}, 256 | "outputs": [ 257 | { 258 | "data": { 259 | "text/html": [ 260 | "
\n", 261 | "\n", 274 | "\n", 275 | " \n", 276 | " \n", 277 | " \n", 278 | " \n", 279 | " \n", 280 | " \n", 281 | " \n", 282 | " \n", 283 | " \n", 284 | " \n", 285 | " \n", 286 | " \n", 287 | "
SYSTEM$TYPEOF(TO_DATE(TO_TIMESTAMP(0)))
0DATE[SB4]
\n", 288 | "
" 289 | ], 290 | "text/plain": [ 291 | " SYSTEM$TYPEOF(TO_DATE(TO_TIMESTAMP(0)))\n", 292 | "0 DATE[SB4]" 293 | ] 294 | }, 295 | "execution_count": 22, 296 | "metadata": {}, 297 | "output_type": "execute_result" 298 | } 299 | ], 300 | "source": [ 301 | "%sql SELECT system$typeof(to_date(to_timestamp(0)))" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": 14, 307 | "metadata": {}, 308 | "outputs": [ 309 | { 310 | "data": { 311 | "text/plain": [ 312 | "[(datetime.datetime(2013, 4, 5, 1, 2, 3),)]" 313 | ] 314 | }, 315 | "execution_count": 14, 316 | "metadata": {}, 317 | "output_type": "execute_result" 318 | } 319 | ], 320 | "source": [ 321 | "cur.execute(\"SELECT to_timestamp('2013-04-05 01:02:03')\").fetchall()" 322 | ] 323 | } 324 | ], 325 | "metadata": { 326 | "kernelspec": { 327 | "display_name": ".venv", 328 | "language": "python", 329 | "name": "python3" 330 | }, 331 | "language_info": { 332 | "codemirror_mode": { 333 | "name": "ipython", 334 | "version": 3 335 | }, 336 | "file_extension": ".py", 337 | "mimetype": "text/x-python", 338 | "name": "python", 339 | "nbconvert_exporter": "python", 340 | "pygments_lexer": "ipython3", 341 | "version": "3.9.18" 342 | }, 343 | "orig_nbformat": 4, 344 | "vscode": { 345 | "interpreter": { 346 | "hash": "f59249d332647baa27896e48b602655774b2ab27cda0296fe135a6398572f9c3" 347 | } 348 | } 349 | }, 350 | "nbformat": 4, 351 | "nbformat_minor": 2 352 | } 353 | -------------------------------------------------------------------------------- /notebooks/sqlglot.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 2, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import sqlglot\n", 10 | "from sqlglot import exp\n", 11 | "\n", 12 | "import fakesnow.transforms as transforms" 13 | ] 14 | }, 15 | { 16 | "cell_type": "code", 17 | "execution_count": 76, 18 | "metadata": {}, 19 | "outputs": [ 20 | { 21 | "data": { 22 | "text/plain": [ 23 | "'SELECT t.id, flat.value[\\'fruit\\'] FROM (SELECT 1, JSON(\\'[{\"fruit\":\"banana\"}]\\') UNION SELECT 2, JSON(\\'[{\"fruit\":\"coconut\"}, {\"fruit\":\"durian\"}]\\')) AS t(id, fruits), LATERAL UNNEST(input => t.fruits) AS _flattened(SEQ, KEY, PATH, INDEX, VALUE, THIS)'" 24 | ] 25 | }, 26 | "execution_count": 76, 27 | "metadata": {}, 28 | "output_type": "execute_result" 29 | } 30 | ], 31 | "source": [ 32 | "sqlglot.parse_one(\"\"\"\n", 33 | " select t.id, flat.value:fruit from\n", 34 | " (\n", 35 | " select 1, parse_json('[{\"fruit\":\"banana\"}]')\n", 36 | " union\n", 37 | " select 2, parse_json('[{\"fruit\":\"coconut\"}, {\"fruit\":\"durian\"}]')\n", 38 | " ) as t(id, fruits), lateral flatten(input => t.fruits)\n", 39 | " \"\"\", read=\"snowflake\").sql(dialect=\"duckdb\")" 40 | ] 41 | } 42 | ], 43 | "metadata": { 44 | "kernelspec": { 45 | "display_name": ".venv", 46 | "language": "python", 47 | "name": "python3" 48 | }, 49 | "language_info": { 50 | "codemirror_mode": { 51 | "name": "ipython", 52 | "version": 3 53 | }, 54 | "file_extension": ".py", 55 | "mimetype": "text/x-python", 56 | "name": "python", 57 | "nbconvert_exporter": "python", 58 | "pygments_lexer": "ipython3", 59 | "version": "3.9.18" 60 | }, 61 | "orig_nbformat": 4, 62 | "vscode": { 63 | "interpreter": { 64 | "hash": "f59249d332647baa27896e48b602655774b2ab27cda0296fe135a6398572f9c3" 65 | } 66 | } 67 | }, 68 | "nbformat": 4, 69 | "nbformat_minor": 2 70 | } 71 | -------------------------------------------------------------------------------- /notebooks/timezones.md: -------------------------------------------------------------------------------- 1 | # timezones 2 | 3 | duckdb: 4 | 5 | ``` 6 | select current_timestamp; // 2023-06-24 17:06:31.483+10 (TIMESTAMP WITH TIME ZONE) 7 | select current_timestamp::TIMESTAMP; // 2023-06-24 07:06:31.483 (TIMESTAMP) 8 | select current_timestamp::TIMESTAMP::TIMESTAMP(9); // 2023-06-24 07:06:31.483 (TIMESTAMP_NS) 9 | select current_timestamp AT TIME ZONE 'UTC'; // 2023-06-24 07:06:31.483 (TIMESTAMP) 10 | select (current_timestamp AT TIME ZONE 'UTC')::TIMESTAMP(9); // 2023-06-24 07:06:31.483 (TIMESTAMP_NS) 11 | select current_timestamp::TIMESTAMP(9); // Error: Conversion Error: Unimplemented type for cast (TIMESTAMP WITH TIME ZONE -> TIMESTAMP_NS) 12 | ``` 13 | 14 | postgres 15 | 16 | ``` 17 | select current_timestamp; // 2023-06-24 07:06:31.483+00 (TIMESTAMP WITH TIME ZONE) 18 | select current_timestamp::TIMESTAMP; // 2023-06-24 07:06:31.483 (TIMESTAMP WITHOUT TIME ZONE) 19 | select current_timestamp::TIMESTAMP::TIMESTAMP(9); // 2023-06-24 07:06:31.483 (TIMESTAMP WITHOUT TIME ZONE) 20 | select current_timestamp AT TIME ZONE 'UTC'; // 2023-06-24 07:06:31.483 (TIMESTAMP WITHOUT TIME ZONE) 21 | select (current_timestamp AT TIME ZONE 'UTC')::TIMESTAMP(9); // 2023-06-24 07:06:31.483 (TIMESTAMP WITHOUT TIME ZONE) 22 | select current_timestamp::TIMESTAMP(9); // 2023-06-24 07:06:31.483 (TIMESTAMP WITHOUT TIME ZONE) 23 | ``` 24 | 25 | snowflake: 26 | 27 | ``` 28 | select current_timestamp; // 2023-06-24 07:06:31.483+00 (TIMESTAMP_LTZ(9)) 29 | select current_timestamp::TIMESTAMP; // 2023-06-24 07:06:31.483 (TIMESTAMP_NTZ(9)) 30 | ``` 31 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "devDependencies": { 3 | "pyright": "1.1.401" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "fakesnow" 3 | description = "Fake Snowflake Connector for Python. Run, mock and test Snowflake DB locally." 4 | version = "0.9.39" 5 | readme = "README.md" 6 | license = { file = "LICENSE" } 7 | classifiers = ["License :: OSI Approved :: MIT License"] 8 | keywords = ["snowflake", "snowflakedb", "fake", "local", "mock", "testing"] 9 | requires-python = ">=3.9" 10 | dependencies = [ 11 | "duckdb~=1.2.0", 12 | "pyarrow", 13 | "snowflake-connector-python", 14 | "sqlglot~=26.24.0", 15 | ] 16 | 17 | [project.urls] 18 | Source = "https://github.com/tekumara/fakesnow" 19 | Changelog = "https://github.com/tekumara/fakesnow/blob/main/CHANGELOG.md" 20 | 21 | [project.scripts] 22 | fakesnow = "fakesnow.cli:main" 23 | 24 | [dependency-groups] 25 | dev = [ 26 | "boto3", 27 | "boto3-stubs[s3,sts]", 28 | "build~=1.0", 29 | "dirty-equals", 30 | "moto[server] >= 5", 31 | # to fix https://github.com/pandas-dev/pandas/issues/56995 32 | "pandas-stubs", 33 | "pre-commit~=4.0", 34 | "pyarrow-stubs==17.19", 35 | "pyright==1.1.399", 36 | "pytest~=8.0", 37 | "ruff~=0.11.2", 38 | # include compatible version of pandas, and secure-local-storage for token caching 39 | "snowflake-connector-python[pandas, secure-local-storage]", 40 | "snowflake-sqlalchemy~=1.7.0", 41 | "twine~=6.1", 42 | ] 43 | # for debugging, see https://duckdb.org/docs/guides/python/jupyter.html 44 | notebook = ["duckdb-engine", "ipykernel", "jupysql"] 45 | 46 | # for the standalone server 47 | [project.optional-dependencies] 48 | server = ["starlette", "uvicorn"] 49 | 50 | [build-system] 51 | requires = ["setuptools~=80.1"] 52 | build-backend = "setuptools.build_meta" 53 | 54 | [tool.setuptools.packages.find] 55 | where = ["."] 56 | exclude = ["tests*", "build*"] 57 | 58 | [tool.pyright] 59 | venvPath = "." 60 | venv = ".venv" 61 | exclude = ["**/__pycache__", "**/.*", "build"] 62 | strictListInference = true 63 | strictDictionaryInference = true 64 | strictParameterNoneValue = true 65 | reportTypedDictNotRequiredAccess = false 66 | reportIncompatibleVariableOverride = true 67 | reportIncompatibleMethodOverride = true 68 | reportMatchNotExhaustive = true 69 | reportUnnecessaryTypeIgnoreComment = true 70 | 71 | [tool.pytest.ini_options] 72 | # error on unhandled exceptions in background threads 73 | # useful for catching errors in server or snowflake connector threads 74 | filterwarnings = [ 75 | "error::pytest.PytestUnhandledThreadExceptionWarning", 76 | "ignore::pytest.PytestUnknownMarkWarning", 77 | ] 78 | 79 | [tool.ruff] 80 | line-length = 120 81 | # first-party imports for sorting 82 | src = ["."] 83 | fix = true 84 | show-fixes = true 85 | exclude = ["notebooks"] 86 | 87 | [tool.ruff.lint] 88 | # rules to enable/ignore 89 | select = [ 90 | "F", # pyflakes 91 | "E", # pycodestyle 92 | "W", # pycodestyle 93 | "ANN", # type annotations 94 | "N", # pep8-naming 95 | "B", # bugbear 96 | "I", # isort 97 | # "ARG", # flake8-unused-arguments - disabled because our fakes don't use all arguments 98 | "SLF", # flake8-self 99 | "UP", # pyupgrade 100 | "PERF", # perflint 101 | "RUF", # ruff-specific 102 | "SIM", # flake8-simplify 103 | "S113", # request-without-timeout 104 | "A", # flake8-builtins 105 | "ASYNC", # flake8-async 106 | ] 107 | 108 | ignore = [ 109 | # allow no return type from dunder methods 110 | "ANN204", 111 | # allow == True because pandas dataframes overload equality 112 | "E712", 113 | ] 114 | 115 | [tool.ruff.lint.isort] 116 | combine-as-imports = true 117 | force-wrap-aliases = true 118 | 119 | [tool.ruff.lint.per-file-ignores] 120 | # test functions don't need return types 121 | "tests/*" = ["ANN201", "ANN202"] 122 | 123 | [tool.ruff.lint.flake8-annotations] 124 | # allow *args: Any, **kwargs: Any 125 | allow-star-arg-any = true 126 | -------------------------------------------------------------------------------- /release-please-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "bump-minor-pre-major": true, 3 | "bump-patch-for-minor-pre-major": true, 4 | "changelog-sections": [ 5 | { "type": "feat", "section": "Features" }, 6 | { "type": "fix", "section": "Bug Fixes" }, 7 | { "type": "chore", "section": "Chores" }, 8 | { "type": "refactor", "section": "Code Refactoring", "hidden": true } 9 | ], 10 | "packages": { 11 | ".": { 12 | "release-type": "python" 13 | } 14 | }, 15 | "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json" 16 | } 17 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tekumara/fakesnow/182ce7ee7ca9c8401db68c5bcc5be16d06ed7dcc/tests/__init__.py -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import os 2 | from collections.abc import Iterator 3 | from typing import cast 4 | 5 | import boto3 6 | import pytest 7 | import snowflake.connector 8 | from mypy_boto3_s3 import S3Client 9 | from sqlalchemy.engine import Engine, create_engine 10 | 11 | import fakesnow 12 | import fakesnow.fixtures 13 | import tests.fixtures.moto 14 | 15 | pytest_plugins = fakesnow.fixtures.__name__, tests.fixtures.moto.__name__ 16 | 17 | 18 | @pytest.fixture 19 | def conn(_fakesnow: None) -> Iterator[snowflake.connector.SnowflakeConnection]: 20 | """ 21 | Yield a snowflake connection once per session. 22 | """ 23 | with snowflake.connector.connect(database="db1", schema="schema1") as c: 24 | yield c 25 | 26 | 27 | @pytest.fixture 28 | def cur(conn: snowflake.connector.SnowflakeConnection) -> Iterator[snowflake.connector.cursor.SnowflakeCursor]: 29 | """ 30 | Yield a snowflake cursor once per session. 31 | """ 32 | with conn.cursor() as cur: 33 | yield cur 34 | 35 | 36 | @pytest.fixture 37 | def dcur(conn: snowflake.connector.SnowflakeConnection) -> Iterator[snowflake.connector.cursor.DictCursor]: 38 | """ 39 | Yield a snowflake cursor once per session. 40 | """ 41 | with conn.cursor(snowflake.connector.cursor.DictCursor) as cur: 42 | yield cast(snowflake.connector.cursor.DictCursor, cur) 43 | 44 | 45 | @pytest.fixture 46 | def snowflake_engine(_fakesnow: None) -> Engine: 47 | return create_engine("snowflake://user:password@account/db1/schema1") 48 | 49 | 50 | @pytest.fixture(scope="session") 51 | def server() -> Iterator[dict]: 52 | # isolate each session to a separate instance to avoid sharing tables between tests 53 | with fakesnow.server( 54 | session_parameters={ 55 | "FAKESNOW_DB_PATH": ":isolated:", 56 | } 57 | ) as conn_kwargs: 58 | yield conn_kwargs 59 | 60 | 61 | @pytest.fixture 62 | def sconn(server: dict) -> Iterator[snowflake.connector.SnowflakeConnection]: 63 | with snowflake.connector.connect( 64 | **server, 65 | database="db1", 66 | schema="schema1", 67 | ) as c: 68 | yield c 69 | 70 | 71 | @pytest.fixture 72 | def scur( 73 | sconn: snowflake.connector.SnowflakeConnection, 74 | ) -> Iterator[snowflake.connector.cursor.SnowflakeCursor]: 75 | with sconn.cursor() as cur: 76 | yield cur 77 | 78 | 79 | @pytest.fixture 80 | def sdcur( 81 | sconn: snowflake.connector.SnowflakeConnection, 82 | ) -> Iterator[snowflake.connector.cursor.DictCursor]: 83 | with sconn.cursor(snowflake.connector.cursor.DictCursor) as cur: 84 | yield cast(snowflake.connector.cursor.DictCursor, cur) 85 | 86 | 87 | @pytest.fixture() 88 | def s3_client(moto_session: boto3.Session, cur: snowflake.connector.cursor.SnowflakeCursor) -> S3Client: 89 | """Configures duckdb to use the moto session and returns an s3 client.""" 90 | 91 | client = moto_session.client("s3") 92 | endpoint_url = client.meta.endpoint_url 93 | 94 | creds = moto_session.get_credentials() 95 | assert creds 96 | 97 | # NOTE: This is a duckdb query, not a transformed snowflake one! 98 | cur.execute( 99 | f""" 100 | CREATE SECRET s3_secret ( 101 | TYPE s3, 102 | ENDPOINT '{endpoint_url.removeprefix("http://")}', 103 | KEY_ID '{creds.access_key}', 104 | SECRET '{creds.secret_key}', 105 | SESSION_TOKEN '{creds.token}', 106 | URL_STYLE 'path', 107 | USE_SSL false, 108 | REGION '{moto_session.region_name}' 109 | ); 110 | """ 111 | ) 112 | 113 | return client 114 | 115 | 116 | if os.getenv("TEST_SERVER"): 117 | # use server to run all tests 118 | conn = sconn # type: ignore 119 | -------------------------------------------------------------------------------- /tests/fixtures/moto.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | 4 | import boto3 5 | import pytest 6 | from moto.server import ThreadedMotoServer 7 | 8 | 9 | @pytest.fixture(scope="session") 10 | def moto_server(): 11 | server = ThreadedMotoServer(port=0) 12 | server.start() 13 | host, port = server.get_host_and_port() 14 | 15 | endpoint_url = f"http://{host}:{port}" 16 | 17 | # will be used implicitly by boto3 clients and resources 18 | os.environ["AWS_ENDPOINT_URL"] = endpoint_url 19 | yield endpoint_url 20 | 21 | server.stop() 22 | 23 | 24 | @pytest.fixture() 25 | def moto_session(moto_server: str) -> boto3.Session: 26 | """Create a boto session using the moto server. 27 | 28 | Note each session uses a unique mock moto AWS account in order to ensure 29 | isolation of data/state between tests. 30 | 31 | See https://docs.getmoto.org/en/latest/docs/multi_account.html 32 | """ 33 | region = "us-east-1" 34 | 35 | # Attempt at a cross-process way of generating unique 12-character integers. 36 | account_id = str(time.time_ns())[:12] 37 | 38 | sts = boto3.client( 39 | "sts", 40 | endpoint_url=moto_server, 41 | aws_access_key_id="test", 42 | aws_secret_access_key="test", 43 | region_name=region, 44 | ) 45 | response = sts.assume_role( 46 | RoleArn=f"arn:aws:iam::{account_id}:role/my-role", 47 | RoleSessionName="test-session-name", 48 | ExternalId="test-external-id", 49 | ) 50 | 51 | credentials = response["Credentials"] 52 | 53 | access_key_id = credentials["AccessKeyId"] 54 | secret_access_key = credentials["SecretAccessKey"] 55 | session_token = credentials["SessionToken"] 56 | 57 | return boto3.Session( 58 | aws_access_key_id=access_key_id, 59 | aws_secret_access_key=secret_access_key, 60 | aws_session_token=session_token, 61 | region_name=region, 62 | ) 63 | -------------------------------------------------------------------------------- /tests/hello.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | import snowflake.connector 4 | 5 | names = sys.argv[1:] if len(sys.argv) > 1 else ["world"] 6 | 7 | conn = snowflake.connector.connect() 8 | 9 | print( 10 | conn.cursor().execute(f"SELECT 'Hello fake {' '.join(names)}!'").fetchone() # pyright: ignore[reportOptionalMemberAccess] 11 | ) 12 | -------------------------------------------------------------------------------- /tests/matchers.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | 3 | from dirty_equals import DirtyEquals 4 | from snowflake.connector.cursor import ResultMetadata 5 | 6 | 7 | class IsResultMetadata(DirtyEquals[ResultMetadata]): 8 | """ 9 | A custom dirty_equals matcher that does a partial match against ResultMetadata NamedTuples. 10 | 11 | Example: 12 | assert result == IsResultMetadata(name='COLUMN_NAME', type_code=2) 13 | """ 14 | 15 | def __init__(self, **kwargs: Any) -> None: 16 | self.partial_kwargs = kwargs 17 | super().__init__(**kwargs) 18 | 19 | def equals(self, other: Any) -> bool: # noqa: ANN401 20 | if not isinstance(other, ResultMetadata): 21 | return False 22 | 23 | # Convert the namedtuple to a dict for comparison 24 | other_dict = other._asdict() 25 | 26 | # Check the provided fields match 27 | for key, expected in self.partial_kwargs.items(): 28 | if key not in other_dict or other_dict[key] != expected: 29 | return False 30 | 31 | return True 32 | -------------------------------------------------------------------------------- /tests/patch_other.py: -------------------------------------------------------------------------------- 1 | from snowflake.connector import connect # noqa: F401 2 | -------------------------------------------------------------------------------- /tests/test_checks.py: -------------------------------------------------------------------------------- 1 | import sqlglot 2 | 3 | from fakesnow.checks import is_unqualified_table_expression 4 | 5 | 6 | def test_check_unqualified_select() -> None: 7 | assert is_unqualified_table_expression(sqlglot.parse_one("SELECT * FROM customers")) == (True, True) 8 | 9 | assert is_unqualified_table_expression(sqlglot.parse_one("SELECT * FROM jaffles.customers")) == (True, False) 10 | 11 | assert is_unqualified_table_expression(sqlglot.parse_one("SELECT * FROM marts.jaffles.customers")) == (False, False) 12 | 13 | 14 | def test_check_unqualified_create_table() -> None: 15 | assert is_unqualified_table_expression(sqlglot.parse_one("CREATE TABLE customers (ID INT)")) == (True, True) 16 | 17 | assert is_unqualified_table_expression(sqlglot.parse_one("CREATE TABLE jaffles.customers (ID INT)")) == ( 18 | True, 19 | False, 20 | ) 21 | 22 | 23 | def test_check_unqualified_drop_table() -> None: 24 | assert is_unqualified_table_expression(sqlglot.parse_one("DROP TABLE customers")) == (True, True) 25 | 26 | assert is_unqualified_table_expression(sqlglot.parse_one("DROP TABLE jaffles.customers")) == ( 27 | True, 28 | False, 29 | ) 30 | 31 | 32 | def test_check_unqualified_schema() -> None: 33 | # assert is_unqualified_table_expression(sqlglot.parse_one("CREATE SCHEMA jaffles")) == (True, False) 34 | 35 | # assert is_unqualified_table_expression(sqlglot.parse_one("CREATE SCHEMA marts.jaffles")) == (False, False) 36 | 37 | assert is_unqualified_table_expression(sqlglot.parse_one("USE SCHEMA jaffles")) == (True, False) 38 | 39 | assert is_unqualified_table_expression(sqlglot.parse_one("USE SCHEMA marts.jaffles")) == (False, False) 40 | 41 | 42 | def test_check_unqualified_database() -> None: 43 | assert is_unqualified_table_expression(sqlglot.parse_one("CREATE DATABASE marts")) == (False, False) 44 | 45 | assert is_unqualified_table_expression(sqlglot.parse_one("USE DATABASE marts")) == (False, False) 46 | -------------------------------------------------------------------------------- /tests/test_cli.py: -------------------------------------------------------------------------------- 1 | from pytest import CaptureFixture 2 | 3 | import fakesnow.cli 4 | 5 | 6 | def test_split() -> None: 7 | assert fakesnow.cli.split(["pytest", "-m", "integration"]) == (["pytest"], ["-m", "integration"]) 8 | assert fakesnow.cli.split(["-m", "pytest", "-m", "integration"]) == (["-m", "pytest"], ["-m", "integration"]) 9 | assert fakesnow.cli.split(["pytest"]) == (["pytest"], []) 10 | assert fakesnow.cli.split(["-m", "pytest"]) == (["-m", "pytest"], []) 11 | assert fakesnow.cli.split(["-d", "databases/", "--module", "pytest", "-m", "integration"]) == ( 12 | ["-d", "databases/", "--module", "pytest"], 13 | ["-m", "integration"], 14 | ) 15 | 16 | 17 | def test_run_module(capsys: CaptureFixture) -> None: 18 | fakesnow.cli.main(["-m", "tests.hello"]) 19 | 20 | captured = capsys.readouterr() 21 | assert captured.out == "('Hello fake world!',)\n" 22 | 23 | fakesnow.cli.main(["-m", "tests.hello", "frobnitz", "--colour", "rainbow", "-m", "integration"]) 24 | 25 | captured = capsys.readouterr() 26 | assert captured.out == "('Hello fake frobnitz --colour rainbow -m integration!',)\n" 27 | 28 | 29 | def test_run_path(capsys: CaptureFixture) -> None: 30 | fakesnow.cli.main(["tests/hello.py"]) 31 | 32 | captured = capsys.readouterr() 33 | assert captured.out == "('Hello fake world!',)\n" 34 | 35 | fakesnow.cli.main(["tests/hello.py", "frobnitz", "--colour", "rainbow", "-m", "integration"]) 36 | 37 | captured = capsys.readouterr() 38 | assert captured.out == "('Hello fake frobnitz --colour rainbow -m integration!',)\n" 39 | 40 | 41 | def test_run_no_args_shows_usage(capsys: CaptureFixture) -> None: 42 | fakesnow.cli.main([]) 43 | 44 | captured = capsys.readouterr() 45 | assert "usage" in captured.out 46 | -------------------------------------------------------------------------------- /tests/test_connect.py: -------------------------------------------------------------------------------- 1 | # ruff: noqa: E501 2 | # pyright: reportOptionalMemberAccess=false 3 | 4 | from __future__ import annotations 5 | 6 | import concurrent.futures 7 | import tempfile 8 | 9 | import pytest 10 | import snowflake.connector 11 | import snowflake.connector.cursor 12 | import snowflake.connector.pandas_tools 13 | 14 | import fakesnow 15 | 16 | 17 | def test_close_conn(conn: snowflake.connector.SnowflakeConnection): 18 | assert not conn.is_closed() 19 | 20 | conn.close() 21 | with pytest.raises(snowflake.connector.errors.DatabaseError) as excinfo: 22 | conn.execute_string("select 1") 23 | 24 | # actual snowflake error message is: 25 | # 250002 (08003): Connection is closed 26 | assert "250002 (08003)" in str(excinfo.value) 27 | 28 | assert conn.is_closed() 29 | 30 | 31 | def test_close_cur(cur: snowflake.connector.cursor.SnowflakeCursor): 32 | assert cur.close() is True 33 | 34 | 35 | def test_connect_auto_create(_fakesnow: None): 36 | with snowflake.connector.connect(database="db1", schema="schema1"): 37 | # creates db1 and schema1 38 | pass 39 | 40 | with snowflake.connector.connect(database="db1", schema="schema1"): 41 | # connects again and reuses db1 and schema1 42 | pass 43 | 44 | 45 | def test_connect_different_sessions_use_database(_fakesnow_no_auto_create: None): 46 | # connect without default database and schema 47 | with snowflake.connector.connect() as conn1, conn1.cursor() as cur: 48 | # use the table's fully qualified name 49 | cur.execute("create database marts") 50 | cur.execute("create schema marts.jaffles") 51 | cur.execute("create table marts.jaffles.customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 52 | cur.execute("insert into marts.jaffles.customers values (1, 'Jenny', 'P')") 53 | 54 | # use database and schema 55 | cur.execute("use database marts") 56 | assert cur.fetchall() == [("Statement executed successfully.",)] 57 | assert cur.description[0].name == "status" 58 | 59 | cur.execute("use schema jaffles") 60 | assert cur.fetchall() == [("Statement executed successfully.",)] 61 | assert cur.description[0].name == "status" 62 | 63 | cur.execute("insert into customers values (2, 'Jasper', 'M')") 64 | 65 | # in a separate connection, connect using the database and schema from above 66 | with snowflake.connector.connect(database="marts", schema="jaffles") as conn2, conn2.cursor() as cur: 67 | cur.execute("select id, first_name, last_name from customers") 68 | assert cur.fetchall() == [(1, "Jenny", "P"), (2, "Jasper", "M")] 69 | 70 | 71 | def test_connect_concurrently(_fakesnow: None) -> None: 72 | with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: 73 | future_a = executor.submit(snowflake.connector.connect) 74 | future_b = executor.submit(snowflake.connector.connect) 75 | 76 | futures = [future_a, future_b] 77 | 78 | for future in concurrent.futures.as_completed(futures): 79 | # exceptions if any will be raised here. we want to avoid 80 | # duckdb.duckdb.TransactionException: TransactionContext Error: Catalog write-write conflict 81 | _ = future.result() 82 | 83 | 84 | def test_connect_db_path_can_create_database() -> None: 85 | with tempfile.TemporaryDirectory(prefix="fakesnow-test") as db_path, fakesnow.patch(db_path=db_path): 86 | cursor = snowflake.connector.connect().cursor() 87 | cursor.execute("CREATE DATABASE db2") 88 | 89 | 90 | def test_connect_db_path_reuse(): 91 | with tempfile.TemporaryDirectory(prefix="fakesnow-test") as db_path: 92 | with ( 93 | fakesnow.patch(db_path=db_path), 94 | snowflake.connector.connect(database="db1", schema="schema1") as conn, 95 | conn.cursor() as cur, 96 | ): 97 | # creates db1.schema1.example 98 | cur.execute("create table example (x int)") 99 | cur.execute("insert into example values (420)") 100 | 101 | # reconnect 102 | with ( 103 | fakesnow.patch(db_path=db_path), 104 | snowflake.connector.connect(database="db1", schema="schema1") as conn, 105 | conn.cursor() as cur, 106 | ): 107 | assert cur.execute("select * from example").fetchall() == [(420,)] 108 | 109 | 110 | def test_connect_db_path_doesnt_exist(): 111 | with fakesnow.patch(db_path="db-path-foobar"): 112 | with pytest.raises(NotADirectoryError) as excinfo: 113 | snowflake.connector.connect(database="db1") 114 | 115 | assert "No such directory: 'db-path-foobar'. Please ensure db_path exists." in str(excinfo.value) 116 | 117 | 118 | def test_connect_information_schema(): 119 | with fakesnow.patch(create_schema_on_connect=False): 120 | conn = snowflake.connector.connect(database="db1", schema="information_schema") 121 | assert conn.schema == "INFORMATION_SCHEMA" 122 | with conn, conn.cursor() as cur: 123 | # shouldn't fail 124 | cur.execute("SELECT * FROM databases") 125 | 126 | 127 | def test_connect_then_unset_schema(_fakesnow: None): 128 | with snowflake.connector.connect(database="db1", schema="schema1") as conn, conn.cursor() as cur: 129 | # this will unset the schema 130 | cur.execute("USE DATABASE db1") 131 | 132 | with pytest.raises(snowflake.connector.errors.ProgrammingError) as excinfo: 133 | cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 134 | 135 | assert ( 136 | "090106 (22000): Cannot perform CREATE TABLE. This session does not have a current schema. Call 'USE SCHEMA', or use a qualified name." 137 | in str(excinfo.value) 138 | ) 139 | 140 | 141 | def test_connect_without_database(_fakesnow_no_auto_create: None): 142 | with snowflake.connector.connect() as conn, conn.cursor() as cur: 143 | with pytest.raises(snowflake.connector.errors.ProgrammingError) as excinfo: 144 | cur.execute("select * from customers") 145 | 146 | # actual snowflake error message is: 147 | # 148 | # 002003 (42S02): SQL compilation error: 149 | # Object 'CUSTOMERS' does not exist or not authorized. 150 | # assert ( 151 | # "002003 (42S02): Catalog Error: Table with name customers does not exist!" 152 | # in str(excinfo.value) 153 | # ) 154 | 155 | with pytest.raises(snowflake.connector.errors.ProgrammingError) as excinfo: 156 | cur.execute("select * from jaffles.customers") 157 | 158 | assert ( 159 | "090105 (22000): Cannot perform SELECT. This session does not have a current database. Call 'USE DATABASE', or use a qualified name." 160 | in str(excinfo.value) 161 | ) 162 | 163 | with pytest.raises(snowflake.connector.errors.ProgrammingError) as excinfo: 164 | cur.execute("create schema jaffles") 165 | 166 | assert ( 167 | "090105 (22000): Cannot perform CREATE SCHEMA. This session does not have a current database. Call 'USE DATABASE', or use a qualified name." 168 | in str(excinfo.value) 169 | ) 170 | 171 | with pytest.raises(snowflake.connector.errors.ProgrammingError) as excinfo: 172 | cur.execute("use schema jaffles") 173 | 174 | # assert ( 175 | # "002043 (02000): SQL compilation error:\nObject does not exist, or operation cannot be performed." 176 | # in str(excinfo.value) 177 | # ) 178 | 179 | with pytest.raises(snowflake.connector.errors.ProgrammingError) as excinfo: 180 | cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 181 | 182 | assert ( 183 | "090105 (22000): Cannot perform CREATE TABLE. This session does not have a current database. Call 'USE DATABASE', or use a qualified name." 184 | in str(excinfo.value) 185 | ) 186 | 187 | cur.execute("create database db1") 188 | # should succeed even though there is no current database (used by dbeaver) 189 | cur.execute("show objects in schema db1.information_schema") 190 | 191 | # test description works without database 192 | assert cur.execute("SELECT 1").fetchall() == [(1,)] 193 | assert cur.description 194 | 195 | 196 | def test_connect_without_schema(_fakesnow: None): 197 | # database will be created but not schema 198 | with snowflake.connector.connect(database="marts") as conn, conn.cursor() as cur: 199 | assert not conn.schema 200 | 201 | with pytest.raises(snowflake.connector.errors.ProgrammingError) as excinfo: 202 | cur.execute("select * from customers") 203 | 204 | # actual snowflake error message is: 205 | # 206 | # 002003 (42S02): SQL compilation error: 207 | # Object 'CUSTOMERS' does not exist or not authorized. 208 | # assert ( 209 | # "002003 (42S02): Catalog Error: Table with name customers does not exist!" 210 | # in str(excinfo.value) 211 | # ) 212 | 213 | with pytest.raises(snowflake.connector.errors.ProgrammingError) as excinfo: 214 | cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 215 | 216 | assert ( 217 | "090106 (22000): Cannot perform CREATE TABLE. This session does not have a current schema. Call 'USE SCHEMA', or use a qualified name." 218 | in str(excinfo.value) 219 | ) 220 | 221 | # test description works without schema 222 | assert cur.execute("SELECT 1").fetchall() == [(1,)] 223 | assert cur.description 224 | 225 | conn.execute_string("CREATE SCHEMA schema1; USE SCHEMA schema1;") 226 | assert conn.schema == "SCHEMA1" 227 | 228 | 229 | def test_connect_with_non_existent_db_or_schema(_fakesnow_no_auto_create: None): 230 | # can connect with db that doesn't exist 231 | with snowflake.connector.connect(database="marts") as conn, conn.cursor() as cur: 232 | # but no valid database set 233 | with pytest.raises(snowflake.connector.errors.ProgrammingError) as excinfo: 234 | cur.execute("create table foobar (i int)") 235 | 236 | assert ( 237 | "090105 (22000): Cannot perform CREATE TABLE. This session does not have a current database. Call 'USE DATABASE', or use a qualified name." 238 | in str(excinfo.value) 239 | ) 240 | 241 | # database still present on connection 242 | assert conn.database == "MARTS" 243 | 244 | cur.execute("CREATE database marts") 245 | 246 | # can connect with schema that doesn't exist 247 | with snowflake.connector.connect(database="marts", schema="jaffles") as conn, conn.cursor() as cur: 248 | # but no valid schema set 249 | with pytest.raises(snowflake.connector.errors.ProgrammingError) as excinfo: 250 | cur.execute("create table foobar (i int)") 251 | 252 | assert ( 253 | "090106 (22000): Cannot perform CREATE TABLE. This session does not have a current schema. Call 'USE SCHEMA', or use a qualified name." 254 | in str(excinfo.value) 255 | ) 256 | 257 | # schema still present on connection 258 | assert conn.schema == "JAFFLES" 259 | 260 | 261 | def test_current_database_schema(conn: snowflake.connector.SnowflakeConnection): 262 | with conn.cursor(snowflake.connector.cursor.DictCursor) as cur: 263 | cur.execute("select current_database(), current_schema()") 264 | 265 | assert cur.fetchall() == [ 266 | {"current_database()": "DB1", "current_schema()": "SCHEMA1"}, 267 | ] 268 | -------------------------------------------------------------------------------- /tests/test_converter.py: -------------------------------------------------------------------------------- 1 | # ruff: noqa: SLF001 2 | import datetime 3 | 4 | import snowflake.connector.converter 5 | 6 | from fakesnow.converter import from_binary, from_boolean, from_date, from_datetime, from_time 7 | 8 | converter = snowflake.connector.converter.SnowflakeConverter() 9 | date_converter = converter._DATE_to_python({}) 10 | 11 | 12 | def test_from_binary() -> None: 13 | value = b"Jenny" 14 | assert from_binary(converter._bytes_to_snowflake_bindings(..., value)) == value 15 | 16 | 17 | def test_from_boolean() -> None: 18 | value = True 19 | assert from_boolean(converter._bool_to_snowflake_bindings(..., value)) == value 20 | 21 | 22 | def test_from_date() -> None: 23 | value = datetime.date(2023, 1, 2) 24 | assert from_date(converter._date_to_snowflake_bindings(..., value)) == value 25 | 26 | 27 | def test_from_time() -> None: 28 | value = datetime.time(12, 30, 45, 123456) 29 | assert from_time(converter._time_to_snowflake_bindings(..., value)) == value 30 | 31 | 32 | def test_from_datetime() -> None: 33 | value = datetime.datetime(2023, 1, 2, 12, 30, 45, 123456, tzinfo=datetime.timezone.utc) 34 | assert from_datetime(converter._datetime_to_snowflake_bindings("TIMESTAMP_NTZ", value)) == value 35 | -------------------------------------------------------------------------------- /tests/test_cursor.py: -------------------------------------------------------------------------------- 1 | # ruff: noqa: E501 2 | # pyright: reportOptionalMemberAccess=false 3 | from __future__ import annotations 4 | 5 | import pandas as pd 6 | import pytest 7 | import snowflake.connector 8 | import snowflake.connector.cursor 9 | from dirty_equals import IsUUID 10 | from pandas.testing import assert_frame_equal 11 | from snowflake.connector.cursor import ResultMetadata 12 | 13 | 14 | def test_binding_pyformat(conn: snowflake.connector.SnowflakeConnection): 15 | # check pyformat is the default paramstyle 16 | assert snowflake.connector.paramstyle == "pyformat" 17 | with conn.cursor() as cur: 18 | cur.execute("create table customers (ID int, FIRST_NAME varchar, ACTIVE boolean)") 19 | cur.execute("insert into customers values (%s, %s, %s)", (1, "Jenny", True)) 20 | cur.execute( 21 | "insert into customers values (%(id)s, %(name)s, %(active)s)", {"id": 2, "name": "Jasper", "active": False} 22 | ) 23 | cur.execute("select * from customers") 24 | assert cur.fetchall() == [(1, "Jenny", True), (2, "Jasper", False)] 25 | 26 | 27 | def test_binding_qmark(_fakesnow: None): 28 | snowflake.connector.paramstyle = "qmark" 29 | 30 | with snowflake.connector.connect(database="db1", schema="schema1") as conn, conn.cursor() as cur: 31 | cur.execute("create table customers (ID int, FIRST_NAME varchar, ACTIVE boolean)") 32 | cur.execute("insert into customers values (?, ?, ?)", (1, "Jenny", True)) 33 | cur.execute("select * from customers") 34 | assert cur.fetchall() == [(1, "Jenny", True)] 35 | 36 | # this has no effect after connection created, so qmark style still works 37 | snowflake.connector.paramstyle = "pyformat" 38 | cur.execute("select * from customers where id = ?", (1,)) 39 | 40 | 41 | def test_binding_conn_kwarg(_fakesnow: None): 42 | assert snowflake.connector.paramstyle == "pyformat" 43 | 44 | with ( 45 | snowflake.connector.connect(database="db1", schema="schema1", paramstyle="qmark") as conn, 46 | conn.cursor() as cur, 47 | ): 48 | cur.execute("create table customers (ID int, FIRST_NAME varchar, ACTIVE boolean)") 49 | cur.execute("insert into customers values (?, ?, ?)", (1, "Jenny", True)) 50 | cur.execute("select * from customers") 51 | assert cur.fetchall() == [(1, "Jenny", True)] 52 | 53 | 54 | def test_executemany(cur: snowflake.connector.cursor.SnowflakeCursor): 55 | cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 56 | 57 | customers = [(1, "Jenny", "P"), (2, "Jasper", "M")] 58 | cur.executemany("insert into customers (id, first_name, last_name) values (%s,%s,%s)", customers) 59 | 60 | cur.execute("select id, first_name, last_name from customers") 61 | assert cur.fetchall() == customers 62 | 63 | 64 | def test_execute_string(conn: snowflake.connector.SnowflakeConnection): 65 | *_, cur = conn.execute_string( 66 | """ 67 | create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar); 68 | -- test comments are ignored 69 | select count(*) customers 70 | """ 71 | ) 72 | assert cur.fetchall() == [(1,)] 73 | 74 | 75 | def test_fetchall(conn: snowflake.connector.SnowflakeConnection): 76 | with conn.cursor() as cur: 77 | # no result set 78 | with pytest.raises(TypeError) as _: 79 | cur.fetchall() 80 | 81 | cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 82 | cur.execute("insert into customers values (1, 'Jenny', 'P')") 83 | cur.execute("insert into customers values (2, 'Jasper', 'M')") 84 | cur.execute("select id, first_name, last_name from customers") 85 | 86 | assert cur.fetchall() == [(1, "Jenny", "P"), (2, "Jasper", "M")] 87 | assert cur.fetchall() == [] 88 | 89 | with conn.cursor(snowflake.connector.cursor.DictCursor) as cur: 90 | cur.execute("select id, first_name, last_name from customers") 91 | 92 | assert cur.fetchall() == [ 93 | {"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"}, 94 | {"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"}, 95 | ] 96 | assert cur.fetchall() == [] 97 | 98 | 99 | def test_fetchone(conn: snowflake.connector.SnowflakeConnection): 100 | with conn.cursor() as cur: 101 | cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 102 | cur.execute("insert into customers values (1, 'Jenny', 'P')") 103 | cur.execute("insert into customers values (2, 'Jasper', 'M')") 104 | cur.execute("select id, first_name, last_name from customers") 105 | 106 | assert cur.fetchone() == (1, "Jenny", "P") 107 | assert cur.fetchone() == (2, "Jasper", "M") 108 | assert cur.fetchone() is None 109 | 110 | with conn.cursor(snowflake.connector.cursor.DictCursor) as cur: 111 | cur.execute("select id, first_name, last_name from customers") 112 | 113 | assert cur.fetchone() == {"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"} 114 | assert cur.fetchone() == {"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"} 115 | assert cur.fetchone() is None 116 | 117 | 118 | def test_fetchmany(conn: snowflake.connector.SnowflakeConnection): 119 | with conn.cursor() as cur: 120 | # no result set 121 | with pytest.raises(TypeError) as _: 122 | cur.fetchmany() 123 | 124 | cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 125 | cur.execute("insert into customers values (1, 'Jenny', 'P')") 126 | cur.execute("insert into customers values (2, 'Jasper', 'M')") 127 | cur.execute("insert into customers values (3, 'Jeremy', 'K')") 128 | cur.execute("select id, first_name, last_name from customers") 129 | 130 | # mimic jupysql fetchmany behaviour 131 | assert cur.fetchmany(2) == [(1, "Jenny", "P"), (2, "Jasper", "M")] 132 | assert cur.fetchmany(5) == [(3, "Jeremy", "K")] 133 | assert cur.fetchmany(5) == [] 134 | 135 | with conn.cursor(snowflake.connector.cursor.DictCursor) as cur: 136 | cur.execute("select id, first_name, last_name from customers") 137 | assert cur.fetchmany(2) == [ 138 | {"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"}, 139 | {"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"}, 140 | ] 141 | assert cur.fetchmany(5) == [ 142 | {"ID": 3, "FIRST_NAME": "Jeremy", "LAST_NAME": "K"}, 143 | ] 144 | assert cur.fetchmany(5) == [] 145 | 146 | 147 | def test_fetch_pandas_all(cur: snowflake.connector.cursor.SnowflakeCursor): 148 | # no result set 149 | with pytest.raises(snowflake.connector.NotSupportedError) as _: 150 | cur.fetch_pandas_all() 151 | 152 | cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 153 | cur.execute("insert into customers values (1, 'Jenny', 'P')") 154 | cur.execute("insert into customers values (2, 'Jasper', 'M')") 155 | cur.execute("select id, first_name, last_name from customers") 156 | 157 | expected_df = pd.DataFrame.from_records( 158 | [ 159 | {"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"}, 160 | {"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"}, 161 | ] 162 | ) 163 | # integers have dtype int64 (TODO: snowflake returns int8) 164 | assert_frame_equal(cur.fetch_pandas_all(), expected_df) 165 | 166 | # can refetch 167 | assert_frame_equal(cur.fetch_pandas_all(), expected_df) 168 | 169 | 170 | def test_get_result_batches(cur: snowflake.connector.cursor.SnowflakeCursor): 171 | # no result set 172 | assert cur.get_result_batches() is None 173 | 174 | cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 175 | cur.execute("insert into customers values (1, 'Jenny', 'P')") 176 | cur.execute("insert into customers values (2, 'Jasper', 'M')") 177 | cur.execute("select id, first_name, last_name from customers") 178 | batches = cur.get_result_batches() 179 | assert batches 180 | 181 | rows = [row for batch in batches for row in batch] 182 | assert rows == [(1, "Jenny", "P"), (2, "Jasper", "M")] 183 | assert sum(batch.rowcount for batch in batches) == 2 184 | 185 | 186 | def test_get_result_batches_dict(dcur: snowflake.connector.cursor.DictCursor): 187 | # no result set 188 | assert dcur.get_result_batches() is None 189 | 190 | dcur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 191 | dcur.execute("insert into customers values (1, 'Jenny', 'P')") 192 | dcur.execute("insert into customers values (2, 'Jasper', 'M')") 193 | dcur.execute("select id, first_name, last_name from customers") 194 | batches = dcur.get_result_batches() 195 | assert batches 196 | 197 | rows = [row for batch in batches for row in batch] 198 | assert rows == [ 199 | {"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"}, 200 | {"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"}, 201 | ] 202 | assert sum(batch.rowcount for batch in batches) == 2 203 | 204 | assert_frame_equal( 205 | batches[0].to_pandas(), 206 | pd.DataFrame.from_records( 207 | [ 208 | {"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"}, 209 | {"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"}, 210 | ] 211 | ), 212 | ) 213 | 214 | 215 | def test_sqlstate(cur: snowflake.connector.cursor.SnowflakeCursor): 216 | cur.execute("select 'hello world'") 217 | # sqlstate is None on success 218 | assert cur.sqlstate is None 219 | 220 | with pytest.raises(snowflake.connector.errors.ProgrammingError) as _: 221 | cur.execute("select * from this_table_does_not_exist") 222 | 223 | assert cur.sqlstate == "42S02" 224 | 225 | 226 | def test_sfqid(cur: snowflake.connector.cursor.SnowflakeCursor): 227 | assert not cur.sfqid 228 | cur.execute("select 1") 229 | assert cur.sfqid == IsUUID() 230 | 231 | 232 | def test_transactions(conn: snowflake.connector.SnowflakeConnection): 233 | # test behaviours required for sqlalchemy 234 | 235 | conn.execute_string( 236 | """CREATE OR REPLACE TABLE table1 (i int); 237 | BEGIN TRANSACTION; 238 | INSERT INTO table1 (i) VALUES (1);""" 239 | ) 240 | conn.rollback() 241 | conn.execute_string( 242 | """BEGIN TRANSACTION; 243 | INSERT INTO table1 (i) VALUES (2);""" 244 | ) 245 | 246 | # transactions are per session, cursors are just different result sets, 247 | # so a new cursor will see the uncommitted values 248 | with conn.cursor() as cur: 249 | cur.execute("select * from table1") 250 | assert cur.fetchall() == [(2,)] 251 | 252 | conn.commit() 253 | 254 | with conn.cursor() as cur: 255 | # interleaved commit() doesn't lose result set because its on a different cursor 256 | cur.execute("select * from table1") 257 | conn.commit() 258 | assert cur.fetchall() == [(2,)] 259 | 260 | # check rollback and commit without transaction is a success (to mimic snowflake) 261 | # also check description can be retrieved, needed for ipython-sql/jupysql which runs description implicitly 262 | with conn.cursor() as cur: 263 | cur.execute("COMMIT") 264 | assert cur.description == [ResultMetadata(name='status', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True)] # fmt: skip 265 | assert cur.fetchall() == [("Statement executed successfully.",)] 266 | 267 | cur.execute("ROLLBACK") 268 | assert cur.description == [ResultMetadata(name='status', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True)] # fmt: skip 269 | assert cur.fetchall() == [("Statement executed successfully.",)] 270 | -------------------------------------------------------------------------------- /tests/test_expr.py: -------------------------------------------------------------------------------- 1 | import sqlglot 2 | from sqlglot import exp 3 | 4 | import fakesnow.expr as expr 5 | 6 | 7 | def parse(s: str) -> exp.Expression: 8 | return sqlglot.parse_one(s, read="snowflake") 9 | 10 | 11 | def test_key_command_create() -> None: 12 | assert expr.key_command(parse("drop schema foobar")) == "DROP SCHEMA" 13 | assert expr.key_command(parse("create table customers(id int)")) == "CREATE TABLE" 14 | 15 | 16 | def test_key_command_use() -> None: 17 | assert expr.key_command(parse("use database foobar")) == "USE DATABASE" 18 | assert expr.key_command(parse("use schema foobar")) == "USE SCHEMA" 19 | 20 | 21 | def test_key_command_set() -> None: 22 | assert expr.key_command(parse("set schema = 'foobar'")) == "SET" 23 | 24 | 25 | def test_key_command_select() -> None: 26 | assert expr.key_command(parse("select * from foobar")) == "SELECT" 27 | -------------------------------------------------------------------------------- /tests/test_flatten.py: -------------------------------------------------------------------------------- 1 | # ruff: noqa: E501 2 | 3 | from __future__ import annotations 4 | 5 | import snowflake.connector 6 | import snowflake.connector.cursor 7 | import sqlglot 8 | 9 | from fakesnow.transforms import flatten 10 | from tests.matchers import IsResultMetadata 11 | from tests.utils import strip 12 | 13 | 14 | def test_transform_lateral_flatten() -> None: 15 | # sqlglot introduces the identifiers SEQ, KEY, PATH, INDEX, VALUE, THIS 16 | # for lineage tracking see https://github.com/tobymao/sqlglot/pull/2417 17 | expected = strip("SELECT * FROM _FS_FLATTEN([1, 2]) AS F(SEQ, KEY, PATH, INDEX, VALUE, THIS)") 18 | 19 | assert ( 20 | sqlglot.parse_one( 21 | "SELECT * FROM LATERAL FLATTEN(input => [1,2]) AS F", 22 | read="snowflake", 23 | ) 24 | .transform(flatten) 25 | .sql(dialect="duckdb") 26 | == expected 27 | ) 28 | 29 | 30 | def test_transform_table_flatten() -> None: 31 | # table flatten is the same as lateral flatten 32 | # except sqlglot doesn't add identifiers for lineage tracking 33 | expected = strip("SELECT * FROM _FS_FLATTEN([1, 2]) AS F") 34 | 35 | assert ( 36 | sqlglot.parse_one( 37 | "SELECT * FROM TABLE(FLATTEN(input => [1,2])) AS F", 38 | read="snowflake", 39 | ) 40 | .transform(flatten) 41 | .sql(dialect="duckdb") 42 | == expected 43 | ) 44 | 45 | # position arg (no input =>) 46 | assert ( 47 | sqlglot.parse_one( 48 | "SELECT * FROM TABLE(FLATTEN([1,2])) AS F", 49 | read="snowflake", 50 | ) 51 | .transform(flatten) 52 | .sql(dialect="duckdb") 53 | == expected 54 | ) 55 | 56 | 57 | def test_flatten_alias_none(cur: snowflake.connector.cursor.SnowflakeCursor) -> None: 58 | sql = "SELECT * FROM table(flatten([1, 2]))" 59 | assert sqlglot.parse_one( 60 | sql, 61 | read="snowflake", 62 | ).transform(flatten).sql(dialect="duckdb") == strip("SELECT * FROM _FS_FLATTEN([1, 2])") 63 | cur.execute(sql) 64 | # check order, names and types of cols 65 | assert cur.description == [ 66 | IsResultMetadata(name="SEQ", type_code=0), 67 | IsResultMetadata(name="KEY", type_code=2), 68 | IsResultMetadata(name="PATH", type_code=2), 69 | IsResultMetadata(name="INDEX", type_code=0), 70 | IsResultMetadata(name="VALUE", type_code=5), 71 | IsResultMetadata(name="THIS", type_code=5), 72 | ] 73 | 74 | 75 | def test_flatten_alias_rename(cur: snowflake.connector.cursor.SnowflakeCursor) -> None: 76 | sql = "SELECT * FROM table(flatten([1, 2])) as rename (a, b, c)" 77 | assert sqlglot.parse_one( 78 | sql, 79 | read="snowflake", 80 | ).transform(flatten).sql(dialect="duckdb") == strip("SELECT * FROM _FS_FLATTEN([1, 2]) AS rename(a, b, c)") 81 | cur.execute(sql) 82 | assert [d.name for d in cur.description] == ["A", "B", "C", "INDEX", "VALUE", "THIS"] 83 | 84 | 85 | def test_flatten_json(cur: snowflake.connector.cursor.SnowflakeCursor): 86 | cur.execute( 87 | """ 88 | select t.id, flat.value:fruit from 89 | ( 90 | select 1, parse_json('[{"fruit":"banana"}]') 91 | union 92 | select 2, parse_json('[{"fruit":"coconut"}, {"fruit":"durian"}]') 93 | ) as t(id, fruits), lateral flatten(input => t.fruits) AS flat 94 | order by id 95 | """ 96 | # duckdb lateral join order is non-deterministic so order by id 97 | # within an id the order of fruits should match the json array 98 | ) 99 | assert cur.fetchall() == [(1, '"banana"'), (2, '"coconut"'), (2, '"durian"')] 100 | 101 | 102 | def test_flatten_index(cur: snowflake.connector.cursor.SnowflakeCursor): 103 | cur.execute(""" 104 | select id, f.value::varchar as v, f.index as i 105 | from (select column1 as id, column2 as col from (values (1, 's1,s3,s2'), (2, 's2,s1'))) as t 106 | , lateral flatten(input => split(t.col, ',')) as f order by id; 107 | """) 108 | 109 | assert cur.fetchall() == [(1, "s1", 0), (1, "s3", 1), (1, "s2", 2), (2, "s2", 0), (2, "s1", 1)] 110 | 111 | 112 | def test_flatten_value_cast_as_varchar(cur: snowflake.connector.cursor.SnowflakeCursor): 113 | cur.execute("SELECT VALUE::VARCHAR FROM LATERAL FLATTEN(input => ['a','b'])") 114 | # should be raw string not json string with double quotes 115 | assert cur.fetchall() == [("a",), ("b",)] 116 | -------------------------------------------------------------------------------- /tests/test_info_schema.py: -------------------------------------------------------------------------------- 1 | # ruff: noqa: E501 2 | 3 | from datetime import datetime 4 | 5 | import pytz 6 | import snowflake.connector.cursor 7 | from snowflake.connector.cursor import ResultMetadata 8 | 9 | 10 | def test_info_schema_table_comments(cur: snowflake.connector.cursor.SnowflakeCursor): 11 | def read_comment() -> str: 12 | cur.execute( 13 | """SELECT COALESCE(COMMENT, '') FROM INFORMATION_SCHEMA.TABLES 14 | WHERE TABLE_NAME = 'INGREDIENTS' AND TABLE_SCHEMA = 'SCHEMA1' LIMIT 1""" 15 | ) 16 | return cur.fetchall()[0][0] 17 | 18 | cur.execute("CREATE TABLE ingredients (id int) COMMENT = 'cheese'") 19 | assert read_comment() == "cheese" 20 | cur.execute("COMMENT ON TABLE ingredients IS 'pepperoni'") 21 | assert read_comment() == "pepperoni" 22 | cur.execute("COMMENT IF EXISTS ON TABLE schema1.ingredients IS 'mushrooms'") 23 | assert read_comment() == "mushrooms" 24 | cur.execute("ALTER TABLE ingredients SET comment = 'pineapple'") 25 | assert read_comment() == "pineapple" 26 | 27 | 28 | def test_info_schema_columns_describe(cur: snowflake.connector.cursor.SnowflakeCursor): 29 | # test we can handle the column types returned from the info schema, which are created by duckdb 30 | # and so don't go through our transforms 31 | cur.execute("select column_name, ordinal_position from information_schema.columns") 32 | # fmt: off 33 | expected_metadata = [ 34 | ResultMetadata(name='column_name', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 35 | ResultMetadata(name='ordinal_position', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True) 36 | ] 37 | # fmt: on 38 | 39 | assert cur.description == expected_metadata 40 | 41 | 42 | def test_describe_view_columns(dcur: snowflake.connector.cursor.DictCursor): 43 | cols = [ 44 | "name", 45 | "type", 46 | "kind", 47 | "null?", 48 | "default", 49 | "primary key", 50 | "unique key", 51 | "check", 52 | "expression", 53 | "comment", 54 | "policy name", 55 | "privacy domain", 56 | ] 57 | dcur.execute("describe view information_schema.columns") 58 | result: list[dict] = dcur.fetchall() # type: ignore 59 | assert list(result[0].keys()) == cols 60 | names = [r["name"] for r in result] 61 | # should contain snowflake-specific columns 62 | assert "comment" in names 63 | # fmt: off 64 | assert dcur.description[:-1] == [ 65 | ResultMetadata(name='name', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 66 | ResultMetadata(name='type', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 67 | ResultMetadata(name='kind', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 68 | ResultMetadata(name='null?', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 69 | ResultMetadata(name='default', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 70 | ResultMetadata(name='primary key', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 71 | ResultMetadata(name='unique key', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 72 | ResultMetadata(name='check', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 73 | ResultMetadata(name='expression', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 74 | ResultMetadata(name='comment', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 75 | ResultMetadata(name='policy name', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True), 76 | # TODO: return correct type_code, see https://github.com/tekumara/fakesnow/issues/26 77 | # ResultMetadata(name='privacy domain', type_code=9, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True) 78 | ] 79 | # fmt: on 80 | 81 | 82 | def test_info_schema_columns(conn: snowflake.connector.SnowflakeConnection): 83 | with conn.cursor(snowflake.connector.cursor.DictCursor) as cur: 84 | cur.execute("CREATE TABLE foo (id INTEGER, name VARCHAR)") 85 | cur.execute("CREATE DATABASE db2") 86 | # should not be returned 87 | cur.execute("CREATE SCHEMA db2.schema2") 88 | cur.execute("CREATE TABLE db2.schema2.bar (id INTEGER)") 89 | 90 | cur.execute( 91 | "SELECT table_catalog, table_schema, table_name, column_name FROM information_schema.columns where column_name = 'ID'" 92 | ) 93 | 94 | assert cur.fetchall() == [ 95 | { 96 | "table_catalog": "DB1", 97 | "table_schema": "SCHEMA1", 98 | "table_name": "FOO", 99 | "column_name": "ID", 100 | } 101 | ] 102 | 103 | 104 | def test_info_schema_columns_numeric(cur: snowflake.connector.cursor.SnowflakeCursor): 105 | # see https://docs.snowflake.com/en/sql-reference/data-types-numeric 106 | cur.execute( 107 | """ 108 | create or replace table example ( 109 | XBOOLEAN BOOLEAN, XDOUBLE DOUBLE, XFLOAT FLOAT, XNUMBER82 NUMBER(8,2), XNUMBER NUMBER, XDECIMAL DECIMAL, XNUMERIC NUMERIC, 110 | XINT INT, XINTEGER INTEGER, XBIGINT BIGINT, XSMALLINT SMALLINT, XTINYINT TINYINT, XBYTEINT BYTEINT 111 | ) 112 | """ 113 | ) 114 | 115 | cur.execute( 116 | """ 117 | select column_name,data_type,numeric_precision,numeric_precision_radix,numeric_scale 118 | from information_schema.columns where table_name = 'EXAMPLE' order by ordinal_position 119 | """ 120 | ) 121 | 122 | assert cur.fetchall() == [ 123 | ("XBOOLEAN", "BOOLEAN", None, None, None), 124 | ("XDOUBLE", "FLOAT", None, None, None), 125 | ("XFLOAT", "FLOAT", None, None, None), 126 | ("XNUMBER82", "NUMBER", 8, 10, 2), 127 | ("XNUMBER", "NUMBER", 38, 10, 0), 128 | ("XDECIMAL", "NUMBER", 38, 10, 0), 129 | ("XNUMERIC", "NUMBER", 38, 10, 0), 130 | ("XINT", "NUMBER", 38, 10, 0), 131 | ("XINTEGER", "NUMBER", 38, 10, 0), 132 | ("XBIGINT", "NUMBER", 38, 10, 0), 133 | ("XSMALLINT", "NUMBER", 38, 10, 0), 134 | ("XTINYINT", "NUMBER", 38, 10, 0), 135 | ("XBYTEINT", "NUMBER", 38, 10, 0), 136 | ] 137 | 138 | 139 | def test_info_schema_columns_other(cur: snowflake.connector.cursor.SnowflakeCursor): 140 | # see https://docs.snowflake.com/en/sql-reference/data-types-datetime 141 | cur.execute( 142 | """ 143 | create or replace table example ( 144 | XTIMESTAMP TIMESTAMP, XTIMESTAMP_NTZ TIMESTAMP_NTZ, XTIMESTAMP_NTZ9 TIMESTAMP_NTZ(9), XTIMESTAMP_TZ TIMESTAMP_TZ, XDATE DATE, XTIME TIME, 145 | XBINARY BINARY, /* XARRAY ARRAY, XOBJECT OBJECT */ XVARIANT VARIANT 146 | ) 147 | """ 148 | ) 149 | 150 | cur.execute( 151 | """ 152 | select column_name,data_type 153 | from information_schema.columns where table_name = 'EXAMPLE' order by ordinal_position 154 | """ 155 | ) 156 | 157 | assert cur.fetchall() == [ 158 | ("XTIMESTAMP", "TIMESTAMP_NTZ"), 159 | ("XTIMESTAMP_NTZ", "TIMESTAMP_NTZ"), 160 | ("XTIMESTAMP_NTZ9", "TIMESTAMP_NTZ"), 161 | ("XTIMESTAMP_TZ", "TIMESTAMP_TZ"), 162 | ("XDATE", "DATE"), 163 | ("XTIME", "TIME"), 164 | ("XBINARY", "BINARY"), 165 | # TODO: support these types https://github.com/tekumara/fakesnow/issues/27 166 | # ("XARRAY", "ARRAY"), 167 | # ("XOBJECT", "OBJECT"), 168 | ("XVARIANT", "VARIANT"), 169 | ] 170 | 171 | 172 | def test_info_schema_columns_text(cur: snowflake.connector.cursor.SnowflakeCursor): 173 | # see https://docs.snowflake.com/en/sql-reference/data-types-text 174 | cur.execute( 175 | """ 176 | create or replace table example ( 177 | XVARCHAR20 VARCHAR(20), XVARCHAR VARCHAR, XTEXT TEXT 178 | ) 179 | """ 180 | ) 181 | 182 | cur.execute( 183 | """ 184 | select column_name,data_type,character_maximum_length,character_octet_length 185 | from information_schema.columns where table_name = 'EXAMPLE' order by ordinal_position 186 | """ 187 | ) 188 | 189 | assert cur.fetchall() == [ 190 | ("XVARCHAR20", "TEXT", 20, 80), 191 | ("XVARCHAR", "TEXT", 16777216, 16777216), 192 | ("XTEXT", "TEXT", 16777216, 16777216), 193 | ] 194 | 195 | 196 | def test_info_schema_databases(conn: snowflake.connector.SnowflakeConnection): 197 | # see https://docs.snowflake.com/en/sql-reference/info-schema/databases 198 | 199 | with conn.cursor(snowflake.connector.cursor.DictCursor) as cur: 200 | cur.execute("create database db2") 201 | cur.execute("select * from information_schema.databases") 202 | 203 | assert cur.fetchall() == [ 204 | { 205 | "database_name": "DB1", 206 | "database_owner": "SYSADMIN", 207 | "is_transient": "NO", 208 | "comment": None, 209 | "created": datetime(1970, 1, 1, 0, 0, tzinfo=pytz.utc), 210 | "last_altered": datetime(1970, 1, 1, 0, 0, tzinfo=pytz.utc), 211 | "retention_time": 1, 212 | "type": "STANDARD", 213 | }, 214 | { 215 | "database_name": "DB2", 216 | "database_owner": "SYSADMIN", 217 | "is_transient": "NO", 218 | "comment": None, 219 | "created": datetime(1970, 1, 1, 0, 0, tzinfo=pytz.utc), 220 | "last_altered": datetime(1970, 1, 1, 0, 0, tzinfo=pytz.utc), 221 | "retention_time": 1, 222 | "type": "STANDARD", 223 | }, 224 | ] 225 | 226 | 227 | def test_info_schema_tables(conn: snowflake.connector.SnowflakeConnection): 228 | with conn.cursor(snowflake.connector.cursor.DictCursor) as cur: 229 | cur.execute("CREATE TABLE foo (id INTEGER)") 230 | cur.execute("CREATE DATABASE db2") 231 | # should not be returned 232 | cur.execute("CREATE SCHEMA db2.schema2") 233 | cur.execute("CREATE TABLE db2.schema2.bar (name VARCHAR)") 234 | 235 | cur.execute("SELECT table_catalog, table_schema, table_name FROM information_schema.tables") 236 | 237 | assert cur.fetchall() == [ 238 | { 239 | "table_catalog": "DB1", 240 | "table_schema": "SCHEMA1", 241 | "table_name": "FOO", 242 | } 243 | ] 244 | 245 | 246 | def test_info_schema_views_empty(cur: snowflake.connector.cursor.SnowflakeCursor): 247 | result = cur.execute("SELECT * FROM information_schema.views") 248 | assert result 249 | assert result.fetchall() == [] 250 | 251 | 252 | def test_info_schema_views(conn: snowflake.connector.SnowflakeConnection): 253 | with conn.cursor(snowflake.connector.cursor.DictCursor) as cur: 254 | cur.execute("CREATE TABLE foo (id INTEGER, name VARCHAR)") 255 | cur.execute("CREATE VIEW bar AS SELECT * FROM foo WHERE id > 5") 256 | cur.execute("CREATE DATABASE db2") 257 | # should not be returned 258 | cur.execute("CREATE SCHEMA db2.schema2") 259 | cur.execute("CREATE TABLE db2.schema2.foo (id INTEGER, name VARCHAR)") 260 | cur.execute("CREATE VIEW db2.schema2.baz AS SELECT * FROM db2.schema2.foo WHERE id > 5") 261 | 262 | cur.execute("SELECT * FROM information_schema.views") 263 | 264 | assert cur.fetchall() == [ 265 | { 266 | "table_catalog": "DB1", 267 | "table_schema": "SCHEMA1", 268 | "table_name": "BAR", 269 | "table_owner": "SYSADMIN", 270 | "view_definition": "CREATE VIEW SCHEMA1.BAR AS SELECT * FROM FOO WHERE (ID > 5);", 271 | "check_option": "NONE", 272 | "is_updatable": "NO", 273 | "insertable_into": "NO", 274 | "is_secure": "NO", 275 | "created": datetime(1970, 1, 1, tzinfo=pytz.utc), 276 | "last_altered": datetime(1970, 1, 1, tzinfo=pytz.utc), 277 | "last_ddl": datetime(1970, 1, 1, tzinfo=pytz.utc), 278 | "last_ddl_by": "SYSADMIN", 279 | "comment": None, 280 | } 281 | ] 282 | 283 | 284 | def test_type_column_is_not_null(cur: snowflake.connector.cursor.SnowflakeCursor) -> None: 285 | for table in [ 286 | "information_schema.databases", 287 | "information_schema.views", 288 | "information_schema.columns", 289 | ]: 290 | cur.execute(f"DESCRIBE VIEW {table}") 291 | result = cur.fetchall() 292 | data_types = [dt for (_, dt, *_) in result] 293 | nulls = [dt for dt in data_types if "NULL" in dt] 294 | assert not nulls 295 | -------------------------------------------------------------------------------- /tests/test_matchers.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from snowflake.connector.cursor import ResultMetadata 3 | 4 | from tests.matchers import IsResultMetadata 5 | 6 | 7 | def test_is_result_metadata_with_partial_match(): 8 | metadata = ResultMetadata( 9 | name="COL1", type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True 10 | ) 11 | 12 | assert metadata == IsResultMetadata(name="COL1", type_code=0) 13 | assert metadata == IsResultMetadata(type_code=0, precision=38, scale=0) 14 | 15 | 16 | def test_is_result_metadata_with_non_match(): 17 | metadata = ResultMetadata( 18 | name="COL1", type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True 19 | ) 20 | 21 | assert metadata != IsResultMetadata(name="DIFFERENT", type_code=0) 22 | assert metadata != IsResultMetadata(name="COL1", type_code=2) 23 | 24 | 25 | def test_repr(): 26 | metadata = ResultMetadata( 27 | name="COL1", type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True 28 | ) 29 | 30 | matcher = IsResultMetadata(name="DIFFERENT", type_code=5) 31 | 32 | with pytest.raises(AssertionError): 33 | assert metadata == matcher 34 | 35 | assert repr(matcher) == "IsResultMetadata(name='DIFFERENT', type_code=5)" 36 | 37 | 38 | def test_is_result_metadata_with_non_result_metadata(): 39 | matcher = IsResultMetadata(name="COL1", type_code=2) 40 | assert ("COL1", 2) != matcher # noqa: SIM300 41 | -------------------------------------------------------------------------------- /tests/test_patch.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import MagicMock 2 | 3 | import pytest 4 | import snowflake.connector 5 | import snowflake.connector.pandas_tools 6 | from snowflake.connector import connect 7 | from snowflake.connector.pandas_tools import write_pandas 8 | 9 | import fakesnow 10 | 11 | 12 | def test_patch_nop_regexes(): 13 | with fakesnow.patch(nop_regexes=["^CALL.*"]), snowflake.connector.connect() as conn, conn.cursor() as cur: 14 | cur.execute("call this_procedure_does_not_exist('foo', 'bar);") 15 | assert cur.fetchall() == [("Statement executed successfully.",)] 16 | 17 | 18 | def test_patch_snowflake_connector_connect(_fakesnow_no_auto_create: None) -> None: 19 | assert isinstance(snowflake.connector.connect, MagicMock), "snowflake.connector.connect is not mocked" 20 | 21 | 22 | def test_patch_snowflake_connector_pandas_tools_write_pandas(_fakesnow_no_auto_create: None) -> None: 23 | assert isinstance(snowflake.connector.pandas_tools.write_pandas, MagicMock), ( 24 | "snowflake.connector.pandas_tools.write_pandas is not mocked" 25 | ) 26 | 27 | 28 | def test_patch_this_modules_connect() -> None: 29 | with fakesnow.patch(f"{__name__}.connect"): 30 | assert isinstance(connect, MagicMock), "connect is not mocked" 31 | 32 | 33 | def test_patch_this_modules_write_pandas() -> None: 34 | with fakesnow.patch(f"{__name__}.write_pandas"): 35 | assert isinstance(write_pandas, MagicMock), "write_pandas is not mocked" 36 | 37 | 38 | def test_patch_other_unloaded_module() -> None: 39 | with fakesnow.patch("tests.patch_other.connect"): 40 | import tests.patch_other 41 | 42 | assert isinstance(tests.patch_other.connect, MagicMock), "tests.patch_other.connect is not mocked" 43 | 44 | 45 | def test_cannot_patch_twice(_fakesnow_no_auto_create: None) -> None: 46 | # _fakesnow is the first patch 47 | 48 | with pytest.raises(AssertionError) as excinfo: # noqa: SIM117 49 | # second patch will fail 50 | with fakesnow.patch(): 51 | pass 52 | 53 | assert "Snowflake connector is already patched" in str(excinfo.value) 54 | -------------------------------------------------------------------------------- /tests/test_semis.py: -------------------------------------------------------------------------------- 1 | # ruff: noqa: E501 2 | 3 | from __future__ import annotations 4 | 5 | import json 6 | 7 | import snowflake.connector 8 | import snowflake.connector.cursor 9 | 10 | from tests.utils import dindent, indent 11 | 12 | 13 | def test_get_path_as_varchar(cur: snowflake.connector.cursor.SnowflakeCursor): 14 | cur.execute("""select parse_json('{"fruit":"banana"}'):fruit""") 15 | assert cur.fetchall() == [('"banana"',)] 16 | 17 | # converting json to varchar returns unquoted string 18 | cur.execute("""select parse_json('{"fruit":"banana"}'):fruit::varchar""") 19 | assert cur.fetchall() == [("banana",)] 20 | 21 | # nested json 22 | cur.execute("""select get_path(parse_json('{"food":{"fruit":"banana"}}'), 'food.fruit')::varchar""") 23 | assert cur.fetchall() == [("banana",)] 24 | 25 | cur.execute("""select parse_json('{"food":{"fruit":"banana"}}'):food.fruit::varchar""") 26 | assert cur.fetchall() == [("banana",)] 27 | 28 | cur.execute("""select parse_json('{"food":{"fruit":"banana"}}'):food:fruit::varchar""") 29 | assert cur.fetchall() == [("banana",)] 30 | 31 | # json number is varchar 32 | cur.execute("""select parse_json('{"count":42}'):count""") 33 | assert cur.fetchall() == [("42",)] 34 | 35 | # lower/upper converts to varchar (ie: no quotes) ¯\_(ツ)_/¯ 36 | cur.execute("""select upper(parse_json('{"fruit":"banana"}'):fruit)""") 37 | assert cur.fetchall() == [("BANANA",)] 38 | 39 | cur.execute("""select lower(parse_json('{"fruit":"banana"}'):fruit)""") 40 | assert cur.fetchall() == [("banana",)] 41 | 42 | # lower/upper converts json number to varchar too 43 | cur.execute("""select upper(parse_json('{"count":"42"}'):count)""") 44 | assert cur.fetchall() == [("42",)] 45 | 46 | 47 | def test_get_path_as_number(dcur: snowflake.connector.cursor.SnowflakeCursor): 48 | dcur.execute("CREATE TABLE example (j VARIANT)") 49 | dcur.execute("""INSERT INTO example SELECT PARSE_JSON('{"str": "100", "num" : 200}')""") 50 | 51 | dcur.execute("SELECT j:str::varchar as j_str_varchar, j:num::varchar as j_num_varchar FROM example") 52 | assert dcur.fetchall() == [{"J_STR_VARCHAR": "100", "J_NUM_VARCHAR": "200"}] 53 | 54 | dcur.execute("SELECT j:str::number as j_str_number, j:num::number as j_num_number FROM example") 55 | assert dcur.fetchall() == [{"J_STR_NUMBER": 100, "J_NUM_NUMBER": 200}] 56 | 57 | 58 | def test_get_path_precedence(cur: snowflake.connector.cursor.SnowflakeCursor): 59 | cur.execute("select {'K1': {'K2': 1}} as col where col:K1:K2 > 0") 60 | assert indent(cur.fetchall()) == [('{\n "K1": {\n "K2": 1\n }\n}',)] 61 | 62 | cur.execute( 63 | """select parse_json('{"K1": "a", "K2": "b"}') as col, case when col:K1::VARCHAR = 'a' and col:K2::VARCHAR = 'b' then 'yes' end""" 64 | ) 65 | assert indent(cur.fetchall()) == [('{\n "K1": "a",\n "K2": "b"\n}', "yes")] 66 | 67 | 68 | def test_indices_cast_as_varchar(cur: snowflake.connector.cursor.SnowflakeCursor): 69 | cur.execute("""select parse_json('["banana", "coconut"]')[0]::varchar""") 70 | assert cur.fetchall() == [("banana",)] 71 | 72 | 73 | def test_object_construct(conn: snowflake.connector.SnowflakeConnection): 74 | with conn.cursor() as cur: 75 | cur.execute("SELECT OBJECT_CONSTRUCT('a',1,'b','BBBB', 'c',null)") 76 | 77 | # TODO: strip null within duckdb via python UDF 78 | def strip_none_values(d: dict) -> dict: 79 | return {k: v for k, v in d.items() if v} 80 | 81 | result = cur.fetchone() 82 | assert isinstance(result, tuple) 83 | assert strip_none_values(json.loads(result[0])) == json.loads('{\n "a": 1,\n "b": "BBBB"\n}') 84 | 85 | with conn.cursor() as cur: 86 | cur.execute("SELECT OBJECT_CONSTRUCT('a', 1, null, 'nulkeyed') as col") 87 | 88 | result = cur.fetchone() 89 | assert isinstance(result, tuple) 90 | assert strip_none_values(json.loads(result[0])) == json.loads('{\n "a": 1\n}') 91 | 92 | with conn.cursor() as cur: 93 | cur.execute( 94 | "SELECT NULL as col, OBJECT_CONSTRUCT( 'k1', 'v1', 'k2', CASE WHEN ZEROIFNULL(col) + 1 >= 2 THEN 'v2' ELSE NULL END, 'k3', 'v3')" 95 | ) 96 | 97 | result = cur.fetchone() 98 | assert isinstance(result, tuple) 99 | assert strip_none_values(json.loads(result[1])) == json.loads('{\n "k1": "v1",\n "k3": "v3"\n}') 100 | 101 | with conn.cursor() as cur: 102 | cur.execute( 103 | "SELECT 1 as col, OBJECT_CONSTRUCT( 'k1', 'v1', 'k2', CASE WHEN ZEROIFNULL(col) + 1 >= 2 THEN 'v2' ELSE NULL END, 'k3', 'v3')" 104 | ) 105 | 106 | result = cur.fetchone() 107 | assert isinstance(result, tuple) 108 | assert strip_none_values(json.loads(result[1])) == json.loads( 109 | '{\n "k1": "v1",\n "k2": "v2",\n "k3": "v3"\n}' 110 | ) 111 | 112 | 113 | def test_semi_structured_types(cur: snowflake.connector.cursor.SnowflakeCursor): 114 | cur.execute("create or replace table semis (emails array, names object, notes variant)") 115 | cur.execute( 116 | """insert into semis(emails, names, notes) SELECT ['A', 'B'], OBJECT_CONSTRUCT('k','v1'), ARRAY_CONSTRUCT('foo')::VARIANT""" 117 | ) 118 | cur.execute( 119 | """insert into semis(emails, names, notes) SELECT ['C','D'], parse_json('{"k": "v2"}'), parse_json('{"b": "ar"}')""" 120 | ) 121 | 122 | # results are returned as strings, because the underlying type is JSON (duckdb) / VARIANT (snowflake) 123 | 124 | cur.execute("select emails from semis") 125 | assert indent(cur.fetchall()) == [('[\n "A",\n "B"\n]',), ('[\n "C",\n "D"\n]',)] 126 | 127 | cur.execute("select emails[0] from semis") 128 | assert cur.fetchall() == [('"A"',), ('"C"',)] 129 | 130 | cur.execute("select names['k'] from semis") 131 | assert cur.fetchall() == [('"v1"',), ('"v2"',)] 132 | 133 | cur.execute("select notes[0] from semis") 134 | assert cur.fetchall() == [('"foo"',), (None,)] 135 | 136 | cur.execute( 137 | """ 138 | SELECT OBJECT_CONSTRUCT('key_1', 'one', 'key_2', NULL) AS WITHOUT_KEEP_NULL, 139 | OBJECT_CONSTRUCT_KEEP_NULL('key_1', 'one', 'key_2', NULL) AS KEEP_NULL_1, 140 | OBJECT_CONSTRUCT_KEEP_NULL('key_1', 'one', NULL, 'two') AS KEEP_NULL_2 141 | """ 142 | ) 143 | assert indent(cur.fetchall()) == [ 144 | ('{\n "key_1": "one"\n}', '{\n "key_1": "one",\n "key_2": null\n}', '{\n "key_1": "one"\n}') 145 | ] 146 | 147 | 148 | def test_try_parse_json(dcur: snowflake.connector.cursor.DictCursor): 149 | dcur.execute("""SELECT TRY_PARSE_JSON('{"first":"foo", "last":"bar"}') AS j""") 150 | assert dindent(dcur.fetchall()) == [{"J": '{\n "first": "foo",\n "last": "bar"\n}'}] 151 | 152 | dcur.execute("""SELECT TRY_PARSE_JSON('{invalid: ,]') AS j""") 153 | assert dcur.fetchall() == [{"J": None}] 154 | -------------------------------------------------------------------------------- /tests/test_sqlalchemy.py: -------------------------------------------------------------------------------- 1 | from typing import cast 2 | 3 | from sqlalchemy import Column, MetaData, Table, types 4 | from sqlalchemy.engine import Engine 5 | from sqlalchemy.sql.expression import TextClause 6 | 7 | 8 | def test_engine(snowflake_engine: Engine): 9 | # verifies cursor.description, commit, and rollback issued by SQLAlchemy 10 | with snowflake_engine.connect() as conn: 11 | conn.execute(TextClause("CREATE VIEW foo AS SELECT * FROM information_schema.databases")) 12 | 13 | result = conn.execute(TextClause("SELECT database_name FROM foo")) 14 | assert result 15 | assert result.fetchall() == [("DB1",)] 16 | 17 | 18 | def test_metadata_create_all(snowflake_engine: Engine): 19 | metadata = MetaData() 20 | 21 | table = cast(Table, Table("foo", metadata, Column(types.Integer, name="id"), Column(types.String, name="name"))) 22 | metadata.create_all(bind=snowflake_engine) 23 | 24 | with snowflake_engine.connect() as conn: 25 | result = conn.execute(table.select()) 26 | assert result 27 | assert result.fetchall() == [] 28 | 29 | 30 | def test_reflect(snowflake_engine: Engine): 31 | with snowflake_engine.connect() as conn: 32 | conn.execute(TextClause("CREATE TABLE foo (id INTEGER, name VARCHAR)")) 33 | 34 | metadata = MetaData() 35 | metadata.reflect(bind=snowflake_engine, only=["foo"]) 36 | 37 | assert metadata.tables 38 | foo_table: Table = metadata.tables["foo"] 39 | 40 | with snowflake_engine.connect() as conn: 41 | result = conn.execute(foo_table.insert().values(id=1, name="one")) 42 | 43 | result = conn.execute(foo_table.select()) 44 | 45 | assert result 46 | assert result.fetchall() == [(1, "one")] 47 | -------------------------------------------------------------------------------- /tests/test_stage.py: -------------------------------------------------------------------------------- 1 | from datetime import timezone 2 | 3 | import snowflake.connector.cursor 4 | from dirty_equals import IsNow 5 | 6 | 7 | def test_create_stage(dcur: snowflake.connector.cursor.SnowflakeCursor): 8 | dcur.execute("CREATE DATABASE db2") 9 | dcur.execute("CREATE SCHEMA db2.schema2") 10 | dcur.execute("CREATE SCHEMA schema3") 11 | 12 | dcur.execute("CREATE STAGE stage1") 13 | assert dcur.fetchall() == [{"status": "Stage area STAGE1 successfully created."}] 14 | 15 | dcur.execute("CREATE TEMP STAGE db2.schema2.stage2") 16 | dcur.execute("CREATE STAGE schema3.stage3 URL='s3://bucket/path/'") 17 | # lowercase url 18 | dcur.execute("CREATE TEMP STAGE stage4 url='s3://bucket/path/'") 19 | 20 | common_fields = { 21 | "created_on": IsNow(tz=timezone.utc), 22 | "has_credentials": "N", 23 | "has_encryption_key": "N", 24 | "owner": "SYSADMIN", 25 | "comment": "", 26 | "region": None, 27 | "notification_channel": None, 28 | "storage_integration": None, 29 | "endpoint": None, 30 | "owner_role_type": "ROLE", 31 | "directory_enabled": "N", 32 | } 33 | 34 | stage1 = { 35 | **common_fields, 36 | "name": "STAGE1", 37 | "database_name": "DB1", 38 | "schema_name": "SCHEMA1", 39 | "url": "", 40 | "type": "INTERNAL", 41 | "cloud": None, 42 | } 43 | stage2 = { 44 | **common_fields, 45 | "name": "STAGE2", 46 | "database_name": "DB2", 47 | "schema_name": "SCHEMA2", 48 | "url": "", 49 | "type": "INTERNAL TEMPORARY", 50 | "cloud": None, 51 | } 52 | stage3 = { 53 | **common_fields, 54 | "name": "STAGE3", 55 | "database_name": "DB1", 56 | "schema_name": "SCHEMA3", 57 | "url": "s3://bucket/path/", 58 | "type": "EXTERNAL", 59 | "cloud": "AWS", 60 | } 61 | stage4 = { 62 | **common_fields, 63 | "name": "STAGE4", 64 | "database_name": "DB1", 65 | "schema_name": "SCHEMA1", 66 | "url": "s3://bucket/path/", 67 | "type": "EXTERNAL TEMPORARY", 68 | "cloud": "AWS", 69 | } 70 | 71 | dcur.execute("SHOW STAGES") 72 | assert dcur.fetchall() == [ 73 | stage1, 74 | stage4, 75 | ] 76 | 77 | dcur.execute("SHOW STAGES in DATABASE db2") 78 | assert dcur.fetchall() == [ 79 | stage2, 80 | ] 81 | 82 | dcur.execute("SHOW STAGES in SCHEMA schema3") 83 | assert dcur.fetchall() == [ 84 | stage3, 85 | ] 86 | 87 | dcur.execute("SHOW STAGES in db2.schema2") 88 | assert dcur.fetchall() == [ 89 | stage2, 90 | ] 91 | 92 | dcur.execute("SHOW STAGES IN ACCOUNT") 93 | assert dcur.fetchall() == [ 94 | stage1, 95 | stage2, 96 | stage3, 97 | stage4, 98 | ] 99 | 100 | 101 | def test_create_stage_qmark(_fakesnow: None): 102 | with ( 103 | snowflake.connector.connect(database="db1", schema="schema1", paramstyle="qmark") as conn, 104 | conn.cursor(snowflake.connector.cursor.DictCursor) as dcur, 105 | ): 106 | dcur.execute("CREATE STAGE identifier(?)", ("stage1",)) 107 | assert dcur.fetchall() == [{"status": "Stage area STAGE1 successfully created."}] 108 | -------------------------------------------------------------------------------- /tests/test_users.py: -------------------------------------------------------------------------------- 1 | import snowflake.connector.cursor 2 | 3 | 4 | def test_show_users_base_case(cur: snowflake.connector.cursor.SnowflakeCursor): 5 | result = cur.execute("SHOW USERS") 6 | assert result 7 | assert result.fetchall() == [] 8 | 9 | 10 | def test_show_users_with_users(cur: snowflake.connector.cursor.SnowflakeCursor): 11 | result = cur.execute("CREATE USER foo") 12 | result = cur.execute("CREATE USER bar") 13 | 14 | result = cur.execute("SHOW USERS") 15 | assert result 16 | 17 | rows = result.fetchall() 18 | names = [row[0] for row in rows] 19 | assert names == ["foo", "bar"] 20 | -------------------------------------------------------------------------------- /tests/test_write_pandas.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import datetime 4 | import json 5 | 6 | import pandas as pd 7 | import pytz 8 | import snowflake.connector 9 | import snowflake.connector.cursor 10 | import snowflake.connector.pandas_tools 11 | 12 | from tests.utils import indent 13 | 14 | 15 | def test_write_pandas_auto_create(conn: snowflake.connector.SnowflakeConnection): 16 | with conn.cursor() as cur: 17 | df = pd.DataFrame.from_records( 18 | [ 19 | {"ID": 1, "FIRST_NAME": "Jenny"}, 20 | {"ID": 2, "FIRST_NAME": "Jasper"}, 21 | ] 22 | ) 23 | snowflake.connector.pandas_tools.write_pandas(conn, df, "CUSTOMERS", auto_create_table=True) 24 | 25 | cur.execute("select id, first_name from customers") 26 | 27 | assert cur.fetchall() == [(1, "Jenny"), (2, "Jasper")] 28 | 29 | 30 | def test_write_pandas_quoted_column_names(conn: snowflake.connector.SnowflakeConnection): 31 | with conn.cursor(snowflake.connector.cursor.DictCursor) as dcur: 32 | # colunmn names with spaces 33 | dcur.execute('create table customers (id int, "first name" varchar)') 34 | df = pd.DataFrame.from_records( 35 | [ 36 | {"ID": 1, "first name": "Jenny"}, 37 | {"ID": 2, "first name": "Jasper"}, 38 | ] 39 | ) 40 | snowflake.connector.pandas_tools.write_pandas(conn, df, "CUSTOMERS") 41 | 42 | dcur.execute("select * from customers") 43 | 44 | assert dcur.fetchall() == [ 45 | {"ID": 1, "first name": "Jenny"}, 46 | {"ID": 2, "first name": "Jasper"}, 47 | ] 48 | 49 | 50 | def test_write_pandas_array(conn: snowflake.connector.SnowflakeConnection): 51 | with conn.cursor() as cur: 52 | cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar, ORDERS array)") 53 | 54 | df = pd.DataFrame.from_records( 55 | [ 56 | {"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P", "ORDERS": ["A", "B"]}, 57 | {"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M", "ORDERS": ["C", "D"]}, 58 | ] 59 | ) 60 | snowflake.connector.pandas_tools.write_pandas(conn, df, "CUSTOMERS") 61 | 62 | cur.execute("select * from customers") 63 | 64 | assert indent(cur.fetchall()) == [ 65 | (1, "Jenny", "P", '[\n "A",\n "B"\n]'), 66 | (2, "Jasper", "M", '[\n "C",\n "D"\n]'), 67 | ] 68 | 69 | 70 | def test_write_pandas_timestamp_ntz(conn: snowflake.connector.SnowflakeConnection): 71 | # compensate for https://github.com/duckdb/duckdb/issues/7980 72 | with conn.cursor() as cur: 73 | cur.execute("create table example (UPDATE_AT_NTZ timestamp_ntz(9))") 74 | # cur.execute("create table example (UPDATE_AT_NTZ timestamp)") 75 | 76 | now_utc = datetime.datetime.now(pytz.utc) 77 | df = pd.DataFrame([(now_utc,)], columns=["UPDATE_AT_NTZ"]) 78 | snowflake.connector.pandas_tools.write_pandas(conn, df, "EXAMPLE") 79 | 80 | cur.execute("select * from example") 81 | 82 | assert cur.fetchall() == [(now_utc.replace(tzinfo=None),)] 83 | 84 | 85 | def test_write_pandas_partial_columns(conn: snowflake.connector.SnowflakeConnection): 86 | with conn.cursor() as cur: 87 | cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 88 | 89 | df = pd.DataFrame.from_records( 90 | [ 91 | {"ID": 1, "FIRST_NAME": "Jenny"}, 92 | {"ID": 2, "FIRST_NAME": "Jasper"}, 93 | ] 94 | ) 95 | snowflake.connector.pandas_tools.write_pandas(conn, df, "CUSTOMERS") 96 | 97 | cur.execute("select id, first_name, last_name from customers") 98 | 99 | # columns not in dataframe will receive their default value 100 | assert cur.fetchall() == [(1, "Jenny", None), (2, "Jasper", None)] 101 | 102 | 103 | def test_write_pandas_dict_as_varchar(conn: snowflake.connector.SnowflakeConnection): 104 | with conn.cursor() as cur: 105 | cur.execute("create or replace table example (vc varchar, o object)") 106 | 107 | df = pd.DataFrame([({"kind": "vc", "count": 1}, {"kind": "obj", "amount": 2})], columns=["VC", "O"]) 108 | snowflake.connector.pandas_tools.write_pandas(conn, df, "EXAMPLE") 109 | 110 | cur.execute("select * from example") 111 | 112 | # returned values are valid json strings 113 | # NB: snowflake orders object keys alphabetically, we don't 114 | r = cur.fetchall() 115 | assert [(sort_keys(r[0][0], indent=None), sort_keys(r[0][1], indent=2))] == [ 116 | ('{"count":1,"kind":"vc"}', '{\n "amount": 2,\n "kind": "obj"\n}') 117 | ] 118 | 119 | 120 | def test_write_pandas_dict_different_keys(conn: snowflake.connector.SnowflakeConnection): 121 | with conn.cursor() as cur: 122 | cur.execute("create or replace table customers (notes variant)") 123 | 124 | df = pd.DataFrame.from_records( 125 | [ 126 | # rows have dicts with unique keys and values 127 | {"NOTES": {"k": "v1"}}, 128 | # test single and double quoting 129 | {"NOTES": {"k2": ["v'2", 'v"3']}}, 130 | ] 131 | ) 132 | snowflake.connector.pandas_tools.write_pandas(conn, df, "CUSTOMERS") 133 | 134 | cur.execute("select * from customers") 135 | 136 | assert indent(cur.fetchall()) == [('{\n "k": "v1"\n}',), ('{\n "k2": [\n "v\'2",\n "v\\"3"\n ]\n}',)] 137 | 138 | 139 | def test_write_pandas_db_schema(conn: snowflake.connector.SnowflakeConnection): 140 | with conn.cursor() as cur: 141 | cur.execute("create database db2") 142 | cur.execute("create schema db2.schema2") 143 | cur.execute("create or replace table db2.schema2.customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)") 144 | 145 | df = pd.DataFrame.from_records( 146 | [ 147 | {"ID": 1, "FIRST_NAME": "Jenny"}, 148 | {"ID": 2, "FIRST_NAME": "Jasper"}, 149 | ] 150 | ) 151 | snowflake.connector.pandas_tools.write_pandas(conn, df, "CUSTOMERS", "DB2", "SCHEMA2") 152 | 153 | cur.execute("select id, first_name, last_name from db2.schema2.customers") 154 | 155 | # columns not in dataframe will receive their default value 156 | assert cur.fetchall() == [(1, "Jenny", None), (2, "Jasper", None)] 157 | 158 | 159 | def sort_keys(sdict: str, indent: int | None = 2) -> str: 160 | return json.dumps( 161 | json.loads(sdict, object_pairs_hook=lambda x: dict(sorted(x))), 162 | indent=indent, 163 | separators=None if indent else (",", ":"), 164 | ) 165 | -------------------------------------------------------------------------------- /tests/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import json 4 | from collections.abc import Sequence 5 | from typing import cast 6 | 7 | 8 | def indent(rows: Sequence[tuple] | Sequence[dict]) -> list[tuple]: 9 | # indent duckdb json strings tuple values to match snowflake json strings 10 | assert isinstance(rows[0], tuple), f"{type(rows[0]).__name__} is not tuple" 11 | return [ 12 | (*[json.dumps(json.loads(c), indent=2) if (isinstance(c, str) and c.startswith(("[", "{"))) else c for c in r],) 13 | for r in rows 14 | ] 15 | 16 | 17 | def dindent(rows: Sequence[tuple] | Sequence[dict]) -> list[dict]: 18 | # indent duckdb json strings dict values to match snowflake json strings 19 | assert isinstance(rows[0], dict), f"{type(rows[0]).__name__} is not dict" 20 | return [ 21 | { 22 | k: json.dumps(json.loads(v), indent=2) if (isinstance(v, str) and v.startswith(("[", "{"))) else v 23 | for k, v in cast(dict, r).items() 24 | } 25 | for r in rows 26 | ] 27 | 28 | 29 | def strip(s: str) -> str: 30 | ''' 31 | Removes newlines and all leading whitespace from each line in the text. For example: 32 | 33 | text = """ 34 | an example 35 | text with indentation 36 | hehe 37 | """ 38 | dedent(text) == "an example text with indentation hehe" 39 | ''' 40 | 41 | # Split the string into lines 42 | lines = s.split("\n") 43 | 44 | # Remove empty lines at the beginning and end, and strip whitespace from each line 45 | lines = [line.strip() for line in lines if line.strip()] 46 | 47 | return " ".join(lines) if lines else "" 48 | -------------------------------------------------------------------------------- /toast.yml: -------------------------------------------------------------------------------- 1 | image: python:3.9-slim 2 | command_prefix: set -euo pipefail 3 | tasks: 4 | install-packages: 5 | command: 6 | # gcc python3-dev needed to build psutil 7 | apt-get update && apt-get install -y curl git make gcc python3-dev 8 | install-node: 9 | dependencies: 10 | - install-packages 11 | command: | 12 | curl -sL https://deb.nodesource.com/setup_lts.x | bash - 13 | apt-get install -y nodejs 14 | install: 15 | dependencies: 16 | - install-node 17 | input_paths: 18 | - Makefile 19 | - Makefile-common.mk 20 | - .python-version 21 | - pyproject.toml 22 | - package.json 23 | - .pre-commit-config.yaml 24 | environment: 25 | # don't install hooks 26 | CI: true 27 | command: make install 28 | hooks: 29 | description: make hooks 30 | dependencies: 31 | - install 32 | input_paths: 33 | # needed to avoid running hooks on *.egg-info files generated by pip install -e . 34 | - .gitignore 35 | - fakesnow/ 36 | - tests/ 37 | command: | 38 | # needed for pre-commit to work and see files 39 | git init . --initial-branch=main 40 | git add fakesnow tests 41 | make hooks 42 | -------------------------------------------------------------------------------- /tools/decode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import base64 3 | import sys 4 | 5 | import pyarrow as pa 6 | 7 | 8 | def dump_field_metadata(field: pa.Field, index: int) -> None: 9 | """Dump metadata for a single field.""" 10 | print(f"Field {index}: {field.name}") 11 | print(f" Type: {field.type}") 12 | print(f" Nullable: {field.nullable}") 13 | print(" Metadata:") 14 | assert field.metadata 15 | for key, value in field.metadata.items(): 16 | try: 17 | print(f" {key.decode('utf-8')}: {value.decode('utf-8')}") 18 | except UnicodeDecodeError: # noqa: PERF203 19 | print(f" {key.decode('utf-8')}: ") 20 | print() 21 | 22 | 23 | def main() -> None: 24 | if len(sys.argv) > 1: 25 | print("Usage: python dump_rowset_metadata.py < base64_encoded_file") 26 | print(" or: cat base64_encoded_file | python dump_rowset_metadata.py") 27 | print() 28 | print("Dump pyarrow metadata for a base64-encoded rowset.") 29 | sys.exit(1) 30 | 31 | # Read base64 input from stdin 32 | rowset_b64 = sys.stdin.read().strip() 33 | 34 | try: 35 | # Decode base64 36 | data = base64.b64decode(rowset_b64) 37 | 38 | # Parse with PyArrow 39 | reader = pa.ipc.open_stream(data) 40 | 41 | except Exception as e: 42 | full_class_name = f"{e.__module__}.{e.__class__.__name__}" 43 | print(f"Error processing rowset: {full_class_name} {e}") 44 | sys.exit(1) 45 | 46 | # Get the first batch 47 | batch = next(iter(reader)) 48 | 49 | print(f"Total fields: {batch.num_columns}") 50 | print("=" * 50) 51 | 52 | # Dump metadata for each field 53 | for i, field in enumerate(batch.schema): 54 | dump_field_metadata(field, i) 55 | 56 | # Also print a sample of the array data 57 | print(f" Batch data: {batch[i]}") 58 | print(f" Batch data type: {type(batch[i])}") 59 | print("=" * 50) 60 | 61 | 62 | if __name__ == "__main__": 63 | main() 64 | --------------------------------------------------------------------------------