Harbor format: 871 coding_baseline tasks (part 13)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/tests/trusted-inventory.jsonAdded+152
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/canaries/first-hunk-only.shAdded+28
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/canaries/original-bug.shAdded+3
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/openenv.jsonAdded+27
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/LICENSE.sourceAdded+25
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/adapter.jsonAdded+126
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/dependency-setup.shAdded+8
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/environment/DockerfileAdded+3
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/instruction.mdAdded+72
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/metadata.jsonAdded+533
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/provenance.jsonAdded+88
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/provided-gold.diffAdded+140
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/solution/solve.shAdded+146
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/task.tomlAdded+24
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/check_pytest.pyAdded+91
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/expected-panels.jsonAdded+337
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/grade.pyAdded+128
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/panel-config.jsonAdded+22
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/test.shAdded+6
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted-inventory.jsonAdded+152
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/pyproject.tomlAdded+104
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/__init__.pyAdded
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/conftest.pyAdded+47
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/_Make_DirEntry.sqlAdded+6
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/begintag.sqlAdded+4
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/begintag_2.sqlAdded+13
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/casewhen_procedure.sqlAdded+8
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/dashcomment.sqlAdded+5
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/encoding_gbk.sqlAdded+3
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/encoding_utf8.sqlAdded+3
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function.sqlAdded+13
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql.sqlAdded+72
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql2.sqlAdded+7
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql3.sqlAdded+8
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql4.sqlAdded+12
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/huge_select.sqlAdded+1
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/multiple_case_in_begin.sqlAdded+8
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/mysql_handler.sqlAdded+10
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/stream.sqlAdded+2
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/test_cp1251.sqlAdded+1
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_cli.pyAdded+122
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_format.pyAdded+774
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_grouping.pyAdded+679
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_keywords.pyAdded+13
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_parse.pyAdded+595
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_regressions.pyAdded+467
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_split.pyAdded+210
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_tokenize.pyAdded+247
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_utils.pyAdded+12
- tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/validation/canaries/original-bug.shAdded+3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152{ "directory_roots": [ "tests" ], "files": { "pyproject.toml": { "bytes": 2671, "mode": 420, "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" }, "tests/__init__.py": { "bytes": 0, "mode": 420, "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" }, "tests/conftest.py": { "bytes": 1571, "mode": 420, "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" }, "tests/files/_Make_DirEntry.sql": { "bytes": 109, "mode": 420, "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" }, "tests/files/begintag.sql": { "bytes": 45, "mode": 420, "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" }, "tests/files/begintag_2.sql": { "bytes": 357, "mode": 420, "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" }, "tests/files/casewhen_procedure.sql": { "bytes": 150, "mode": 420, "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" }, "tests/files/dashcomment.sql": { "bytes": 88, "mode": 420, "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" }, "tests/files/encoding_gbk.sql": { "bytes": 50, "mode": 420, "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" }, "tests/files/encoding_utf8.sql": { "bytes": 76, "mode": 420, "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" }, "tests/files/function.sql": { "bytes": 187, "mode": 420, "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" }, "tests/files/function_psql.sql": { "bytes": 3066, "mode": 420, "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" }, "tests/files/function_psql2.sql": { "bytes": 177, "mode": 420, "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" }, "tests/files/function_psql3.sql": { "bytes": 171, "mode": 420, "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" }, "tests/files/function_psql4.sql": { "bytes": 221, "mode": 420, "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" }, "tests/files/huge_select.sql": { "bytes": 9434, "mode": 420, "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" }, "tests/files/multiple_case_in_begin.sql": { "bytes": 193, "mode": 420, "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" }, "tests/files/mysql_handler.sql": { "bytes": 134, "mode": 420, "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" }, "tests/files/stream.sql": { "bytes": 44, "mode": 420, "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" }, "tests/files/test_cp1251.sql": { "bytes": 49, "mode": 420, "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" }, "tests/test_cli.py": { "bytes": 3521, "mode": 420, "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" }, "tests/test_format.py": { "bytes": 28438, "mode": 420, "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" }, "tests/test_grouping.py": { "bytes": 23973, "mode": 420, "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" }, "tests/test_keywords.py": { "bytes": 447, "mode": 420, "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" }, "tests/test_parse.py": { "bytes": 18335, "mode": 420, "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" }, "tests/test_regressions.py": { "bytes": 14896, "mode": 420, "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" }, "tests/test_split.py": { "bytes": 6147, "mode": 420, "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" }, "tests/test_tokenize.py": { "bytes": 6364, "mode": 420, "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" }, "tests/test_utils.py": { "bytes": 268, "mode": 420, "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" } }}12345678910111213141516171819202122232425262728#!/bin/bashset -Eeuo pipefailcd /testbed/repocat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL'diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.pyindex 0db01500de3a15f2520b499a228c94c091c0dac4..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644--- a/sqlparse/filters/reindent.py+++ b/sqlparse/filters/reindent.py@@ -42,13 +42,14 @@ def _get_offset(self, token): raw = ''.join(map(str, self._flatten_up_to_token(token)))- line = (raw or '\n').splitlines()[0]- return len(line) + len(self.char * self.leading_ws)+ line = (raw or '\n').splitlines()[-1]+ # Now take current offset into account and return relative offset.+ return len(line) - len(self.char * self.leading_ws) def nl(self, offset=0): return sql.Token( T.Whitespace,- self.char + self.n * max(0, self.leading_ws - offset))+ self.n + self.char * max(0, self.leading_ws + offset)) def _next_token(self, tlist, idx=-1): split_words = ('FROM', 'STRAIGHT_JOIN$', 'JOIN$', 'AND', 'OR',OPENENV_PARTIAL/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff123#!/bin/bashset -Eeuo pipefail:123456789101112131415161718192021222324252627{ "canaries": "validation/canaries", "profile": "harbor-semantic-v1", "requires_credentials": false, "resources": { "cpu": 2, "disk_mb": 16384, "episode_timeout_s": 1800, "memory_mb": 8192 }, "reward": { "floor_margin": 0.1, "oracle_tolerance": 0, "range": [ 0, 1 ] }, "reward_key": "reward", "types": { "tags": [ "swe", "python", "mutation-repair" ] }}12345678910111213141516171819202122232425Copyright (c) 2016, Andi Albrecht <albrecht.andi@gmail.com>All rights reserved.
Redistribution and use in source and binary forms, with or without modification,are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the authors nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ANDANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FORANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126{ "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", "collector_sha256": "352e555112f2de8a1393f939903e4971c9ace0e944843762b707a725c5c72481", "dependency_installation_pinned": false, "dependency_setup_sha256": "2e52e9227520b938b0d5e8c191d3be78b387ebb587cb89223302ec79a00fc6c6", "gold_patch_sha256": "72f5fe26e2bcf89e95ecf0b33fc9a7ac32adcf57cdb7cd214246c7657779e8d0", "hostile_code_isolation_established": false, "known_wrong_semantic_implementations": 0, "native_inventory_sha256": "62c106d225f429842ce6685d0492ec430d9e809d3e0e5a60a7f586fbcdf998cf", "new_files_deletions_and_executable_modes_supported": true, "official_profile": { "eval_sets": [], "profile_class": "SqlparseE57923b3", "profile_lines": [ 921, 924 ], "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", "profile_source_path": "swesmith/profiles/python.py", "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", "upstream_repo": "andialbrecht/sqlparse" }, "original_bug_canary_nop_equivalent": true, "original_bug_runtime_wrongness_established": false, "partial_repair_canary": false, "partial_repair_sha256": null, "partial_repair_wrongness_established": false, "provided_original_bug_control": true, "repo_url": "https://github.com/swesmith/andialbrecht__sqlparse.e57923b3.git", "runtime_image": null, "runtime_ready": false, "runtime_recipe": { "dependency_installation_pinned": false, "official_install_cmds": [ "python -m pip install -e ." ], "official_pytest_argv": [ "pytest", "--disable-warnings", "--color=no", "--tb=no", "--verbose" ], "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", "python_version": "3.10", "source_bound_test_dependency_cmds": [ "python -m pip install pytest" ], "test_dependency_source_sha256": { "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" } }, "runtime_resource_review_required": false, "schema": "python-git-patch-jobs-v1", "source_base_commit": "0a9d7bd6099eb7485cce76aaa64eccf051c3af11", "source_completion_sha256": "b15bfd1bc278417c61ba7077bb9d5ab7317004249b9dbbac6b931044591e5804", "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", "source_pr_url": null, "source_record": { "anti_training_canary": false, "anti_training_reviewed": true, "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8", "cloud_launch_ready": false, "eligibility": { "reasons": [], "semantic_nonoverlap_established": false, "status": "eligible_for_controls", "training_admissible": false, "warnings": [] }, "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", "instruction_sha256": "326bf50cfeaa4f4da27ee48ca722c808558b74b2f413bf3c9315da47bec58717", "is_fork": true, "learner_path": "tasks/05a0823b586743dd0d70582b/learner", "license_evidence": { "source_code": { "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", "reviewed": true, "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", "spdx": "BSD-3-Clause", "training_allowed": true, "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/0a9d7bd6099eb7485cce76aaa64eccf051c3af11/LICENSE" }, "task_bundle": { "reviewed": true, "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", "spdx": "MIT", "training_allowed": true, "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" } }, "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", "patch_sha256": "74dfe295502d7b187873c1fc51d168daf456ea04ce7d244b32a658068fabcd86", "provenance_path": "tasks/05a0823b586743dd0d70582b/source-proof.json", "repository_lineage": [ "swesmith/andialbrecht__sqlparse.e57923b3", "andialbrecht/sqlparse" ], "rfc008_complete": false, "runtime_qualified": false, "semantic_nonoverlap_established": false, "source_commit": "0a9d7bd6099eb7485cce76aaa64eccf051c3af11", "source_dataset": "SWE-bench/SWE-smith-py", "source_head_commit": "3156a48aa066c199b7ed4e207716c9eaa4125561", "source_kind": "mutation", "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", "source_split": "train", "target_model_calibrated": false, "task_id": "andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8", "task_sha256": "1a2ff5ccb9869420d4e874908a0801559c727928cd3b21c4da9c0be88d93bde2", "training_admissible": false, "upstream_identity_reviewed": true, "upstream_repo": "andialbrecht/sqlparse", "usage": "quarantine_only" }, "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", "symlink_submodule_changes_supported": false, "task_id": "andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8", "transfer": "index-independent-worktree-to-Git-binary-patch", "transfer_path": "/testbed/submission.patch", "upstream_repo": "andialbrecht/sqlparse"}12345678#!/bin/bashset -Eeuo pipefailsource /opt/miniconda3/bin/activateconda activate testbedcd /testbed/repopython -c 'import sys; assert sys.version_info[:2] == (3, 10)'python -m pip install -e .python -m pip install pytest123# Runtime is selected only by an independently qualified immutable amd64 receipt.FROM ubuntu:22.04RUN false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172# Output formatting issues with Python and PHP formatters
I'm having issues with the output formatters in sqlparse. The Python and PHP output formatters seem to be generating incorrect output.
## Python formatter issues
When I try to format a simple SQL query with the Python output formatter, I'm getting unexpected results:
```pythonimport sqlparse
sql = 'select * from foo;'result = sqlparse.format(sql, output_format='python')print(result)# Expected: sql = 'select * from foo;'# Actual: sql0 = 'select * from foo;'```
The variable name is incorrect - it's adding a "0" suffix to the variable name.
Also, when I try to format multiple statements, the numbering is off:
```pythonsql = 'select * from foo; select 1 from dual'result = sqlparse.format(sql, output_format='python')print(result)# Expected: # sql = 'select * from foo; '# sql2 = 'select 1 from dual'# # Actual:# sql0 = 'select * from foo; '# sql0 = 'select 1 from dual'```
The second statement is using the same variable name as the first one.
## PHP formatter issues
The PHP formatter has similar problems:
```pythonsql = 'select * from foo;'result = sqlparse.format(sql, output_format='php')print(result)# Expected: $sql = "select * from foo;";# Actual: $sql0 = "select * from foo;",```
Notice the incorrect variable name and the comma at the end instead of a semicolon.
When using reindent=True, the concatenation operator is wrong:
```pythonresult = sqlparse.format(sql, output_format='php', reindent=True)print(result)# Expected: # $sql = "select * ";# $sql .= "from foo;";# # Actual:# $sql0 = "select * ";# $sql0 =: "from foo;",```
The concatenation operator should be `.=` but it's showing as `=:`.
I think there might be several issues with the variable naming, indexing, and symbol handling in the output formatters.
## Environment
The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest <tests>`. Don't install packages: the tests need nothing else, and the sandbox may have no network access.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533{ "all_runtime_and_training_flags": false, "official_profile": { "eval_sets": [], "profile_class": "SqlparseE57923b3", "profile_lines": [ 921, 924 ], "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", "profile_source_path": "swesmith/profiles/python.py", "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", "upstream_repo": "andialbrecht/sqlparse" }, "source_healthy_reference_proof": { "FAIL_TO_PASS": [ "tests/test_format.py::TestOutputFormat::test_python", "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", "tests/test_format.py::TestOutputFormat::test_php" ], "PASS_TO_PASS": [ "tests/test_cli.py::test_cli_main_empty", "tests/test_cli.py::test_parser_empty", "tests/test_cli.py::test_main_help", "tests/test_cli.py::test_valid_args", "tests/test_cli.py::test_invalid_choice", "tests/test_cli.py::test_invalid_args", "tests/test_cli.py::test_invalid_infile", "tests/test_cli.py::test_invalid_outfile", "tests/test_cli.py::test_stdout", "tests/test_cli.py::test_script", "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", "tests/test_cli.py::test_encoding", "tests/test_format.py::TestFormat::test_keywordcase", "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", "tests/test_format.py::TestFormat::test_identifiercase", "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", "tests/test_format.py::TestFormat::test_identifiercase_quotes", "tests/test_format.py::TestFormat::test_strip_comments_single", "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", "tests/test_format.py::TestFormat::test_strip_comments_multi", "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", "tests/test_format.py::TestFormat::test_strip_ws", "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", "tests/test_format.py::TestFormat::test_preserve_ws", "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", "tests/test_format.py::TestFormatReindentAligned::test_basic", "tests/test_format.py::TestFormatReindentAligned::test_joins", "tests/test_format.py::TestFormatReindentAligned::test_case_statement", "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", "tests/test_format.py::TestFormatReindentAligned::test_group_by", "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", "tests/test_format.py::TestFormatReindentAligned::test_window_functions", "tests/test_format.py::TestSpacesAroundOperators::test_basic", "tests/test_format.py::TestSpacesAroundOperators::test_bools", "tests/test_format.py::TestSpacesAroundOperators::test_nested", "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", "tests/test_format.py::TestFormatReindent::test_option", "tests/test_format.py::TestFormatReindent::test_stmts", "tests/test_format.py::TestFormatReindent::test_keywords", "tests/test_format.py::TestFormatReindent::test_keywords_between", "tests/test_format.py::TestFormatReindent::test_parenthesis", "tests/test_format.py::TestFormatReindent::test_where", "tests/test_format.py::TestFormatReindent::test_join", "tests/test_format.py::TestFormatReindent::test_identifier_list", "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", "tests/test_format.py::TestFormatReindent::test_case", "tests/test_format.py::TestFormatReindent::test_case2", "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", "tests/test_format.py::TestFormatReindent::test_keywordfunctions", "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", "tests/test_format.py::TestFormatReindent::test_insert_values", "tests/test_format.py::TestOutputFormat::test_sql", "tests/test_format.py::TestOutputFormat::test_invalid_option", "tests/test_format.py::test_format_column_ordering", "tests/test_format.py::test_truncate_strings", "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", "tests/test_format.py::test_truncate_strings_invalid_option2[0]", "tests/test_format.py::test_having_produces_newline", "tests/test_format.py::test_format_right_margin_invalid_option[ten]", "tests/test_format.py::test_format_right_margin_invalid_option[2]", "tests/test_format.py::test_format_json_ops", "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", "tests/test_grouping.py::test_grouping_parenthesis", "tests/test_grouping.py::test_grouping_identifiers", "tests/test_grouping.py::test_grouping_identifier_wildcard", "tests/test_grouping.py::test_grouping_identifier_name_wildcard", "tests/test_grouping.py::test_grouping_identifier_invalid", "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", "tests/test_grouping.py::test_grouping_identifier_as_invalid", "tests/test_grouping.py::test_grouping_identifier_function", "tests/test_grouping.py::test_grouping_operation[foo+100]", "tests/test_grouping.py::test_grouping_operation[foo*100]", "tests/test_grouping.py::test_grouping_identifier_list", "tests/test_grouping.py::test_grouping_identifier_list_subquery", "tests/test_grouping.py::test_grouping_identifier_list_case", "tests/test_grouping.py::test_grouping_identifier_list_other", "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", "tests/test_grouping.py::test_grouping_identifiers_with_operators", "tests/test_grouping.py::test_grouping_identifier_list_with_order", "tests/test_grouping.py::test_grouping_nested_identifier_with_order", "tests/test_grouping.py::test_grouping_where", "tests/test_grouping.py::test_returning_kw_ends_where_clause", "tests/test_grouping.py::test_into_kw_ends_where_clause", "tests/test_grouping.py::test_grouping_alias", "tests/test_grouping.py::test_grouping_alias_case", "tests/test_grouping.py::test_grouping_alias_ctas", "tests/test_grouping.py::test_grouping_subquery_no_parens", "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", "tests/test_grouping.py::test_grouping_idlist_function", "tests/test_grouping.py::test_grouping_comparison_exclude", "tests/test_grouping.py::test_grouping_function", "tests/test_grouping.py::test_grouping_function_not_in", "tests/test_grouping.py::test_grouping_varchar", "tests/test_grouping.py::test_statement_get_type", "tests/test_grouping.py::test_identifier_with_operators", "tests/test_grouping.py::test_identifier_with_op_trailing_ws", "tests/test_grouping.py::test_identifier_with_string_literals", "tests/test_grouping.py::test_identifier_consumes_ordering", "tests/test_grouping.py::test_comparison_with_keywords", "tests/test_grouping.py::test_comparison_with_floats", "tests/test_grouping.py::test_comparison_with_parenthesis", "tests/test_grouping.py::test_comparison_with_strings[=]", "tests/test_grouping.py::test_comparison_with_strings[!=]", "tests/test_grouping.py::test_comparison_with_strings[>]", "tests/test_grouping.py::test_comparison_with_strings[<]", "tests/test_grouping.py::test_comparison_with_strings[<=]", "tests/test_grouping.py::test_comparison_with_strings[>=]", "tests/test_grouping.py::test_comparison_with_strings[~]", "tests/test_grouping.py::test_comparison_with_strings[~~]", "tests/test_grouping.py::test_comparison_with_strings[!~~]", "tests/test_grouping.py::test_comparison_with_strings[LIKE]", "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", "tests/test_grouping.py::test_like_and_ilike_comparison", "tests/test_grouping.py::test_comparison_with_functions", "tests/test_grouping.py::test_comparison_with_typed_literal", "tests/test_grouping.py::test_forloops[FOR]", "tests/test_grouping.py::test_forloops[FOREACH]", "tests/test_grouping.py::test_nested_for", "tests/test_grouping.py::test_begin", "tests/test_grouping.py::test_keyword_followed_by_parenthesis", "tests/test_grouping.py::test_nested_begin", "tests/test_grouping.py::test_aliased_column_without_as", "tests/test_grouping.py::test_qualified_function", "tests/test_grouping.py::test_aliased_function_without_as", "tests/test_grouping.py::test_aliased_literal_without_as", "tests/test_grouping.py::test_grouping_as_cte", "tests/test_grouping.py::test_grouping_create_table", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", "tests/test_parse.py::test_parse_tokenize", "tests/test_parse.py::test_parse_multistatement", "tests/test_parse.py::test_parse_within", "tests/test_parse.py::test_parse_child_of", "tests/test_parse.py::test_parse_has_ancestor", "tests/test_parse.py::test_parse_float[.5]", "tests/test_parse.py::test_parse_float[.51]", "tests/test_parse.py::test_parse_float[1.5]", "tests/test_parse.py::test_parse_float[12.5]", "tests/test_parse.py::test_parse_modulo_not_placeholder", "tests/test_parse.py::test_parse_access_symbol", "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", "tests/test_parse.py::test_parse_keyword_like_identifier", "tests/test_parse.py::test_parse_function_parameter", "tests/test_parse.py::test_parse_function_param_single_literal", "tests/test_parse.py::test_parse_nested_function", "tests/test_parse.py::test_parse_casted_params", "tests/test_parse.py::test_parse_div_operator", "tests/test_parse.py::test_quoted_identifier", "tests/test_parse.py::test_valid_identifier_names[foo]", "tests/test_parse.py::test_valid_identifier_names[_foo]", "tests/test_parse.py::test_valid_identifier_names[1_data]", "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", "tests/test_parse.py::test_psql_quotation_marks", "tests/test_parse.py::test_double_precision_is_builtin", "tests/test_parse.py::test_placeholder[?]", "tests/test_parse.py::test_placeholder[:1]", "tests/test_parse.py::test_placeholder[:foo]", "tests/test_parse.py::test_placeholder[%s]", "tests/test_parse.py::test_placeholder[%(foo)s]", "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", "tests/test_parse.py::test_scientific_numbers[e1-None]", "tests/test_parse.py::test_single_quotes_are_strings", "tests/test_parse.py::test_double_quotes_are_identifiers", "tests/test_parse.py::test_single_quotes_with_linebreaks", "tests/test_parse.py::test_sqlite_identifiers", "tests/test_parse.py::test_simple_1d_array_index", "tests/test_parse.py::test_2d_array_index", "tests/test_parse.py::test_array_index_function_result", "tests/test_parse.py::test_schema_qualified_array_index", "tests/test_parse.py::test_aliased_array_index", "tests/test_parse.py::test_array_literal", "tests/test_parse.py::test_typed_array_definition", "tests/test_parse.py::test_names_and_special_names[foo]", "tests/test_parse.py::test_names_and_special_names[@foo]", "tests/test_parse.py::test_names_and_special_names[#foo]", "tests/test_parse.py::test_names_and_special_names[##foo]", "tests/test_parse.py::test_get_token_at_offset", "tests/test_parse.py::test_pprint", "tests/test_parse.py::test_wildcard_multiplication", "tests/test_parse.py::test_stmt_tokens_parents", "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", "tests/test_parse.py::test_non_ascii", "tests/test_parse.py::test_get_real_name", "tests/test_parse.py::test_from_subquery", "tests/test_parse.py::test_parenthesis", "tests/test_parse.py::test_configurable_keywords", "tests/test_parse.py::test_configurable_regex", "tests/test_parse.py::test_json_operators[->]", "tests/test_parse.py::test_json_operators[->>]", "tests/test_parse.py::test_json_operators[#>]", "tests/test_parse.py::test_json_operators[#>>]", "tests/test_parse.py::test_json_operators[@>]", "tests/test_parse.py::test_json_operators[<@]", "tests/test_parse.py::test_json_operators[||]", "tests/test_parse.py::test_json_operators[-]", "tests/test_parse.py::test_json_operators[#-]", "tests/test_regressions.py::test_issue9", "tests/test_regressions.py::test_issue13", "tests/test_regressions.py::test_issue26[--hello]", "tests/test_regressions.py::test_issue26[--hello\\n]", "tests/test_regressions.py::test_issue26[--]", "tests/test_regressions.py::test_issue26[--\\n]", "tests/test_regressions.py::test_issue34[create]", "tests/test_regressions.py::test_issue34[CREATE]", "tests/test_regressions.py::test_issue35", "tests/test_regressions.py::test_issue38", "tests/test_regressions.py::test_issue39", "tests/test_regressions.py::test_issue40", "tests/test_regressions.py::test_issue83", "tests/test_regressions.py::test_comment_encoding_when_reindent", "tests/test_regressions.py::test_parse_sql_with_binary", "tests/test_regressions.py::test_dont_alias_keywords", "tests/test_regressions.py::test_format_accepts_encoding", "tests/test_regressions.py::test_stream", "tests/test_regressions.py::test_issue90", "tests/test_regressions.py::test_except_formatting", "tests/test_regressions.py::test_null_with_as", "tests/test_regressions.py::test_issue190_open_file", "tests/test_regressions.py::test_issue193_splitting_function", "tests/test_regressions.py::test_issue194_splitting_function", "tests/test_regressions.py::test_issue186_get_type", "tests/test_regressions.py::test_issue212_py2unicode", "tests/test_regressions.py::test_issue213_leadingws", "tests/test_regressions.py::test_issue227_gettype_cte", "tests/test_regressions.py::test_issue207_runaway_format", "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", "tests/test_regressions.py::test_issue284_as_grouping[AS]", "tests/test_regressions.py::test_issue315_utf8_by_default", "tests/test_regressions.py::test_issue322_concurrently_is_keyword", "tests/test_regressions.py::test_issue469_copy_as_psql_command", "tests/test_regressions.py::test_issue485_split_multi", "tests/test_regressions.py::test_issue489_tzcasts", "tests/test_regressions.py::test_issue562_tzcasts", "tests/test_regressions.py::test_as_in_parentheses_indents", "tests/test_regressions.py::test_format_invalid_where_clause", "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", "tests/test_regressions.py::test_copy_issue672", "tests/test_regressions.py::test_primary_key_issue740", "tests/test_regressions.py::test_max_recursion", "tests/test_split.py::test_split_semicolon", "tests/test_split.py::test_split_backslash", "tests/test_split.py::test_split_create_function[function.sql]", "tests/test_split.py::test_split_create_function[function_psql.sql]", "tests/test_split.py::test_split_create_function[function_psql2.sql]", "tests/test_split.py::test_split_create_function[function_psql3.sql]", "tests/test_split.py::test_split_create_function[function_psql4.sql]", "tests/test_split.py::test_split_dashcomments", "tests/test_split.py::test_split_begintag", "tests/test_split.py::test_split_begintag_2", "tests/test_split.py::test_split_dropif", "tests/test_split.py::test_split_comment_with_umlaut", "tests/test_split.py::test_split_comment_end_of_line", "tests/test_split.py::test_split_casewhen", "tests/test_split.py::test_split_casewhen_procedure", "tests/test_split.py::test_split_cursor_declare", "tests/test_split.py::test_split_if_function", "tests/test_split.py::test_split_stream", "tests/test_split.py::test_split_encoding_parsestream", "tests/test_split.py::test_split_unicode_parsestream", "tests/test_split.py::test_split_simple", "tests/test_split.py::test_split_ignores_empty_newlines", "tests/test_split.py::test_split_quotes_with_new_line", "tests/test_split.py::test_split_mysql_handler_for", "tests/test_split.py::test_split_strip_semicolon_procedure", "tests/test_split.py::test_split_multiple_case_in_begin", "tests/test_tokenize.py::test_tokenize_simple", "tests/test_tokenize.py::test_tokenize_backticks", "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", "tests/test_tokenize.py::test_tokenize_inline_keywords", "tests/test_tokenize.py::test_tokenize_negative_numbers", "tests/test_tokenize.py::test_token_str", "tests/test_tokenize.py::test_token_repr", "tests/test_tokenize.py::test_token_flatten", "tests/test_tokenize.py::test_tokenlist_repr", "tests/test_tokenize.py::test_single_quotes", "tests/test_tokenize.py::test_tokenlist_first", "tests/test_tokenize.py::test_tokenlist_token_matching", "tests/test_tokenize.py::test_stream_simple", "tests/test_tokenize.py::test_stream_error", "tests/test_tokenize.py::test_parse_join[JOIN]", "tests/test_tokenize.py::test_parse_union", "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", "tests/test_tokenize.py::test_parse_order[ASC]", "tests/test_tokenize.py::test_parse_order[DESC]", "tests/test_tokenize.py::test_parse_identifiers[foo]", "tests/test_tokenize.py::test_parse_identifiers[Foo]", "tests/test_tokenize.py::test_parse_identifiers[FOO]", "tests/test_tokenize.py::test_parse_identifiers[v$name]", "tests/test_tokenize.py::test_parse_group_by", "tests/test_tokenize.py::test_parse_order_by", "tests/test_tokenize.py::test_parse_window_as", "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", "tests/test_tokenize.py::test_cli_commands", "tests/test_utils.py::test_remove_quotes[None-None]", "tests/test_utils.py::test_remove_quotes['foo'-foo]", "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", "tests/test_utils.py::test_remove_quotes[`foo`-foo]" ], "all_git_blobs_modes_verified": true, "cloud_launch_ready": false, "commits": { "bug": "3156a48aa066c199b7ed4e207716c9eaa4125561", "healthy": "d802518f3673051449163fc84fe1455448f79b3b", "learner": "0a9d7bd6099eb7485cce76aaa64eccf051c3af11" }, "existing_squirrel_snapshot_reused": false, "full_transfer_allowlist": [ "/testbed/.flake8", "/testbed/.github/CODE_OF_CONDUCT.md", "/testbed/.github/ISSUE_TEMPLATE/bug_report.md", "/testbed/.github/ISSUE_TEMPLATE/config.yml", "/testbed/.github/ISSUE_TEMPLATE/feature_request.md", "/testbed/.github/PULL_REQUEST_TEMPLATE.md", "/testbed/.gitignore", "/testbed/.readthedocs.yaml", "/testbed/AUTHORS", "/testbed/CHANGELOG", "/testbed/CONTRIBUTING.md", "/testbed/LICENSE", "/testbed/Makefile", "/testbed/README.rst", "/testbed/SECURITY.md", "/testbed/TODO", "/testbed/docs/Makefile", "/testbed/docs/source/analyzing.rst", "/testbed/docs/source/api.rst", "/testbed/docs/source/changes.rst", "/testbed/docs/source/conf.py", "/testbed/docs/source/extending.rst", "/testbed/docs/source/index.rst", "/testbed/docs/source/indices.rst", "/testbed/docs/source/intro.rst", "/testbed/docs/source/license.rst", "/testbed/docs/source/ui.rst", "/testbed/docs/sqlformat.1", "/testbed/examples/column_defs_lowlevel.py", "/testbed/examples/extract_table_names.py", "/testbed/pyproject.toml", "/testbed/sqlparse/__init__.py", "/testbed/sqlparse/__main__.py", "/testbed/sqlparse/cli.py", "/testbed/sqlparse/engine/__init__.py", "/testbed/sqlparse/engine/filter_stack.py", "/testbed/sqlparse/engine/grouping.py", "/testbed/sqlparse/engine/statement_splitter.py", "/testbed/sqlparse/exceptions.py", "/testbed/sqlparse/filters/__init__.py", "/testbed/sqlparse/filters/aligned_indent.py", "/testbed/sqlparse/filters/others.py", "/testbed/sqlparse/filters/output.py", "/testbed/sqlparse/filters/reindent.py", "/testbed/sqlparse/filters/right_margin.py", "/testbed/sqlparse/filters/tokens.py", "/testbed/sqlparse/formatter.py", "/testbed/sqlparse/keywords.py", "/testbed/sqlparse/lexer.py", "/testbed/sqlparse/sql.py", "/testbed/sqlparse/tokens.py", "/testbed/sqlparse/utils.py", "/testbed/tests/__init__.py", "/testbed/tests/conftest.py", "/testbed/tests/files/_Make_DirEntry.sql", "/testbed/tests/files/begintag.sql", "/testbed/tests/files/begintag_2.sql", "/testbed/tests/files/casewhen_procedure.sql", "/testbed/tests/files/dashcomment.sql", "/testbed/tests/files/encoding_gbk.sql", "/testbed/tests/files/encoding_utf8.sql", "/testbed/tests/files/function.sql", "/testbed/tests/files/function_psql.sql", "/testbed/tests/files/function_psql2.sql", "/testbed/tests/files/function_psql3.sql", "/testbed/tests/files/function_psql4.sql", "/testbed/tests/files/huge_select.sql", "/testbed/tests/files/multiple_case_in_begin.sql", "/testbed/tests/files/mysql_handler.sql", "/testbed/tests/files/stream.sql", "/testbed/tests/files/test_cp1251.sql", "/testbed/tests/test_cli.py", "/testbed/tests/test_grouping.py", "/testbed/tests/test_keywords.py", "/testbed/tests/test_parse.py", "/testbed/tests/test_regressions.py", "/testbed/tests/test_split.py", "/testbed/tests/test_tokenize.py", "/testbed/tests/test_utils.py" ], "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", "mutation_matches_dataset_and_git_blobs": true, "official_profile": { "eval_sets": [], "profile_class": "SqlparseE57923b3", "profile_lines": [ 921, 924 ], "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", "profile_source_path": "swesmith/profiles/python.py", "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", "upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", "upstream_repo": "andialbrecht/sqlparse" }, "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", "private_test_paths": [ "tests/test_format.py" ], "private_tests_unchanged": true, "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", "qwen_calibrated": false, "runtime_qualified": false, "source_paths": [ "sqlparse/filters/output.py" ], "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", "source_stages_bytes": 912387, "task_id": "andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8", "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", "upstream_repo": "andialbrecht/sqlparse" }, "source_record": { "anti_training_canary": false, "anti_training_reviewed": true, "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8", "cloud_launch_ready": false, "eligibility": { "reasons": [], "semantic_nonoverlap_established": false, "status": "eligible_for_controls", "training_admissible": false, "warnings": [] }, "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", "instruction_sha256": "326bf50cfeaa4f4da27ee48ca722c808558b74b2f413bf3c9315da47bec58717", "is_fork": true, "learner_path": "tasks/05a0823b586743dd0d70582b/learner", "license_evidence": { "source_code": { "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", "reviewed": true, "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", "spdx": "BSD-3-Clause", "training_allowed": true, "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/0a9d7bd6099eb7485cce76aaa64eccf051c3af11/LICENSE" }, "task_bundle": { "reviewed": true, "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", "spdx": "MIT", "training_allowed": true, "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" } }, "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", "patch_sha256": "74dfe295502d7b187873c1fc51d168daf456ea04ce7d244b32a658068fabcd86", "provenance_path": "tasks/05a0823b586743dd0d70582b/source-proof.json", "repository_lineage": [ "swesmith/andialbrecht__sqlparse.e57923b3", "andialbrecht/sqlparse" ], "rfc008_complete": false, "runtime_qualified": false, "semantic_nonoverlap_established": false, "source_commit": "0a9d7bd6099eb7485cce76aaa64eccf051c3af11", "source_dataset": "SWE-bench/SWE-smith-py", "source_head_commit": "3156a48aa066c199b7ed4e207716c9eaa4125561", "source_kind": "mutation", "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", "source_split": "train", "target_model_calibrated": false, "task_id": "andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8", "task_sha256": "1a2ff5ccb9869420d4e874908a0801559c727928cd3b21c4da9c0be88d93bde2", "training_admissible": false, "upstream_identity_reviewed": true, "upstream_repo": "andialbrecht/sqlparse", "usage": "quarantine_only" }, "task_kind": "original-source-mutation"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788{ "generated_reference": false, "healthy_reference_delta_sha256": "72f5fe26e2bcf89e95ecf0b33fc9a7ac32adcf57cdb7cd214246c7657779e8d0", "native_pytest_ids_preserved": true, "original_source_code_license": { "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", "reviewed": true, "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", "spdx": "BSD-3-Clause", "training_allowed": true, "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/0a9d7bd6099eb7485cce76aaa64eccf051c3af11/LICENSE" }, "provided_reference": true, "qwen_calibrated": false, "runtime_qualified": false, "source_completion_sha256": "b15bfd1bc278417c61ba7077bb9d5ab7317004249b9dbbac6b931044591e5804", "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", "source_proof_sha256": "57d6c3e930326965f79f5b81a9c778cecba7baf7836e8301973a81f7fb49195e", "source_record": { "anti_training_canary": false, "anti_training_reviewed": true, "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8", "cloud_launch_ready": false, "eligibility": { "reasons": [], "semantic_nonoverlap_established": false, "status": "eligible_for_controls", "training_admissible": false, "warnings": [] }, "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", "instruction_sha256": "326bf50cfeaa4f4da27ee48ca722c808558b74b2f413bf3c9315da47bec58717", "is_fork": true, "learner_path": "tasks/05a0823b586743dd0d70582b/learner", "license_evidence": { "source_code": { "actual_upstream_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", "actual_upstream_url": "https://raw.githubusercontent.com/andialbrecht/sqlparse/e57923b3aa823c524c807953cecc48cf6eec2cb2/LICENSE", "reviewed": true, "sha256": "c1938235b80d39e93138eae89edc3af67e18ecbc40d266529fa57b2dce426310", "spdx": "BSD-3-Clause", "training_allowed": true, "url": "https://raw.githubusercontent.com/swesmith/andialbrecht__sqlparse.e57923b3/0a9d7bd6099eb7485cce76aaa64eccf051c3af11/LICENSE" }, "task_bundle": { "reviewed": true, "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", "spdx": "MIT", "training_allowed": true, "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" } }, "original_source_commit": "e57923b3aa823c524c807953cecc48cf6eec2cb2", "patch_sha256": "74dfe295502d7b187873c1fc51d168daf456ea04ce7d244b32a658068fabcd86", "provenance_path": "tasks/05a0823b586743dd0d70582b/source-proof.json", "repository_lineage": [ "swesmith/andialbrecht__sqlparse.e57923b3", "andialbrecht/sqlparse" ], "rfc008_complete": false, "runtime_qualified": false, "semantic_nonoverlap_established": false, "source_commit": "0a9d7bd6099eb7485cce76aaa64eccf051c3af11", "source_dataset": "SWE-bench/SWE-smith-py", "source_head_commit": "3156a48aa066c199b7ed4e207716c9eaa4125561", "source_kind": "mutation", "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", "source_split": "train", "target_model_calibrated": false, "task_id": "andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8", "task_sha256": "1a2ff5ccb9869420d4e874908a0801559c727928cd3b21c4da9c0be88d93bde2", "training_admissible": false, "upstream_identity_reviewed": true, "upstream_repo": "andialbrecht/sqlparse", "usage": "quarantine_only" }, "task_bundle_license": { "reviewed": true, "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", "spdx": "MIT", "training_allowed": true, "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" }, "training_admissible": false, "trusted_tests_sha256": "ea16a768523e5e923d71ad99188edd31f721472432f18fb42d7e93c417d066cf"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140diff --git a/sqlparse/filters/output.py b/sqlparse/filters/output.pyindex 9578e970f584d45a8ae26ddf7d07bfa9ce5a5861..253537e04ccf1b1b5526fe4485c9bd1d441967ae 100644--- a/sqlparse/filters/output.py+++ b/sqlparse/filters/output.py@@ -12,94 +12,111 @@ varname_prefix = '' def __init__(self, varname='sql'):- self.varname = varname + self.varname_prefix- self.count = 1+ self.varname = self.varname_prefix + varname+ self.count = 0 def _process(self, stream, varname, has_nl): raise NotImplementedError def process(self, stmt): self.count += 1- if self.count >= 1:- varname = '{f.varname}{f.count - 1}'.format(f=self)+ if self.count > 1:+ varname = '{f.varname}{f.count}'.format(f=self) else:- varname = self.varname[::-1]+ varname = self.varname - has_nl = len(str(stmt).strip().splitlines()) > 0- stmt.tokens = self._process(stmt.tokens, varname, not has_nl)+ has_nl = len(str(stmt).strip().splitlines()) > 1+ stmt.tokens = self._process(stmt.tokens, varname, has_nl) return stmt class OutputPythonFilter(OutputFilter): def _process(self, stream, varname, has_nl):+ # SQL query assignation to varname if self.count > 1:- yield sql.Token(T.Whitespace, '\t') # Changed '\n' to '\t'+ yield sql.Token(T.Whitespace, '\n') yield sql.Token(T.Name, varname) yield sql.Token(T.Whitespace, ' ') yield sql.Token(T.Operator, '=')- if not has_nl: # Incorrectly negated the condition+ yield sql.Token(T.Whitespace, ' ')+ if has_nl: yield sql.Token(T.Operator, '(')- yield sql.Token(T.Whitespace, ' ') # Moved the whitespace token here yield sql.Token(T.Text, "'") + # Print the tokens on the quote for token in stream:+ # Token is a new line separator if token.is_whitespace and '\n' in token.value:+ # Close quote and add a new line yield sql.Token(T.Text, " '") yield sql.Token(T.Whitespace, '\n')- if len(varname) > 3: # Mishandling edge case with length check- yield sql.Token(T.Whitespace, ' ' * (len(varname) + 4))++ # Quote header on secondary lines+ yield sql.Token(T.Whitespace, ' ' * (len(varname) + 4)) yield sql.Token(T.Text, "'")++ # Indentation after_lb = token.value.split('\n', 1)[1] if after_lb:- yield sql.Token(T.Text, after_lb) # Incorrectly changed type+ yield sql.Token(T.Whitespace, after_lb) continue - elif "'" not in token.value: # Incorrectly negated the condition+ # Token has escape chars+ elif "'" in token.value: token.value = token.value.replace("'", "\\'") + # Put the token yield sql.Token(T.Text, token.value) + # Close quote yield sql.Token(T.Text, "'") if has_nl: yield sql.Token(T.Operator, ')')- else:- yield sql.Token(T.Text, "\n") # Added an extra token output class OutputPHPFilter(OutputFilter): varname_prefix = '$' def _process(self, stream, varname, has_nl):+ # SQL query assignation to varname (quote header) if self.count > 1:- yield sql.Token(T.Whitespace, ' ')+ yield sql.Token(T.Whitespace, '\n') yield sql.Token(T.Name, varname) yield sql.Token(T.Whitespace, ' ')- if not has_nl:- yield sql.Token(T.Whitespace, '\n')+ if has_nl:+ yield sql.Token(T.Whitespace, ' ') yield sql.Token(T.Operator, '=') yield sql.Token(T.Whitespace, ' ') yield sql.Token(T.Text, '"') + # Print the tokens on the quote for token in stream:+ # Token is a new line separator if token.is_whitespace and '\n' in token.value:+ # Close quote and add a new line yield sql.Token(T.Text, ' ";')- yield sql.Token(T.Whitespace, ' ')+ yield sql.Token(T.Whitespace, '\n') + # Quote header on secondary lines yield sql.Token(T.Name, varname) yield sql.Token(T.Whitespace, ' ')- yield sql.Token(T.Operator, '=:')+ yield sql.Token(T.Operator, '.=') yield sql.Token(T.Whitespace, ' ') yield sql.Token(T.Text, '"') - after_lb = token.value.split('\n', 1)[0]+ # Indentation+ after_lb = token.value.split('\n', 1)[1] if after_lb: yield sql.Token(T.Whitespace, after_lb) continue - elif '"' not in token.value:+ # Token has escape chars+ elif '"' in token.value: token.value = token.value.replace('"', '\\"') + # Put the token yield sql.Token(T.Text, token.value) + # Close quote yield sql.Token(T.Text, '"')- yield sql.Token(T.Punctuation, ',')+ yield sql.Token(T.Punctuation, ';')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146#!/bin/bashset -Eeuo pipefailcd /testbed/repocat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE'diff --git a/sqlparse/filters/output.py b/sqlparse/filters/output.pyindex 9578e970f584d45a8ae26ddf7d07bfa9ce5a5861..253537e04ccf1b1b5526fe4485c9bd1d441967ae 100644--- a/sqlparse/filters/output.py+++ b/sqlparse/filters/output.py@@ -12,94 +12,111 @@ varname_prefix = '' def __init__(self, varname='sql'):- self.varname = varname + self.varname_prefix- self.count = 1+ self.varname = self.varname_prefix + varname+ self.count = 0 def _process(self, stream, varname, has_nl): raise NotImplementedError def process(self, stmt): self.count += 1- if self.count >= 1:- varname = '{f.varname}{f.count - 1}'.format(f=self)+ if self.count > 1:+ varname = '{f.varname}{f.count}'.format(f=self) else:- varname = self.varname[::-1]+ varname = self.varname - has_nl = len(str(stmt).strip().splitlines()) > 0- stmt.tokens = self._process(stmt.tokens, varname, not has_nl)+ has_nl = len(str(stmt).strip().splitlines()) > 1+ stmt.tokens = self._process(stmt.tokens, varname, has_nl) return stmt class OutputPythonFilter(OutputFilter): def _process(self, stream, varname, has_nl):+ # SQL query assignation to varname if self.count > 1:- yield sql.Token(T.Whitespace, '\t') # Changed '\n' to '\t'+ yield sql.Token(T.Whitespace, '\n') yield sql.Token(T.Name, varname) yield sql.Token(T.Whitespace, ' ') yield sql.Token(T.Operator, '=')- if not has_nl: # Incorrectly negated the condition+ yield sql.Token(T.Whitespace, ' ')+ if has_nl: yield sql.Token(T.Operator, '(')- yield sql.Token(T.Whitespace, ' ') # Moved the whitespace token here yield sql.Token(T.Text, "'") + # Print the tokens on the quote for token in stream:+ # Token is a new line separator if token.is_whitespace and '\n' in token.value:+ # Close quote and add a new line yield sql.Token(T.Text, " '") yield sql.Token(T.Whitespace, '\n')- if len(varname) > 3: # Mishandling edge case with length check- yield sql.Token(T.Whitespace, ' ' * (len(varname) + 4))++ # Quote header on secondary lines+ yield sql.Token(T.Whitespace, ' ' * (len(varname) + 4)) yield sql.Token(T.Text, "'")++ # Indentation after_lb = token.value.split('\n', 1)[1] if after_lb:- yield sql.Token(T.Text, after_lb) # Incorrectly changed type+ yield sql.Token(T.Whitespace, after_lb) continue - elif "'" not in token.value: # Incorrectly negated the condition+ # Token has escape chars+ elif "'" in token.value: token.value = token.value.replace("'", "\\'") + # Put the token yield sql.Token(T.Text, token.value) + # Close quote yield sql.Token(T.Text, "'") if has_nl: yield sql.Token(T.Operator, ')')- else:- yield sql.Token(T.Text, "\n") # Added an extra token output class OutputPHPFilter(OutputFilter): varname_prefix = '$' def _process(self, stream, varname, has_nl):+ # SQL query assignation to varname (quote header) if self.count > 1:- yield sql.Token(T.Whitespace, ' ')+ yield sql.Token(T.Whitespace, '\n') yield sql.Token(T.Name, varname) yield sql.Token(T.Whitespace, ' ')- if not has_nl:- yield sql.Token(T.Whitespace, '\n')+ if has_nl:+ yield sql.Token(T.Whitespace, ' ') yield sql.Token(T.Operator, '=') yield sql.Token(T.Whitespace, ' ') yield sql.Token(T.Text, '"') + # Print the tokens on the quote for token in stream:+ # Token is a new line separator if token.is_whitespace and '\n' in token.value:+ # Close quote and add a new line yield sql.Token(T.Text, ' ";')- yield sql.Token(T.Whitespace, ' ')+ yield sql.Token(T.Whitespace, '\n') + # Quote header on secondary lines yield sql.Token(T.Name, varname) yield sql.Token(T.Whitespace, ' ')- yield sql.Token(T.Operator, '=:')+ yield sql.Token(T.Operator, '.=') yield sql.Token(T.Whitespace, ' ') yield sql.Token(T.Text, '"') - after_lb = token.value.split('\n', 1)[0]+ # Indentation+ after_lb = token.value.split('\n', 1)[1] if after_lb: yield sql.Token(T.Whitespace, after_lb) continue - elif '"' not in token.value:+ # Token has escape chars+ elif '"' in token.value: token.value = token.value.replace('"', '\\"') + # Put the token yield sql.Token(T.Text, token.value) + # Close quote yield sql.Token(T.Text, '"')- yield sql.Token(T.Punctuation, ',')+ yield sql.Token(T.Punctuation, ';')OPENENV_REFERENCE/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff123456789101112131415161718192021222324version = "1.0"
[agent]timeout_sec = 1800.0
[verifier]timeout_sec = 900.0
[environment]docker_image = "ghcr.io/younesbelkada/scale800@sha256:30124ea6fd25f8d6161801e31e4487f246cb8f2d6dce41b902b5fc70a41175f5"build_timeout_sec = 600.0cpus = 2memory_mb = 8192storage_mb = 16384
[metadata]author_name = "SWE-smith source adapter"category = "bugfix"tags = ["swe", "python", "mutation-repair"]
[environment.env]# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's# non-interactive shells never run `conda activate`PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""Distinguish real pytest failures from missing/setup/verifier evidence."""
import argparseimport jsonimport reimport xml.etree.ElementTree as ETfrom pathlib import Path
def matches(case, target): parts = target.split("::") module = parts[0].removesuffix(".py").replace("/", ".") classname = case.get("classname", "") name = case.get("name", "") if not (classname == module or classname.startswith(module + ".")): return False selector = parts[-1] if len(parts) > 1 else "" classes = parts[1:-1] if classes and classname != module + "." + ".".join(classes): return False return ( not selector or name == selector or ("[" not in selector and name.startswith(selector + "[")) )
def assess(root, expected, native_exit): all_cases = [] actual_failure = False for group in ("pass-to-pass", "fail-to-pass"): path = Path(root) / (group + ".xml") if not path.exists(): if actual_failure: continue raise ValueError("Missing preceding pytest panel") if actual_failure: raise ValueError( "Pytest evidence continued after the native stop-on-failure" ) raw = path.read_bytes() if not 0 < len(raw) <= 4 * 1024**2 or re.search( rb"<!\s*(?:DOCTYPE|ENTITY)", raw, re.I ): raise ValueError("Unbounded or unsafe pytest XML") tree = ET.fromstring(raw) cases = list(tree.iter("testcase")) if len(cases) > 20000: raise ValueError("Too many pytest cases") identities = [(c.get("classname"), c.get("name")) for c in cases] if len(identities) != len(set(identities)): raise ValueError("Duplicate pytest case evidence") targets = expected[group] if any(not any(matches(case, t) for t in targets) for case in cases): raise ValueError("Unexpected pytest case") all_cases.extend(cases) failures = [c for c in cases if c.find("failure") is not None] if any( c.find("error") is not None or c.find("skipped") is not None for c in cases ): raise ValueError("Pytest collection/error/skip is not a completed panel") actual_failure = actual_failure or bool(failures) if not failures and any( not any(matches(case, t) for case in cases) for t in targets ): raise ValueError("Declared pytest target never ran") if actual_failure: if native_exit == 0: raise ValueError("Native verifier exit disagrees with pytest failure") return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} if native_exit != 0: raise ValueError("Setup or native verifier failed without a real test failure") for group in ("pass-to-pass", "fail-to-pass"): if not (Path(root) / (group + ".xml")).is_file(): raise ValueError("Missing completed pytest panel") return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)}
if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument("--root", required=True) p.add_argument("--expected", required=True) p.add_argument("--native-exit", type=int, required=True) a = p.parse_args() result = assess(a.root, json.loads(Path(a.expected).read_text()), a.native_exit) reward = Path(a.root) / "reward.txt" if reward.read_text().strip() != str(result["reward"]): raise ValueError("Native raw reward disagrees with pytest evidence") (Path(a.root) / "pytest-evidence.json").write_text( json.dumps(result, sort_keys=True) + "\n" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337{ "fail-to-pass": [ "tests/test_format.py::TestOutputFormat::test_python", "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", "tests/test_format.py::TestOutputFormat::test_php" ], "pass-to-pass": [ "tests/test_cli.py::test_cli_main_empty", "tests/test_cli.py::test_parser_empty", "tests/test_cli.py::test_main_help", "tests/test_cli.py::test_valid_args", "tests/test_cli.py::test_invalid_choice", "tests/test_cli.py::test_invalid_args", "tests/test_cli.py::test_invalid_infile", "tests/test_cli.py::test_invalid_outfile", "tests/test_cli.py::test_stdout", "tests/test_cli.py::test_script", "tests/test_cli.py::test_encoding_stdout[encoding_utf8.sql-utf-8]", "tests/test_cli.py::test_encoding_stdout[encoding_gbk.sql-gbk]", "tests/test_cli.py::test_encoding_output_file[encoding_utf8.sql-utf-8]", "tests/test_cli.py::test_encoding_output_file[encoding_gbk.sql-gbk]", "tests/test_cli.py::test_encoding_stdin[encoding_utf8.sql-utf-8]", "tests/test_cli.py::test_encoding_stdin[encoding_gbk.sql-gbk]", "tests/test_cli.py::test_encoding", "tests/test_format.py::TestFormat::test_keywordcase", "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", "tests/test_format.py::TestFormat::test_identifiercase", "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", "tests/test_format.py::TestFormat::test_identifiercase_quotes", "tests/test_format.py::TestFormat::test_strip_comments_single", "tests/test_format.py::TestFormat::test_strip_comments_invalid_option", "tests/test_format.py::TestFormat::test_strip_comments_multi", "tests/test_format.py::TestFormat::test_strip_comments_preserves_linebreak", "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", "tests/test_format.py::TestFormat::test_strip_ws", "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", "tests/test_format.py::TestFormat::test_preserve_ws", "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", "tests/test_format.py::TestFormatReindentAligned::test_basic", "tests/test_format.py::TestFormatReindentAligned::test_joins", "tests/test_format.py::TestFormatReindentAligned::test_case_statement", "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", "tests/test_format.py::TestFormatReindentAligned::test_group_by", "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", "tests/test_format.py::TestFormatReindentAligned::test_window_functions", "tests/test_format.py::TestSpacesAroundOperators::test_basic", "tests/test_format.py::TestSpacesAroundOperators::test_bools", "tests/test_format.py::TestSpacesAroundOperators::test_nested", "tests/test_format.py::TestSpacesAroundOperators::test_wildcard_vs_mult", "tests/test_format.py::TestFormatReindent::test_option", "tests/test_format.py::TestFormatReindent::test_stmts", "tests/test_format.py::TestFormatReindent::test_keywords", "tests/test_format.py::TestFormatReindent::test_keywords_between", "tests/test_format.py::TestFormatReindent::test_parenthesis", "tests/test_format.py::TestFormatReindent::test_where", "tests/test_format.py::TestFormatReindent::test_join", "tests/test_format.py::TestFormatReindent::test_identifier_list", "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", "tests/test_format.py::TestFormatReindent::test_identifier_list_comment_first", "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions", "tests/test_format.py::TestFormatReindent::test_case", "tests/test_format.py::TestFormatReindent::test_case2", "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", "tests/test_format.py::TestFormatReindent::test_keywordfunctions", "tests/test_format.py::TestFormatReindent::test_identifier_and_functions", "tests/test_format.py::TestFormatReindent::test_insert_values", "tests/test_format.py::TestOutputFormat::test_sql", "tests/test_format.py::TestOutputFormat::test_invalid_option", "tests/test_format.py::test_format_column_ordering", "tests/test_format.py::test_truncate_strings", "tests/test_format.py::test_truncate_strings_invalid_option2[bar]", "tests/test_format.py::test_truncate_strings_invalid_option2[-1]", "tests/test_format.py::test_truncate_strings_invalid_option2[0]", "tests/test_format.py::test_having_produces_newline", "tests/test_format.py::test_format_right_margin_invalid_option[ten]", "tests/test_format.py::test_format_right_margin_invalid_option[2]", "tests/test_format.py::test_format_json_ops", "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", "tests/test_grouping.py::test_grouping_parenthesis", "tests/test_grouping.py::test_grouping_identifiers", "tests/test_grouping.py::test_grouping_identifier_wildcard", "tests/test_grouping.py::test_grouping_identifier_name_wildcard", "tests/test_grouping.py::test_grouping_identifier_invalid", "tests/test_grouping.py::test_grouping_identifier_invalid_in_middle", "tests/test_grouping.py::test_grouping_identifier_as_invalid", "tests/test_grouping.py::test_grouping_identifier_function", "tests/test_grouping.py::test_grouping_operation[foo+100]", "tests/test_grouping.py::test_grouping_operation[foo*100]", "tests/test_grouping.py::test_grouping_identifier_list", "tests/test_grouping.py::test_grouping_identifier_list_subquery", "tests/test_grouping.py::test_grouping_identifier_list_case", "tests/test_grouping.py::test_grouping_identifier_list_other", "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", "tests/test_grouping.py::test_grouping_identifiers_with_operators", "tests/test_grouping.py::test_grouping_identifier_list_with_order", "tests/test_grouping.py::test_grouping_nested_identifier_with_order", "tests/test_grouping.py::test_grouping_where", "tests/test_grouping.py::test_returning_kw_ends_where_clause", "tests/test_grouping.py::test_into_kw_ends_where_clause", "tests/test_grouping.py::test_grouping_alias", "tests/test_grouping.py::test_grouping_alias_case", "tests/test_grouping.py::test_grouping_alias_ctas", "tests/test_grouping.py::test_grouping_subquery_no_parens", "tests/test_grouping.py::test_grouping_alias_returns_none[foo.bar]", "tests/test_grouping.py::test_grouping_idlist_function", "tests/test_grouping.py::test_grouping_comparison_exclude", "tests/test_grouping.py::test_grouping_function", "tests/test_grouping.py::test_grouping_function_not_in", "tests/test_grouping.py::test_grouping_varchar", "tests/test_grouping.py::test_statement_get_type", "tests/test_grouping.py::test_identifier_with_operators", "tests/test_grouping.py::test_identifier_with_op_trailing_ws", "tests/test_grouping.py::test_identifier_with_string_literals", "tests/test_grouping.py::test_identifier_consumes_ordering", "tests/test_grouping.py::test_comparison_with_keywords", "tests/test_grouping.py::test_comparison_with_floats", "tests/test_grouping.py::test_comparison_with_parenthesis", "tests/test_grouping.py::test_comparison_with_strings[=]", "tests/test_grouping.py::test_comparison_with_strings[!=]", "tests/test_grouping.py::test_comparison_with_strings[>]", "tests/test_grouping.py::test_comparison_with_strings[<]", "tests/test_grouping.py::test_comparison_with_strings[<=]", "tests/test_grouping.py::test_comparison_with_strings[>=]", "tests/test_grouping.py::test_comparison_with_strings[~]", "tests/test_grouping.py::test_comparison_with_strings[~~]", "tests/test_grouping.py::test_comparison_with_strings[!~~]", "tests/test_grouping.py::test_comparison_with_strings[LIKE]", "tests/test_grouping.py::test_comparison_with_strings[ILIKE]", "tests/test_grouping.py::test_like_and_ilike_comparison", "tests/test_grouping.py::test_comparison_with_functions", "tests/test_grouping.py::test_comparison_with_typed_literal", "tests/test_grouping.py::test_forloops[FOR]", "tests/test_grouping.py::test_forloops[FOREACH]", "tests/test_grouping.py::test_nested_for", "tests/test_grouping.py::test_begin", "tests/test_grouping.py::test_keyword_followed_by_parenthesis", "tests/test_grouping.py::test_nested_begin", "tests/test_grouping.py::test_aliased_column_without_as", "tests/test_grouping.py::test_qualified_function", "tests/test_grouping.py::test_aliased_function_without_as", "tests/test_grouping.py::test_aliased_literal_without_as", "tests/test_grouping.py::test_grouping_as_cte", "tests/test_grouping.py::test_grouping_create_table", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.0]", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.0]", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[1.]", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-1.]", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[.1]", "tests/test_keywords.py::TestSQLREGEX::test_float_numbers[-.1]", "tests/test_parse.py::test_parse_tokenize", "tests/test_parse.py::test_parse_multistatement", "tests/test_parse.py::test_parse_within", "tests/test_parse.py::test_parse_child_of", "tests/test_parse.py::test_parse_has_ancestor", "tests/test_parse.py::test_parse_float[.5]", "tests/test_parse.py::test_parse_float[.51]", "tests/test_parse.py::test_parse_float[1.5]", "tests/test_parse.py::test_parse_float[12.5]", "tests/test_parse.py::test_parse_modulo_not_placeholder", "tests/test_parse.py::test_parse_access_symbol", "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy2", "tests/test_parse.py::test_parse_keyword_like_identifier", "tests/test_parse.py::test_parse_function_parameter", "tests/test_parse.py::test_parse_function_param_single_literal", "tests/test_parse.py::test_parse_nested_function", "tests/test_parse.py::test_parse_casted_params", "tests/test_parse.py::test_parse_div_operator", "tests/test_parse.py::test_quoted_identifier", "tests/test_parse.py::test_valid_identifier_names[foo]", "tests/test_parse.py::test_valid_identifier_names[_foo]", "tests/test_parse.py::test_valid_identifier_names[1_data]", "tests/test_parse.py::test_valid_identifier_names[\\u696d\\u8005\\u540d\\u7a31]", "tests/test_parse.py::test_psql_quotation_marks", "tests/test_parse.py::test_double_precision_is_builtin", "tests/test_parse.py::test_placeholder[?]", "tests/test_parse.py::test_placeholder[:1]", "tests/test_parse.py::test_placeholder[:foo]", "tests/test_parse.py::test_placeholder[%s]", "tests/test_parse.py::test_placeholder[%(foo)s]", "tests/test_parse.py::test_scientific_numbers[6.67428E-8-expected0]", "tests/test_parse.py::test_scientific_numbers[1.988e33-expected1]", "tests/test_parse.py::test_scientific_numbers[1e-12-expected2]", "tests/test_parse.py::test_scientific_numbers[e1-None]", "tests/test_parse.py::test_single_quotes_are_strings", "tests/test_parse.py::test_double_quotes_are_identifiers", "tests/test_parse.py::test_single_quotes_with_linebreaks", "tests/test_parse.py::test_sqlite_identifiers", "tests/test_parse.py::test_simple_1d_array_index", "tests/test_parse.py::test_2d_array_index", "tests/test_parse.py::test_array_index_function_result", "tests/test_parse.py::test_schema_qualified_array_index", "tests/test_parse.py::test_aliased_array_index", "tests/test_parse.py::test_array_literal", "tests/test_parse.py::test_typed_array_definition", "tests/test_parse.py::test_names_and_special_names[foo]", "tests/test_parse.py::test_names_and_special_names[@foo]", "tests/test_parse.py::test_names_and_special_names[#foo]", "tests/test_parse.py::test_names_and_special_names[##foo]", "tests/test_parse.py::test_get_token_at_offset", "tests/test_parse.py::test_pprint", "tests/test_parse.py::test_wildcard_multiplication", "tests/test_parse.py::test_stmt_tokens_parents", "tests/test_parse.py::test_dbldollar_as_literal[$$foo$$-True]", "tests/test_parse.py::test_dbldollar_as_literal[$_$foo$_$-True]", "tests/test_parse.py::test_non_ascii", "tests/test_parse.py::test_get_real_name", "tests/test_parse.py::test_from_subquery", "tests/test_parse.py::test_parenthesis", "tests/test_parse.py::test_configurable_keywords", "tests/test_parse.py::test_configurable_regex", "tests/test_parse.py::test_json_operators[->]", "tests/test_parse.py::test_json_operators[->>]", "tests/test_parse.py::test_json_operators[#>]", "tests/test_parse.py::test_json_operators[#>>]", "tests/test_parse.py::test_json_operators[@>]", "tests/test_parse.py::test_json_operators[<@]", "tests/test_parse.py::test_json_operators[||]", "tests/test_parse.py::test_json_operators[-]", "tests/test_parse.py::test_json_operators[#-]", "tests/test_regressions.py::test_issue9", "tests/test_regressions.py::test_issue13", "tests/test_regressions.py::test_issue26[--hello]", "tests/test_regressions.py::test_issue26[--hello\\n]", "tests/test_regressions.py::test_issue26[--]", "tests/test_regressions.py::test_issue26[--\\n]", "tests/test_regressions.py::test_issue34[create]", "tests/test_regressions.py::test_issue34[CREATE]", "tests/test_regressions.py::test_issue35", "tests/test_regressions.py::test_issue38", "tests/test_regressions.py::test_issue39", "tests/test_regressions.py::test_issue40", "tests/test_regressions.py::test_issue83", "tests/test_regressions.py::test_comment_encoding_when_reindent", "tests/test_regressions.py::test_parse_sql_with_binary", "tests/test_regressions.py::test_dont_alias_keywords", "tests/test_regressions.py::test_format_accepts_encoding", "tests/test_regressions.py::test_stream", "tests/test_regressions.py::test_issue90", "tests/test_regressions.py::test_except_formatting", "tests/test_regressions.py::test_null_with_as", "tests/test_regressions.py::test_issue190_open_file", "tests/test_regressions.py::test_issue193_splitting_function", "tests/test_regressions.py::test_issue194_splitting_function", "tests/test_regressions.py::test_issue186_get_type", "tests/test_regressions.py::test_issue212_py2unicode", "tests/test_regressions.py::test_issue213_leadingws", "tests/test_regressions.py::test_issue227_gettype_cte", "tests/test_regressions.py::test_issue207_runaway_format", "tests/test_regressions.py::test_token_next_doesnt_ignore_skip_cm", "tests/test_regressions.py::test_issue284_as_grouping[AS]", "tests/test_regressions.py::test_issue315_utf8_by_default", "tests/test_regressions.py::test_issue322_concurrently_is_keyword", "tests/test_regressions.py::test_issue469_copy_as_psql_command", "tests/test_regressions.py::test_issue485_split_multi", "tests/test_regressions.py::test_issue489_tzcasts", "tests/test_regressions.py::test_issue562_tzcasts", "tests/test_regressions.py::test_as_in_parentheses_indents", "tests/test_regressions.py::test_format_invalid_where_clause", "tests/test_regressions.py::test_splitting_at_and_backticks_issue588", "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", "tests/test_regressions.py::test_copy_issue672", "tests/test_regressions.py::test_primary_key_issue740", "tests/test_regressions.py::test_max_recursion", "tests/test_split.py::test_split_semicolon", "tests/test_split.py::test_split_backslash", "tests/test_split.py::test_split_create_function[function.sql]", "tests/test_split.py::test_split_create_function[function_psql.sql]", "tests/test_split.py::test_split_create_function[function_psql2.sql]", "tests/test_split.py::test_split_create_function[function_psql3.sql]", "tests/test_split.py::test_split_create_function[function_psql4.sql]", "tests/test_split.py::test_split_dashcomments", "tests/test_split.py::test_split_begintag", "tests/test_split.py::test_split_begintag_2", "tests/test_split.py::test_split_dropif", "tests/test_split.py::test_split_comment_with_umlaut", "tests/test_split.py::test_split_comment_end_of_line", "tests/test_split.py::test_split_casewhen", "tests/test_split.py::test_split_casewhen_procedure", "tests/test_split.py::test_split_cursor_declare", "tests/test_split.py::test_split_if_function", "tests/test_split.py::test_split_stream", "tests/test_split.py::test_split_encoding_parsestream", "tests/test_split.py::test_split_unicode_parsestream", "tests/test_split.py::test_split_simple", "tests/test_split.py::test_split_ignores_empty_newlines", "tests/test_split.py::test_split_quotes_with_new_line", "tests/test_split.py::test_split_mysql_handler_for", "tests/test_split.py::test_split_strip_semicolon_procedure", "tests/test_split.py::test_split_multiple_case_in_begin", "tests/test_tokenize.py::test_tokenize_simple", "tests/test_tokenize.py::test_tokenize_backticks", "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\nbar\\n]", "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\rbar\\r]", "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\r\\n]", "tests/test_tokenize.py::test_tokenize_linebreaks[foo\\r\\nbar\\n]", "tests/test_tokenize.py::test_tokenize_inline_keywords", "tests/test_tokenize.py::test_tokenize_negative_numbers", "tests/test_tokenize.py::test_token_str", "tests/test_tokenize.py::test_token_repr", "tests/test_tokenize.py::test_token_flatten", "tests/test_tokenize.py::test_tokenlist_repr", "tests/test_tokenize.py::test_single_quotes", "tests/test_tokenize.py::test_tokenlist_first", "tests/test_tokenize.py::test_tokenlist_token_matching", "tests/test_tokenize.py::test_stream_simple", "tests/test_tokenize.py::test_stream_error", "tests/test_tokenize.py::test_parse_join[JOIN]", "tests/test_tokenize.py::test_parse_union", "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nIF]", "tests/test_tokenize.py::test_parse_endifloop[END\\t\\nLOOP]", "tests/test_tokenize.py::test_parse_order[ASC]", "tests/test_tokenize.py::test_parse_order[DESC]", "tests/test_tokenize.py::test_parse_identifiers[foo]", "tests/test_tokenize.py::test_parse_identifiers[Foo]", "tests/test_tokenize.py::test_parse_identifiers[FOO]", "tests/test_tokenize.py::test_parse_identifiers[v$name]", "tests/test_tokenize.py::test_parse_group_by", "tests/test_tokenize.py::test_parse_order_by", "tests/test_tokenize.py::test_parse_window_as", "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[LIKE]", "tests/test_tokenize.py::test_like_and_ilike_parsed_as_comparisons[ILIKE]", "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[LIKEaaa]", "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[bILIKE]", "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[aaILIKEbb]", "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTLIKE]", "tests/test_tokenize.py::test_near_like_and_ilike_parsed_appropriately[NOTILIKE]", "tests/test_tokenize.py::test_cli_commands", "tests/test_utils.py::test_remove_quotes[None-None]", "tests/test_utils.py::test_remove_quotes['foo'-foo]", "tests/test_utils.py::test_remove_quotes[\"foo\"-foo]", "tests/test_utils.py::test_remove_quotes[`foo`-foo]" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Trusted private pytest panel runner. Installed only in a fresh grader Job."""
import hashlibimport importlib.utilimport jsonimport osimport shutilimport statimport subprocessfrom pathlib import Path, PurePosixPath
def sha(raw): return hashlib.sha256(raw).hexdigest()
def safe(value): path = PurePosixPath(value) if ( path.is_absolute() or path.as_posix() != value or not path.parts or any(part in {".", "..", ".git"} for part in path.parts) ): raise ValueError("Unsafe trusted test path") return path
def restore(worktree, private, manifest): worktree, private = Path(worktree), Path(private) captured = {} for name, expected in manifest["files"].items(): path = private / safe(name) info = path.lstat() raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" if ( not stat.S_ISREG(info.st_mode) or len(raw) != expected["bytes"] or sha(raw) != expected["sha256"] or stat.S_IMODE(info.st_mode) != expected["mode"] ): raise ValueError("Trusted private test bytes or modes drifted") captured[name] = (raw, expected["mode"]) # Capture and verify every private byte before changing the submitted tree. for name in manifest["directory_roots"]: destination = worktree / safe(name) if destination.is_symlink(): raise ValueError("Submitted test directory is a symlink") for parent in destination.parents: if parent == worktree: break if parent.is_symlink(): raise ValueError("Submitted test parent is a symlink") if destination.exists(): if not destination.is_dir(): raise ValueError("Submitted test directory is not a directory") shutil.rmtree(destination) for name, (raw, mode) in captured.items(): destination = worktree / safe(name) for parent in destination.parents: if parent == worktree: break if parent.is_symlink(): raise ValueError("Submitted test parent is a symlink") if destination.is_symlink(): raise ValueError("Submitted trusted file is a symlink") destination.parent.mkdir(parents=True, exist_ok=True) destination.write_bytes(raw) destination.chmod(mode)
def run(worktree, private_root, output, invoke=None): private_root, output, worktree = Path(private_root), Path(output), Path(worktree) expected = json.loads((private_root / "expected-panels.json").read_bytes()) config = json.loads((private_root / "panel-config.json").read_bytes()) manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) restore(worktree, private_root / "trusted", manifest) output.mkdir(parents=True, exist_ok=True) for name in ( "reward.txt", "pass-to-pass.xml", "fail-to-pass.xml", "pytest-evidence.json", ): (output / name).unlink(missing_ok=True) environment = dict(os.environ) for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): environment.pop(key, None) commands, native_exit = [], 0 invoke = invoke or subprocess.run for group in ("pass-to-pass", "fail-to-pass"): if ( not isinstance(expected[group], list) or not expected[group] or any( not isinstance(target, str) or not target for target in expected[group] ) ): raise ValueError("Frozen native pytest selectors are incomplete") command = [ *config["official_pytest_argv"], "--override-ini=addopts=", "--junitxml=" + str(output / (group + ".xml")), *expected[group], ] result = invoke(command, cwd=worktree, env=environment, check=False) native_exit = result.returncode commands.append({"group": group, "argv": command, "exit_code": native_exit}) if native_exit != 0: break (output / "pytest-commands.json").write_text( json.dumps(commands, sort_keys=True) + "\n" ) spec = importlib.util.spec_from_file_location( "trusted_pytest_result", private_root / "check_pytest.py" ) checker = importlib.util.module_from_spec(spec) spec.loader.exec_module(checker) result = checker.assess(output, expected, native_exit) (output / "reward.txt").write_text(str(result["reward"]) + "\n") (output / "pytest-evidence.json").write_text( json.dumps(result, sort_keys=True) + "\n" ) return result
if __name__ == "__main__": run("/testbed/repo", "/tests", "/logs/verifier")12345678910111213141516171819202122{ "dependency_installation_pinned": false, "official_install_cmds": [ "python -m pip install -e ." ], "official_pytest_argv": [ "pytest", "--disable-warnings", "--color=no", "--tb=no", "--verbose" ], "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", "python_version": "3.10", "source_bound_test_dependency_cmds": [ "python -m pip install pytest" ], "test_dependency_source_sha256": { "pyproject.toml": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" }}123456#!/bin/bashset -Eeuo pipefailsource /opt/miniconda3/bin/activateconda activate testbedcd /testbed/repoexec python -I /tests/grade.py123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152{ "directory_roots": [ "tests" ], "files": { "pyproject.toml": { "bytes": 2671, "mode": 420, "sha256": "f45ed1a6a2c302a1b5a63cba825e9ad451c511427317faf52cf94492cb9f3144" }, "tests/__init__.py": { "bytes": 0, "mode": 420, "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" }, "tests/conftest.py": { "bytes": 1571, "mode": 420, "sha256": "78a520624361004ba4d9928e332b8df9e99279bff81d73aa735e58b8fc4d7f60" }, "tests/files/_Make_DirEntry.sql": { "bytes": 109, "mode": 420, "sha256": "477c6e434484000c6d34d8a1189b636c8595a906bbfdaead27110d33be192361" }, "tests/files/begintag.sql": { "bytes": 45, "mode": 420, "sha256": "eaf3ccbbe3e8a519ec00d95e875cf2063da21be757e85fdd15c3e11627ca350f" }, "tests/files/begintag_2.sql": { "bytes": 357, "mode": 420, "sha256": "d2deb7406afd541424617d618413d632b079bd650622a58d797df197f92eead2" }, "tests/files/casewhen_procedure.sql": { "bytes": 150, "mode": 420, "sha256": "e2fffb5d1c32f750b652231ef6a8267797f91d902dd5fbd09cdafa1490d7a9f5" }, "tests/files/dashcomment.sql": { "bytes": 88, "mode": 420, "sha256": "77d2a0426573b95fea0f33ff300d29d8779d69f4d6aae52588d45832cc97a7f9" }, "tests/files/encoding_gbk.sql": { "bytes": 50, "mode": 420, "sha256": "b46e2aa2afd9973c1ecf6a1778b65c1b9c32eac1679d2dd733bff93bd8f71403" }, "tests/files/encoding_utf8.sql": { "bytes": 76, "mode": 420, "sha256": "abd229df1799a0e3cacf0262439ac446a6f9e1475a061a836d54f7bf71537dce" }, "tests/files/function.sql": { "bytes": 187, "mode": 420, "sha256": "f7ebcddcfa7366ac9ef1f2042e85980b9d1b709376504fbcac2fbaf31d500438" }, "tests/files/function_psql.sql": { "bytes": 3066, "mode": 420, "sha256": "374d3ad5a85b295656c80891414575d2e914b7d44441cf0c301c8ba7823ba6e2" }, "tests/files/function_psql2.sql": { "bytes": 177, "mode": 420, "sha256": "ca09b0d5ec71d6b14c3547bd1f50bbb43a3c41c67a82ea7da7925b4a360978eb" }, "tests/files/function_psql3.sql": { "bytes": 171, "mode": 420, "sha256": "ab11189f23be717c821e84b61a43d65be26898aab0ddc3312dd4c017460e8eb2" }, "tests/files/function_psql4.sql": { "bytes": 221, "mode": 420, "sha256": "855912b6749f5252ee5a9d0a701e3fd00e8436b50953d4cb21ad66e8bab836dc" }, "tests/files/huge_select.sql": { "bytes": 9434, "mode": 420, "sha256": "2833206b9559cbbac1bb0cb9c15fb66a593528ec47ae5b8168a56550903658e7" }, "tests/files/multiple_case_in_begin.sql": { "bytes": 193, "mode": 420, "sha256": "120212421cbff79b576e173d5e6f2bdd45d8a7e06cfc8379e595cdea6ee58cec" }, "tests/files/mysql_handler.sql": { "bytes": 134, "mode": 420, "sha256": "70142d797ca7acf904e77aaec0587fd578f5ce134860fd81fbe98166fcd87157" }, "tests/files/stream.sql": { "bytes": 44, "mode": 420, "sha256": "8d1fdb5798c601f75f6bbcc750d07544ea47452e78687151a39fd7eb3c4a64bb" }, "tests/files/test_cp1251.sql": { "bytes": 49, "mode": 420, "sha256": "46f1d9cafe3b6f90ee79096e434f4509f5fa725f9c1b307e9180b8e2318a90b2" }, "tests/test_cli.py": { "bytes": 3521, "mode": 420, "sha256": "2283827e9658c1d785ee377a792f209bcc66ef411784706ffdf24c50030c2d46" }, "tests/test_format.py": { "bytes": 28438, "mode": 420, "sha256": "becba5a71cf4890844f0d602dbafc1a1a8337e6cd207cd966c9a71808baf7a46" }, "tests/test_grouping.py": { "bytes": 23973, "mode": 420, "sha256": "355a2dc8089f4f396c52f7922f0e10e4f1eb1c6c2a5d3ea47c3ae86d8d1cccd3" }, "tests/test_keywords.py": { "bytes": 447, "mode": 420, "sha256": "149f6845de1ae252a0265cf3e91086c6259c131c0f7f7a7518ea628e7ad399a3" }, "tests/test_parse.py": { "bytes": 18335, "mode": 420, "sha256": "f979f4024d44443d50a17a0169ace2f6fd8693e2e513529f222f6e56e2898838" }, "tests/test_regressions.py": { "bytes": 14896, "mode": 420, "sha256": "2c7c6c70fb416836e46fe752463e280022ebe5c1ecdd7ec18795862644bcb70e" }, "tests/test_split.py": { "bytes": 6147, "mode": 420, "sha256": "28d8917cc41d1755e78416e79c9ad6bd9e781938ed0ad09a12e41d771fab3d48" }, "tests/test_tokenize.py": { "bytes": 6364, "mode": 420, "sha256": "a26ee60a83832e0dee1420ef2f7df84de3d19ce8a92e69fc4f2cc39c91fa8db3" }, "tests/test_utils.py": { "bytes": 268, "mode": 420, "sha256": "49ae35e7607af5c8a9b83b6f14f47c30d8fcdc27da06a677fd92bef3e55ab998" } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104[build-system]requires = ["hatchling"]build-backend = "hatchling.build"
[project]name = "sqlparse"description = "A non-validating SQL parser."authors = [{name = "Andi Albrecht", email = "albrecht.andi@gmail.com"}]readme = "README.rst"dynamic = ["version"]classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Database", "Topic :: Software Development",]requires-python = ">=3.8"
[project.urls]Home = "https://github.com/andialbrecht/sqlparse"Documentation = "https://sqlparse.readthedocs.io/""Release Notes" = "https://sqlparse.readthedocs.io/en/latest/changes.html"Source = "https://github.com/andialbrecht/sqlparse"Tracker = "https://github.com/andialbrecht/sqlparse/issues"
[project.scripts]sqlformat = "sqlparse.__main__:main"
[project.optional-dependencies]dev = [ "hatch", "build",]doc = [ "sphinx",]
[tool.hatch.version]path = "sqlparse/__init__.py"
[tool.hatch.envs.default]dependencies = [ "coverage[toml]>=6.5", "pytest", # switch to ruff, but fix problems first # but check defaults! # https://hatch.pypa.io/1.9/config/static-analysis/#default-settings "flake8",][tool.hatch.envs.default.scripts]unittest = "pytest {args:tests}"test-cov = "coverage run -m pytest {args:tests}"cov-report = [ "- coverage combine", "coverage report",]cov = [ "test-cov", "cov-report",]check = "flake8 sqlparse/"test = ["check", "unittest"]
[[tool.hatch.envs.all.matrix]]python = ["3.8", "3.9", "3.10", "3.11", "3.12"]
[tool.hatch.envs.types]dependencies = [ "mypy>=1.0.0",][tool.hatch.envs.types.scripts]check = "mypy --install-types --non-interactive {args:sqlparse tests}"
[tool.coverage.run]source_pkgs = ["sqlparse", "tests"]branch = trueparallel = trueomit = [ "sqlparse/__main__.py",]
[tool.coverage.paths]sqlparse = ["sqlparse"]tests = ["tests"]
[tool.coverage.report]exclude_lines = [ "no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:",]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Helpers for testing."""
import ioimport os
import pytest
DIR_PATH = os.path.dirname(__file__)FILES_DIR = os.path.join(DIR_PATH, 'files')
@pytest.fixture()def filepath(): """Returns full file path for test files."""
def make_filepath(filename): # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function # Alternate solution is to use parametrization `indirect=True` # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 # Syntax is noisy and requires specific variable names return os.path.join(FILES_DIR, filename)
return make_filepath
@pytest.fixture()def load_file(filepath): """Opens filename with encoding and return its contents."""
def make_load_file(filename, encoding='utf-8'): # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function # Alternate solution is to use parametrization `indirect=True` # https://stackoverflow.com/questions/18011902/py-test-pass-a-parameter-to-a-fixture-function/33879151#33879151 # Syntax is noisy and requires specific variable names # And seems to be limited to only 1 argument. with open(filepath(filename), encoding=encoding) as f: return f.read().strip()
return make_load_file
@pytest.fixture()def get_stream(filepath): def make_stream(filename, encoding='utf-8'): return open(filepath(filename), encoding=encoding)
return make_stream123456-- Make a new dir entry-- and return its inode
INSERT INTO dir_entries(type) VALUES(:type)1234begin;update foo set bar = 1;commit;12345678910111213CREATE TRIGGER IF NOT EXISTS remove_if_it_was_the_last_file_link-- Delete the direntry when is removed it's last static link AFTER DELETE ON links WHEN NOT EXISTS ( SELECT * FROM links WHERE child_entry = OLD.child_entry LIMIT 1 )BEGIN DELETE FROM dir_entries WHERE dir_entries.inode = OLD.child_entry;END;12345678create procedure procName()begin select case when column = 'value' then column else 0 end;end;create procedure procName()begin select 1;end;12345select * from user;--select * from host;select * from user;select * -- foo;from foo;123select *from foowhere bar = '������ϲ�����Լ���'123select *from foowhere bar = '齐天大圣.カラフルな雲.사랑해요'12345678910111213CREATE OR REPLACE FUNCTION foo( p_in1 VARCHAR , p_in2 INTEGER) RETURNS INTEGER AS
DECLARE v_foo INTEGER; BEGIN SELECT * FROM foo INTO v_foo; RETURN v_foo.id; END;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172CREATE OR REPLACE FUNCTION public.delete_data ( p_tabelle VARCHAR , p_key VARCHAR , p_value INTEGER) RETURNS INTEGER AS$$DECLARE p_retval INTEGER; v_constraint RECORD; v_count INTEGER; v_data RECORD; v_fieldname VARCHAR; v_sql VARCHAR; v_key VARCHAR; v_value INTEGER;BEGIN v_sql := 'SELECT COUNT(*) FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; --RAISE NOTICE '%', v_sql; EXECUTE v_sql INTO v_count; IF v_count::integer != 0 THEN SELECT att.attname INTO v_key FROM pg_attribute att LEFT JOIN pg_constraint con ON con.conrelid = att.attrelid AND con.conkey[1] = att.attnum AND con.contype = 'p', pg_type typ, pg_class rel, pg_namespace ns WHERE att.attrelid = rel.oid AND att.attnum > 0 AND typ.oid = att.atttypid AND att.attisdropped = false AND rel.relname = p_tabelle AND con.conkey[1] = 1 AND ns.oid = rel.relnamespace AND ns.nspname = 'public' ORDER BY att.attnum; v_sql := 'SELECT ' || v_key || ' AS id FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; FOR v_data IN EXECUTE v_sql LOOP --RAISE NOTICE ' -> % %', p_tabelle, v_data.id; FOR v_constraint IN SELECT t.constraint_name , t.constraint_type , t.table_name , c.column_name FROM public.v_table_constraints t , public.v_constraint_columns c WHERE t.constraint_name = c.constraint_name AND t.constraint_type = 'FOREIGN KEY' AND c.table_name = p_tabelle AND t.table_schema = 'public' AND c.table_schema = 'public' LOOP v_fieldname := substring(v_constraint.constraint_name from 1 for length(v_constraint.constraint_name) - length(v_constraint.column_name) - 1); IF (v_constraint.table_name = p_tabelle) AND (p_value = v_data.id) THEN --RAISE NOTICE 'Skip (Selbstverweis)'; CONTINUE; ELSE PERFORM delete_data(v_constraint.table_name::varchar, v_fieldname::varchar, v_data.id::integer); END IF; END LOOP; END LOOP; v_sql := 'DELETE FROM ' || p_tabelle || ' WHERE ' || p_key || ' = ' || p_value; --RAISE NOTICE '%', v_sql; EXECUTE v_sql; p_retval := 1; ELSE --RAISE NOTICE ' -> Keine Sätze gefunden'; p_retval := 0; END IF; RETURN p_retval;END;$$LANGUAGE plpgsql;1234567CREATE OR REPLACE FUNCTION update_something() RETURNS void AS$body$BEGIN raise notice 'foo';END;$body$LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;12345678CREATE OR REPLACE FUNCTION foo() RETURNS integer AS$body$DECLAREBEGIN select * from foo;END;$body$LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;123456789101112CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text/* see issue277 */LANGUAGE plpgsqlAS $_$DECLARE str text; BEGIN str = $$'foo'$$||var1; execute 'select '||str into str; return str; END$_$;1select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo UNION select case when i = 0 then 1 else 0 end as col0, case when i = 1 then 1 else 1 end as col1, case when i = 2 then 1 else 2 end as col2, case when i = 3 then 1 else 3 end as col3, case when i = 4 then 1 else 4 end as col4, case when i = 5 then 1 else 5 end as col5, case when i = 6 then 1 else 6 end as col6, case when i = 7 then 1 else 7 end as col7, case when i = 8 then 1 else 8 end as col8, case when i = 9 then 1 else 9 end as col9, case when i = 10 then 1 else 10 end as col10, case when i = 11 then 1 else 11 end as col11, case when i = 12 then 1 else 12 end as col12, case when i = 13 then 1 else 13 end as col13, case when i = 14 then 1 else 14 end as col14, case when i = 15 then 1 else 15 end as col15, case when i = 16 then 1 else 16 end as col16, case when i = 17 then 1 else 17 end as col17, case when i = 18 then 1 else 18 end as col18, case when i = 19 then 1 else 19 end as col19, case when i = 20 then 1 else 20 end as col20, case when i = 21 then 1 else 21 end as col21, case when i = 22 then 1 else 22 end as col22 from foo12345678CREATE TRIGGER mytrigAFTER UPDATE OF vvv ON mytableBEGIN UPDATE aa SET mycola = (CASE WHEN (A=1) THEN 2 END); UPDATE bb SET mycolb = (CASE WHEN (B=1) THEN 5 END);END;12345678910create procedure proc1()begin declare handler for foo begin end; select 1;end;
create procedure proc2()begin select 1;end;12-- this file is streamed ininsert into foo1insert into foo values (1); -- ����� ��� �������123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122import subprocessimport sys
import pytest
import sqlparse
def test_cli_main_empty(): with pytest.raises(SystemExit): sqlparse.cli.main([])
def test_parser_empty(): with pytest.raises(SystemExit): parser = sqlparse.cli.create_parser() parser.parse_args([])
def test_main_help(): # Call with the --help option as a basic sanity check. with pytest.raises(SystemExit) as exinfo: sqlparse.cli.main(["--help", ]) assert exinfo.value.code == 0
def test_valid_args(filepath): # test doesn't abort path = filepath('function.sql') assert sqlparse.cli.main([path, '-r']) is not None
def test_invalid_choice(filepath): path = filepath('function.sql') with pytest.raises(SystemExit): sqlparse.cli.main([path, '-l', 'Spanish'])
def test_invalid_args(filepath, capsys): path = filepath('function.sql') sqlparse.cli.main([path, '-r', '--indent_width', '0']) _, err = capsys.readouterr() assert err == ("[ERROR] Invalid options: indent_width requires " "a positive integer\n")
def test_invalid_infile(filepath, capsys): path = filepath('missing.sql') sqlparse.cli.main([path, '-r']) _, err = capsys.readouterr() assert err[:22] == "[ERROR] Failed to read"
def test_invalid_outfile(filepath, capsys): path = filepath('function.sql') outpath = filepath('/missing/function.sql') sqlparse.cli.main([path, '-r', '-o', outpath]) _, err = capsys.readouterr() assert err[:22] == "[ERROR] Failed to open"
def test_stdout(filepath, load_file, capsys): path = filepath('begintag.sql') expected = load_file('begintag.sql') sqlparse.cli.main([path]) out, _ = capsys.readouterr() assert out == expected
def test_script(): # Call with the --help option as a basic sanity check. cmd = [sys.executable, '-m', 'sqlparse.cli', '--help'] assert subprocess.call(cmd) == 0
@pytest.mark.parametrize('fpath, encoding', ( ('encoding_utf8.sql', 'utf-8'), ('encoding_gbk.sql', 'gbk'),))def test_encoding_stdout(fpath, encoding, filepath, load_file, capfd): path = filepath(fpath) expected = load_file(fpath, encoding) sqlparse.cli.main([path, '--encoding', encoding]) out, _ = capfd.readouterr() assert out == expected
@pytest.mark.parametrize('fpath, encoding', ( ('encoding_utf8.sql', 'utf-8'), ('encoding_gbk.sql', 'gbk'),))def test_encoding_output_file(fpath, encoding, filepath, load_file, tmpdir): in_path = filepath(fpath) expected = load_file(fpath, encoding) out_path = tmpdir.dirname + '/encoding_out.sql' sqlparse.cli.main([in_path, '--encoding', encoding, '-o', out_path]) out = load_file(out_path, encoding) assert out == expected
@pytest.mark.parametrize('fpath, encoding', ( ('encoding_utf8.sql', 'utf-8'), ('encoding_gbk.sql', 'gbk'),))def test_encoding_stdin(fpath, encoding, filepath, load_file, capfd): path = filepath(fpath) expected = load_file(fpath, encoding) old_stdin = sys.stdin with open(path) as f: sys.stdin = f sqlparse.cli.main(['-', '--encoding', encoding]) sys.stdin = old_stdin out, _ = capfd.readouterr() assert out == expected
def test_encoding(filepath, capsys): path = filepath('test_cp1251.sql') expected = 'insert into foo values (1); -- Песня про надежду\n' sqlparse.cli.main([path, '--encoding=cp1251']) out, _ = capsys.readouterr() assert out == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774import pytest
import sqlparsefrom sqlparse.exceptions import SQLParseError
class TestFormat: def test_keywordcase(self): sql = 'select * from bar; -- select foo\n' res = sqlparse.format(sql, keyword_case='upper') assert res == 'SELECT * FROM bar; -- select foo\n' res = sqlparse.format(sql, keyword_case='capitalize') assert res == 'Select * From bar; -- select foo\n' res = sqlparse.format(sql.upper(), keyword_case='lower') assert res == 'select * from BAR; -- SELECT FOO\n'
def test_keywordcase_invalid_option(self): sql = 'select * from bar; -- select foo\n' with pytest.raises(SQLParseError): sqlparse.format(sql, keyword_case='foo')
def test_identifiercase(self): sql = 'select * from bar; -- select foo\n' res = sqlparse.format(sql, identifier_case='upper') assert res == 'select * from BAR; -- select foo\n' res = sqlparse.format(sql, identifier_case='capitalize') assert res == 'select * from Bar; -- select foo\n' res = sqlparse.format(sql.upper(), identifier_case='lower') assert res == 'SELECT * FROM bar; -- SELECT FOO\n'
def test_identifiercase_invalid_option(self): sql = 'select * from bar; -- select foo\n' with pytest.raises(SQLParseError): sqlparse.format(sql, identifier_case='foo')
def test_identifiercase_quotes(self): sql = 'select * from "foo"."bar"' res = sqlparse.format(sql, identifier_case="upper") assert res == 'select * from "foo"."bar"'
def test_strip_comments_single(self): sql = 'select *-- statement starts here\nfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == 'select *\nfrom foo' sql = 'select * -- statement starts here\nfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == 'select *\nfrom foo' sql = 'select-- foo\nfrom -- bar\nwhere' res = sqlparse.format(sql, strip_comments=True) assert res == 'select\nfrom\nwhere' sql = 'select *-- statement starts here\n\nfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == 'select *\n\nfrom foo' sql = 'select * from foo-- statement starts here\nwhere' res = sqlparse.format(sql, strip_comments=True) assert res == 'select * from foo\nwhere' sql = 'select a-- statement starts here\nfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == 'select a\nfrom foo' sql = '--comment\nselect a-- statement starts here\n' \ 'from foo--comment\nf' res = sqlparse.format(sql, strip_comments=True) assert res == 'select a\nfrom foo\nf'
def test_strip_comments_invalid_option(self): sql = 'select-- foo\nfrom -- bar\nwhere' with pytest.raises(SQLParseError): sqlparse.format(sql, strip_comments=None)
def test_strip_comments_multi(self): sql = '/* sql starts here */\nselect' res = sqlparse.format(sql, strip_comments=True) assert res == 'select' sql = '/* sql starts here */ select' res = sqlparse.format(sql, strip_comments=True) assert res == ' select' # note whitespace is preserved, see issue 772 sql = '/*\n * sql starts here\n */\nselect' res = sqlparse.format(sql, strip_comments=True) assert res == 'select' sql = 'select (/* sql starts here */ select 2)' res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) assert res == 'select (select 2)' sql = 'select (/* sql /* starts here */ select 2)' res = sqlparse.format(sql, strip_comments=True, strip_whitespace=True) assert res == 'select (select 2)'
def test_strip_comments_preserves_linebreak(self): sql = 'select * -- a comment\r\nfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == 'select *\nfrom foo' sql = 'select * -- a comment\nfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == 'select *\nfrom foo' sql = 'select * -- a comment\rfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == 'select *\nfrom foo' sql = 'select * -- a comment\r\n\r\nfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == 'select *\n\nfrom foo' sql = 'select * -- a comment\n\nfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == 'select *\n\nfrom foo'
def test_strip_comments_preserves_whitespace(self): sql = 'SELECT 1/*bar*/ AS foo' # see issue772 res = sqlparse.format(sql, strip_comments=True) assert res == 'SELECT 1 AS foo'
def test_strip_comments_preserves_hint(self): sql = 'select --+full(u)' res = sqlparse.format(sql, strip_comments=True) assert res == sql sql = '#+ hint\nselect * from foo' res = sqlparse.format(sql, strip_comments=True) assert res == sql sql = 'select --+full(u)\n--comment simple' res = sqlparse.format(sql, strip_comments=True) assert res == 'select --+full(u)\n' sql = '#+ hint\nselect * from foo\n# comment simple' res = sqlparse.format(sql, strip_comments=True) assert res == '#+ hint\nselect * from foo\n' sql = 'SELECT /*+cluster(T)*/* FROM T_EEE T where A >:1' res = sqlparse.format(sql, strip_comments=True) assert res == sql sql = 'insert /*+ DIRECT */ into sch.table_name as select * from foo' res = sqlparse.format(sql, strip_comments=True) assert res == sql
def test_strip_ws(self): f = lambda sql: sqlparse.format(sql, strip_whitespace=True) s = 'select\n* from foo\n\twhere ( 1 = 2 )\n' assert f(s) == 'select * from foo where (1 = 2)' s = 'select -- foo\nfrom bar\n' assert f(s) == 'select -- foo\nfrom bar'
def test_strip_ws_invalid_option(self): s = 'select -- foo\nfrom bar\n' with pytest.raises(SQLParseError): sqlparse.format(s, strip_whitespace=None)
def test_preserve_ws(self): # preserve at least one whitespace after subgroups f = lambda sql: sqlparse.format(sql, strip_whitespace=True) s = 'select\n* /* foo */ from bar ' assert f(s) == 'select * /* foo */ from bar'
def test_notransform_of_quoted_crlf(self): # Make sure that CR/CR+LF characters inside string literals don't get # affected by the formatter.
s1 = "SELECT some_column LIKE 'value\r'" s2 = "SELECT some_column LIKE 'value\r'\r\nWHERE id = 1\n" s3 = "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\r" s4 = "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\r\n"
f = lambda x: sqlparse.format(x)
# Because of the use of assert f(s1) == "SELECT some_column LIKE 'value\r'" assert f(s2) == "SELECT some_column LIKE 'value\r'\nWHERE id = 1\n" assert f(s3) == "SELECT some_column LIKE 'value\\'\r' WHERE id = 1\n" assert (f(s4) == "SELECT some_column LIKE 'value\\\\\\'\r' WHERE id = 1\n")
class TestFormatReindentAligned: @staticmethod def formatter(sql): return sqlparse.format(sql, reindent_aligned=True)
def test_basic(self): sql = """ select a, b as bb,c from table join (select a * 2 as a from new_table) other on table.a = other.a where c is true and b between 3 and 4 or d is 'blue' limit 10 """
assert self.formatter(sql) == '\n'.join([ 'select a,', ' b as bb,', ' c', ' from table', ' join (', ' select a * 2 as a', ' from new_table', ' ) other', ' on table.a = other.a', ' where c is true', ' and b between 3 and 4', " or d is 'blue'", ' limit 10'])
def test_joins(self): sql = """ select * from a join b on a.one = b.one left join c on c.two = a.two and c.three = a.three full outer join d on d.three = a.three cross join e on e.four = a.four join f using (one, two, three) """ assert self.formatter(sql) == '\n'.join([ 'select *', ' from a', ' join b', ' on a.one = b.one', ' left join c', ' on c.two = a.two', ' and c.three = a.three', ' full outer join d', ' on d.three = a.three', ' cross join e', ' on e.four = a.four', ' join f using (one, two, three)'])
def test_case_statement(self): sql = """ select a, case when a = 0 then 1 when bb = 1 then 1 when c = 2 then 2 else 0 end as d, extra_col from table where c is true and b between 3 and 4 """ assert self.formatter(sql) == '\n'.join([ 'select a,', ' case when a = 0 then 1', ' when bb = 1 then 1', ' when c = 2 then 2', ' else 0', ' end as d,', ' extra_col', ' from table', ' where c is true', ' and b between 3 and 4'])
def test_case_statement_with_between(self): sql = """ select a, case when a = 0 then 1 when bb = 1 then 1 when c = 2 then 2 when d between 3 and 5 then 3 else 0 end as d, extra_col from table where c is true and b between 3 and 4 """ assert self.formatter(sql) == '\n'.join([ 'select a,', ' case when a = 0 then 1', ' when bb = 1 then 1', ' when c = 2 then 2', ' when d between 3 and 5 then 3', ' else 0', ' end as d,', ' extra_col', ' from table', ' where c is true', ' and b between 3 and 4'])
def test_group_by(self): sql = """ select a, b, c, sum(x) as sum_x, count(y) as cnt_y from table group by a,b,c having sum(x) > 1 and count(y) > 5 order by 3,2,1 """ assert self.formatter(sql) == '\n'.join([ 'select a,', ' b,', ' c,', ' sum(x) as sum_x,', ' count(y) as cnt_y', ' from table', ' group by a,', ' b,', ' c', 'having sum(x) > 1', ' and count(y) > 5', ' order by 3,', ' 2,', ' 1'])
def test_group_by_subquery(self): # TODO: add subquery alias when test_identifier_list_subquery fixed sql = """ select *, sum_b + 2 as mod_sum from ( select a, sum(b) as sum_b from table group by a,z) order by 1,2 """ assert self.formatter(sql) == '\n'.join([ 'select *,', ' sum_b + 2 as mod_sum', ' from (', ' select a,', ' sum(b) as sum_b', ' from table', ' group by a,', ' z', ' )', ' order by 1,', ' 2'])
def test_window_functions(self): sql = """ select a, SUM(a) OVER (PARTITION BY b ORDER BY c ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a, ROW_NUMBER() OVER (PARTITION BY b, c ORDER BY d DESC) as row_num from table""" assert self.formatter(sql) == '\n'.join([ 'select a,', ' SUM(a) OVER (PARTITION BY b ORDER BY c ROWS ' 'BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_a,', ' ROW_NUMBER() OVER ' '(PARTITION BY b, c ORDER BY d DESC) as row_num', ' from table'])
class TestSpacesAroundOperators: @staticmethod def formatter(sql): return sqlparse.format(sql, use_space_around_operators=True)
def test_basic(self): sql = ('select a+b as d from table ' 'where (c-d)%2= 1 and e> 3.0/4 and z^2 <100') assert self.formatter(sql) == ( 'select a + b as d from table ' 'where (c - d) % 2 = 1 and e > 3.0 / 4 and z ^ 2 < 100')
def test_bools(self): sql = 'select * from table where a &&b or c||d' assert self.formatter( sql) == 'select * from table where a && b or c || d'
def test_nested(self): sql = 'select *, case when a-b then c end from table' assert self.formatter( sql) == 'select *, case when a - b then c end from table'
def test_wildcard_vs_mult(self): sql = 'select a*b-c from table' assert self.formatter(sql) == 'select a * b - c from table'
class TestFormatReindent: def test_option(self): with pytest.raises(SQLParseError): sqlparse.format('foo', reindent=2) with pytest.raises(SQLParseError): sqlparse.format('foo', indent_tabs=2) with pytest.raises(SQLParseError): sqlparse.format('foo', reindent=True, indent_width='foo') with pytest.raises(SQLParseError): sqlparse.format('foo', reindent=True, indent_width=-12) with pytest.raises(SQLParseError): sqlparse.format('foo', reindent=True, wrap_after='foo') with pytest.raises(SQLParseError): sqlparse.format('foo', reindent=True, wrap_after=-12) with pytest.raises(SQLParseError): sqlparse.format('foo', reindent=True, comma_first='foo')
def test_stmts(self): f = lambda sql: sqlparse.format(sql, reindent=True) s = 'select foo; select bar' assert f(s) == 'select foo;\n\nselect bar' s = 'select foo' assert f(s) == 'select foo' s = 'select foo; -- test\n select bar' assert f(s) == 'select foo; -- test\n\nselect bar'
def test_keywords(self): f = lambda sql: sqlparse.format(sql, reindent=True) s = 'select * from foo union select * from bar;' assert f(s) == '\n'.join([ 'select *', 'from foo', 'union', 'select *', 'from bar;'])
def test_keywords_between(self): # issue 14 # don't break AND after BETWEEN f = lambda sql: sqlparse.format(sql, reindent=True) s = 'and foo between 1 and 2 and bar = 3' assert f(s) == '\n'.join([ '', 'and foo between 1 and 2', 'and bar = 3'])
def test_parenthesis(self): f = lambda sql: sqlparse.format(sql, reindent=True) s = 'select count(*) from (select * from foo);' assert f(s) == '\n'.join([ 'select count(*)', 'from', ' (select *', ' from foo);']) assert f("select f(1)") == 'select f(1)' assert f("select f( 1 )") == 'select f(1)' assert f("select f(\n\n\n1\n\n\n)") == 'select f(1)' assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)' assert f("select f(\n\n\n 1 \n\n\n)") == 'select f(1)'
def test_where(self): f = lambda sql: sqlparse.format(sql, reindent=True) s = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' assert f(s) == '\n'.join([ 'select *', 'from foo', 'where bar = 1', ' and baz = 2', ' or bzz = 3;'])
s = 'select * from foo where bar = 1 and (baz = 2 or bzz = 3);' assert f(s) == '\n'.join([ 'select *', 'from foo', 'where bar = 1', ' and (baz = 2', ' or bzz = 3);'])
def test_join(self): f = lambda sql: sqlparse.format(sql, reindent=True) s = 'select * from foo join bar on 1 = 2' assert f(s) == '\n'.join([ 'select *', 'from foo', 'join bar on 1 = 2']) s = 'select * from foo inner join bar on 1 = 2' assert f(s) == '\n'.join([ 'select *', 'from foo', 'inner join bar on 1 = 2']) s = 'select * from foo left outer join bar on 1 = 2' assert f(s) == '\n'.join([ 'select *', 'from foo', 'left outer join bar on 1 = 2']) s = 'select * from foo straight_join bar on 1 = 2' assert f(s) == '\n'.join([ 'select *', 'from foo', 'straight_join bar on 1 = 2'])
def test_identifier_list(self): f = lambda sql: sqlparse.format(sql, reindent=True) s = 'select foo, bar, baz from table1, table2 where 1 = 2' assert f(s) == '\n'.join([ 'select foo,', ' bar,', ' baz', 'from table1,', ' table2', 'where 1 = 2']) s = 'select a.*, b.id from a, b' assert f(s) == '\n'.join([ 'select a.*,', ' b.id', 'from a,', ' b'])
def test_identifier_list_with_wrap_after(self): f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=14) s = 'select foo, bar, baz from table1, table2 where 1 = 2' assert f(s) == '\n'.join([ 'select foo, bar,', ' baz', 'from table1, table2', 'where 1 = 2'])
def test_identifier_list_comment_first(self): f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) # not the 3: It cleans up whitespace too! s = 'select foo, bar, baz from table where foo in (1, 2,3)' assert f(s) == '\n'.join([ 'select foo', ' , bar', ' , baz', 'from table', 'where foo in (1', ' , 2', ' , 3)'])
def test_identifier_list_with_functions(self): f = lambda sql: sqlparse.format(sql, reindent=True) s = ("select 'abc' as foo, coalesce(col1, col2)||col3 as bar," "col3 from my_table") assert f(s) == '\n'.join([ "select 'abc' as foo,", " coalesce(col1, col2)||col3 as bar,", " col3", "from my_table"])
def test_long_identifier_list_with_functions(self): f = lambda sql: sqlparse.format(sql, reindent=True, wrap_after=30) s = ("select 'abc' as foo, json_build_object('a', a," "'b', b, 'c', c, 'd', d, 'e', e) as col2" "col3 from my_table") assert f(s) == '\n'.join([ "select 'abc' as foo,", " json_build_object('a',", " a, 'b', b, 'c', c, 'd', d,", " 'e', e) as col2col3", "from my_table"])
def test_case(self): f = lambda sql: sqlparse.format(sql, reindent=True) s = 'case when foo = 1 then 2 when foo = 3 then 4 else 5 end' assert f(s) == '\n'.join([ 'case', ' when foo = 1 then 2', ' when foo = 3 then 4', ' else 5', 'end'])
def test_case2(self): f = lambda sql: sqlparse.format(sql, reindent=True) s = 'case(foo) when bar = 1 then 2 else 3 end' assert f(s) == '\n'.join([ 'case(foo)', ' when bar = 1 then 2', ' else 3', 'end'])
def test_nested_identifier_list(self): # issue4 f = lambda sql: sqlparse.format(sql, reindent=True) s = '(foo as bar, bar1, bar2 as bar3, b4 as b5)' assert f(s) == '\n'.join([ '(foo as bar,', ' bar1,', ' bar2 as bar3,', ' b4 as b5)'])
def test_duplicate_linebreaks(self): # issue3 f = lambda sql: sqlparse.format(sql, reindent=True) s = 'select c1 -- column1\nfrom foo' assert f(s) == '\n'.join([ 'select c1 -- column1', 'from foo']) s = 'select c1 -- column1\nfrom foo' r = sqlparse.format(s, reindent=True, strip_comments=True) assert r == '\n'.join([ 'select c1', 'from foo']) s = 'select c1\nfrom foo\norder by c1' assert f(s) == '\n'.join([ 'select c1', 'from foo', 'order by c1']) s = 'select c1 from t1 where (c1 = 1) order by c1' assert f(s) == '\n'.join([ 'select c1', 'from t1', 'where (c1 = 1)', 'order by c1'])
def test_keywordfunctions(self): # issue36 f = lambda sql: sqlparse.format(sql, reindent=True) s = 'select max(a) b, foo, bar' assert f(s) == '\n'.join([ 'select max(a) b,', ' foo,', ' bar'])
def test_identifier_and_functions(self): # issue45 f = lambda sql: sqlparse.format(sql, reindent=True) s = 'select foo.bar, nvl(1) from dual' assert f(s) == '\n'.join([ 'select foo.bar,', ' nvl(1)', 'from dual'])
def test_insert_values(self): # issue 329 f = lambda sql: sqlparse.format(sql, reindent=True) s = 'insert into foo values (1, 2)' assert f(s) == '\n'.join([ 'insert into foo', 'values (1, 2)'])
s = 'insert into foo values (1, 2), (3, 4), (5, 6)' assert f(s) == '\n'.join([ 'insert into foo', 'values (1, 2),', ' (3, 4),', ' (5, 6)'])
s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' assert f(s) == '\n'.join([ 'insert into foo(a, b)', 'values (1, 2),', ' (3, 4),', ' (5, 6)'])
f = lambda sql: sqlparse.format(sql, reindent=True, comma_first=True) s = 'insert into foo values (1, 2)' assert f(s) == '\n'.join([ 'insert into foo', 'values (1, 2)'])
s = 'insert into foo values (1, 2), (3, 4), (5, 6)' assert f(s) == '\n'.join([ 'insert into foo', 'values (1, 2)', ' , (3, 4)', ' , (5, 6)'])
s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' assert f(s) == '\n'.join([ 'insert into foo(a, b)', 'values (1, 2)', ' , (3, 4)', ' , (5, 6)'])
class TestOutputFormat: def test_python(self): sql = 'select * from foo;' f = lambda sql: sqlparse.format(sql, output_format='python') assert f(sql) == "sql = 'select * from foo;'" f = lambda sql: sqlparse.format(sql, output_format='python', reindent=True) assert f(sql) == '\n'.join([ "sql = ('select * '", " 'from foo;')"])
def test_python_multiple_statements(self): sql = 'select * from foo; select 1 from dual' f = lambda sql: sqlparse.format(sql, output_format='python') assert f(sql) == '\n'.join([ "sql = 'select * from foo; '", "sql2 = 'select 1 from dual'"])
@pytest.mark.xfail(reason="Needs fixing") def test_python_multiple_statements_with_formatting(self): sql = 'select * from foo; select 1 from dual' f = lambda sql: sqlparse.format(sql, output_format='python', reindent=True) assert f(sql) == '\n'.join([ "sql = ('select * '", " 'from foo;')", "sql2 = ('select 1 '", " 'from dual')"])
def test_php(self): sql = 'select * from foo;' f = lambda sql: sqlparse.format(sql, output_format='php') assert f(sql) == '$sql = "select * from foo;";' f = lambda sql: sqlparse.format(sql, output_format='php', reindent=True) assert f(sql) == '\n'.join([ '$sql = "select * ";', '$sql .= "from foo;";'])
def test_sql(self): # "sql" is an allowed option but has no effect sql = 'select * from foo;' f = lambda sql: sqlparse.format(sql, output_format='sql') assert f(sql) == 'select * from foo;'
def test_invalid_option(self): sql = 'select * from foo;' with pytest.raises(SQLParseError): sqlparse.format(sql, output_format='foo')
def test_format_column_ordering(): # issue89 sql = 'select * from foo order by c1 desc, c2, c3;' formatted = sqlparse.format(sql, reindent=True) expected = '\n'.join([ 'select *', 'from foo', 'order by c1 desc,', ' c2,', ' c3;']) assert formatted == expected
def test_truncate_strings(): sql = "update foo set value = '{}';".format('x' * 1000) formatted = sqlparse.format(sql, truncate_strings=10) assert formatted == "update foo set value = 'xxxxxxxxxx[...]';" formatted = sqlparse.format(sql, truncate_strings=3, truncate_char='YYY') assert formatted == "update foo set value = 'xxxYYY';"
@pytest.mark.parametrize('option', ['bar', -1, 0])def test_truncate_strings_invalid_option2(option): with pytest.raises(SQLParseError): sqlparse.format('foo', truncate_strings=option)
@pytest.mark.parametrize('sql', [ 'select verrrylongcolumn from foo', 'select "verrrylongcolumn" from "foo"'])def test_truncate_strings_doesnt_truncate_identifiers(sql): formatted = sqlparse.format(sql, truncate_strings=2) assert formatted == sql
def test_having_produces_newline(): sql = ('select * from foo, bar where bar.id = foo.bar_id ' 'having sum(bar.value) > 100') formatted = sqlparse.format(sql, reindent=True) expected = [ 'select *', 'from foo,', ' bar', 'where bar.id = foo.bar_id', 'having sum(bar.value) > 100'] assert formatted == '\n'.join(expected)
@pytest.mark.parametrize('right_margin', ['ten', 2])def test_format_right_margin_invalid_option(right_margin): with pytest.raises(SQLParseError): sqlparse.format('foo', right_margin=right_margin)
@pytest.mark.xfail(reason="Needs fixing")def test_format_right_margin(): # TODO: Needs better test, only raises exception right now sqlparse.format('foo', right_margin="79")
def test_format_json_ops(): # issue542 formatted = sqlparse.format( "select foo->'bar', foo->'bar';", reindent=True) expected = "select foo->'bar',\n foo->'bar';" assert formatted == expected
@pytest.mark.parametrize('sql, expected_normal, expected_compact', [ ('case when foo then 1 else bar end', 'case\n when foo then 1\n else bar\nend', 'case when foo then 1 else bar end')])def test_compact(sql, expected_normal, expected_compact): # issue783 formatted_normal = sqlparse.format(sql, reindent=True) formatted_compact = sqlparse.format(sql, reindent=True, compact=True) assert formatted_normal == expected_normal assert formatted_compact == expected_compact
def test_strip_ws_removes_trailing_ws_in_groups(): # issue782 formatted = sqlparse.format('( where foo = bar ) from', strip_whitespace=True) expected = '(where foo = bar) from' assert formatted == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679import pytest
import sqlparsefrom sqlparse import sql, tokens as T
def test_grouping_parenthesis(): s = 'select (select (x3) x2) and (y2) bar' parsed = sqlparse.parse(s)[0] assert str(parsed) == s assert len(parsed.tokens) == 7 assert isinstance(parsed.tokens[2], sql.Parenthesis) assert isinstance(parsed.tokens[-1], sql.Identifier) assert len(parsed.tokens[2].tokens) == 5 assert isinstance(parsed.tokens[2].tokens[3], sql.Identifier) assert isinstance(parsed.tokens[2].tokens[3].tokens[0], sql.Parenthesis) assert len(parsed.tokens[2].tokens[3].tokens) == 3
@pytest.mark.parametrize('s', ['foo := 1;', 'foo := 1'])def test_grouping_assignment(s): parsed = sqlparse.parse(s)[0] assert len(parsed.tokens) == 1 assert isinstance(parsed.tokens[0], sql.Assignment)
@pytest.mark.parametrize('s', ["x > DATE '2020-01-01'", "x > TIMESTAMP '2020-01-01 00:00:00'"])def test_grouping_typed_literal(s): parsed = sqlparse.parse(s)[0] assert isinstance(parsed[0][4], sql.TypedLiteral)
@pytest.mark.parametrize('s, a, b', [ ('select a from b where c < d + e', sql.Identifier, sql.Identifier), ('select a from b where c < d + interval \'1 day\'', sql.Identifier, sql.TypedLiteral), ('select a from b where c < d + interval \'6\' month', sql.Identifier, sql.TypedLiteral), ('select a from b where c < current_timestamp - interval \'1 day\'', sql.Token, sql.TypedLiteral),])def test_compare_expr(s, a, b): parsed = sqlparse.parse(s)[0] assert str(parsed) == s assert isinstance(parsed.tokens[2], sql.Identifier) assert isinstance(parsed.tokens[6], sql.Identifier) assert isinstance(parsed.tokens[8], sql.Where) assert len(parsed.tokens) == 9 where = parsed.tokens[8] assert isinstance(where.tokens[2], sql.Comparison) assert len(where.tokens) == 3 comparison = where.tokens[2] assert isinstance(comparison.tokens[0], sql.Identifier) assert comparison.tokens[2].ttype is T.Operator.Comparison assert isinstance(comparison.tokens[4], sql.Operation) assert len(comparison.tokens) == 5 operation = comparison.tokens[4] assert isinstance(operation.tokens[0], a) assert operation.tokens[2].ttype is T.Operator assert isinstance(operation.tokens[4], b) assert len(operation.tokens) == 5
def test_grouping_identifiers(): s = 'select foo.bar from "myscheme"."table" where fail. order' parsed = sqlparse.parse(s)[0] assert str(parsed) == s assert isinstance(parsed.tokens[2], sql.Identifier) assert isinstance(parsed.tokens[6], sql.Identifier) assert isinstance(parsed.tokens[8], sql.Where) s = 'select * from foo where foo.id = 1' parsed = sqlparse.parse(s)[0] assert str(parsed) == s assert isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier) s = 'select * from (select "foo"."id" from foo)' parsed = sqlparse.parse(s)[0] assert str(parsed) == s assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier)
for s in ["INSERT INTO `test` VALUES('foo', 'bar');", "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: parsed = sqlparse.parse(s)[0] types = [l.ttype for l in parsed.tokens if not l.is_whitespace] assert types == [T.DML, T.Keyword, None, None, T.Punctuation] assert isinstance(parsed.tokens[6], sql.Values)
s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" parsed = sqlparse.parse(s)[0] assert len(parsed.tokens) == 7 assert isinstance(parsed.tokens[2], sql.IdentifierList) assert len(parsed.tokens[2].tokens) == 4 identifiers = list(parsed.tokens[2].get_identifiers()) assert len(identifiers) == 2 assert identifiers[0].get_alias() == "col"
@pytest.mark.parametrize('s', [ '1 as f', 'foo as f', 'foo f', '1/2 as f', '1/2 f', '1<2 as f', # issue327 '1<2 f',])def test_simple_identifiers(s): parsed = sqlparse.parse(s)[0] assert isinstance(parsed.tokens[0], sql.Identifier)
@pytest.mark.parametrize('s', [ 'foo, bar', 'sum(a), sum(b)', 'sum(a) as x, b as y', 'sum(a)::integer, b', 'sum(a)/count(b) as x, y', 'sum(a)::integer as x, y', 'sum(a)::integer/count(b) as x, y', # issue297])def test_group_identifier_list(s): parsed = sqlparse.parse(s)[0] assert isinstance(parsed.tokens[0], sql.IdentifierList)
def test_grouping_identifier_wildcard(): p = sqlparse.parse('a.*, b.id')[0] assert isinstance(p.tokens[0], sql.IdentifierList) assert isinstance(p.tokens[0].tokens[0], sql.Identifier) assert isinstance(p.tokens[0].tokens[-1], sql.Identifier)
def test_grouping_identifier_name_wildcard(): p = sqlparse.parse('a.*')[0] t = p.tokens[0] assert t.get_name() == '*' assert t.is_wildcard() is True
def test_grouping_identifier_invalid(): p = sqlparse.parse('a.')[0] assert isinstance(p.tokens[0], sql.Identifier) assert p.tokens[0].has_alias() is False assert p.tokens[0].get_name() is None assert p.tokens[0].get_real_name() is None assert p.tokens[0].get_parent_name() == 'a'
def test_grouping_identifier_invalid_in_middle(): # issue261 s = 'SELECT foo. FROM foo' p = sqlparse.parse(s)[0] assert isinstance(p[2], sql.Identifier) assert p[2][1].ttype == T.Punctuation assert p[3].ttype == T.Whitespace assert str(p[2]) == 'foo.'
@pytest.mark.parametrize('s', ['foo as (select *)', 'foo as(select *)'])def test_grouping_identifer_as(s): # issue507 p = sqlparse.parse(s)[0] assert isinstance(p.tokens[0], sql.Identifier) token = p.tokens[0].tokens[2] assert token.ttype == T.Keyword assert token.normalized == 'AS'
def test_grouping_identifier_as_invalid(): # issue8 p = sqlparse.parse('foo as select *')[0] assert len(p.tokens), 5 assert isinstance(p.tokens[0], sql.Identifier) assert len(p.tokens[0].tokens) == 1 assert p.tokens[2].ttype == T.Keyword
def test_grouping_identifier_function(): p = sqlparse.parse('foo() as bar')[0] assert isinstance(p.tokens[0], sql.Identifier) assert isinstance(p.tokens[0].tokens[0], sql.Function) p = sqlparse.parse('foo()||col2 bar')[0] assert isinstance(p.tokens[0], sql.Identifier) assert isinstance(p.tokens[0].tokens[0], sql.Operation) assert isinstance(p.tokens[0].tokens[0].tokens[0], sql.Function) p = sqlparse.parse('foo(c1) over win1 as bar')[0] assert isinstance(p.tokens[0], sql.Identifier) assert isinstance(p.tokens[0].tokens[0], sql.Function) assert len(p.tokens[0].tokens[0].tokens) == 4 assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], sql.Identifier) p = sqlparse.parse('foo(c1) over (partition by c2 order by c3) as bar')[0] assert isinstance(p.tokens[0], sql.Identifier) assert isinstance(p.tokens[0].tokens[0], sql.Function) assert len(p.tokens[0].tokens[0].tokens) == 4 assert isinstance(p.tokens[0].tokens[0].tokens[3], sql.Over) assert isinstance(p.tokens[0].tokens[0].tokens[3].tokens[2], sql.Parenthesis)
@pytest.mark.parametrize('s', ['foo+100', 'foo + 100', 'foo*100'])def test_grouping_operation(s): p = sqlparse.parse(s)[0] assert isinstance(p.tokens[0], sql.Operation)
def test_grouping_identifier_list(): p = sqlparse.parse('a, b, c')[0] assert isinstance(p.tokens[0], sql.IdentifierList) p = sqlparse.parse('(a, b, c)')[0] assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList)
def test_grouping_identifier_list_subquery(): """identifier lists should still work in subqueries with aliases""" p = sqlparse.parse("select * from (" "select a, b + c as d from table) sub")[0] subquery = p.tokens[-1].tokens[0] idx, iden_list = subquery.token_next_by(i=sql.IdentifierList) assert iden_list is not None # all the identifiers should be within the IdentifierList _, ilist = subquery.token_next_by(i=sql.Identifier, idx=idx) assert ilist is None
def test_grouping_identifier_list_case(): p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] assert isinstance(p.tokens[0], sql.IdentifierList) p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] assert isinstance(p.tokens[0].tokens[1], sql.IdentifierList)
def test_grouping_identifier_list_other(): # issue2 p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] assert isinstance(p.tokens[2], sql.IdentifierList) assert len(p.tokens[2].tokens) == 13
def test_grouping_identifier_list_with_inline_comments(): # issue163 p = sqlparse.parse('foo /* a comment */, bar')[0] assert isinstance(p.tokens[0], sql.IdentifierList) assert isinstance(p.tokens[0].tokens[0], sql.Identifier) assert isinstance(p.tokens[0].tokens[3], sql.Identifier)
def test_grouping_identifiers_with_operators(): p = sqlparse.parse('a+b as c from table where (d-e)%2= 1')[0] assert len([x for x in p.flatten() if x.ttype == T.Name]) == 5
def test_grouping_identifier_list_with_order(): # issue101 p = sqlparse.parse('1, 2 desc, 3')[0] assert isinstance(p.tokens[0], sql.IdentifierList) assert isinstance(p.tokens[0].tokens[3], sql.Identifier) assert str(p.tokens[0].tokens[3]) == '2 desc'
def test_grouping_nested_identifier_with_order(): # issue745 p = sqlparse.parse('(a desc)')[0] assert isinstance(p.tokens[0], sql.Parenthesis) assert isinstance(p.tokens[0].tokens[1], sql.Identifier) assert str(p.tokens[0].tokens[1]) == 'a desc'
def test_grouping_where(): s = 'select * from foo where bar = 1 order by id desc' p = sqlparse.parse(s)[0] assert str(p) == s assert len(p.tokens) == 12
s = 'select x from (select y from foo where bar = 1) z' p = sqlparse.parse(s)[0] assert str(p) == s assert isinstance(p.tokens[-1].tokens[0].tokens[-2], sql.Where)
@pytest.mark.parametrize('s', ( 'select 1 where 1 = 2 union select 2', 'select 1 where 1 = 2 union all select 2',))def test_grouping_where_union(s): p = sqlparse.parse(s)[0] assert p.tokens[5].value.startswith('union')
def test_returning_kw_ends_where_clause(): s = 'delete from foo where x > y returning z' p = sqlparse.parse(s)[0] assert isinstance(p.tokens[6], sql.Where) assert p.tokens[7].ttype == T.Keyword assert p.tokens[7].value == 'returning'
def test_into_kw_ends_where_clause(): # issue324 s = 'select * from foo where a = 1 into baz' p = sqlparse.parse(s)[0] assert isinstance(p.tokens[8], sql.Where) assert p.tokens[9].ttype == T.Keyword assert p.tokens[9].value == 'into'
@pytest.mark.parametrize('sql, expected', [ # note: typecast needs to be 2nd token for this test ('select foo::integer from bar', 'integer'), ('select (current_database())::information_schema.sql_identifier', 'information_schema.sql_identifier'),])def test_grouping_typecast(sql, expected): p = sqlparse.parse(sql)[0] assert p.tokens[2].get_typecast() == expected
def test_grouping_alias(): s = 'select foo as bar from mytable' p = sqlparse.parse(s)[0] assert str(p) == s assert p.tokens[2].get_real_name() == 'foo' assert p.tokens[2].get_alias() == 'bar' s = 'select foo from mytable t1' p = sqlparse.parse(s)[0] assert str(p) == s assert p.tokens[6].get_real_name() == 'mytable' assert p.tokens[6].get_alias() == 't1' s = 'select foo::integer as bar from mytable' p = sqlparse.parse(s)[0] assert str(p) == s assert p.tokens[2].get_alias() == 'bar' s = ('SELECT DISTINCT ' '(current_database())::information_schema.sql_identifier AS view') p = sqlparse.parse(s)[0] assert str(p) == s assert p.tokens[4].get_alias() == 'view'
def test_grouping_alias_case(): # see issue46 p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] assert len(p.tokens) == 1 assert p.tokens[0].get_alias() == 'foo'
def test_grouping_alias_ctas(): p = sqlparse.parse('CREATE TABLE tbl1 AS SELECT coalesce(t1.col1, 0) AS col1 FROM t1')[0] assert p.tokens[10].get_alias() == 'col1' assert isinstance(p.tokens[10].tokens[0], sql.Function)
def test_grouping_subquery_no_parens(): # Not totally sure if this is the right approach... # When a THEN clause contains a subquery w/o parenthesis around it *and* # a WHERE condition, the WHERE grouper consumes END too. # This takes makes sure that it doesn't fail. p = sqlparse.parse('CASE WHEN 1 THEN select 2 where foo = 1 end')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Case)
@pytest.mark.parametrize('s', ['foo.bar', 'x, y', 'x > y', 'x / y'])def test_grouping_alias_returns_none(s): # see issue185 and issue445 p = sqlparse.parse(s)[0] assert len(p.tokens) == 1 assert p.tokens[0].get_alias() is None
def test_grouping_idlist_function(): # see issue10 too p = sqlparse.parse('foo(1) x, bar')[0] assert isinstance(p.tokens[0], sql.IdentifierList)
def test_grouping_comparison_exclude(): # make sure operators are not handled too lazy p = sqlparse.parse('(=)')[0] assert isinstance(p.tokens[0], sql.Parenthesis) assert not isinstance(p.tokens[0].tokens[1], sql.Comparison) p = sqlparse.parse('(a=1)')[0] assert isinstance(p.tokens[0].tokens[1], sql.Comparison) p = sqlparse.parse('(a>=1)')[0] assert isinstance(p.tokens[0].tokens[1], sql.Comparison)
def test_grouping_function(): p = sqlparse.parse('foo()')[0] assert isinstance(p.tokens[0], sql.Function) p = sqlparse.parse('foo(null, bar)')[0] assert isinstance(p.tokens[0], sql.Function) assert len(list(p.tokens[0].get_parameters())) == 2 p = sqlparse.parse('foo(5) over win1')[0] assert isinstance(p.tokens[0], sql.Function) assert len(list(p.tokens[0].get_parameters())) == 1 assert isinstance(p.tokens[0].get_window(), sql.Identifier) p = sqlparse.parse('foo(5) over (PARTITION BY c1)')[0] assert isinstance(p.tokens[0], sql.Function) assert len(list(p.tokens[0].get_parameters())) == 1 assert isinstance(p.tokens[0].get_window(), sql.Parenthesis)
def test_grouping_function_not_in(): # issue183 p = sqlparse.parse('in(1, 2)')[0] assert len(p.tokens) == 2 assert p.tokens[0].ttype == T.Keyword assert isinstance(p.tokens[1], sql.Parenthesis)
def test_grouping_varchar(): p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] assert isinstance(p.tokens[2], sql.Function)
def test_statement_get_type(): def f(sql): return sqlparse.parse(sql)[0]
assert f('select * from foo').get_type() == 'SELECT' assert f('update foo').get_type() == 'UPDATE' assert f(' update foo').get_type() == 'UPDATE' assert f('\nupdate foo').get_type() == 'UPDATE' assert f('foo').get_type() == 'UNKNOWN'
def test_identifier_with_operators(): # issue 53 p = sqlparse.parse('foo||bar')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Operation) # again with whitespaces p = sqlparse.parse('foo || bar')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Operation)
def test_identifier_with_op_trailing_ws(): # make sure trailing whitespace isn't grouped with identifier p = sqlparse.parse('foo || bar ')[0] assert len(p.tokens) == 2 assert isinstance(p.tokens[0], sql.Operation) assert p.tokens[1].ttype is T.Whitespace
def test_identifier_with_string_literals(): p = sqlparse.parse("foo + 'bar'")[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Operation)
# This test seems to be wrong. It was introduced when fixing #53, but #111# showed that this shouldn't be an identifier at all. I'm leaving this# commented in the source for a while.# def test_identifier_string_concat():# p = sqlparse.parse("'foo' || bar")[0]# assert len(p.tokens) == 1# assert isinstance(p.tokens[0], sql.Identifier)
def test_identifier_consumes_ordering(): # issue89 p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] assert isinstance(p.tokens[-1], sql.IdentifierList) ids = list(p.tokens[-1].get_identifiers()) assert len(ids) == 3 assert ids[0].get_name() == 'c1' assert ids[0].get_ordering() == 'DESC' assert ids[1].get_name() == 'c2' assert ids[1].get_ordering() is None
def test_comparison_with_keywords(): # issue90 # in fact these are assignments, but for now we don't distinguish them p = sqlparse.parse('foo = NULL')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Comparison) assert len(p.tokens[0].tokens) == 5 assert p.tokens[0].left.value == 'foo' assert p.tokens[0].right.value == 'NULL' # make sure it's case-insensitive p = sqlparse.parse('foo = null')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Comparison)
def test_comparison_with_floats(): # issue145 p = sqlparse.parse('foo = 25.5')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Comparison) assert len(p.tokens[0].tokens) == 5 assert p.tokens[0].left.value == 'foo' assert p.tokens[0].right.value == '25.5'
def test_comparison_with_parenthesis(): # issue23 p = sqlparse.parse('(3 + 4) = 7')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Comparison) comp = p.tokens[0] assert isinstance(comp.left, sql.Parenthesis) assert comp.right.ttype is T.Number.Integer
@pytest.mark.parametrize('operator', ( '=', '!=', '>', '<', '<=', '>=', '~', '~~', '!~~', 'LIKE', 'NOT LIKE', 'ILIKE', 'NOT ILIKE',))def test_comparison_with_strings(operator): # issue148 p = sqlparse.parse("foo {} 'bar'".format(operator))[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Comparison) assert p.tokens[0].right.value == "'bar'" assert p.tokens[0].right.ttype == T.String.Single
def test_like_and_ilike_comparison(): def validate_where_clause(where_clause, expected_tokens): assert len(where_clause.tokens) == len(expected_tokens) for where_token, expected_token in zip(where_clause, expected_tokens): expected_ttype, expected_value = expected_token if where_token.ttype is not None: assert where_token.match(expected_ttype, expected_value, regex=True) else: # Certain tokens, such as comparison tokens, do not define a ttype that can be # matched against. For these tokens, we ensure that the token instance is of # the expected type and has a value conforming to specified regular expression import re assert (isinstance(where_token, expected_ttype) and re.match(expected_value, where_token.value))
[p1] = sqlparse.parse("select * from mytable where mytable.mycolumn LIKE 'expr%' limit 5;") [p1_where] = [token for token in p1 if isinstance(token, sql.Where)] validate_where_clause(p1_where, [ (T.Keyword, "where"), (T.Whitespace, None), (sql.Comparison, r"mytable.mycolumn LIKE.*"), (T.Whitespace, None), ])
[p2] = sqlparse.parse( "select * from mytable where mycolumn NOT ILIKE '-expr' group by othercolumn;") [p2_where] = [token for token in p2 if isinstance(token, sql.Where)] validate_where_clause(p2_where, [ (T.Keyword, "where"), (T.Whitespace, None), (sql.Comparison, r"mycolumn NOT ILIKE.*"), (T.Whitespace, None), ])
def test_comparison_with_functions(): # issue230 p = sqlparse.parse('foo = DATE(bar.baz)')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Comparison) assert len(p.tokens[0].tokens) == 5 assert p.tokens[0].left.value == 'foo' assert p.tokens[0].right.value == 'DATE(bar.baz)'
p = sqlparse.parse('DATE(foo.bar) = DATE(bar.baz)')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Comparison) assert len(p.tokens[0].tokens) == 5 assert p.tokens[0].left.value == 'DATE(foo.bar)' assert p.tokens[0].right.value == 'DATE(bar.baz)'
p = sqlparse.parse('DATE(foo.bar) = bar.baz')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Comparison) assert len(p.tokens[0].tokens) == 5 assert p.tokens[0].left.value == 'DATE(foo.bar)' assert p.tokens[0].right.value == 'bar.baz'
def test_comparison_with_typed_literal(): p = sqlparse.parse("foo = DATE 'bar.baz'")[0] assert len(p.tokens) == 1 comp = p.tokens[0] assert isinstance(comp, sql.Comparison) assert len(comp.tokens) == 5 assert comp.left.value == 'foo' assert isinstance(comp.right, sql.TypedLiteral) assert comp.right.value == "DATE 'bar.baz'"
@pytest.mark.parametrize('start', ['FOR', 'FOREACH'])def test_forloops(start): p = sqlparse.parse('{} foo in bar LOOP foobar END LOOP'.format(start))[0] assert (len(p.tokens)) == 1 assert isinstance(p.tokens[0], sql.For)
def test_nested_for(): p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] assert len(p.tokens) == 1 for1 = p.tokens[0] assert for1.tokens[0].value == 'FOR' assert for1.tokens[-1].value == 'END LOOP' for2 = for1.tokens[6] assert isinstance(for2, sql.For) assert for2.tokens[0].value == 'FOR' assert for2.tokens[-1].value == 'END LOOP'
def test_begin(): p = sqlparse.parse('BEGIN foo END')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Begin)
def test_keyword_followed_by_parenthesis(): p = sqlparse.parse('USING(somecol')[0] assert len(p.tokens) == 3 assert p.tokens[0].ttype == T.Keyword assert p.tokens[1].ttype == T.Punctuation
def test_nested_begin(): p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] assert len(p.tokens) == 1 outer = p.tokens[0] assert outer.tokens[0].value == 'BEGIN' assert outer.tokens[-1].value == 'END' inner = outer.tokens[4] assert inner.tokens[0].value == 'BEGIN' assert inner.tokens[-1].value == 'END' assert isinstance(inner, sql.Begin)
def test_aliased_column_without_as(): p = sqlparse.parse('foo bar')[0].tokens assert len(p) == 1 assert p[0].get_real_name() == 'foo' assert p[0].get_alias() == 'bar'
p = sqlparse.parse('foo.bar baz')[0].tokens[0] assert p.get_parent_name() == 'foo' assert p.get_real_name() == 'bar' assert p.get_alias() == 'baz'
def test_qualified_function(): p = sqlparse.parse('foo()')[0].tokens[0] assert p.get_parent_name() is None assert p.get_real_name() == 'foo'
p = sqlparse.parse('foo.bar()')[0].tokens[0] assert p.get_parent_name() == 'foo' assert p.get_real_name() == 'bar'
def test_aliased_function_without_as(): p = sqlparse.parse('foo() bar')[0].tokens[0] assert p.get_parent_name() is None assert p.get_real_name() == 'foo' assert p.get_alias() == 'bar'
p = sqlparse.parse('foo.bar() baz')[0].tokens[0] assert p.get_parent_name() == 'foo' assert p.get_real_name() == 'bar' assert p.get_alias() == 'baz'
def test_aliased_literal_without_as(): p = sqlparse.parse('1 foo')[0].tokens assert len(p) == 1 assert p[0].get_alias() == 'foo'
def test_grouping_as_cte(): p = sqlparse.parse('foo AS WITH apple AS 1, banana AS 2')[0].tokens assert len(p) > 4 assert p[0].get_alias() is None assert p[2].value == 'AS' assert p[4].value == 'WITH'
def test_grouping_create_table(): p = sqlparse.parse("create table db.tbl (a string)")[0].tokens assert p[4].value == "db.tbl"12345678910111213import pytest
from sqlparse import tokensfrom sqlparse.lexer import Lexer
class TestSQLREGEX: @pytest.mark.parametrize('number', ['1.0', '-1.0', '1.', '-1.', '.1', '-.1']) def test_float_numbers(self, number): ttype = next(tt for action, tt in Lexer.get_default_instance()._SQL_REGEX if action(number)) assert tokens.Number.Float == ttype123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595"""Tests sqlparse.parse()."""from io import StringIO
import pytest
import sqlparsefrom sqlparse import sql, tokens as T, keywordsfrom sqlparse.lexer import Lexer
def test_parse_tokenize(): s = 'select * from foo;' stmts = sqlparse.parse(s) assert len(stmts) == 1 assert str(stmts[0]) == s
def test_parse_multistatement(): sql1 = 'select * from foo;' sql2 = 'select * from bar;' stmts = sqlparse.parse(sql1 + sql2) assert len(stmts) == 2 assert str(stmts[0]) == sql1 assert str(stmts[1]) == sql2
@pytest.mark.parametrize('s', ['select\n*from foo;', 'select\r\n*from foo', 'select\r*from foo', 'select\r\n*from foo\n'])def test_parse_newlines(s): p = sqlparse.parse(s)[0] assert str(p) == s
def test_parse_within(): s = 'foo(col1, col2)' p = sqlparse.parse(s)[0] col1 = p.tokens[0].tokens[1].tokens[1].tokens[0] assert col1.within(sql.Function)
def test_parse_child_of(): s = '(col1, col2)' p = sqlparse.parse(s)[0] assert p.tokens[0].tokens[1].is_child_of(p.tokens[0]) s = 'select foo' p = sqlparse.parse(s)[0] assert not p.tokens[2].is_child_of(p.tokens[0]) assert p.tokens[2].is_child_of(p)
def test_parse_has_ancestor(): s = 'foo or (bar, baz)' p = sqlparse.parse(s)[0] baz = p.tokens[-1].tokens[1].tokens[-1] assert baz.has_ancestor(p.tokens[-1].tokens[1]) assert baz.has_ancestor(p.tokens[-1]) assert baz.has_ancestor(p)
@pytest.mark.parametrize('s', ['.5', '.51', '1.5', '12.5'])def test_parse_float(s): t = sqlparse.parse(s)[0].tokens assert len(t) == 1 assert t[0].ttype is sqlparse.tokens.Number.Float
@pytest.mark.parametrize('s, holder', [ ('select * from foo where user = ?', '?'), ('select * from foo where user = :1', ':1'), ('select * from foo where user = :name', ':name'), ('select * from foo where user = %s', '%s'), ('select * from foo where user = $a', '$a')])def test_parse_placeholder(s, holder): t = sqlparse.parse(s)[0].tokens[-1].tokens assert t[-1].ttype is sqlparse.tokens.Name.Placeholder assert t[-1].value == holder
def test_parse_modulo_not_placeholder(): tokens = list(sqlparse.lexer.tokenize('x %3')) assert tokens[2][0] == sqlparse.tokens.Operator
def test_parse_access_symbol(): # see issue27 t = sqlparse.parse('select a.[foo bar] as foo')[0].tokens assert isinstance(t[-1], sql.Identifier) assert t[-1].get_name() == 'foo' assert t[-1].get_real_name() == '[foo bar]' assert t[-1].get_parent_name() == 'a'
def test_parse_square_brackets_notation_isnt_too_greedy(): # see issue153 t = sqlparse.parse('[foo], [bar]')[0].tokens assert isinstance(t[0], sql.IdentifierList) assert len(t[0].tokens) == 4 assert t[0].tokens[0].get_real_name() == '[foo]' assert t[0].tokens[-1].get_real_name() == '[bar]'
def test_parse_square_brackets_notation_isnt_too_greedy2(): # see issue583 t = sqlparse.parse('[(foo[i])]')[0].tokens assert isinstance(t[0], sql.SquareBrackets) # not Identifier!
def test_parse_keyword_like_identifier(): # see issue47 t = sqlparse.parse('foo.key')[0].tokens assert len(t) == 1 assert isinstance(t[0], sql.Identifier)
def test_parse_function_parameter(): # see issue94 t = sqlparse.parse('abs(some_col)')[0].tokens[0].get_parameters() assert len(t) == 1 assert isinstance(t[0], sql.Identifier)
def test_parse_function_param_single_literal(): t = sqlparse.parse('foo(5)')[0].tokens[0].get_parameters() assert len(t) == 1 assert t[0].ttype is T.Number.Integer
def test_parse_nested_function(): t = sqlparse.parse('foo(bar(5))')[0].tokens[0].get_parameters() assert len(t) == 1 assert type(t[0]) is sql.Function
def test_parse_casted_params(): t = sqlparse.parse("foo(DATE '2023-11-14', TIMESTAMP '2023-11-15')")[0].tokens[0].get_parameters() assert len(t) == 2
def test_parse_div_operator(): p = sqlparse.parse('col1 DIV 5 AS div_col1')[0].tokens assert p[0].tokens[0].tokens[2].ttype is T.Operator assert p[0].get_alias() == 'div_col1'
def test_quoted_identifier(): t = sqlparse.parse('select x.y as "z" from foo')[0].tokens assert isinstance(t[2], sql.Identifier) assert t[2].get_name() == 'z' assert t[2].get_real_name() == 'y'
@pytest.mark.parametrize('name', [ 'foo', '_foo', # issue175 '1_data', # valid MySQL table name, see issue337 '業者名稱', # valid at least for SQLite3, see issue641])def test_valid_identifier_names(name): t = sqlparse.parse(name)[0].tokens assert isinstance(t[0], sql.Identifier) assert t[0].get_name() == name
def test_psql_quotation_marks(): # issue83
# regression: make sure plain $$ work t = sqlparse.split(""" CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $$ .... $$ LANGUAGE plpgsql; CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $$ .... $$ LANGUAGE plpgsql;""") assert len(t) == 2
# make sure $SOMETHING$ works too t = sqlparse.split(""" CREATE OR REPLACE FUNCTION testfunc1(integer) RETURNS integer AS $PROC_1$ .... $PROC_1$ LANGUAGE plpgsql; CREATE OR REPLACE FUNCTION testfunc2(integer) RETURNS integer AS $PROC_2$ .... $PROC_2$ LANGUAGE plpgsql;""") assert len(t) == 2
# operators are valid infront of dollar quoted strings t = sqlparse.split("""UPDATE SET foo =$$bar;SELECT bar$$""") assert len(t) == 1 # identifiers must be separated by whitespace t = sqlparse.split("""UPDATE SET foo TO$$bar;SELECT bar$$""") assert len(t) == 2
def test_double_precision_is_builtin(): s = 'DOUBLE PRECISION' t = sqlparse.parse(s)[0].tokens assert len(t) == 1 assert t[0].ttype == sqlparse.tokens.Name.Builtin assert t[0].value == 'DOUBLE PRECISION'
@pytest.mark.parametrize('ph', ['?', ':1', ':foo', '%s', '%(foo)s'])def test_placeholder(ph): p = sqlparse.parse(ph)[0].tokens assert len(p) == 1 assert p[0].ttype is T.Name.Placeholder
@pytest.mark.parametrize('num, expected', [ ('6.67428E-8', T.Number.Float), ('1.988e33', T.Number.Float), ('1e-12', T.Number.Float), ('e1', None),])def test_scientific_numbers(num, expected): p = sqlparse.parse(num)[0].tokens assert len(p) == 1 assert p[0].ttype is expected
def test_single_quotes_are_strings(): p = sqlparse.parse("'foo'")[0].tokens assert len(p) == 1 assert p[0].ttype is T.String.Single
def test_double_quotes_are_identifiers(): p = sqlparse.parse('"foo"')[0].tokens assert len(p) == 1 assert isinstance(p[0], sql.Identifier)
def test_single_quotes_with_linebreaks(): # issue118 p = sqlparse.parse("'f\nf'")[0].tokens assert len(p) == 1 assert p[0].ttype is T.String.Single
def test_sqlite_identifiers(): # Make sure we still parse sqlite style escapes p = sqlparse.parse('[col1],[col2]')[0].tokens id_names = [id_.get_name() for id_ in p[0].get_identifiers()] assert len(p) == 1 assert isinstance(p[0], sql.IdentifierList) assert id_names == ['[col1]', '[col2]']
p = sqlparse.parse('[col1]+[col2]')[0] types = [tok.ttype for tok in p.flatten()] assert types == [T.Name, T.Operator, T.Name]
def test_simple_1d_array_index(): p = sqlparse.parse('col[1]')[0].tokens assert len(p) == 1 assert p[0].get_name() == 'col' indices = list(p[0].get_array_indices()) assert len(indices) == 1 # 1-dimensional index assert len(indices[0]) == 1 # index is single token assert indices[0][0].value == '1'
def test_2d_array_index(): p = sqlparse.parse('col[x][(y+1)*2]')[0].tokens assert len(p) == 1 assert p[0].get_name() == 'col' assert len(list(p[0].get_array_indices())) == 2 # 2-dimensional index
def test_array_index_function_result(): p = sqlparse.parse('somefunc()[1]')[0].tokens assert len(p) == 1 assert len(list(p[0].get_array_indices())) == 1
def test_schema_qualified_array_index(): p = sqlparse.parse('schem.col[1]')[0].tokens assert len(p) == 1 assert p[0].get_parent_name() == 'schem' assert p[0].get_name() == 'col' assert list(p[0].get_array_indices())[0][0].value == '1'
def test_aliased_array_index(): p = sqlparse.parse('col[1] x')[0].tokens assert len(p) == 1 assert p[0].get_alias() == 'x' assert p[0].get_real_name() == 'col' assert list(p[0].get_array_indices())[0][0].value == '1'
def test_array_literal(): # See issue #176 p = sqlparse.parse('ARRAY[%s, %s]')[0] assert len(p.tokens) == 2 assert len(list(p.flatten())) == 7
def test_typed_array_definition(): # array indices aren't grouped with built-ins, but make sure we can extract # identifier names p = sqlparse.parse('x int, y int[], z int')[0] names = [x.get_name() for x in p.get_sublists() if isinstance(x, sql.Identifier)] assert names == ['x', 'y', 'z']
@pytest.mark.parametrize('s', ['select 1 -- foo', 'select 1 # foo'])def test_single_line_comments(s): # see issue178 p = sqlparse.parse(s)[0] assert len(p.tokens) == 5 assert p.tokens[-1].ttype == T.Comment.Single
@pytest.mark.parametrize('s', ['foo', '@foo', '#foo', '##foo'])def test_names_and_special_names(s): # see issue192 p = sqlparse.parse(s)[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Identifier)
def test_get_token_at_offset(): p = sqlparse.parse('select * from dual')[0] # 0123456789 assert p.get_token_at_offset(0) == p.tokens[0] assert p.get_token_at_offset(1) == p.tokens[0] assert p.get_token_at_offset(6) == p.tokens[1] assert p.get_token_at_offset(7) == p.tokens[2] assert p.get_token_at_offset(8) == p.tokens[3] assert p.get_token_at_offset(9) == p.tokens[4] assert p.get_token_at_offset(10) == p.tokens[4]
def test_pprint(): p = sqlparse.parse('select a0, b0, c0, d0, e0 from ' '(select * from dual) q0 where 1=1 and 2=2')[0] output = StringIO()
p._pprint_tree(f=output) pprint = '\n'.join([ "|- 0 DML 'select'", "|- 1 Whitespace ' '", "|- 2 IdentifierList 'a0, b0...'", "| |- 0 Identifier 'a0'", "| | `- 0 Name 'a0'", "| |- 1 Punctuation ','", "| |- 2 Whitespace ' '", "| |- 3 Identifier 'b0'", "| | `- 0 Name 'b0'", "| |- 4 Punctuation ','", "| |- 5 Whitespace ' '", "| |- 6 Identifier 'c0'", "| | `- 0 Name 'c0'", "| |- 7 Punctuation ','", "| |- 8 Whitespace ' '", "| |- 9 Identifier 'd0'", "| | `- 0 Name 'd0'", "| |- 10 Punctuation ','", "| |- 11 Whitespace ' '", "| `- 12 Identifier 'e0'", "| `- 0 Name 'e0'", "|- 3 Whitespace ' '", "|- 4 Keyword 'from'", "|- 5 Whitespace ' '", "|- 6 Identifier '(selec...'", "| |- 0 Parenthesis '(selec...'", "| | |- 0 Punctuation '('", "| | |- 1 DML 'select'", "| | |- 2 Whitespace ' '", "| | |- 3 Wildcard '*'", "| | |- 4 Whitespace ' '", "| | |- 5 Keyword 'from'", "| | |- 6 Whitespace ' '", "| | |- 7 Identifier 'dual'", "| | | `- 0 Name 'dual'", "| | `- 8 Punctuation ')'", "| |- 1 Whitespace ' '", "| `- 2 Identifier 'q0'", "| `- 0 Name 'q0'", "|- 7 Whitespace ' '", "`- 8 Where 'where ...'", " |- 0 Keyword 'where'", " |- 1 Whitespace ' '", " |- 2 Comparison '1=1'", " | |- 0 Integer '1'", " | |- 1 Comparison '='", " | `- 2 Integer '1'", " |- 3 Whitespace ' '", " |- 4 Keyword 'and'", " |- 5 Whitespace ' '", " `- 6 Comparison '2=2'", " |- 0 Integer '2'", " |- 1 Comparison '='", " `- 2 Integer '2'", ""]) assert output.getvalue() == pprint
def test_wildcard_multiplication(): p = sqlparse.parse('select * from dual')[0] assert p.tokens[2].ttype == T.Wildcard
p = sqlparse.parse('select a0.* from dual a0')[0] assert p.tokens[2][2].ttype == T.Wildcard
p = sqlparse.parse('select 1 * 2 from dual')[0] assert p.tokens[2][2].ttype == T.Operator
def test_stmt_tokens_parents(): # see issue 226 s = "CREATE TABLE test();" stmt = sqlparse.parse(s)[0] for token in stmt.tokens: assert token.has_ancestor(stmt)
@pytest.mark.parametrize('sql, is_literal', [ ('$$foo$$', True), ('$_$foo$_$', True), ('$token$ foo $token$', True), # don't parse inner tokens ('$_$ foo $token$bar$token$ baz$_$', True), ('$A$ foo $B$', False) # tokens don't match])def test_dbldollar_as_literal(sql, is_literal): # see issue 277 p = sqlparse.parse(sql)[0] if is_literal: assert len(p.tokens) == 1 assert p.tokens[0].ttype == T.Literal else: for token in p.tokens: assert token.ttype != T.Literal
def test_non_ascii(): _test_non_ascii = "insert into test (id, name) values (1, 'тест');"
s = _test_non_ascii stmts = sqlparse.parse(s) assert len(stmts) == 1 statement = stmts[0] assert str(statement) == s assert statement._pprint_tree() is None
s = _test_non_ascii.encode('utf-8') stmts = sqlparse.parse(s, 'utf-8') assert len(stmts) == 1 statement = stmts[0] assert str(statement) == _test_non_ascii assert statement._pprint_tree() is None
def test_get_real_name(): # issue 369 s = "update a t set t.b=1" stmts = sqlparse.parse(s) assert len(stmts) == 1 assert 'a' == stmts[0].tokens[2].get_real_name() assert 't' == stmts[0].tokens[2].get_alias()
def test_from_subquery(): # issue 446 s = 'from(select 1)' stmts = sqlparse.parse(s) assert len(stmts) == 1 assert len(stmts[0].tokens) == 2 assert stmts[0].tokens[0].value == 'from' assert stmts[0].tokens[0].ttype == T.Keyword
s = 'from (select 1)' stmts = sqlparse.parse(s) assert len(stmts) == 1 assert len(stmts[0].tokens) == 3 assert stmts[0].tokens[0].value == 'from' assert stmts[0].tokens[0].ttype == T.Keyword assert stmts[0].tokens[1].ttype == T.Whitespace
def test_parenthesis(): tokens = sqlparse.parse("(\n\n1\n\n)")[0].tokens[0].tokens assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, T.Newline, T.Newline, T.Number.Integer, T.Newline, T.Newline, T.Punctuation] tokens = sqlparse.parse("(\n\n 1 \n\n)")[0].tokens[0].tokens assert list(map(lambda t: t.ttype, tokens)) == [T.Punctuation, T.Newline, T.Newline, T.Whitespace, T.Number.Integer, T.Whitespace, T.Newline, T.Newline, T.Punctuation]
def test_configurable_keywords(): sql = """select * from foo BACON SPAM EGGS;""" tokens = sqlparse.parse(sql)[0]
assert list( (t.ttype, t.value) for t in tokens if t.ttype not in sqlparse.tokens.Whitespace ) == [ (sqlparse.tokens.Keyword.DML, "select"), (sqlparse.tokens.Wildcard, "*"), (sqlparse.tokens.Keyword, "from"), (None, "foo BACON"), (None, "SPAM EGGS"), (sqlparse.tokens.Punctuation, ";"), ]
Lexer.get_default_instance().add_keywords( { "BACON": sqlparse.tokens.Name.Builtin, "SPAM": sqlparse.tokens.Keyword, "EGGS": sqlparse.tokens.Keyword, } )
tokens = sqlparse.parse(sql)[0]
# reset the syntax for later tests. Lexer.get_default_instance().default_initialization()
assert list( (t.ttype, t.value) for t in tokens if t.ttype not in sqlparse.tokens.Whitespace ) == [ (sqlparse.tokens.Keyword.DML, "select"), (sqlparse.tokens.Wildcard, "*"), (sqlparse.tokens.Keyword, "from"), (None, "foo"), (sqlparse.tokens.Name.Builtin, "BACON"), (sqlparse.tokens.Keyword, "SPAM"), (sqlparse.tokens.Keyword, "EGGS"), (sqlparse.tokens.Punctuation, ";"), ]
def test_configurable_regex(): lex = Lexer.get_default_instance() lex.clear()
my_regex = (r"ZORDER\s+BY\b", sqlparse.tokens.Keyword)
lex.set_SQL_REGEX( keywords.SQL_REGEX[:38] + [my_regex] + keywords.SQL_REGEX[38:] ) lex.add_keywords(keywords.KEYWORDS_COMMON) lex.add_keywords(keywords.KEYWORDS_ORACLE) lex.add_keywords(keywords.KEYWORDS_PLPGSQL) lex.add_keywords(keywords.KEYWORDS_HQL) lex.add_keywords(keywords.KEYWORDS_MSACCESS) lex.add_keywords(keywords.KEYWORDS)
tokens = sqlparse.parse("select * from foo zorder by bar;")[0]
# reset the syntax for later tests. Lexer.get_default_instance().default_initialization()
assert list( (t.ttype, t.value) for t in tokens if t.ttype not in sqlparse.tokens.Whitespace )[4] == (sqlparse.tokens.Keyword, "zorder by")
@pytest.mark.parametrize('sql', [ '->', '->>', '#>', '#>>', '@>', '<@', # leaving ? out for now, they're somehow ambiguous as placeholders # '?', '?|', '?&', '||', '-', '#-'])def test_json_operators(sql): p = sqlparse.parse(sql) assert len(p) == 1 assert len(p[0].tokens) == 1 assert p[0].tokens[0].ttype == sqlparse.tokens.Operator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467import copyimport sys
import pytest
import sqlparsefrom sqlparse import sql, tokens as Tfrom sqlparse.exceptions import SQLParseError
def test_issue9(): # make sure where doesn't consume parenthesis p = sqlparse.parse('(where 1)')[0] assert isinstance(p, sql.Statement) assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Parenthesis) prt = p.tokens[0] assert len(prt.tokens) == 3 assert prt.tokens[0].ttype == T.Punctuation assert prt.tokens[-1].ttype == T.Punctuation
def test_issue13(): parsed = sqlparse.parse("select 'one';\n" "select 'two\\'';\n" "select 'three';") assert len(parsed) == 3 assert str(parsed[1]).strip() == "select 'two\\'';"
@pytest.mark.parametrize('s', ['--hello', '-- hello', '--hello\n', '--', '--\n'])def test_issue26(s): # parse stand-alone comments p = sqlparse.parse(s)[0] assert len(p.tokens) == 1 assert p.tokens[0].ttype is T.Comment.Single
@pytest.mark.parametrize('value', ['create', 'CREATE'])def test_issue34(value): t = sqlparse.parse("create")[0].token_first() assert t.match(T.Keyword.DDL, value) is True
def test_issue35(): # missing space before LIMIT. Updated for #321 sql = sqlparse.format("select * from foo where bar = 1 limit 1", reindent=True) assert sql == "\n".join([ "select *", "from foo", "where bar = 1", "limit 1"])
def test_issue38(): sql = sqlparse.format("SELECT foo; -- comment", strip_comments=True) assert sql == "SELECT foo;" sql = sqlparse.format("/* foo */", strip_comments=True) assert sql == ""
def test_issue39(): p = sqlparse.parse('select user.id from user')[0] assert len(p.tokens) == 7 idt = p.tokens[2] assert idt.__class__ == sql.Identifier assert len(idt.tokens) == 3 assert idt.tokens[0].match(T.Name, 'user') is True assert idt.tokens[1].match(T.Punctuation, '.') is True assert idt.tokens[2].match(T.Name, 'id') is True
def test_issue40(): # make sure identifier lists in subselects are grouped p = sqlparse.parse('SELECT id, name FROM ' '(SELECT id, name FROM bar) as foo')[0] assert len(p.tokens) == 7 assert p.tokens[2].__class__ == sql.IdentifierList assert p.tokens[-1].__class__ == sql.Identifier assert p.tokens[-1].get_name() == 'foo' sp = p.tokens[-1].tokens[0] assert sp.tokens[3].__class__ == sql.IdentifierList # make sure that formatting works as expected s = sqlparse.format('SELECT id == name FROM ' '(SELECT id, name FROM bar)', reindent=True) assert s == '\n'.join([ 'SELECT id == name', 'FROM', ' (SELECT id,', ' name', ' FROM bar)'])
s = sqlparse.format('SELECT id == name FROM ' '(SELECT id, name FROM bar) as foo', reindent=True) assert s == '\n'.join([ 'SELECT id == name', 'FROM', ' (SELECT id,', ' name', ' FROM bar) as foo'])
@pytest.mark.parametrize('s', ['select x.y::text as z from foo', 'select x.y::text as "z" from foo', 'select x."y"::text as z from foo', 'select x."y"::text as "z" from foo', 'select "x".y::text as z from foo', 'select "x".y::text as "z" from foo', 'select "x"."y"::text as z from foo', 'select "x"."y"::text as "z" from foo'])@pytest.mark.parametrize('func_name, result', [('get_name', 'z'), ('get_real_name', 'y'), ('get_parent_name', 'x'), ('get_alias', 'z'), ('get_typecast', 'text')])def test_issue78(s, func_name, result): # the bug author provided this nice examples, let's use them! p = sqlparse.parse(s)[0] i = p.tokens[2] assert isinstance(i, sql.Identifier)
func = getattr(i, func_name) assert func() == result
def test_issue83(): sql = """ CREATE OR REPLACE FUNCTION func_a(text) RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS $_$ BEGIN ... END; $_$;
CREATE OR REPLACE FUNCTION func_b(text) RETURNS boolean LANGUAGE plpgsql STRICT IMMUTABLE AS $_$ BEGIN ... END; $_$;
ALTER TABLE..... ;""" t = sqlparse.split(sql) assert len(t) == 3
def test_comment_encoding_when_reindent(): # There was an UnicodeEncodeError in the reindent filter that # casted every comment followed by a keyword to str. sql = 'select foo -- Comment containing Ümläuts\nfrom bar' formatted = sqlparse.format(sql, reindent=True) assert formatted == sql
def test_parse_sql_with_binary(): # See https://github.com/andialbrecht/sqlparse/pull/88 # digest = '|ËêplL4¡høN{' digest = '\x82|\xcb\x0e\xea\x8aplL4\xa1h\x91\xf8N{' sql = "select * from foo where bar = '{}'".format(digest) formatted = sqlparse.format(sql, reindent=True) tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) assert formatted == tformatted
def test_dont_alias_keywords(): # The _group_left_right function had a bug where the check for the # left side wasn't handled correctly. In one case this resulted in # a keyword turning into an identifier. p = sqlparse.parse('FROM AS foo')[0] assert len(p.tokens) == 5 assert p.tokens[0].ttype is T.Keyword assert p.tokens[2].ttype is T.Keyword
def test_format_accepts_encoding(load_file): # issue20 sql = load_file('test_cp1251.sql', 'cp1251') formatted = sqlparse.format(sql, reindent=True, encoding='cp1251') tformatted = 'insert into foo\nvalues (1); -- Песня про надежду'
assert formatted == tformatted
def test_stream(get_stream): with get_stream("stream.sql") as stream: p = sqlparse.parse(stream)[0] assert p.get_type() == 'INSERT'
def test_issue90(): sql = ('UPDATE "gallery_photo" SET "owner_id" = 4018, "deleted_at" = NULL,' ' "width" = NULL, "height" = NULL, "rating_votes" = 0,' ' "rating_score" = 0, "thumbnail_width" = NULL,' ' "thumbnail_height" = NULL, "price" = 1, "description" = NULL') formatted = sqlparse.format(sql, reindent=True) tformatted = '\n'.join([ 'UPDATE "gallery_photo"', 'SET "owner_id" = 4018,', ' "deleted_at" = NULL,', ' "width" = NULL,', ' "height" = NULL,', ' "rating_votes" = 0,', ' "rating_score" = 0,', ' "thumbnail_width" = NULL,', ' "thumbnail_height" = NULL,', ' "price" = 1,', ' "description" = NULL']) assert formatted == tformatted
def test_except_formatting(): sql = 'SELECT 1 FROM foo WHERE 2 = 3 EXCEPT SELECT 2 FROM bar WHERE 1 = 2' formatted = sqlparse.format(sql, reindent=True) tformatted = '\n'.join([ 'SELECT 1', 'FROM foo', 'WHERE 2 = 3', 'EXCEPT', 'SELECT 2', 'FROM bar', 'WHERE 1 = 2']) assert formatted == tformatted
def test_null_with_as(): sql = 'SELECT NULL AS c1, NULL AS c2 FROM t1' formatted = sqlparse.format(sql, reindent=True) tformatted = '\n'.join([ 'SELECT NULL AS c1,', ' NULL AS c2', 'FROM t1']) assert formatted == tformatted
def test_issue190_open_file(filepath): path = filepath('stream.sql') with open(path) as stream: p = sqlparse.parse(stream)[0] assert p.get_type() == 'INSERT'
def test_issue193_splitting_function(): sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) BEGIN DECLARE y VARCHAR(20); RETURN x; END; SELECT * FROM a.b;""" statements = sqlparse.split(sql) assert len(statements) == 2
def test_issue194_splitting_function(): sql = """ CREATE FUNCTION a(x VARCHAR(20)) RETURNS VARCHAR(20) BEGIN DECLARE y VARCHAR(20); IF (1 = 1) THEN SET x = y; END IF; RETURN x; END; SELECT * FROM a.b;""" statements = sqlparse.split(sql) assert len(statements) == 2
def test_issue186_get_type(): sql = "-- comment\ninsert into foo" p = sqlparse.parse(sql)[0] assert p.get_type() == 'INSERT'
def test_issue212_py2unicode(): t1 = sql.Token(T.String, 'schöner ') t2 = sql.Token(T.String, 'bug') token_list = sql.TokenList([t1, t2]) assert str(token_list) == 'schöner bug'
def test_issue213_leadingws(): sql = " select * from foo" assert sqlparse.format(sql, strip_whitespace=True) == "select * from foo"
def test_issue227_gettype_cte(): select_stmt = sqlparse.parse('SELECT 1, 2, 3 FROM foo;') assert select_stmt[0].get_type() == 'SELECT' with_stmt = sqlparse.parse('WITH foo AS (SELECT 1, 2, 3)' 'SELECT * FROM foo;') assert with_stmt[0].get_type() == 'SELECT' with2_stmt = sqlparse.parse(""" WITH foo AS (SELECT 1 AS abc, 2 AS def), bar AS (SELECT * FROM something WHERE x > 1) INSERT INTO elsewhere SELECT * FROM foo JOIN bar;""") assert with2_stmt[0].get_type() == 'INSERT'
def test_issue207_runaway_format(): sql = 'select 1 from (select 1 as one, 2 as two, 3 from dual) t0' p = sqlparse.format(sql, reindent=True) assert p == '\n'.join([ "select 1", "from", " (select 1 as one,", " 2 as two,", " 3", " from dual) t0"])
def test_token_next_doesnt_ignore_skip_cm(): sql = '--comment\nselect 1' tok = sqlparse.parse(sql)[0].token_next(-1, skip_cm=True)[1] assert tok.value == 'select'
@pytest.mark.parametrize('s', [ 'SELECT x AS', 'AS'])def test_issue284_as_grouping(s): p = sqlparse.parse(s)[0] assert s == str(p)
def test_issue315_utf8_by_default(): # Make sure the lexer can handle utf-8 string by default correctly # digest = '齐天大圣.カラフルな雲.사랑해요' # The digest contains Chinese, Japanese and Korean characters # All in 'utf-8' encoding. digest = ( '\xe9\xbd\x90\xe5\xa4\xa9\xe5\xa4\xa7\xe5\x9c\xa3.' '\xe3\x82\xab\xe3\x83\xa9\xe3\x83\x95\xe3\x83\xab\xe3\x81\xaa\xe9' '\x9b\xb2.' '\xec\x82\xac\xeb\x9e\x91\xed\x95\xb4\xec\x9a\x94' ) sql = "select * from foo where bar = '{}'".format(digest) formatted = sqlparse.format(sql, reindent=True) tformatted = "select *\nfrom foo\nwhere bar = '{}'".format(digest) assert formatted == tformatted
def test_issue322_concurrently_is_keyword(): s = 'CREATE INDEX CONCURRENTLY myindex ON mytable(col1);' p = sqlparse.parse(s)[0]
assert len(p.tokens) == 12 assert p.tokens[0].ttype is T.Keyword.DDL # CREATE assert p.tokens[2].ttype is T.Keyword # INDEX assert p.tokens[4].ttype is T.Keyword # CONCURRENTLY assert p.tokens[4].value == 'CONCURRENTLY' assert isinstance(p.tokens[6], sql.Identifier) assert p.tokens[6].value == 'myindex'
@pytest.mark.parametrize('s', [ 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop;', 'SELECT @min_price:=MIN(price), @max_price:=MAX(price) FROM shop',
])def test_issue359_index_error_assignments(s): sqlparse.parse(s) sqlparse.format(s, strip_comments=True)
def test_issue469_copy_as_psql_command(): formatted = sqlparse.format( '\\copy select * from foo', keyword_case='upper', identifier_case='capitalize') assert formatted == '\\copy SELECT * FROM Foo'
@pytest.mark.xfail(reason='Needs to be fixed')def test_issue484_comments_and_newlines(): formatted = sqlparse.format('\n'.join([ 'Create table myTable', '(', ' myId TINYINT NOT NULL, --my special comment', ' myName VARCHAR2(100) NOT NULL', ')']), strip_comments=True) assert formatted == ('\n'.join([ 'Create table myTable', '(', ' myId TINYINT NOT NULL,', ' myName VARCHAR2(100) NOT NULL', ')']))
def test_issue485_split_multi(): p_sql = '''CREATE OR REPLACE RULE ruled_tab_2rules AS ON INSERTTO public.ruled_tabDO instead (select 1;select 2;);''' assert len(sqlparse.split(p_sql)) == 1
def test_issue489_tzcasts(): p = sqlparse.parse('select bar at time zone \'UTC\' as foo')[0] assert p.tokens[-1].has_alias() is True assert p.tokens[-1].get_alias() == 'foo'
def test_issue562_tzcasts(): # Test that whitespace between 'from' and 'bar' is retained formatted = sqlparse.format( 'SELECT f(HOUR from bar AT TIME ZONE \'UTC\') from foo', reindent=True ) assert formatted == \ 'SELECT f(HOUR\n from bar AT TIME ZONE \'UTC\')\nfrom foo'
def test_as_in_parentheses_indents(): # did raise NoneType has no attribute is_group in _process_parentheses formatted = sqlparse.format('(as foo)', reindent=True) assert formatted == '(as foo)'
def test_format_invalid_where_clause(): # did raise ValueError formatted = sqlparse.format('where, foo', reindent=True) assert formatted == 'where, foo'
def test_splitting_at_and_backticks_issue588(): splitted = sqlparse.split( 'grant foo to user1@`myhost`; grant bar to user1@`myhost`;') assert len(splitted) == 2 assert splitted[-1] == 'grant bar to user1@`myhost`;'
def test_comment_between_cte_clauses_issue632(): p, = sqlparse.parse(""" WITH foo AS (), -- A comment before baz subquery baz AS () SELECT * FROM baz;""") assert p.get_type() == "SELECT"
def test_copy_issue672(): p = sqlparse.parse('select * from foo')[0] copied = copy.deepcopy(p) assert str(p) == str(copied)
def test_primary_key_issue740(): p = sqlparse.parse('PRIMARY KEY')[0] assert len(p.tokens) == 1 assert p.tokens[0].ttype == T.Keyword
@pytest.fixturedef limit_recursion(): curr_limit = sys.getrecursionlimit() sys.setrecursionlimit(100) yield sys.setrecursionlimit(curr_limit)
def test_max_recursion(limit_recursion): with pytest.raises(SQLParseError): sqlparse.parse('[' * 1000 + ']' * 1000)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210# Tests splitting functions.
import typesfrom io import StringIO
import pytest
import sqlparse
def test_split_semicolon(): sql1 = 'select * from foo;' sql2 = "select * from foo where bar = 'foo;bar';" stmts = sqlparse.parse(''.join([sql1, sql2])) assert len(stmts) == 2 assert str(stmts[0]) == sql1 assert str(stmts[1]) == sql2
def test_split_backslash(): stmts = sqlparse.parse("select '\'; select '\'';") assert len(stmts) == 2
@pytest.mark.parametrize('fn', ['function.sql', 'function_psql.sql', 'function_psql2.sql', 'function_psql3.sql', 'function_psql4.sql'])def test_split_create_function(load_file, fn): sql = load_file(fn) stmts = sqlparse.parse(sql) assert len(stmts) == 1 assert str(stmts[0]) == sql
def test_split_dashcomments(load_file): sql = load_file('dashcomment.sql') stmts = sqlparse.parse(sql) assert len(stmts) == 3 assert ''.join(str(q) for q in stmts) == sql
@pytest.mark.parametrize('s', ['select foo; -- comment\n', 'select foo; -- comment\r', 'select foo; -- comment\r\n', 'select foo; -- comment'])def test_split_dashcomments_eol(s): stmts = sqlparse.parse(s) assert len(stmts) == 1
def test_split_begintag(load_file): sql = load_file('begintag.sql') stmts = sqlparse.parse(sql) assert len(stmts) == 3 assert ''.join(str(q) for q in stmts) == sql
def test_split_begintag_2(load_file): sql = load_file('begintag_2.sql') stmts = sqlparse.parse(sql) assert len(stmts) == 1 assert ''.join(str(q) for q in stmts) == sql
def test_split_dropif(): sql = 'DROP TABLE IF EXISTS FOO;\n\nSELECT * FROM BAR;' stmts = sqlparse.parse(sql) assert len(stmts) == 2 assert ''.join(str(q) for q in stmts) == sql
def test_split_comment_with_umlaut(): sql = ('select * from foo;\n' '-- Testing an umlaut: ä\n' 'select * from bar;') stmts = sqlparse.parse(sql) assert len(stmts) == 2 assert ''.join(str(q) for q in stmts) == sql
def test_split_comment_end_of_line(): sql = ('select * from foo; -- foo\n' 'select * from bar;') stmts = sqlparse.parse(sql) assert len(stmts) == 2 assert ''.join(str(q) for q in stmts) == sql # make sure the comment belongs to first query assert str(stmts[0]) == 'select * from foo; -- foo\n'
def test_split_casewhen(): sql = ("SELECT case when val = 1 then 2 else null end as foo;\n" "comment on table actor is 'The actor table.';") stmts = sqlparse.split(sql) assert len(stmts) == 2
def test_split_casewhen_procedure(load_file): # see issue580 stmts = sqlparse.split(load_file('casewhen_procedure.sql')) assert len(stmts) == 2
def test_split_cursor_declare(): sql = ('DECLARE CURSOR "foo" AS SELECT 1;\n' 'SELECT 2;') stmts = sqlparse.split(sql) assert len(stmts) == 2
def test_split_if_function(): # see issue 33 # don't let IF as a function confuse the splitter sql = ('CREATE TEMPORARY TABLE tmp ' 'SELECT IF(a=1, a, b) AS o FROM one; ' 'SELECT t FROM two') stmts = sqlparse.split(sql) assert len(stmts) == 2
def test_split_stream(): stream = StringIO("SELECT 1; SELECT 2;") stmts = sqlparse.parsestream(stream) assert isinstance(stmts, types.GeneratorType) assert len(list(stmts)) == 2
def test_split_encoding_parsestream(): stream = StringIO("SELECT 1; SELECT 2;") stmts = list(sqlparse.parsestream(stream)) assert isinstance(stmts[0].tokens[0].value, str)
def test_split_unicode_parsestream(): stream = StringIO('SELECT ö') stmts = list(sqlparse.parsestream(stream)) assert str(stmts[0]) == 'SELECT ö'
def test_split_simple(): stmts = sqlparse.split('select * from foo; select * from bar;') assert len(stmts) == 2 assert stmts[0] == 'select * from foo;' assert stmts[1] == 'select * from bar;'
def test_split_ignores_empty_newlines(): stmts = sqlparse.split('select foo;\nselect bar;\n') assert len(stmts) == 2 assert stmts[0] == 'select foo;' assert stmts[1] == 'select bar;'
def test_split_quotes_with_new_line(): stmts = sqlparse.split('select "foo\nbar"') assert len(stmts) == 1 assert stmts[0] == 'select "foo\nbar"'
stmts = sqlparse.split("select 'foo\n\bar'") assert len(stmts) == 1 assert stmts[0] == "select 'foo\n\bar'"
def test_split_mysql_handler_for(load_file): # see issue581 stmts = sqlparse.split(load_file('mysql_handler.sql')) assert len(stmts) == 2
@pytest.mark.parametrize('sql, expected', [ ('select * from foo;', ['select * from foo']), ('select * from foo', ['select * from foo']), ('select * from foo; select * from bar;', [ 'select * from foo', 'select * from bar', ]), (' select * from foo;\n\nselect * from bar;\n\n\n\n', [ 'select * from foo', 'select * from bar', ]), ('select * from foo\n\n; bar', ['select * from foo', 'bar']),])def test_split_strip_semicolon(sql, expected): stmts = sqlparse.split(sql, strip_semicolon=True) assert len(stmts) == len(expected) for idx, expectation in enumerate(expected): assert stmts[idx] == expectation
def test_split_strip_semicolon_procedure(load_file): stmts = sqlparse.split(load_file('mysql_handler.sql'), strip_semicolon=True) assert len(stmts) == 2 assert stmts[0].endswith('end') assert stmts[1].endswith('end')
@pytest.mark.parametrize('sql, num', [ ('USE foo;\nGO\nSELECT 1;\nGO', 4), ('SELECT * FROM foo;\nGO', 2), ('USE foo;\nGO 2\nSELECT 1;', 3)])def test_split_go(sql, num): # issue762 stmts = sqlparse.split(sql) assert len(stmts) == num
def test_split_multiple_case_in_begin(load_file): # issue784 stmts = sqlparse.split(load_file('multiple_case_in_begin.sql')) assert len(stmts) == 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247import typesfrom io import StringIO
import pytest
import sqlparsefrom sqlparse import lexerfrom sqlparse import sql, tokens as T
def test_tokenize_simple(): s = 'select * from foo;' stream = lexer.tokenize(s) assert isinstance(stream, types.GeneratorType) tokens = list(stream) assert len(tokens) == 8 assert len(tokens[0]) == 2 assert tokens[0] == (T.Keyword.DML, 'select') assert tokens[-1] == (T.Punctuation, ';')
def test_tokenize_backticks(): s = '`foo`.`bar`' tokens = list(lexer.tokenize(s)) assert len(tokens) == 3 assert tokens[0] == (T.Name, '`foo`')
@pytest.mark.parametrize('s', ['foo\nbar\n', 'foo\rbar\r', 'foo\r\nbar\r\n', 'foo\r\nbar\n'])def test_tokenize_linebreaks(s): # issue1 tokens = lexer.tokenize(s) assert ''.join(str(x[1]) for x in tokens) == s
def test_tokenize_inline_keywords(): # issue 7 s = "create created_foo" tokens = list(lexer.tokenize(s)) assert len(tokens) == 3 assert tokens[0][0] == T.Keyword.DDL assert tokens[2][0] == T.Name assert tokens[2][1] == 'created_foo' s = "enddate" tokens = list(lexer.tokenize(s)) assert len(tokens) == 1 assert tokens[0][0] == T.Name s = "join_col" tokens = list(lexer.tokenize(s)) assert len(tokens) == 1 assert tokens[0][0] == T.Name s = "left join_col" tokens = list(lexer.tokenize(s)) assert len(tokens) == 3 assert tokens[2][0] == T.Name assert tokens[2][1] == 'join_col'
def test_tokenize_negative_numbers(): s = "values(-1)" tokens = list(lexer.tokenize(s)) assert len(tokens) == 4 assert tokens[2][0] == T.Number.Integer assert tokens[2][1] == '-1'
def test_token_str(): token = sql.Token(None, 'FoO') assert str(token) == 'FoO'
def test_token_repr(): token = sql.Token(T.Keyword, 'foo') tst = "<Keyword 'foo' at 0x" assert repr(token)[:len(tst)] == tst token = sql.Token(T.Keyword, '1234567890') tst = "<Keyword '123456...' at 0x" assert repr(token)[:len(tst)] == tst
def test_token_flatten(): token = sql.Token(T.Keyword, 'foo') gen = token.flatten() assert isinstance(gen, types.GeneratorType) lgen = list(gen) assert lgen == [token]
def test_tokenlist_repr(): p = sqlparse.parse('foo, bar, baz')[0] tst = "<IdentifierList 'foo, b...' at 0x" assert repr(p.tokens[0])[:len(tst)] == tst
def test_single_quotes(): p = sqlparse.parse("'test'")[0] tst = "<Single \"'test'\" at 0x" assert repr(p.tokens[0])[:len(tst)] == tst
def test_tokenlist_first(): p = sqlparse.parse(' select foo')[0] first = p.token_first() assert first.value == 'select' assert p.token_first(skip_ws=False).value == ' ' assert sql.TokenList([]).token_first() is None
def test_tokenlist_token_matching(): t1 = sql.Token(T.Keyword, 'foo') t2 = sql.Token(T.Punctuation, ',') x = sql.TokenList([t1, t2]) assert x.token_matching([lambda t: t.ttype is T.Keyword], 0) == t1 assert x.token_matching([lambda t: t.ttype is T.Punctuation], 0) == t2 assert x.token_matching([lambda t: t.ttype is T.Keyword], 1) is None
def test_stream_simple(): stream = StringIO("SELECT 1; SELECT 2;")
tokens = lexer.tokenize(stream) assert len(list(tokens)) == 9
stream.seek(0) tokens = list(lexer.tokenize(stream)) assert len(tokens) == 9
stream.seek(0) tokens = list(lexer.tokenize(stream)) assert len(tokens) == 9
def test_stream_error(): stream = StringIO("FOOBAR{")
tokens = list(lexer.tokenize(stream)) assert len(tokens) == 2 assert tokens[1][0] == T.Error
@pytest.mark.parametrize('expr', [ 'JOIN', 'LEFT JOIN', 'LEFT OUTER JOIN', 'FULL OUTER JOIN', 'NATURAL JOIN', 'CROSS JOIN', 'STRAIGHT JOIN', 'INNER JOIN', 'LEFT INNER JOIN'])def test_parse_join(expr): p = sqlparse.parse('{} foo'.format(expr))[0] assert len(p.tokens) == 3 assert p.tokens[0].ttype is T.Keyword
def test_parse_union(): # issue294 p = sqlparse.parse('UNION ALL')[0] assert len(p.tokens) == 1 assert p.tokens[0].ttype is T.Keyword
@pytest.mark.parametrize('s', ['END IF', 'END IF', 'END\t\nIF', 'END LOOP', 'END LOOP', 'END\t\nLOOP'])def test_parse_endifloop(s): p = sqlparse.parse(s)[0] assert len(p.tokens) == 1 assert p.tokens[0].ttype is T.Keyword
@pytest.mark.parametrize('s', [ 'ASC', 'DESC', 'NULLS FIRST', 'NULLS LAST', 'ASC NULLS FIRST', 'ASC NULLS LAST', 'DESC NULLS FIRST', 'DESC NULLS LAST',])def test_parse_order(s): # issue487 p = sqlparse.parse(s)[0] assert len(p.tokens) == 1 assert p.tokens[0].ttype is T.Keyword.Order
@pytest.mark.parametrize('s', [ 'foo', 'Foo', 'FOO', 'v$name', # issue291])def test_parse_identifiers(s): p = sqlparse.parse(s)[0] assert len(p.tokens) == 1 token = p.tokens[0] assert str(token) == s assert isinstance(token, sql.Identifier)
def test_parse_group_by(): p = sqlparse.parse('GROUP BY')[0] assert len(p.tokens) == 1 assert p.tokens[0].ttype is T.Keyword
def test_parse_order_by(): p = sqlparse.parse('ORDER BY')[0] assert len(p.tokens) == 1 assert p.tokens[0].ttype is T.Keyword
def test_parse_window_as(): p = sqlparse.parse('WINDOW w AS')[0] assert len(p.tokens) == 5 assert p.tokens[0].ttype is T.Keyword
@pytest.mark.parametrize('s', ( "LIKE", "ILIKE", "NOT LIKE", "NOT ILIKE", "NOT LIKE", "NOT ILIKE",))def test_like_and_ilike_parsed_as_comparisons(s): p = sqlparse.parse(s)[0] assert len(p.tokens) == 1 assert p.tokens[0].ttype == T.Operator.Comparison
@pytest.mark.parametrize('s', ( "LIKEaaa", "bILIKE", "aaILIKEbb", "NOTLIKE", "NOTILIKE",))def test_near_like_and_ilike_parsed_appropriately(s): p = sqlparse.parse(s)[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Identifier)
@pytest.mark.parametrize('s', ( 'AT TIME ZONE \'UTC\'',))def test_parse_tzcast(s): p = sqlparse.parse(s)[0] assert len(p.tokens) == 1 assert p.tokens[0].ttype == T.Keyword.TZCast
def test_cli_commands(): p = sqlparse.parse('\\copy')[0] assert len(p.tokens) == 1 assert p.tokens[0].ttype == T.Command123456789101112import pytest
from sqlparse import utils
@pytest.mark.parametrize('value, expected', ( [None, None], ['\'foo\'', 'foo'], ['"foo"', 'foo'], ['`foo`', 'foo']))def test_remove_quotes(value, expected): assert utils.remove_quotes(value) == expected123#!/bin/bashset -Eeuo pipefail:tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/tests/trusted-inventory.jsonAdded+152
tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/canaries/first-hunk-only.shAdded+28
tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/canaries/original-bug.shAdded+3
tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/openenv.jsonAdded+27
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/LICENSE.sourceAdded+25
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/adapter.jsonAdded+126
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/dependency-setup.shAdded+8
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/environment/DockerfileAdded+3
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/instruction.mdAdded+72
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/metadata.jsonAdded+533
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/provenance.jsonAdded+88
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/provided-gold.diffAdded+140
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/solution/solve.shAdded+146
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/task.tomlAdded+24
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/check_pytest.pyAdded+91
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/expected-panels.jsonAdded+337
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/grade.pyAdded+128
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/panel-config.jsonAdded+22
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/test.shAdded+6
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted-inventory.jsonAdded+152
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/pyproject.tomlAdded+104
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/__init__.pyAdded
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/conftest.pyAdded+47
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/_Make_DirEntry.sqlAdded+6
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/begintag.sqlAdded+4
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/begintag_2.sqlAdded+13
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/casewhen_procedure.sqlAdded+8
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/dashcomment.sqlAdded+5
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/encoding_gbk.sqlAdded+3
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/encoding_utf8.sqlAdded+3
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function.sqlAdded+13
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql.sqlAdded+72
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql2.sqlAdded+7
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql3.sqlAdded+8
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql4.sqlAdded+12
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/huge_select.sqlAdded+1
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/multiple_case_in_begin.sqlAdded+8
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/mysql_handler.sqlAdded+10
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/stream.sqlAdded+2
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/test_cp1251.sqlAdded+1
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_cli.pyAdded+122
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_format.pyAdded+774
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_grouping.pyAdded+679
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_keywords.pyAdded+13
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_parse.pyAdded+595
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_regressions.pyAdded+467
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_split.pyAdded+210
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_tokenize.pyAdded+247
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_utils.pyAdded+12
tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/validation/canaries/original-bug.shAdded+3