diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/canaries/first-hunk-only.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..ecc0963b28b90aae4a8d268f3a4b404e893c2bc9 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/canaries/first-hunk-only.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 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.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__gclrk0qy/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..3953946db0d533f31b8a4bfd4d2a17e6a73e526d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/adapter.json @@ -0,0 +1,126 @@ +{ + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cb34db157fd9706a63acede07409ab2a793ac57a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/instruction.md @@ -0,0 +1,72 @@ +# 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: + +```python +import 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: + +```python +sql = '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: + +```python +sql = '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: + +```python +result = 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..885a1654b113be68fa779bbd8c825e6bdfd655b3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/metadata.json @@ -0,0 +1,533 @@ +{ + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..f09aa30114b18062f208fee9f86b620dae5cbf74 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/provenance.json @@ -0,0 +1,88 @@ +{ + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..7602532124099abd9ad0390eaf9f560935bbbc1d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/provided-gold.diff @@ -0,0 +1,140 @@ +diff --git a/sqlparse/filters/output.py b/sqlparse/filters/output.py +index 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, ';') diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..399ed7fd9feb921412656bef4e68560e30a53670 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/solution/solve.sh @@ -0,0 +1,146 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/output.py b/sqlparse/filters/output.py +index 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.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2be2326ff8584bd7c5208414e19dfe04a8dba30b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/task.toml @@ -0,0 +1,24 @@ +version = "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.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..7c860a43cd66acb9132c3f32e58de047a832eef2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__kep88kh8/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..cc151a6bf1f93009b69c89f930bdbc640c7f3a69 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "40942e20c436188748327c5a33793295ed697361b7e2707d36c19368d7e81707", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "f7856f76fefa6b9358000b41129605b45fddc260b8a0263f0a426799125c3cd6", + "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": true, + "partial_repair_sha256": "52ddc8ef684509a0957318ae7265a9c48ebdf3189dae6d3a0f85d6b8d9e2e11b", + "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": "d51a640c8b50f4865e1e6264ea3c80b401c3befd", + "source_completion_sha256": "afe8d1713d6e6b18ed52c7d448c93db144415b61ed8fd0a8c56f295066d23451", + "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__oc0uybjx", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "816f584144fb2113fbbfaca4c34f43ffb2259e86c746af9d64d4a4e2b154fe99", + "is_fork": true, + "learner_path": "tasks/100659c1a10007123f12d625/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/d51a640c8b50f4865e1e6264ea3c80b401c3befd/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": "42fc0479bf5eb813aa540ad1f01c317ce59d5bc5e8422011d9682f908d03d2c3", + "provenance_path": "tasks/100659c1a10007123f12d625/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d51a640c8b50f4865e1e6264ea3c80b401c3befd", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "335ecbcc08a27db4e2d900209e4a3502a38e3a5c", + "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__oc0uybjx", + "task_sha256": "73bb1b4aac32347cb116a99c02eff582bd3be2326557c39ef97417ec6bafd0c8", + "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__oc0uybjx", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e3117c6d666cf484f166c178886933c56961010d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/instruction.md @@ -0,0 +1,53 @@ +# Identifier case filter and string truncation not working correctly + +After updating to the latest version, I'm experiencing issues with the identifier case filter and string truncation functionality. + +## Issue 1: Identifier case filter not working + +When trying to format SQL with the `identifier_case` option, identifiers are not being properly converted to the specified case. This used to work in previous versions. + +``` +sql = 'select * from bar' +result = sqlparse.format(sql, identifier_case='upper') +``` + +Expected: `select * from BAR` +Actual: No change in case, still `select * from bar` + +## Issue 2: String truncation filter broken + +The string truncation filter is also not working correctly. When trying to truncate strings, it's either not truncating them at all or producing incorrect output. + +``` +sql = "update foo set value = 'this is a very long string';" +result = sqlparse.format(sql, truncate_strings=10) +``` + +Expected: `update foo set value = 'this is a [...]';` +Actual: The string is not properly truncated or the output is malformed. + +## Reproduction + +Here's a simple script to reproduce both issues: + +```python +import sqlparse + +# Test identifier case +sql1 = 'select * from bar' +print("Original:", sql1) +print("With identifier_case='upper':", sqlparse.format(sql1, identifier_case='upper')) + +# Test string truncation +sql2 = "update foo set value = 'this is a very long string';" +print("\nOriginal:", sql2) +print("With truncate_strings=10:", sqlparse.format(sql2, truncate_strings=10)) +``` + +This issue also affects quoted identifiers and the `\copy` command in PostgreSQL syntax. + +I'm using sqlparse version X.Y.Z on Python 3.10. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..943981e71a7db081d1bc7f9e2dace503124a7883 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/metadata.json @@ -0,0 +1,533 @@ +{ + "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::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::test_truncate_strings", + "tests/test_regressions.py::test_issue469_copy_as_psql_command" + ], + "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_invalid_option", + "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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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_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_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": "335ecbcc08a27db4e2d900209e4a3502a38e3a5c", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "d51a640c8b50f4865e1e6264ea3c80b401c3befd" + }, + "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_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", + "tests/test_regressions.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/tokens.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 898091, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx", + "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__oc0uybjx", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "816f584144fb2113fbbfaca4c34f43ffb2259e86c746af9d64d4a4e2b154fe99", + "is_fork": true, + "learner_path": "tasks/100659c1a10007123f12d625/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/d51a640c8b50f4865e1e6264ea3c80b401c3befd/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": "42fc0479bf5eb813aa540ad1f01c317ce59d5bc5e8422011d9682f908d03d2c3", + "provenance_path": "tasks/100659c1a10007123f12d625/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d51a640c8b50f4865e1e6264ea3c80b401c3befd", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "335ecbcc08a27db4e2d900209e4a3502a38e3a5c", + "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__oc0uybjx", + "task_sha256": "73bb1b4aac32347cb116a99c02eff582bd3be2326557c39ef97417ec6bafd0c8", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..08fe937a7fa7573972fdceab0fffab157d7c3a46 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "40942e20c436188748327c5a33793295ed697361b7e2707d36c19368d7e81707", + "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/d51a640c8b50f4865e1e6264ea3c80b401c3befd/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "afe8d1713d6e6b18ed52c7d448c93db144415b61ed8fd0a8c56f295066d23451", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "1ac1e7b6eee2b8527299fc35744f6d9af492bf07053edc14ed8fc1033377efb4", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "816f584144fb2113fbbfaca4c34f43ffb2259e86c746af9d64d4a4e2b154fe99", + "is_fork": true, + "learner_path": "tasks/100659c1a10007123f12d625/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/d51a640c8b50f4865e1e6264ea3c80b401c3befd/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": "42fc0479bf5eb813aa540ad1f01c317ce59d5bc5e8422011d9682f908d03d2c3", + "provenance_path": "tasks/100659c1a10007123f12d625/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d51a640c8b50f4865e1e6264ea3c80b401c3befd", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "335ecbcc08a27db4e2d900209e4a3502a38e3a5c", + "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__oc0uybjx", + "task_sha256": "73bb1b4aac32347cb116a99c02eff582bd3be2326557c39ef97417ec6bafd0c8", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..22cd825eaec1f5a42063f2ea15cd075eb0a395c8 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/provided-gold.diff @@ -0,0 +1,38 @@ +diff --git a/sqlparse/filters/tokens.py b/sqlparse/filters/tokens.py +index b306313d5db3bd00b4e70969bf7afe6a2ac21a01..cc00a844f2e9f3ff1041acf8777641c66a3ce6d4 100644 +--- a/sqlparse/filters/tokens.py ++++ b/sqlparse/filters/tokens.py +@@ -31,7 +31,7 @@ + + def process(self, stream): + for ttype, value in stream: +- if ttype not in self.ttype or value.strip()[-1] != '"': ++ if ttype in self.ttype and value.strip()[0] != '"': + value = self.convert(value) + yield ttype, value + +@@ -43,16 +43,17 @@ + + def process(self, stream): + for ttype, value in stream: +- if ttype == T.Literal.String.Single: ++ if ttype != T.Literal.String.Single: ++ yield ttype, value + continue + + if value[:2] == "''": +- inner = value[1:-2] ++ inner = value[2:-2] ++ quote = "''" ++ else: ++ inner = value[1:-1] + quote = "'" +- else: +- inner = value[:2] +- quote = "''" + +- if len(inner) < self.width: +- value = ''.join((quote, inner, self.char, quote)) ++ if len(inner) > self.width: ++ value = ''.join((quote, inner[:self.width], self.char, quote)) + yield ttype, value diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..fa0900c0cd52b89f4df8306773f76bee795954f3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/solution/solve.sh @@ -0,0 +1,44 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/tokens.py b/sqlparse/filters/tokens.py +index b306313d5db3bd00b4e70969bf7afe6a2ac21a01..cc00a844f2e9f3ff1041acf8777641c66a3ce6d4 100644 +--- a/sqlparse/filters/tokens.py ++++ b/sqlparse/filters/tokens.py +@@ -31,7 +31,7 @@ + + def process(self, stream): + for ttype, value in stream: +- if ttype not in self.ttype or value.strip()[-1] != '"': ++ if ttype in self.ttype and value.strip()[0] != '"': + value = self.convert(value) + yield ttype, value + +@@ -43,16 +43,17 @@ + + def process(self, stream): + for ttype, value in stream: +- if ttype == T.Literal.String.Single: ++ if ttype != T.Literal.String.Single: ++ yield ttype, value + continue + + if value[:2] == "''": +- inner = value[1:-2] ++ inner = value[2:-2] ++ quote = "''" ++ else: ++ inner = value[1:-1] + quote = "'" +- else: +- inner = value[:2] +- quote = "''" + +- if len(inner) < self.width: +- value = ''.join((quote, inner, self.char, quote)) ++ if len(inner) > self.width: ++ value = ''.join((quote, inner[:self.width], self.char, quote)) + yield ttype, value +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..93fe143106312c493e5ebaaae0846dc1ae5ad329 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:ebef87176e8a276b447b123cf81a5570d2deb3c19afaf7cc6da6104bf71fe476" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..97a051a9935601628707cf838d25ca4971244241 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormat::test_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::test_truncate_strings", + "tests/test_regressions.py::test_issue469_copy_as_psql_command" + ], + "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_invalid_option", + "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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/tokens.py b/sqlparse/filters/tokens.py +index b306313d5db3bd00b4e70969bf7afe6a2ac21a01..cc00a844f2e9f3ff1041acf8777641c66a3ce6d4 100644 +--- a/sqlparse/filters/tokens.py ++++ b/sqlparse/filters/tokens.py +@@ -31,7 +31,7 @@ + + def process(self, stream): + for ttype, value in stream: +- if ttype not in self.ttype or value.strip()[-1] != '"': ++ if ttype in self.ttype and value.strip()[0] != '"': + value = self.convert(value) + yield ttype, value + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__oc0uybjx/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..c57cd73c0e86dadf0f8d7a50047c9d84aad9d51b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "3c6d16ae5c7c451f6d5682c39ef48d43753f056d61542937a78e54aecdf2af97", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "5666fcf61fc7daff25e52c22c45f73f2b634a1a9981def5712610afe3f67d10a", + "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": true, + "partial_repair_sha256": "17116798bd2e4298e21fcc780dde0ba38edc9c80df46faafdab322cea01445a4", + "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": "e30b0a1fd1891638976494be0a1eb2cf3746491e", + "source_completion_sha256": "d4d281ea1063679028b7f6586dc602e188988ceda9717e28c88aab8268bb5aa6", + "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__y1kb148t", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "4ca6ce3275bf69973656ca69519bfee14c9e945be6ce5abb1f2668d6c86f5d00", + "is_fork": true, + "learner_path": "tasks/1f62aa5f97842e8c8719c19e/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/e30b0a1fd1891638976494be0a1eb2cf3746491e/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": "673c46f3a29949678b32ab152b16cefb48a6cea0b2123233491901ca91a25987", + "provenance_path": "tasks/1f62aa5f97842e8c8719c19e/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e30b0a1fd1891638976494be0a1eb2cf3746491e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d7250a9c4a56ab5c65d4286c1987d311266b292c", + "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__y1kb148t", + "task_sha256": "469a9d979eed73a4f8263585fc95d03e3bccefb309226b1648fb7cbf56be7bfa", + "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__y1kb148t", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b6cb90cbcdb6f9268b2a088edc4ed210e8b00f84 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/instruction.md @@ -0,0 +1,39 @@ +SQL comment stripping and operator spacing issues + +I'm having problems with the SQL comment stripping and spaces around operators functionality in sqlparse. Several issues are occurring: + +1. When stripping comments, the behavior is incorrect: +```python +import sqlparse + +# Single line comments not properly stripped +sql = "SELECT col1 -- comment\nFROM table" +result = sqlparse.format(sql, strip_comments=True) +print(result) # Still contains comment or adds incorrect whitespace + +# Multi-line comments not properly handled +sql = "SELECT col1 /* multi-line\ncomment */FROM table" +result = sqlparse.format(sql, strip_comments=True) +print(result) # Comment not properly removed +``` + +2. The spaces around operators filter is completely broken: +```python +import sqlparse + +# Basic operators +sql = "SELECT a+b, c-d FROM table" +result = sqlparse.format(sql, use_space_around_operators=True) +print(result) # Returns None instead of adding spaces + +# Boolean operators +sql = "SELECT * FROM table WHERE a=1 AND b=2" +result = sqlparse.format(sql, use_space_around_operators=True) +print(result) # Returns None instead of "SELECT * FROM table WHERE a = 1 AND b = 2" +``` + +The issue seems to be in the filters implementation. When using the `use_space_around_operators=True` option, the function returns `None` instead of the formatted SQL string. Also, the comment stripping functionality doesn't properly preserve whitespace or handle SQL hints correctly. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..f79ec7c9d4596295359be1e1e632c3a5a429df1d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/metadata.json @@ -0,0 +1,533 @@ +{ + "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::TestFormat::test_strip_comments_single", + "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::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_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue213_leadingws" + ], + "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_invalid_option", + "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::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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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_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_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": "d7250a9c4a56ab5c65d4286c1987d311266b292c", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "e30b0a1fd1891638976494be0a1eb2cf3746491e" + }, + "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_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", + "tests/test_regressions.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/others.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 895845, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t", + "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__y1kb148t", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "4ca6ce3275bf69973656ca69519bfee14c9e945be6ce5abb1f2668d6c86f5d00", + "is_fork": true, + "learner_path": "tasks/1f62aa5f97842e8c8719c19e/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/e30b0a1fd1891638976494be0a1eb2cf3746491e/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": "673c46f3a29949678b32ab152b16cefb48a6cea0b2123233491901ca91a25987", + "provenance_path": "tasks/1f62aa5f97842e8c8719c19e/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e30b0a1fd1891638976494be0a1eb2cf3746491e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d7250a9c4a56ab5c65d4286c1987d311266b292c", + "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__y1kb148t", + "task_sha256": "469a9d979eed73a4f8263585fc95d03e3bccefb309226b1648fb7cbf56be7bfa", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..f5de48ac5d044c0ce21f9780d36a78ad5e04070b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "3c6d16ae5c7c451f6d5682c39ef48d43753f056d61542937a78e54aecdf2af97", + "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/e30b0a1fd1891638976494be0a1eb2cf3746491e/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "d4d281ea1063679028b7f6586dc602e188988ceda9717e28c88aab8268bb5aa6", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "1531bd7cc5d41d0f5ccba7f3bd572d918c0583a762ce62c4cc3f1eaa0d157260", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "4ca6ce3275bf69973656ca69519bfee14c9e945be6ce5abb1f2668d6c86f5d00", + "is_fork": true, + "learner_path": "tasks/1f62aa5f97842e8c8719c19e/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/e30b0a1fd1891638976494be0a1eb2cf3746491e/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": "673c46f3a29949678b32ab152b16cefb48a6cea0b2123233491901ca91a25987", + "provenance_path": "tasks/1f62aa5f97842e8c8719c19e/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e30b0a1fd1891638976494be0a1eb2cf3746491e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "d7250a9c4a56ab5c65d4286c1987d311266b292c", + "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__y1kb148t", + "task_sha256": "469a9d979eed73a4f8263585fc95d03e3bccefb309226b1648fb7cbf56be7bfa", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..c9dd531ad873bc8c49b2cddfe7bf982af4bab93d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/provided-gold.diff @@ -0,0 +1,105 @@ +diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py +index bb103fc8d6b63a134cb1a3a9926d98d8da5c69c5..6c1680ec4a8cbba52b30c25868b4b849d5b3a935 100644 +--- a/sqlparse/filters/others.py ++++ b/sqlparse/filters/others.py +@@ -15,45 +15,62 @@ + + @staticmethod + def _process(tlist): +- def get_next_comment(idx=0): ++ def get_next_comment(idx=-1): ++ # TODO(andi) Comment types should be unified, see related issue38 + return tlist.token_next_by(i=sql.Comment, t=T.Comment, idx=idx) + + def _get_insert_token(token): +- m = re.search(r'([\r\n]*) *$', token.value) ++ """Returns either a whitespace or the line breaks from token.""" ++ # See issue484 why line breaks should be preserved. ++ # Note: The actual value for a line break is replaced by \n ++ # in SerializerUnicode which will be executed in the ++ # postprocessing state. ++ m = re.search(r'([\r\n]+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: +- return sql.Token(T.Whitespace, '\t') ++ return sql.Token(T.Whitespace, ' ') + +- sql_hints = (T.Comment.Multiline.Hint,) ++ sql_hints = (T.Comment.Multiline.Hint, T.Comment.Single.Hint) + tidx, token = get_next_comment() + while token: ++ # skipping token remove if token is a SQL-Hint. issue262 + is_sql_hint = False + if token.ttype in sql_hints: + is_sql_hint = True + elif isinstance(token, sql.Comment): + comment_tokens = token.tokens +- if len(comment_tokens) >= 0: ++ if len(comment_tokens) > 0: + if comment_tokens[0].ttype in sql_hints: + is_sql_hint = True + + if is_sql_hint: ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + continue + +- pidx, prev_ = tlist.token_prev(tidx, skip_ws=True) +- nidx, next_ = tlist.token_next(tidx, skip_ws=True) ++ pidx, prev_ = tlist.token_prev(tidx, skip_ws=False) ++ nidx, next_ = tlist.token_next(tidx, skip_ws=False) ++ # Replace by whitespace if prev and next exist and if they're not ++ # whitespaces. This doesn't apply if prev or next is a parenthesis. + if ( + prev_ is None or next_ is None +- or prev_.is_whitespace or prev_.match(T.Punctuation, ')') +- or next_.is_whitespace or next_.match(T.Punctuation, '(') ++ or prev_.is_whitespace or prev_.match(T.Punctuation, '(') ++ or next_.is_whitespace or next_.match(T.Punctuation, ')') + ): ++ # Insert a whitespace to ensure the following SQL produces ++ # a valid SQL (see #425). + if prev_ is not None and not prev_.match(T.Punctuation, '('): +- tlist.tokens.insert(tidx + 1, _get_insert_token(token)) ++ tlist.tokens.insert(tidx, _get_insert_token(token)) + tlist.tokens.remove(token) + else: +- tlist.tokens[tidx - 1] = _get_insert_token(token) ++ tlist.tokens[tidx] = _get_insert_token(token) + ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + + def process(self, stmt): +@@ -71,10 +88,12 @@ + @staticmethod + def _stripws_default(tlist): + last_was_ws = False +- for i, token in enumerate(tlist.tokens): ++ is_first_char = True ++ for token in tlist.tokens: + if token.is_whitespace: +- token.value = '' if last_was_ws or i == len(tlist.tokens) - 1 else ' ' ++ token.value = '' if last_was_ws or is_first_char else ' ' + last_was_ws = token.is_whitespace ++ is_first_char = False + + def _stripws_identifierlist(self, tlist): + # Removes newlines before commas, see issue140 +@@ -129,9 +148,9 @@ + tidx, token = tlist.token_next_by(t=ttypes, idx=tidx) + + def process(self, stmt): +- [self.process(sgroup) for sgroup in reversed(stmt.get_sublists())] ++ [self.process(sgroup) for sgroup in stmt.get_sublists()] + SpacesAroundOperatorsFilter._process(stmt) +- return None ++ return stmt + + + class StripTrailingSemicolonFilter: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2300bffe54c43797c21659cfe1755c83996455f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/solution/solve.sh @@ -0,0 +1,111 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py +index bb103fc8d6b63a134cb1a3a9926d98d8da5c69c5..6c1680ec4a8cbba52b30c25868b4b849d5b3a935 100644 +--- a/sqlparse/filters/others.py ++++ b/sqlparse/filters/others.py +@@ -15,45 +15,62 @@ + + @staticmethod + def _process(tlist): +- def get_next_comment(idx=0): ++ def get_next_comment(idx=-1): ++ # TODO(andi) Comment types should be unified, see related issue38 + return tlist.token_next_by(i=sql.Comment, t=T.Comment, idx=idx) + + def _get_insert_token(token): +- m = re.search(r'([\r\n]*) *$', token.value) ++ """Returns either a whitespace or the line breaks from token.""" ++ # See issue484 why line breaks should be preserved. ++ # Note: The actual value for a line break is replaced by \n ++ # in SerializerUnicode which will be executed in the ++ # postprocessing state. ++ m = re.search(r'([\r\n]+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: +- return sql.Token(T.Whitespace, '\t') ++ return sql.Token(T.Whitespace, ' ') + +- sql_hints = (T.Comment.Multiline.Hint,) ++ sql_hints = (T.Comment.Multiline.Hint, T.Comment.Single.Hint) + tidx, token = get_next_comment() + while token: ++ # skipping token remove if token is a SQL-Hint. issue262 + is_sql_hint = False + if token.ttype in sql_hints: + is_sql_hint = True + elif isinstance(token, sql.Comment): + comment_tokens = token.tokens +- if len(comment_tokens) >= 0: ++ if len(comment_tokens) > 0: + if comment_tokens[0].ttype in sql_hints: + is_sql_hint = True + + if is_sql_hint: ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + continue + +- pidx, prev_ = tlist.token_prev(tidx, skip_ws=True) +- nidx, next_ = tlist.token_next(tidx, skip_ws=True) ++ pidx, prev_ = tlist.token_prev(tidx, skip_ws=False) ++ nidx, next_ = tlist.token_next(tidx, skip_ws=False) ++ # Replace by whitespace if prev and next exist and if they're not ++ # whitespaces. This doesn't apply if prev or next is a parenthesis. + if ( + prev_ is None or next_ is None +- or prev_.is_whitespace or prev_.match(T.Punctuation, ')') +- or next_.is_whitespace or next_.match(T.Punctuation, '(') ++ or prev_.is_whitespace or prev_.match(T.Punctuation, '(') ++ or next_.is_whitespace or next_.match(T.Punctuation, ')') + ): ++ # Insert a whitespace to ensure the following SQL produces ++ # a valid SQL (see #425). + if prev_ is not None and not prev_.match(T.Punctuation, '('): +- tlist.tokens.insert(tidx + 1, _get_insert_token(token)) ++ tlist.tokens.insert(tidx, _get_insert_token(token)) + tlist.tokens.remove(token) + else: +- tlist.tokens[tidx - 1] = _get_insert_token(token) ++ tlist.tokens[tidx] = _get_insert_token(token) + ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + + def process(self, stmt): +@@ -71,10 +88,12 @@ + @staticmethod + def _stripws_default(tlist): + last_was_ws = False +- for i, token in enumerate(tlist.tokens): ++ is_first_char = True ++ for token in tlist.tokens: + if token.is_whitespace: +- token.value = '' if last_was_ws or i == len(tlist.tokens) - 1 else ' ' ++ token.value = '' if last_was_ws or is_first_char else ' ' + last_was_ws = token.is_whitespace ++ is_first_char = False + + def _stripws_identifierlist(self, tlist): + # Removes newlines before commas, see issue140 +@@ -129,9 +148,9 @@ + tidx, token = tlist.token_next_by(t=ttypes, idx=tidx) + + def process(self, stmt): +- [self.process(sgroup) for sgroup in reversed(stmt.get_sublists())] ++ [self.process(sgroup) for sgroup in stmt.get_sublists()] + SpacesAroundOperatorsFilter._process(stmt) +- return None ++ return stmt + + + class StripTrailingSemicolonFilter: +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9d312a88e5f0bc4b45c645e4bea4fcdc02a83818 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:db7a5c7de0fabd0c64a7e55248fca04c3bb7c1babaadb2c1fc5d145973cf005f" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..53c16de1484a8f377a4a65e60966b31ecc223f2e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormat::test_strip_comments_single", + "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::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_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue213_leadingws" + ], + "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_invalid_option", + "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::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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py +index bb103fc8d6b63a134cb1a3a9926d98d8da5c69c5..6c1680ec4a8cbba52b30c25868b4b849d5b3a935 100644 +--- a/sqlparse/filters/others.py ++++ b/sqlparse/filters/others.py +@@ -15,45 +15,62 @@ + + @staticmethod + def _process(tlist): +- def get_next_comment(idx=0): ++ def get_next_comment(idx=-1): ++ # TODO(andi) Comment types should be unified, see related issue38 + return tlist.token_next_by(i=sql.Comment, t=T.Comment, idx=idx) + + def _get_insert_token(token): +- m = re.search(r'([\r\n]*) *$', token.value) ++ """Returns either a whitespace or the line breaks from token.""" ++ # See issue484 why line breaks should be preserved. ++ # Note: The actual value for a line break is replaced by \n ++ # in SerializerUnicode which will be executed in the ++ # postprocessing state. ++ m = re.search(r'([\r\n]+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: +- return sql.Token(T.Whitespace, '\t') ++ return sql.Token(T.Whitespace, ' ') + +- sql_hints = (T.Comment.Multiline.Hint,) ++ sql_hints = (T.Comment.Multiline.Hint, T.Comment.Single.Hint) + tidx, token = get_next_comment() + while token: ++ # skipping token remove if token is a SQL-Hint. issue262 + is_sql_hint = False + if token.ttype in sql_hints: + is_sql_hint = True + elif isinstance(token, sql.Comment): + comment_tokens = token.tokens +- if len(comment_tokens) >= 0: ++ if len(comment_tokens) > 0: + if comment_tokens[0].ttype in sql_hints: + is_sql_hint = True + + if is_sql_hint: ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + continue + +- pidx, prev_ = tlist.token_prev(tidx, skip_ws=True) +- nidx, next_ = tlist.token_next(tidx, skip_ws=True) ++ pidx, prev_ = tlist.token_prev(tidx, skip_ws=False) ++ nidx, next_ = tlist.token_next(tidx, skip_ws=False) ++ # Replace by whitespace if prev and next exist and if they're not ++ # whitespaces. This doesn't apply if prev or next is a parenthesis. + if ( + prev_ is None or next_ is None +- or prev_.is_whitespace or prev_.match(T.Punctuation, ')') +- or next_.is_whitespace or next_.match(T.Punctuation, '(') ++ or prev_.is_whitespace or prev_.match(T.Punctuation, '(') ++ or next_.is_whitespace or next_.match(T.Punctuation, ')') + ): ++ # Insert a whitespace to ensure the following SQL produces ++ # a valid SQL (see #425). + if prev_ is not None and not prev_.match(T.Punctuation, '('): +- tlist.tokens.insert(tidx + 1, _get_insert_token(token)) ++ tlist.tokens.insert(tidx, _get_insert_token(token)) + tlist.tokens.remove(token) + else: +- tlist.tokens[tidx - 1] = _get_insert_token(token) ++ tlist.tokens[tidx] = _get_insert_token(token) + ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + + def process(self, stmt): +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__y1kb148t/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..24269983a70e074653e08dded637e8ea701674e9 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "31795755fb1d652f52704cc2283380e8e2f4801d215cdda70b7b97bbffff143b", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "139ee1b2ffcba505480b37a205a56477cf43434dcb592a4a32fe3f3f58e819b2", + "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": true, + "partial_repair_sha256": "0a036005b26ec3d7b8add427aa9feecb6a88babe4f3f792f17f1c16b9b5e3013", + "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": "f986759e556777afcb8e87b2814e5c7f83b15b6c", + "source_completion_sha256": "72dfe52f2a1cc803de90e1ca90c6fb8f354410191aa5d1f5fd3be66e4d83ec4a", + "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__yv7akt1y", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "8861c218eab84d88a55828ba780a9e6e6e281f0ac85e8824457e76bb13d69342", + "is_fork": true, + "learner_path": "tasks/4c54642111096817e3e4b44f/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/f986759e556777afcb8e87b2814e5c7f83b15b6c/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": "278049cfc13432ea9f44b14897c291874005a79b2cf4fa62713aed8d41b54385", + "provenance_path": "tasks/4c54642111096817e3e4b44f/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f986759e556777afcb8e87b2814e5c7f83b15b6c", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "107e25482d5fe4ecae589af4bd6ad6f54269e701", + "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__yv7akt1y", + "task_sha256": "c9e2cfdfe98c77196e3f731abe0014feafeb73ef119b2463a0939071ee3960b7", + "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__yv7akt1y", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f63e308013c7432318f50f56d36ed491e25573e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/instruction.md @@ -0,0 +1,43 @@ +Case filter and truncate string filter broken in latest commit + +Description + +The case filter and truncate string filter are not working correctly anymore. + +When using the keyword_case formatter, it's reversing non-keyword tokens and uppercasing keywords, which is not the expected behavior. For example: + +```sql +select * from bar; +``` + +Should become: +```sql +SELECT * FROM bar; +``` + +When using uppercase, but instead it's doing something weird with the tokens. + +Also, the truncate_strings filter is completely broken. It seems the width and char parameters are swapped in the TruncateStringFilter constructor. When trying to truncate a long string, it fails with a TypeError about '>' not being supported. + +To reproduce: + +```python +import sqlparse + +# Try to format a SQL statement with keyword case +sql = 'select * from bar;' +result = sqlparse.format(sql, keyword_case='upper') +print(result) # Not correctly uppercasing keywords + +# Try to truncate a long string +long_sql = "update foo set value = '{}';".format('x' * 1000) +try: + formatted = sqlparse.format(long_sql, truncate_strings=10) + print(formatted) +except TypeError as e: + print(f"Error: {e}") # Will show TypeError +``` + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..0e64db1135095894cc277e7930c6ccd7e4651bed --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/metadata.json @@ -0,0 +1,533 @@ +{ + "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::TestFormat::test_keywordcase", + "tests/test_format.py::test_truncate_strings", + "tests/test_regressions.py::test_issue469_copy_as_psql_command" + ], + "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_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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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_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_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": "107e25482d5fe4ecae589af4bd6ad6f54269e701", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "f986759e556777afcb8e87b2814e5c7f83b15b6c" + }, + "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_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", + "tests/test_regressions.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/tokens.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 898315, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y", + "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__yv7akt1y", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "8861c218eab84d88a55828ba780a9e6e6e281f0ac85e8824457e76bb13d69342", + "is_fork": true, + "learner_path": "tasks/4c54642111096817e3e4b44f/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/f986759e556777afcb8e87b2814e5c7f83b15b6c/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": "278049cfc13432ea9f44b14897c291874005a79b2cf4fa62713aed8d41b54385", + "provenance_path": "tasks/4c54642111096817e3e4b44f/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f986759e556777afcb8e87b2814e5c7f83b15b6c", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "107e25482d5fe4ecae589af4bd6ad6f54269e701", + "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__yv7akt1y", + "task_sha256": "c9e2cfdfe98c77196e3f731abe0014feafeb73ef119b2463a0939071ee3960b7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..6394cb314c887ec2956c127df71c949d1ce82bc5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "31795755fb1d652f52704cc2283380e8e2f4801d215cdda70b7b97bbffff143b", + "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/f986759e556777afcb8e87b2814e5c7f83b15b6c/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "72dfe52f2a1cc803de90e1ca90c6fb8f354410191aa5d1f5fd3be66e4d83ec4a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "34b4f599b8e1bc16273394db8da1a65b343d5d579c0905f5832522847cd6a8c6", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "8861c218eab84d88a55828ba780a9e6e6e281f0ac85e8824457e76bb13d69342", + "is_fork": true, + "learner_path": "tasks/4c54642111096817e3e4b44f/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/f986759e556777afcb8e87b2814e5c7f83b15b6c/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": "278049cfc13432ea9f44b14897c291874005a79b2cf4fa62713aed8d41b54385", + "provenance_path": "tasks/4c54642111096817e3e4b44f/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f986759e556777afcb8e87b2814e5c7f83b15b6c", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "107e25482d5fe4ecae589af4bd6ad6f54269e701", + "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__yv7akt1y", + "task_sha256": "c9e2cfdfe98c77196e3f731abe0014feafeb73ef119b2463a0939071ee3960b7", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..f9386211ce4966f537febcec3f220dfbc51404bd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/provided-gold.diff @@ -0,0 +1,28 @@ +diff --git a/sqlparse/filters/tokens.py b/sqlparse/filters/tokens.py +index 9b5fbb6a9db691c5172ef8e591342ac12d51f051..cc00a844f2e9f3ff1041acf8777641c66a3ce6d4 100644 +--- a/sqlparse/filters/tokens.py ++++ b/sqlparse/filters/tokens.py +@@ -17,10 +17,8 @@ + + def process(self, stream): + for ttype, value in stream: +- if ttype not in self.ttype: +- value = self.convert(value[::-1]) +- else: +- value = value.upper() ++ if ttype in self.ttype: ++ value = self.convert(value) + yield ttype, value + + +@@ -40,8 +38,8 @@ + + class TruncateStringFilter: + def __init__(self, width, char): +- self.width = char +- self.char = width ++ self.width = width ++ self.char = char + + def process(self, stream): + for ttype, value in stream: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a9dcd59ccdf0f3cc71bee8b4da93a192416330a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/solution/solve.sh @@ -0,0 +1,34 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/tokens.py b/sqlparse/filters/tokens.py +index 9b5fbb6a9db691c5172ef8e591342ac12d51f051..cc00a844f2e9f3ff1041acf8777641c66a3ce6d4 100644 +--- a/sqlparse/filters/tokens.py ++++ b/sqlparse/filters/tokens.py +@@ -17,10 +17,8 @@ + + def process(self, stream): + for ttype, value in stream: +- if ttype not in self.ttype: +- value = self.convert(value[::-1]) +- else: +- value = value.upper() ++ if ttype in self.ttype: ++ value = self.convert(value) + yield ttype, value + + +@@ -40,8 +38,8 @@ + + class TruncateStringFilter: + def __init__(self, width, char): +- self.width = char +- self.char = width ++ self.width = width ++ self.char = char + + def process(self, stream): + for ttype, value in stream: +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c62dbc4a972a6a28e950b933e612fd3e84099514 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:73b4dc2410943bc9ce100cfd767f79fb15a2638bd7bf6a76e62ce4d9b3fe28bd" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..a3a1500ffcb8d9314c5ce51b272eea482dc2e403 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormat::test_keywordcase", + "tests/test_format.py::test_truncate_strings", + "tests/test_regressions.py::test_issue469_copy_as_psql_command" + ], + "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_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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/tokens.py b/sqlparse/filters/tokens.py +index 9b5fbb6a9db691c5172ef8e591342ac12d51f051..cc00a844f2e9f3ff1041acf8777641c66a3ce6d4 100644 +--- a/sqlparse/filters/tokens.py ++++ b/sqlparse/filters/tokens.py +@@ -17,10 +17,8 @@ + + def process(self, stream): + for ttype, value in stream: +- if ttype not in self.ttype: +- value = self.convert(value[::-1]) +- else: +- value = value.upper() ++ if ttype in self.ttype: ++ value = self.convert(value) + yield ttype, value + + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_file__yv7akt1y/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..30e91982f48b5386a1d172dffb0cf3553073e410 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "d92ab1b89054eed8ac3ba0ae0c546e626a1890fb88435733ec2164b557a588bb", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "3255c5c88f573cc0d60486ab2cbaa6a2a9df4bb2ca25fe7edc1b957236cb4f0b", + "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": true, + "partial_repair_sha256": "5d50a69f217f4d913da6ad266e188e098f93c254af15adf85f91dda554ab19cf", + "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": "11b949a2aba170e8b38a05fee66c47bb0f932935", + "source_completion_sha256": "60e088b6dd09239f0c7c03a9ed176a6491b20e497d06609833d5f57d2788d0ae", + "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_module__cwv6tm4l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "77c4890ebc90b4ef118f16028350925fb8954a23b9e52e34dd43953eb47b2247", + "is_fork": true, + "learner_path": "tasks/fa283687d713e60eea9441ad/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/11b949a2aba170e8b38a05fee66c47bb0f932935/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": "06f34fffbece01ba66335afa28c274468ec76b26a83b13a662e87bf46a777114", + "provenance_path": "tasks/fa283687d713e60eea9441ad/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "11b949a2aba170e8b38a05fee66c47bb0f932935", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "1625bd21e6b2db5f7b031d707f62927429a9c9df", + "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_module__cwv6tm4l", + "task_sha256": "4554fac1e248419ad361998d5ad62cfd5713122604206d47f1add5e8ded59586", + "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_module__cwv6tm4l", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..be9e0cea8253a4ecfeaa68f7c6a97329b1b48146 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/instruction.md @@ -0,0 +1,48 @@ +# CASE statement formatting broken in AlignedIndentFilter + +I'm trying to format SQL with CASE statements using the AlignedIndentFilter, but it's causing errors. The formatting is completely broken. + +## Description + +When trying to format SQL with CASE statements, the code crashes with an error. The issue appears to be in the `_process_case` method of the `AlignedIndentFilter` class. + +Here's a simple example that fails: + +```python +import sqlparse + +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 +""" + +# This crashes +formatted = sqlparse.format(sql, reindent=True, reindent_aligned=True) +print(formatted) +``` + +The error seems to be related to the order of operations in the `_process_case` method. It's trying to use variables before they're defined. + +Also, there's an issue with the identifier list formatting in the `ReindentFilter` class. When formatting a long identifier list with functions, the spacing around commas is incorrect. + +For example: +```python +sql = "select 'abc' as foo, json_build_object('a', a,'b', b, 'c', c, 'd', d, 'e', e) as col2col3 from my_table" +formatted = sqlparse.format(sql, reindent=True, wrap_after=30) +print(formatted) +``` + +The output doesn't have proper spacing after commas. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..316ad3f75050b25391add4db751ff094e226b1ad --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/metadata.json @@ -0,0 +1,534 @@ +{ + "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::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions" + ], + "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_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_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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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": "1625bd21e6b2db5f7b031d707f62927429a9c9df", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "11b949a2aba170e8b38a05fee66c47bb0f932935" + }, + "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/aligned_indent.py", + "sqlparse/filters/reindent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 912391, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l", + "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_module__cwv6tm4l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "77c4890ebc90b4ef118f16028350925fb8954a23b9e52e34dd43953eb47b2247", + "is_fork": true, + "learner_path": "tasks/fa283687d713e60eea9441ad/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/11b949a2aba170e8b38a05fee66c47bb0f932935/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": "06f34fffbece01ba66335afa28c274468ec76b26a83b13a662e87bf46a777114", + "provenance_path": "tasks/fa283687d713e60eea9441ad/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "11b949a2aba170e8b38a05fee66c47bb0f932935", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "1625bd21e6b2db5f7b031d707f62927429a9c9df", + "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_module__cwv6tm4l", + "task_sha256": "4554fac1e248419ad361998d5ad62cfd5713122604206d47f1add5e8ded59586", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..0e93236452610a3cfb57bb56702273918800483e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "d92ab1b89054eed8ac3ba0ae0c546e626a1890fb88435733ec2164b557a588bb", + "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/11b949a2aba170e8b38a05fee66c47bb0f932935/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "60e088b6dd09239f0c7c03a9ed176a6491b20e497d06609833d5f57d2788d0ae", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "3956f2c731cb30cdff7a6c413d5671cbfceecf1f887a321ff92d5ef82c00b70e", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "77c4890ebc90b4ef118f16028350925fb8954a23b9e52e34dd43953eb47b2247", + "is_fork": true, + "learner_path": "tasks/fa283687d713e60eea9441ad/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/11b949a2aba170e8b38a05fee66c47bb0f932935/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": "06f34fffbece01ba66335afa28c274468ec76b26a83b13a662e87bf46a777114", + "provenance_path": "tasks/fa283687d713e60eea9441ad/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "11b949a2aba170e8b38a05fee66c47bb0f932935", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "1625bd21e6b2db5f7b031d707f62927429a9c9df", + "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_module__cwv6tm4l", + "task_sha256": "4554fac1e248419ad361998d5ad62cfd5713122604206d47f1add5e8ded59586", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..82c206830b0e546639bf525ee266e9116290915e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/provided-gold.diff @@ -0,0 +1,55 @@ +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index ba790dd910da895618dba78bf212f68d5e16451d..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -65,14 +65,14 @@ + self._process_default(tlist) + + def _process_case(self, tlist): +- cases.append((None, [end_token])) + offset_ = len('case ') + len('when ') ++ cases = tlist.get_cases(skip_ws=True) + # align the end as well + end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1] ++ cases.append((None, [end_token])) + + condition_width = [len(' '.join(map(str, cond))) if cond else 0 + for cond, _ in cases] +- cases = tlist.get_cases(skip_ws=True) + max_cond_width = max(condition_width) + + for i, (cond, value) in enumerate(cases): +@@ -85,6 +85,7 @@ + ws = sql.Token(T.Whitespace, self.char * ( + max_cond_width - condition_width[i])) + tlist.insert_after(cond[-1], ws) ++ + def _next_token(self, tlist, idx=-1): + split_words = T.Keyword, self.split_words, True + tidx, token = tlist.token_next_by(m=split_words, idx=idx) +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 6b126c49a6963783eb02ffdb609685464910d5d2..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -160,6 +160,13 @@ + token, sql.Token(T.Whitespace, ' ')) + position = 0 + else: ++ # ensure whitespace ++ for token in tlist: ++ _, next_ws = tlist.token_next( ++ tlist.token_index(token), skip_ws=False) ++ if token.value == ',' and not next_ws.is_whitespace: ++ tlist.insert_after( ++ token, sql.Token(T.Whitespace, ' ')) + + end_at = self.offset + sum(len(i.value) + 1 for i in identifiers) + adjusted_offset = 0 +@@ -181,6 +188,7 @@ + tlist.insert_before(token, self.nl(offset=adjust)) + position = 0 + self._process_default(tlist) ++ + def _process_case(self, tlist): + iterable = iter(tlist.get_cases()) + cond, _ = next(iterable) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..53b829f4707d95a9b7e912bc9361ea386cc0f8a8 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/solution/solve.sh @@ -0,0 +1,61 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index ba790dd910da895618dba78bf212f68d5e16451d..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -65,14 +65,14 @@ + self._process_default(tlist) + + def _process_case(self, tlist): +- cases.append((None, [end_token])) + offset_ = len('case ') + len('when ') ++ cases = tlist.get_cases(skip_ws=True) + # align the end as well + end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1] ++ cases.append((None, [end_token])) + + condition_width = [len(' '.join(map(str, cond))) if cond else 0 + for cond, _ in cases] +- cases = tlist.get_cases(skip_ws=True) + max_cond_width = max(condition_width) + + for i, (cond, value) in enumerate(cases): +@@ -85,6 +85,7 @@ + ws = sql.Token(T.Whitespace, self.char * ( + max_cond_width - condition_width[i])) + tlist.insert_after(cond[-1], ws) ++ + def _next_token(self, tlist, idx=-1): + split_words = T.Keyword, self.split_words, True + tidx, token = tlist.token_next_by(m=split_words, idx=idx) +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 6b126c49a6963783eb02ffdb609685464910d5d2..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -160,6 +160,13 @@ + token, sql.Token(T.Whitespace, ' ')) + position = 0 + else: ++ # ensure whitespace ++ for token in tlist: ++ _, next_ws = tlist.token_next( ++ tlist.token_index(token), skip_ws=False) ++ if token.value == ',' and not next_ws.is_whitespace: ++ tlist.insert_after( ++ token, sql.Token(T.Whitespace, ' ')) + + end_at = self.offset + sum(len(i.value) + 1 for i in identifiers) + adjusted_offset = 0 +@@ -181,6 +188,7 @@ + tlist.insert_before(token, self.nl(offset=adjust)) + position = 0 + self._process_default(tlist) ++ + def _process_case(self, tlist): + iterable = iter(tlist.get_cases()) + cond, _ = next(iterable) +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d6e796d20dcfb6145ef5076db455ed9c04ca0fda --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:de5c60533450591e3a1260617fcbcccf29df83f86dcec48ada11ed8f6db242cb" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..72ecc8abd5f83ccd4b2d3e92e722b433b79ca965 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions" + ], + "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_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_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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index ba790dd910da895618dba78bf212f68d5e16451d..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -65,14 +65,14 @@ + self._process_default(tlist) + + def _process_case(self, tlist): +- cases.append((None, [end_token])) + offset_ = len('case ') + len('when ') ++ cases = tlist.get_cases(skip_ws=True) + # align the end as well + end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1] ++ cases.append((None, [end_token])) + + condition_width = [len(' '.join(map(str, cond))) if cond else 0 + for cond, _ in cases] +- cases = tlist.get_cases(skip_ws=True) + max_cond_width = max(condition_width) + + for i, (cond, value) in enumerate(cases): +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__cwv6tm4l/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..c8ff82767482acdaa7b95760fc478c3e84325827 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "24bdd27de028959184206f5b445ba00facf5b23fe29cdbd4b718e3648ff1cacb", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "6c79609d03033da510e10f55c9be7a240b4bfecaa239b8a4f35bad78d8ce2da3", + "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": true, + "partial_repair_sha256": "45a55fceed8188ceee8199be318ae5fbdd282af3446ff03f0da3be986382f65c", + "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": "5bf49f57f5e5581aff2031e3dabd158a433af9e1", + "source_completion_sha256": "b696a26fbde4b3424679e0e5382a3176f19b0ee740b4e85f43587122777bb66a", + "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_module__g5ogk1de", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "8095c3e076d740a7c6fe20ff7810b1f2a3547161f098b7f6754f5adabb5bd345", + "is_fork": true, + "learner_path": "tasks/995b0c7d19e46b9c30d96e3a/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/5bf49f57f5e5581aff2031e3dabd158a433af9e1/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": "3806b0888e73b9d2f4c4ec7d8e2f38600af5eb4a1b1009b901b48afe4ca783cf", + "provenance_path": "tasks/995b0c7d19e46b9c30d96e3a/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "5bf49f57f5e5581aff2031e3dabd158a433af9e1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f7bb058cb7b1314ae4b6064cfef14b7cbec5d957", + "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_module__g5ogk1de", + "task_sha256": "e15a180f82b3b257f6ef85fc37ccc7bf2d1361c99eb5e89b563be58178292b0e", + "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_module__g5ogk1de", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..440642130e54d552af207987f2a387c891126368 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/instruction.md @@ -0,0 +1,33 @@ +SQL formatting breaks for CASE statements and identifier lists + +Description + +I've noticed that the SQL formatting functionality is broken for CASE statements and identifier lists with wrap_after option. When trying to format SQL queries with CASE statements, the output is incorrectly indented and aligned. + +For example, when formatting a query like: + +```sql +SELECT +CASE WHEN x = 1 THEN 'one' + WHEN x = 2 THEN 'two' + ELSE 'other' +END as result +FROM table +``` + +The formatting is completely messed up, with incorrect spacing and alignment of the WHEN clauses. + +Similarly, when using the wrap_after option with identifier lists, the wrapping behavior is incorrect. For instance, when formatting a query with a long list of columns: + +```sql +SELECT col1, col2, col3, col4, col5, col6, col7, col8, col9, col10 +FROM table +``` + +With wrap_after set, the columns aren't properly wrapped to new lines as expected. + +I believe this issue was introduced in a recent change to the aligned_indent.py and reindent.py files. The formatting worked correctly in previous versions. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..7192c34dfda52255f60a87f1f364d7bfa6d789e0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/metadata.json @@ -0,0 +1,534 @@ +{ + "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::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions" + ], + "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_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_comment_first", + "tests/test_format.py::TestFormatReindent::test_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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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": "f7bb058cb7b1314ae4b6064cfef14b7cbec5d957", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "5bf49f57f5e5581aff2031e3dabd158a433af9e1" + }, + "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/aligned_indent.py", + "sqlparse/filters/reindent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 913809, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de", + "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_module__g5ogk1de", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "8095c3e076d740a7c6fe20ff7810b1f2a3547161f098b7f6754f5adabb5bd345", + "is_fork": true, + "learner_path": "tasks/995b0c7d19e46b9c30d96e3a/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/5bf49f57f5e5581aff2031e3dabd158a433af9e1/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": "3806b0888e73b9d2f4c4ec7d8e2f38600af5eb4a1b1009b901b48afe4ca783cf", + "provenance_path": "tasks/995b0c7d19e46b9c30d96e3a/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "5bf49f57f5e5581aff2031e3dabd158a433af9e1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f7bb058cb7b1314ae4b6064cfef14b7cbec5d957", + "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_module__g5ogk1de", + "task_sha256": "e15a180f82b3b257f6ef85fc37ccc7bf2d1361c99eb5e89b563be58178292b0e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..2e57bb580c5ae204ce704cf63089f6c3e92dd25e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "24bdd27de028959184206f5b445ba00facf5b23fe29cdbd4b718e3648ff1cacb", + "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/5bf49f57f5e5581aff2031e3dabd158a433af9e1/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "b696a26fbde4b3424679e0e5382a3176f19b0ee740b4e85f43587122777bb66a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "890afbd9e6575c3cfc24805a1d6cadb91bce544be223fe43de7afc5c7a149bdd", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "8095c3e076d740a7c6fe20ff7810b1f2a3547161f098b7f6754f5adabb5bd345", + "is_fork": true, + "learner_path": "tasks/995b0c7d19e46b9c30d96e3a/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/5bf49f57f5e5581aff2031e3dabd158a433af9e1/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": "3806b0888e73b9d2f4c4ec7d8e2f38600af5eb4a1b1009b901b48afe4ca783cf", + "provenance_path": "tasks/995b0c7d19e46b9c30d96e3a/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "5bf49f57f5e5581aff2031e3dabd158a433af9e1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f7bb058cb7b1314ae4b6064cfef14b7cbec5d957", + "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_module__g5ogk1de", + "task_sha256": "e15a180f82b3b257f6ef85fc37ccc7bf2d1361c99eb5e89b563be58178292b0e", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..87667e4df0560d93fe72987284cbec4c0b7534ec --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/provided-gold.diff @@ -0,0 +1,69 @@ +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index b69e8c053fce57c07137821f66c1159a07370557..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -65,26 +65,26 @@ + self._process_default(tlist) + + def _process_case(self, tlist): +- offset_ = len('case') + len('when') # Removed spaces in length calculations +- cases = tlist.get_cases(skip_ws=False) # Changed skip_ws=True to skip_ws=False ++ offset_ = len('case ') + len('when ') ++ cases = tlist.get_cases(skip_ws=True) + # align the end as well +- end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[0] # Altered index from 1 to 0 ++ end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1] + cases.append((None, [end_token])) + +- condition_width = [len(' '.join(map(str, cond))) + 1 if cond else 0 # Added +1 to the length calculation ++ condition_width = [len(' '.join(map(str, cond))) if cond else 0 + for cond, _ in cases] +- max_cond_width = min(condition_width) # Changed max to min in the width determination ++ max_cond_width = max(condition_width) + + for i, (cond, value) in enumerate(cases): + # cond is None when 'else or end' +- stmt = value[0] if cond else cond[0] # Swapped cond and value ordering ++ stmt = cond[0] if cond else value[0] + +- if i < 1: # Changed condition from i > 0 to i < 1 ++ if i > 0: + tlist.insert_before(stmt, self.nl(offset_ - len(str(stmt)))) + if cond: + ws = sql.Token(T.Whitespace, self.char * ( +- max_cond_width + condition_width[i])) # Changed subtraction to addition +- tlist.insert_before(cond[-1], ws) # Changed method from insert_after to insert_before ++ max_cond_width - condition_width[i])) ++ tlist.insert_after(cond[-1], ws) + + def _next_token(self, tlist, idx=-1): + split_words = T.Keyword, self.split_words, True +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index ef3c6fa2791566e9d686d550a905b2cf78a90177..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -140,7 +140,7 @@ + position = 0 + for token in identifiers: + # Add 1 for the "," separator +- position += len(token.value) + 0 ++ position += len(token.value) + 1 + if position > (self.wrap_after - self.offset): + adjust = 0 + if self.comma_first: +@@ -181,13 +181,14 @@ + position = 0 + for token in identifiers: + # Add 1 for the "," separator +- position += len(token.value) + 2 ++ position += len(token.value) + 1 + if (self.wrap_after > 0 + and position > (self.wrap_after - self.offset)): + adjust = 0 + tlist.insert_before(token, self.nl(offset=adjust)) + position = 0 + self._process_default(tlist) ++ + def _process_case(self, tlist): + iterable = iter(tlist.get_cases()) + cond, _ = next(iterable) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a8d7967435ff733e9244067f9f468be783f0bc33 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/solution/solve.sh @@ -0,0 +1,75 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index b69e8c053fce57c07137821f66c1159a07370557..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -65,26 +65,26 @@ + self._process_default(tlist) + + def _process_case(self, tlist): +- offset_ = len('case') + len('when') # Removed spaces in length calculations +- cases = tlist.get_cases(skip_ws=False) # Changed skip_ws=True to skip_ws=False ++ offset_ = len('case ') + len('when ') ++ cases = tlist.get_cases(skip_ws=True) + # align the end as well +- end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[0] # Altered index from 1 to 0 ++ end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1] + cases.append((None, [end_token])) + +- condition_width = [len(' '.join(map(str, cond))) + 1 if cond else 0 # Added +1 to the length calculation ++ condition_width = [len(' '.join(map(str, cond))) if cond else 0 + for cond, _ in cases] +- max_cond_width = min(condition_width) # Changed max to min in the width determination ++ max_cond_width = max(condition_width) + + for i, (cond, value) in enumerate(cases): + # cond is None when 'else or end' +- stmt = value[0] if cond else cond[0] # Swapped cond and value ordering ++ stmt = cond[0] if cond else value[0] + +- if i < 1: # Changed condition from i > 0 to i < 1 ++ if i > 0: + tlist.insert_before(stmt, self.nl(offset_ - len(str(stmt)))) + if cond: + ws = sql.Token(T.Whitespace, self.char * ( +- max_cond_width + condition_width[i])) # Changed subtraction to addition +- tlist.insert_before(cond[-1], ws) # Changed method from insert_after to insert_before ++ max_cond_width - condition_width[i])) ++ tlist.insert_after(cond[-1], ws) + + def _next_token(self, tlist, idx=-1): + split_words = T.Keyword, self.split_words, True +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index ef3c6fa2791566e9d686d550a905b2cf78a90177..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -140,7 +140,7 @@ + position = 0 + for token in identifiers: + # Add 1 for the "," separator +- position += len(token.value) + 0 ++ position += len(token.value) + 1 + if position > (self.wrap_after - self.offset): + adjust = 0 + if self.comma_first: +@@ -181,13 +181,14 @@ + position = 0 + for token in identifiers: + # Add 1 for the "," separator +- position += len(token.value) + 2 ++ position += len(token.value) + 1 + if (self.wrap_after > 0 + and position > (self.wrap_after - self.offset)): + adjust = 0 + tlist.insert_before(token, self.nl(offset=adjust)) + position = 0 + self._process_default(tlist) ++ + def _process_case(self, tlist): + iterable = iter(tlist.get_cases()) + cond, _ = next(iterable) +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d17065dbf4be3e226369be4b8907453beec9af16 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:8ee6b1754fc8aa97c50f981271d7386acb408fb69b054a48324cf868b5162f01" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..38089723027de462a70b64a4a1367fb3cf5bf3cc --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_wrap_after", + "tests/test_format.py::TestFormatReindent::test_long_identifier_list_with_functions" + ], + "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_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_comment_first", + "tests/test_format.py::TestFormatReindent::test_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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index b69e8c053fce57c07137821f66c1159a07370557..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -65,26 +65,26 @@ + self._process_default(tlist) + + def _process_case(self, tlist): +- offset_ = len('case') + len('when') # Removed spaces in length calculations +- cases = tlist.get_cases(skip_ws=False) # Changed skip_ws=True to skip_ws=False ++ offset_ = len('case ') + len('when ') ++ cases = tlist.get_cases(skip_ws=True) + # align the end as well +- end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[0] # Altered index from 1 to 0 ++ end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1] + cases.append((None, [end_token])) + +- condition_width = [len(' '.join(map(str, cond))) + 1 if cond else 0 # Added +1 to the length calculation ++ condition_width = [len(' '.join(map(str, cond))) if cond else 0 + for cond, _ in cases] +- max_cond_width = min(condition_width) # Changed max to min in the width determination ++ max_cond_width = max(condition_width) + + for i, (cond, value) in enumerate(cases): + # cond is None when 'else or end' +- stmt = value[0] if cond else cond[0] # Swapped cond and value ordering ++ stmt = cond[0] if cond else value[0] + +- if i < 1: # Changed condition from i > 0 to i < 1 ++ if i > 0: + tlist.insert_before(stmt, self.nl(offset_ - len(str(stmt)))) + if cond: + ws = sql.Token(T.Whitespace, self.char * ( +- max_cond_width + condition_width[i])) # Changed subtraction to addition +- tlist.insert_before(cond[-1], ws) # Changed method from insert_after to insert_before ++ max_cond_width - condition_width[i])) ++ tlist.insert_after(cond[-1], ws) + + def _next_token(self, tlist, idx=-1): + split_words = T.Keyword, self.split_words, True +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__g5ogk1de/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..9027d4d08b65bee5e8a84feeeaf86b7b6601b24c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "6dda48d5ee1cd5e0e2d705e6388eeadd65f5e2c8b974f79567bfd91fba4cbdff", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "4c2457800e6e0891ec97d23b83d95ce1ef3962fb0cceba516c20df69499c9e22", + "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": true, + "partial_repair_sha256": "d1ff641eb3c5cfc6d2d4f2c305593b0c20ca578f8ca65d88dfac5c9402d36066", + "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": "e8e2385ca55a19d66057eee8b4e7ad46ad4a63fd", + "source_completion_sha256": "c9e310ff1f59609945c867ea40c8cf8a949b0f38625656c7fa7e2cae0372bbee", + "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_module__hjydtpc9", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "1fd15349e028d9412c4e18ae506d94049fb970d282cb18848b5341369b9d8aa4", + "is_fork": true, + "learner_path": "tasks/127d01f762436a115e87e80d/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/e8e2385ca55a19d66057eee8b4e7ad46ad4a63fd/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": "04d9b051925236782ee35233fbc723ca7990afc1779db50b754fcb56f101803b", + "provenance_path": "tasks/127d01f762436a115e87e80d/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e8e2385ca55a19d66057eee8b4e7ad46ad4a63fd", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "11e0744d64fcb333e68aa36fc17cf3e77ff9a8af", + "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_module__hjydtpc9", + "task_sha256": "56d15e71d98ef52b36ba77baa2bd01d01fb115d981b6b6f373818f455b8625cb", + "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_module__hjydtpc9", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fbc084a0e457d2897b07e0006df00c329b5f75c0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/instruction.md @@ -0,0 +1,68 @@ +# SQL formatting issues with aligned indentation and multiple statements + +I've found a bug in the SQL formatting functionality. When using the reindent and aligned indent features, there are several issues with the formatting output. + +## Issue 1: Incorrect indentation for subqueries + +When formatting SQL with subqueries, the indentation is incorrect. For example: + +```python +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 +""" +``` + +The formatted output is incorrect and adds a "FROM" token where it shouldn't be. + +## Issue 2: Multiple statements not properly separated + +When formatting multiple SQL statements, they are not properly separated with newlines: + +```python +sql = 'select foo; select bar' +``` + +The formatted output doesn't include the expected newlines between statements. + +## Reproduction + +Here's a simple script to reproduce the issue: + +```python +import sqlparse + +# Test subquery formatting +sql1 = """ +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 +""" +print(sqlparse.format(sql1, reindent=True, indent_width=2, keyword_case='upper')) + +# Test multiple statements +sql2 = 'select foo; select bar' +print(sqlparse.format(sql2, reindent=True)) +``` + +Expected output for the first example should have proper indentation for the subquery without adding unexpected tokens. + +Expected output for the second example should be: +``` +select foo; + +select bar +``` + +But the actual output doesn't include the proper spacing between statements. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..59eb786a35a10587e9de3151d30b2eb7fa4a1a82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/metadata.json @@ -0,0 +1,534 @@ +{ + "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::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "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::TestFormatReindent::test_stmts" + ], + "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_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "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_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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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": "11e0744d64fcb333e68aa36fc17cf3e77ff9a8af", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "e8e2385ca55a19d66057eee8b4e7ad46ad4a63fd" + }, + "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/aligned_indent.py", + "sqlparse/filters/reindent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 912789, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9", + "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_module__hjydtpc9", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "1fd15349e028d9412c4e18ae506d94049fb970d282cb18848b5341369b9d8aa4", + "is_fork": true, + "learner_path": "tasks/127d01f762436a115e87e80d/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/e8e2385ca55a19d66057eee8b4e7ad46ad4a63fd/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": "04d9b051925236782ee35233fbc723ca7990afc1779db50b754fcb56f101803b", + "provenance_path": "tasks/127d01f762436a115e87e80d/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e8e2385ca55a19d66057eee8b4e7ad46ad4a63fd", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "11e0744d64fcb333e68aa36fc17cf3e77ff9a8af", + "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_module__hjydtpc9", + "task_sha256": "56d15e71d98ef52b36ba77baa2bd01d01fb115d981b6b6f373818f455b8625cb", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..a465237476dba033413d2c2ad9434c25a00ed9ed --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "6dda48d5ee1cd5e0e2d705e6388eeadd65f5e2c8b974f79567bfd91fba4cbdff", + "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/e8e2385ca55a19d66057eee8b4e7ad46ad4a63fd/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "c9e310ff1f59609945c867ea40c8cf8a949b0f38625656c7fa7e2cae0372bbee", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "4fbab2caaf13dae87536a50885d885ef80760b892e998add838e15914312f783", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "1fd15349e028d9412c4e18ae506d94049fb970d282cb18848b5341369b9d8aa4", + "is_fork": true, + "learner_path": "tasks/127d01f762436a115e87e80d/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/e8e2385ca55a19d66057eee8b4e7ad46ad4a63fd/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": "04d9b051925236782ee35233fbc723ca7990afc1779db50b754fcb56f101803b", + "provenance_path": "tasks/127d01f762436a115e87e80d/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e8e2385ca55a19d66057eee8b4e7ad46ad4a63fd", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "11e0744d64fcb333e68aa36fc17cf3e77ff9a8af", + "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_module__hjydtpc9", + "task_sha256": "56d15e71d98ef52b36ba77baa2bd01d01fb115d981b6b6f373818f455b8625cb", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..ce6c9282eead1ff021f4de0c3e49baf13bdd2b7b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/provided-gold.diff @@ -0,0 +1,44 @@ +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index e356fad931e30c29954740e14910beeb59b9362d..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -46,13 +46,16 @@ + self._process(sql.TokenList(tlist.tokens)) + + def _process_parenthesis(self, tlist): ++ # if this isn't a subquery, don't re-indent + _, token = tlist.token_next_by(m=(T.DML, 'SELECT')) +- if token is None: # Alter logic to trigger on the absence of 'SELECT' ++ if token is not None: + with indent(self): + tlist.insert_after(tlist[0], self.nl('SELECT')) ++ # process the inside of the parenthesis + self._process_default(tlist) + +- tlist.insert_before(tlist[-1], self.nl('FROM')) # Change inserted token from an empty new line to 'FROM' ++ # de-indent last parenthesis ++ tlist.insert_before(tlist[-1], self.nl()) + + def _process_identifierlist(self, tlist): + # columns being selected +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 7568cb65a42b9b634c362ec454ac7c2453645784..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -236,8 +236,12 @@ + self._process(sgroup) + + def process(self, stmt): +- """Process a statement by adding whitespaces where needed.""" + self._curr_stmt = stmt ++ self._process(stmt) ++ ++ if self._last_stmt is not None: ++ nl = '\n' if str(self._last_stmt).endswith('\n') else '\n\n' ++ stmt.tokens.insert(0, sql.Token(T.Whitespace, nl)) ++ + self._last_stmt = stmt +- self._process(stmt) +- return stmt +\ No newline at end of file ++ return stmt diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e4bba05bf32788e349b7a77714994d127646784b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/solution/solve.sh @@ -0,0 +1,50 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index e356fad931e30c29954740e14910beeb59b9362d..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -46,13 +46,16 @@ + self._process(sql.TokenList(tlist.tokens)) + + def _process_parenthesis(self, tlist): ++ # if this isn't a subquery, don't re-indent + _, token = tlist.token_next_by(m=(T.DML, 'SELECT')) +- if token is None: # Alter logic to trigger on the absence of 'SELECT' ++ if token is not None: + with indent(self): + tlist.insert_after(tlist[0], self.nl('SELECT')) ++ # process the inside of the parenthesis + self._process_default(tlist) + +- tlist.insert_before(tlist[-1], self.nl('FROM')) # Change inserted token from an empty new line to 'FROM' ++ # de-indent last parenthesis ++ tlist.insert_before(tlist[-1], self.nl()) + + def _process_identifierlist(self, tlist): + # columns being selected +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 7568cb65a42b9b634c362ec454ac7c2453645784..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -236,8 +236,12 @@ + self._process(sgroup) + + def process(self, stmt): +- """Process a statement by adding whitespaces where needed.""" + self._curr_stmt = stmt ++ self._process(stmt) ++ ++ if self._last_stmt is not None: ++ nl = '\n' if str(self._last_stmt).endswith('\n') else '\n\n' ++ stmt.tokens.insert(0, sql.Token(T.Whitespace, nl)) ++ + self._last_stmt = stmt +- self._process(stmt) +- return stmt +\ No newline at end of file ++ return stmt +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bff14fad2bb24f9bbbc62526e37b841f9175d427 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:068baeb0d057f53bb5c6f7e7004c719425a81f8a9c0742124b8343a41a3dd038" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..64e02aac3802fcec7833159a4b70ea413decf693 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "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::TestFormatReindent::test_stmts" + ], + "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_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "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_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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index e356fad931e30c29954740e14910beeb59b9362d..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -46,13 +46,16 @@ + self._process(sql.TokenList(tlist.tokens)) + + def _process_parenthesis(self, tlist): ++ # if this isn't a subquery, don't re-indent + _, token = tlist.token_next_by(m=(T.DML, 'SELECT')) +- if token is None: # Alter logic to trigger on the absence of 'SELECT' ++ if token is not None: + with indent(self): + tlist.insert_after(tlist[0], self.nl('SELECT')) ++ # process the inside of the parenthesis + self._process_default(tlist) + +- tlist.insert_before(tlist[-1], self.nl('FROM')) # Change inserted token from an empty new line to 'FROM' ++ # de-indent last parenthesis ++ tlist.insert_before(tlist[-1], self.nl()) + + def _process_identifierlist(self, tlist): + # columns being selected +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__hjydtpc9/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..5704b01f6f4d10611388c27c0c6b8eca88c4fcfc --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "d77becf73933fbd55db9ad56d9d0f205c8ef123be601793787c87881db7e97a5", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "015c16e473bbabeb41ffcb63fd47d5eb10436d81c5457bae4f27f31eaa7588c4", + "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": true, + "partial_repair_sha256": "9c7077ac5dba2c7a789f2bd86f2e865172b6276efe32c5a842ce80e1d871b4e5", + "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": "387ddc376ff44f20a6c1ac258c8be68467f3a53a", + "source_completion_sha256": "a3f7de49b93e3acaede750f7a62bc0cd7b5eede2dde5d3281c78ea5df5fce3c0", + "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_module__j2zty160", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f53c7f9e35fe089be75a4a799bd7dab2c8b063ad77ffd64bac88b99323268190", + "is_fork": true, + "learner_path": "tasks/d4e7f44cf74f5e3020e72834/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/387ddc376ff44f20a6c1ac258c8be68467f3a53a/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": "fa4743d0ec7ab1241c3a57b0d751400e57f607a9d42042708c877860f006da2f", + "provenance_path": "tasks/d4e7f44cf74f5e3020e72834/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "387ddc376ff44f20a6c1ac258c8be68467f3a53a", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "4b33b639c7f766632d5cc303af16b83a57e3ce7a", + "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_module__j2zty160", + "task_sha256": "6062c67b0b3c0b70afc7a8dd426c9723e1a8513d332b92918928425ac6492d95", + "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_module__j2zty160", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dcbb7952fbe890571ed47299a73310748a97225c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/instruction.md @@ -0,0 +1,76 @@ +# SQL formatting broken with recent changes to indentation + +## Bug report + +**Bug summary** +After recent changes to the indentation code, SQL formatting is completely broken. The indentation is incorrect and newlines are not being inserted properly. + +**Code for reproduction** + +```python +import sqlparse + +# Example 1: Simple SELECT with WHERE +sql = "select * from foo where bar = 1 and baz = 2 or bzz = 3;" +print(sqlparse.format(sql, reindent=True)) + +# Example 2: ORDER BY clause +sql = "select * from foo order by c1 desc, c2, c3;" +print(sqlparse.format(sql, reindent=True)) + +# Example 3: GROUP BY clause +sql = "SELECT a, b FROM table GROUP BY a, b;" +print(sqlparse.format(sql, reindent=True)) + +# Example 4: Unicode characters +digest = 'é½å¤©å¤§å£.ãã©ãã«ãªé¨².ìë¡í´ìš"' +sql = "select * from foo where bar = '{}'".format(digest) +print(sqlparse.format(sql, reindent=True)) +``` + +**Actual outcome** + +The formatted SQL has incorrect indentation. For example, the WHERE clause conditions are not properly indented, and newlines are inserted incorrectly. The GROUP BY and ORDER BY clauses are not properly aligned. + +For the first example, the output looks something like: +``` +select * +from foo +where bar = 1 +and baz = 2 +or bzz = 3; +``` + +When it should have proper indentation for the AND/OR conditions. + +**Expected outcome** + +The SQL should be properly formatted with correct indentation, like: + +``` +select * +from foo +where bar = 1 + and baz = 2 + or bzz = 3; +``` + +And for ORDER BY: +``` +select * +from foo +order by c1 desc, + c2, + c3; +``` + +The GROUP BY clauses should also be properly aligned, and special handling for "GROUP BY" and "ORDER BY" should work correctly. + +**Environment** +- Operating system: Linux +- Python version: 3.10 +- sqlparse version: latest from main branch + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..05e654145bda3b46d6a0ade4ff42745eebebbb11 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/metadata.json @@ -0,0 +1,534 @@ +{ + "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::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue562_tzcasts" + ], + "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_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::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "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_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": "4b33b639c7f766632d5cc303af16b83a57e3ce7a", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "387ddc376ff44f20a6c1ac258c8be68467f3a53a" + }, + "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_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", + "tests/test_regressions.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/aligned_indent.py", + "sqlparse/filters/reindent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 897999, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_module__j2zty160", + "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_module__j2zty160", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f53c7f9e35fe089be75a4a799bd7dab2c8b063ad77ffd64bac88b99323268190", + "is_fork": true, + "learner_path": "tasks/d4e7f44cf74f5e3020e72834/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/387ddc376ff44f20a6c1ac258c8be68467f3a53a/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": "fa4743d0ec7ab1241c3a57b0d751400e57f607a9d42042708c877860f006da2f", + "provenance_path": "tasks/d4e7f44cf74f5e3020e72834/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "387ddc376ff44f20a6c1ac258c8be68467f3a53a", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "4b33b639c7f766632d5cc303af16b83a57e3ce7a", + "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_module__j2zty160", + "task_sha256": "6062c67b0b3c0b70afc7a8dd426c9723e1a8513d332b92918928425ac6492d95", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..318e9d588883bbbb90d347709a7bb1ca73156a46 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "d77becf73933fbd55db9ad56d9d0f205c8ef123be601793787c87881db7e97a5", + "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/387ddc376ff44f20a6c1ac258c8be68467f3a53a/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "a3f7de49b93e3acaede750f7a62bc0cd7b5eede2dde5d3281c78ea5df5fce3c0", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "78bfac48d274033ca74b033b31e574524a4a13d9c407142e34cf69364b320bb0", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_module__j2zty160", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f53c7f9e35fe089be75a4a799bd7dab2c8b063ad77ffd64bac88b99323268190", + "is_fork": true, + "learner_path": "tasks/d4e7f44cf74f5e3020e72834/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/387ddc376ff44f20a6c1ac258c8be68467f3a53a/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": "fa4743d0ec7ab1241c3a57b0d751400e57f607a9d42042708c877860f006da2f", + "provenance_path": "tasks/d4e7f44cf74f5e3020e72834/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "387ddc376ff44f20a6c1ac258c8be68467f3a53a", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "4b33b639c7f766632d5cc303af16b83a57e3ce7a", + "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_module__j2zty160", + "task_sha256": "6062c67b0b3c0b70afc7a8dd426c9723e1a8513d332b92918928425ac6492d95", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..aea86581e6e56c99d0702935bbacf47ac0d9c794 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/provided-gold.diff @@ -0,0 +1,44 @@ +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index 8eef9e4ad728e93207f6dcd9fae67696332d9e2a..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -113,15 +113,18 @@ + tidx, token = self._next_token(tlist, tidx) + + def _process_default(self, tlist): +- """Process tokens that don't have a specific processing method.""" +- # Split the token list on keywords + self._split_kwds(tlist) +- +- # Process each token in the list +- for token in tlist.tokens: +- # If the token is itself a token list, process it recursively +- if isinstance(token, sql.TokenList): +- self._process(token) ++ # process any sub-sub statements ++ for sgroup in tlist.get_sublists(): ++ idx = tlist.token_index(sgroup) ++ pidx, prev_ = tlist.token_prev(idx) ++ # HACK: make "group/order by" work. Longer than max_len. ++ offset_ = 3 if ( ++ prev_ and prev_.match(T.Keyword, self.by_words, regex=True) ++ ) else 0 ++ with offset(self, offset_): ++ self._process(sgroup) ++ + def _process(self, tlist): + func_name = '_process_{cls}'.format(cls=type(tlist).__name__) + func = getattr(self, func_name.lower(), self._process_default) +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index d7e8ea03856299015e111f9c5c1e9113845ad825..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -49,7 +49,7 @@ + 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', diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..52a617fa3abd2405d3fd99b16d90ea9aaae91be2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/solution/solve.sh @@ -0,0 +1,50 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index 8eef9e4ad728e93207f6dcd9fae67696332d9e2a..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -113,15 +113,18 @@ + tidx, token = self._next_token(tlist, tidx) + + def _process_default(self, tlist): +- """Process tokens that don't have a specific processing method.""" +- # Split the token list on keywords + self._split_kwds(tlist) +- +- # Process each token in the list +- for token in tlist.tokens: +- # If the token is itself a token list, process it recursively +- if isinstance(token, sql.TokenList): +- self._process(token) ++ # process any sub-sub statements ++ for sgroup in tlist.get_sublists(): ++ idx = tlist.token_index(sgroup) ++ pidx, prev_ = tlist.token_prev(idx) ++ # HACK: make "group/order by" work. Longer than max_len. ++ offset_ = 3 if ( ++ prev_ and prev_.match(T.Keyword, self.by_words, regex=True) ++ ) else 0 ++ with offset(self, offset_): ++ self._process(sgroup) ++ + def _process(self, tlist): + func_name = '_process_{cls}'.format(cls=type(tlist).__name__) + func = getattr(self, func_name.lower(), self._process_default) +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index d7e8ea03856299015e111f9c5c1e9113845ad825..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -49,7 +49,7 @@ + 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_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..30d57dc11ce0ddd40ee3b41a3bec46ef98cf9f9f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:3ef9623984a18c5d5e37dc23177040c395f251ebde3329518854eac29a4edd8a" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..fa64874e7486d030cfa7254c9f9a6f89c4fed952 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue562_tzcasts" + ], + "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_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::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index 8eef9e4ad728e93207f6dcd9fae67696332d9e2a..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -113,15 +113,18 @@ + tidx, token = self._next_token(tlist, tidx) + + def _process_default(self, tlist): +- """Process tokens that don't have a specific processing method.""" +- # Split the token list on keywords + self._split_kwds(tlist) +- +- # Process each token in the list +- for token in tlist.tokens: +- # If the token is itself a token list, process it recursively +- if isinstance(token, sql.TokenList): +- self._process(token) ++ # process any sub-sub statements ++ for sgroup in tlist.get_sublists(): ++ idx = tlist.token_index(sgroup) ++ pidx, prev_ = tlist.token_prev(idx) ++ # HACK: make "group/order by" work. Longer than max_len. ++ offset_ = 3 if ( ++ prev_ and prev_.match(T.Keyword, self.by_words, regex=True) ++ ) else 0 ++ with offset(self, offset_): ++ self._process(sgroup) ++ + def _process(self, tlist): + func_name = '_process_{cls}'.format(cls=type(tlist).__name__) + func = getattr(self, func_name.lower(), self._process_default) +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__j2zty160/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..bccddcc28c04270521faa5b5fe169618d77702fe --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "61da82e4ea67a1ff295a05f6e497b77450446005b5a383af2520a1d0f01a54d0", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "c3bd46a6f4b0a8e85d366ab060dd21c2e8ea166a8a7dc0dbc606b1b92da36939", + "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": true, + "partial_repair_sha256": "df502fdec1eaf78687b3d8bab98a75282091e1884c1c700bcbf1f2cc6189b403", + "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": "df9fc309d88e169c41ec1bdedbb0fc088a96e272", + "source_completion_sha256": "589d25d841dfa8234b436c01f27efea13f4761b970d85b3d99c02f2e78779bf3", + "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_module__jp1804gl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "d8b6b2e3bcde0fbc0a2d71911fbe55e9f50908e9a2a3bcf1a147c56e14c6a9ba", + "is_fork": true, + "learner_path": "tasks/7dd1c02c4066e7a46a13e274/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/df9fc309d88e169c41ec1bdedbb0fc088a96e272/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": "8cbd6ee48ab1a160a2ce294a494f96cf13b66175bcf79fac919804fdfe21162a", + "provenance_path": "tasks/7dd1c02c4066e7a46a13e274/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "df9fc309d88e169c41ec1bdedbb0fc088a96e272", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "3f4d9a22feaf4f0f47f66c6fdfb27d4f1560f867", + "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_module__jp1804gl", + "task_sha256": "f15c79e334db4b7759ca450ad6f9e40aebe8d39f7bb3f123d207c50b4bf16d6d", + "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_module__jp1804gl", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..90284f01020d5f6a339986c2020ab9320ce4f6ab --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/instruction.md @@ -0,0 +1,56 @@ +# SQL formatting breaks with changes to parenthesis processing and reindent filter + +## Description + +I've discovered an issue with SQL formatting when using the reindent and aligned indent filters. After recent changes, SQL statements with parentheses are not being formatted correctly, and in some cases, the formatter is throwing AttributeError exceptions. + +## Steps to reproduce + +Here's a simple example that demonstrates the issue: + +```python +import sqlparse + +# This should format correctly but now fails +sql = 'select count(*) from (select * from foo);' +formatted = sqlparse.format(sql, reindent=True) +print(formatted) +``` + +When running this code, instead of properly formatting the SQL with nested parentheses, it throws an AttributeError: 'NoneType' object has no attribute 'tokens'. + +## More examples of broken formatting + +The issue affects various SQL constructs: + +1. Window functions: +```python +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''' +formatted = sqlparse.format(sql, reindent=True) +# Formatting is incorrect +``` + +2. Time zone casts: +```python +sql = "SELECT f(HOUR from bar AT TIME ZONE 'UTC') from foo" +formatted = sqlparse.format(sql, reindent=True) +# Should format properly but fails +``` + +3. Keyword functions: +```python +sql = 'select max(a) b, foo, bar' +formatted = sqlparse.format(sql, reindent=True) +# Doesn't format as expected +``` + +The issue seems to be related to changes in how parentheses are processed in the AlignedIndentFilter and the order of operations in the ReindentFilter. The problem occurs when trying to format SQL statements with nested structures or when certain SQL constructs are used with parentheses. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..eda6ef807a09e093c63cc840e6f0597d762bc5b3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/metadata.json @@ -0,0 +1,534 @@ +{ + "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_cli.py::test_valid_args", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "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::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue562_tzcasts" + ], + "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_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_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "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_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_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_except_formatting", + "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_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_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": "3f4d9a22feaf4f0f47f66c6fdfb27d4f1560f867", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "df9fc309d88e169c41ec1bdedbb0fc088a96e272" + }, + "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_grouping.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_parse.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_cli.py", + "tests/test_format.py", + "tests/test_regressions.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/aligned_indent.py", + "sqlparse/filters/reindent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 895828, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl", + "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_module__jp1804gl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "d8b6b2e3bcde0fbc0a2d71911fbe55e9f50908e9a2a3bcf1a147c56e14c6a9ba", + "is_fork": true, + "learner_path": "tasks/7dd1c02c4066e7a46a13e274/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/df9fc309d88e169c41ec1bdedbb0fc088a96e272/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": "8cbd6ee48ab1a160a2ce294a494f96cf13b66175bcf79fac919804fdfe21162a", + "provenance_path": "tasks/7dd1c02c4066e7a46a13e274/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "df9fc309d88e169c41ec1bdedbb0fc088a96e272", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "3f4d9a22feaf4f0f47f66c6fdfb27d4f1560f867", + "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_module__jp1804gl", + "task_sha256": "f15c79e334db4b7759ca450ad6f9e40aebe8d39f7bb3f123d207c50b4bf16d6d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..bbbb8dc699747dbbfbad89ca3c66dad5c77c2c51 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "61da82e4ea67a1ff295a05f6e497b77450446005b5a383af2520a1d0f01a54d0", + "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/df9fc309d88e169c41ec1bdedbb0fc088a96e272/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "589d25d841dfa8234b436c01f27efea13f4761b970d85b3d99c02f2e78779bf3", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "487a1b0b4bff574993066d8e65682e554e17ac245e7548a3d7c6cd19e204911f", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "d8b6b2e3bcde0fbc0a2d71911fbe55e9f50908e9a2a3bcf1a147c56e14c6a9ba", + "is_fork": true, + "learner_path": "tasks/7dd1c02c4066e7a46a13e274/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/df9fc309d88e169c41ec1bdedbb0fc088a96e272/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": "8cbd6ee48ab1a160a2ce294a494f96cf13b66175bcf79fac919804fdfe21162a", + "provenance_path": "tasks/7dd1c02c4066e7a46a13e274/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "df9fc309d88e169c41ec1bdedbb0fc088a96e272", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "3f4d9a22feaf4f0f47f66c6fdfb27d4f1560f867", + "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_module__jp1804gl", + "task_sha256": "f15c79e334db4b7759ca450ad6f9e40aebe8d39f7bb3f123d207c50b4bf16d6d", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..90fa222e4fcb683770f7cfe8a5d34d61f3ea07c3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/provided-gold.diff @@ -0,0 +1,71 @@ +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index 1c710bbd3b211882be9fec5788ddf51e26088d16..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -46,33 +46,17 @@ + self._process(sql.TokenList(tlist.tokens)) + + def _process_parenthesis(self, tlist): +- """Process the content of a parenthesis group.""" +- # Save the old indent level +- old_indent = self.indent +- +- # Increase indent level for the content inside parentheses +- self.indent += 1 +- +- # Process the content inside the parentheses +- for token in tlist.tokens: +- # Skip the opening parenthesis +- if token.is_whitespace or token.match(T.Punctuation, '('): +- continue +- +- # Stop at the closing parenthesis +- if token.match(T.Punctuation, ')'): +- break +- +- # If it's a sublist, process it +- if isinstance(token, sql.TokenList): +- self._process(token) +- # For regular tokens that follow the opening parenthesis, add a newline before them +- elif not token.is_whitespace: +- tlist.insert_before(token, self.nl()) +- break +- +- # Restore the old indent level +- self.indent = old_indent ++ # if this isn't a subquery, don't re-indent ++ _, token = tlist.token_next_by(m=(T.DML, 'SELECT')) ++ if token is not None: ++ with indent(self): ++ tlist.insert_after(tlist[0], self.nl('SELECT')) ++ # process the inside of the parenthesis ++ self._process_default(tlist) ++ ++ # de-indent last parenthesis ++ tlist.insert_before(tlist[-1], self.nl()) ++ + def _process_identifierlist(self, tlist): + # columns being selected + identifiers = list(tlist.get_identifiers()) +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 8b0a8b935068e910dda32a4f959cd66158829fa8..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -236,12 +236,12 @@ + self._process(sgroup) + + def process(self, stmt): ++ self._curr_stmt = stmt + self._process(stmt) +- return stmt +- +- self._last_stmt = stmt + + if self._last_stmt is not None: + nl = '\n' if str(self._last_stmt).endswith('\n') else '\n\n' + stmt.tokens.insert(0, sql.Token(T.Whitespace, nl)) +- self._curr_stmt = stmt +\ No newline at end of file ++ ++ self._last_stmt = stmt ++ return stmt diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ac60d5f4ca4f5e61332dd6cfd92fc86a3258b677 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/solution/solve.sh @@ -0,0 +1,77 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index 1c710bbd3b211882be9fec5788ddf51e26088d16..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -46,33 +46,17 @@ + self._process(sql.TokenList(tlist.tokens)) + + def _process_parenthesis(self, tlist): +- """Process the content of a parenthesis group.""" +- # Save the old indent level +- old_indent = self.indent +- +- # Increase indent level for the content inside parentheses +- self.indent += 1 +- +- # Process the content inside the parentheses +- for token in tlist.tokens: +- # Skip the opening parenthesis +- if token.is_whitespace or token.match(T.Punctuation, '('): +- continue +- +- # Stop at the closing parenthesis +- if token.match(T.Punctuation, ')'): +- break +- +- # If it's a sublist, process it +- if isinstance(token, sql.TokenList): +- self._process(token) +- # For regular tokens that follow the opening parenthesis, add a newline before them +- elif not token.is_whitespace: +- tlist.insert_before(token, self.nl()) +- break +- +- # Restore the old indent level +- self.indent = old_indent ++ # if this isn't a subquery, don't re-indent ++ _, token = tlist.token_next_by(m=(T.DML, 'SELECT')) ++ if token is not None: ++ with indent(self): ++ tlist.insert_after(tlist[0], self.nl('SELECT')) ++ # process the inside of the parenthesis ++ self._process_default(tlist) ++ ++ # de-indent last parenthesis ++ tlist.insert_before(tlist[-1], self.nl()) ++ + def _process_identifierlist(self, tlist): + # columns being selected + identifiers = list(tlist.get_identifiers()) +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 8b0a8b935068e910dda32a4f959cd66158829fa8..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -236,12 +236,12 @@ + self._process(sgroup) + + def process(self, stmt): ++ self._curr_stmt = stmt + self._process(stmt) +- return stmt +- +- self._last_stmt = stmt + + if self._last_stmt is not None: + nl = '\n' if str(self._last_stmt).endswith('\n') else '\n\n' + stmt.tokens.insert(0, sql.Token(T.Whitespace, nl)) +- self._curr_stmt = stmt +\ No newline at end of file ++ ++ self._last_stmt = stmt ++ return stmt +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..48928d45c5bf0f4133ccbfe8560908839470baa3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:6aaf20206ebff8d9083f4592f52f5ad1bd357e2f4f3549d9f9891bc739d80996" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..a84b308011941b988df28e2b78b3d037541b7908 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_cli.py::test_valid_args", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "tests/test_format.py::TestFormatReindentAligned::test_group_by_subquery", + "tests/test_format.py::TestFormatReindentAligned::test_window_functions", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "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::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue562_tzcasts" + ], + "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_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_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "tests/test_format.py::TestFormatReindentAligned::test_group_by", + "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_keywords", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_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_except_formatting", + "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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index 1c710bbd3b211882be9fec5788ddf51e26088d16..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -46,33 +46,17 @@ + self._process(sql.TokenList(tlist.tokens)) + + def _process_parenthesis(self, tlist): +- """Process the content of a parenthesis group.""" +- # Save the old indent level +- old_indent = self.indent +- +- # Increase indent level for the content inside parentheses +- self.indent += 1 +- +- # Process the content inside the parentheses +- for token in tlist.tokens: +- # Skip the opening parenthesis +- if token.is_whitespace or token.match(T.Punctuation, '('): +- continue +- +- # Stop at the closing parenthesis +- if token.match(T.Punctuation, ')'): +- break +- +- # If it's a sublist, process it +- if isinstance(token, sql.TokenList): +- self._process(token) +- # For regular tokens that follow the opening parenthesis, add a newline before them +- elif not token.is_whitespace: +- tlist.insert_before(token, self.nl()) +- break +- +- # Restore the old indent level +- self.indent = old_indent ++ # if this isn't a subquery, don't re-indent ++ _, token = tlist.token_next_by(m=(T.DML, 'SELECT')) ++ if token is not None: ++ with indent(self): ++ tlist.insert_after(tlist[0], self.nl('SELECT')) ++ # process the inside of the parenthesis ++ self._process_default(tlist) ++ ++ # de-indent last parenthesis ++ tlist.insert_before(tlist[-1], self.nl()) ++ + def _process_identifierlist(self, tlist): + # columns being selected + identifiers = list(tlist.get_identifiers()) +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__jp1804gl/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..18c8d4f610e839797b0dd50d0dc29dde905b401f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "5a0c218e337e6ce308662404d0d465490aec081463bb8e1b9b3f8caaabbc1869", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "be46d5a4956d2af9743bbdb94ee91f98cc1f3b4457b8110d3d46cda92048b434", + "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": true, + "partial_repair_sha256": "eca6b2c0418199a2fa2688a47bf40b60722cf6c1c06a34528727228bb6f34257", + "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": "825447e99ddae994ba12900ae42381ed50175a9f", + "source_completion_sha256": "664a6b52e187f3fe9676f915fc718f1448feab7bcfaaa82664426ece1c5bf89f", + "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_module__w8nu5ojp", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "29735a3fb333828811979b3e2d01441e8601151e90f3ae52c7a5c994cf28ec32", + "is_fork": true, + "learner_path": "tasks/72e128cbdb4af26c3f5f0a5a/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/825447e99ddae994ba12900ae42381ed50175a9f/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": "024a46f7c59f99a994fd915ad7101d3234e70300189a868aeb78906c29642780", + "provenance_path": "tasks/72e128cbdb4af26c3f5f0a5a/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "825447e99ddae994ba12900ae42381ed50175a9f", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "dcba79d79625e2b06d8e57804ab83b11c5516974", + "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_module__w8nu5ojp", + "task_sha256": "2973e8af1a933d208accb682474d991a2794cfe6a2728a27adfc8a88a01e6a68", + "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_module__w8nu5ojp", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5f4290016afb35a815194c871f5817c8db4ac170 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/instruction.md @@ -0,0 +1,38 @@ +SQL parsing broken after recent changes + +#### Description + +Something seems to have gone wrong with the SQL parsing logic. Basic SQL statements are not being parsed correctly anymore. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Simple SELECT statement +sql = "SELECT * FROM table" +parsed = sqlparse.parse(sql) +print(parsed) + +# Function calls in SQL +sql2 = "SELECT DATE(foo.bar) FROM table" +parsed2 = sqlparse.parse(sql2) +print(parsed2) + +# Parentheses grouping +sql3 = "SELECT (1 + 2) FROM table" +parsed3 = sqlparse.parse(sql3) +print(parsed3) +``` + +The parsing seems to be completely broken - tokens are not being grouped properly and basic SQL constructs like function calls and parentheses are not recognized correctly. + +#### Expected vs Actual + +Expected: SQL statements should parse into proper token groups with correct identification of functions, parentheses, comparisons, etc. + +Actual: Parsing appears to be fundamentally broken with tokens not being grouped or identified properly. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1fef854e7843575eeec769cf4bc4ebb9649730fe --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/metadata.json @@ -0,0 +1,534 @@ +{ + "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_cli.py::test_stdout", + "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_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "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_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_having_produces_newline", + "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_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_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_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_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_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_scientific_numbers[e1-None]", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "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_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "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_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_parse_sql_with_binary", + "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_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "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_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "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_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_tokenlist_repr", + "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_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]" + ], + "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_script", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "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_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "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::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "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_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_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_single_quotes_are_strings", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_get_token_at_offset", + "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_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_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_issue38", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "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_issue190_open_file", + "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_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_split.py::test_split_backslash", + "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_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_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_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_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": "dcba79d79625e2b06d8e57804ab83b11c5516974", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "825447e99ddae994ba12900ae42381ed50175a9f" + }, + "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_keywords.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_cli.py", + "tests/test_format.py", + "tests/test_grouping.py", + "tests/test_parse.py", + "tests/test_regressions.py", + "tests/test_split.py", + "tests/test_tokenize.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/engine/filter_stack.py", + "sqlparse/engine/grouping.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 839861, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp", + "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_module__w8nu5ojp", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "29735a3fb333828811979b3e2d01441e8601151e90f3ae52c7a5c994cf28ec32", + "is_fork": true, + "learner_path": "tasks/72e128cbdb4af26c3f5f0a5a/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/825447e99ddae994ba12900ae42381ed50175a9f/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": "024a46f7c59f99a994fd915ad7101d3234e70300189a868aeb78906c29642780", + "provenance_path": "tasks/72e128cbdb4af26c3f5f0a5a/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "825447e99ddae994ba12900ae42381ed50175a9f", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "dcba79d79625e2b06d8e57804ab83b11c5516974", + "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_module__w8nu5ojp", + "task_sha256": "2973e8af1a933d208accb682474d991a2794cfe6a2728a27adfc8a88a01e6a68", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..55bb120a2e4a01ec720f95ef24fc0a43110ce685 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "5a0c218e337e6ce308662404d0d465490aec081463bb8e1b9b3f8caaabbc1869", + "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/825447e99ddae994ba12900ae42381ed50175a9f/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "664a6b52e187f3fe9676f915fc718f1448feab7bcfaaa82664426ece1c5bf89f", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "90651b1bc1fb9f58f481f501d5aa166be8f735a5eabd97fff679a92da8d620c0", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "29735a3fb333828811979b3e2d01441e8601151e90f3ae52c7a5c994cf28ec32", + "is_fork": true, + "learner_path": "tasks/72e128cbdb4af26c3f5f0a5a/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/825447e99ddae994ba12900ae42381ed50175a9f/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": "024a46f7c59f99a994fd915ad7101d3234e70300189a868aeb78906c29642780", + "provenance_path": "tasks/72e128cbdb4af26c3f5f0a5a/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "825447e99ddae994ba12900ae42381ed50175a9f", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "dcba79d79625e2b06d8e57804ab83b11c5516974", + "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_module__w8nu5ojp", + "task_sha256": "2973e8af1a933d208accb682474d991a2794cfe6a2728a27adfc8a88a01e6a68", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..8918899268fd4387513243f89a66e8bf7e7afa53 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/provided-gold.diff @@ -0,0 +1,33 @@ +diff --git a/sqlparse/engine/filter_stack.py b/sqlparse/engine/filter_stack.py +index 4375ef06a6b39ab152758ec011d8f528c9b20b74..3feba377b891631655e8ab9fe0ea01ff1028c202 100644 +--- a/sqlparse/engine/filter_stack.py ++++ b/sqlparse/engine/filter_stack.py +@@ -18,12 +18,12 @@ + self.preprocess = [] + self.stmtprocess = [] + self.postprocess = [] +- self._grouping = True +- if not strip_semicolon: ++ self._grouping = False ++ if strip_semicolon: + self.stmtprocess.append(StripTrailingSemicolonFilter()) + + def enable_grouping(self): +- self._grouping = False ++ self._grouping = True + + def run(self, sql, encoding=None): + stream = lexer.tokenize(sql, encoding) +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index 03e4c1cd7f4dfe0322cf70df5fac81f506672b81..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -50,7 +50,7 @@ + + + def group_brackets(tlist): +- _group_matching(tlist[::-1], sql.RoundBrackets) ++ _group_matching(tlist, sql.SquareBrackets) + + + def group_parenthesis(tlist): diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..420a9214cf03b9dd1b43585427b0f9937d00b61b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/solution/solve.sh @@ -0,0 +1,39 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/engine/filter_stack.py b/sqlparse/engine/filter_stack.py +index 4375ef06a6b39ab152758ec011d8f528c9b20b74..3feba377b891631655e8ab9fe0ea01ff1028c202 100644 +--- a/sqlparse/engine/filter_stack.py ++++ b/sqlparse/engine/filter_stack.py +@@ -18,12 +18,12 @@ + self.preprocess = [] + self.stmtprocess = [] + self.postprocess = [] +- self._grouping = True +- if not strip_semicolon: ++ self._grouping = False ++ if strip_semicolon: + self.stmtprocess.append(StripTrailingSemicolonFilter()) + + def enable_grouping(self): +- self._grouping = False ++ self._grouping = True + + def run(self, sql, encoding=None): + stream = lexer.tokenize(sql, encoding) +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index 03e4c1cd7f4dfe0322cf70df5fac81f506672b81..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -50,7 +50,7 @@ + + + def group_brackets(tlist): +- _group_matching(tlist[::-1], sql.RoundBrackets) ++ _group_matching(tlist, sql.SquareBrackets) + + + def group_parenthesis(tlist): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e495995d8c9e29c1b25263f9d111600dce729bdd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:7841746b783e04158518b369739605751144a7841fcc6059ca28b9ca64f29601" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..ccff67a54881419d2829899be82584fa981001a6 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_cli.py::test_stdout", + "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_identifiercase", + "tests/test_format.py::TestFormat::test_identifiercase_quotes", + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "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_wildcard_vs_mult", + "tests/test_format.py::TestFormatReindent::test_stmts", + "tests/test_format.py::TestFormatReindent::test_keywords", + "tests/test_format.py::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_truncate_strings", + "tests/test_format.py::test_having_produces_newline", + "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_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_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_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_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_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_scientific_numbers[e1-None]", + "tests/test_parse.py::test_double_quotes_are_identifiers", + "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_pprint", + "tests/test_parse.py::test_wildcard_multiplication", + "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_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue13", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_parse_sql_with_binary", + "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_issue193_splitting_function", + "tests/test_regressions.py::test_issue194_splitting_function", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "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_splitting_at_and_backticks_issue588", + "tests/test_regressions.py::test_comment_between_cte_clauses_issue632", + "tests/test_regressions.py::test_max_recursion", + "tests/test_split.py::test_split_semicolon", + "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_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_tokenlist_repr", + "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_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]" + ], + "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_script", + "tests/test_format.py::TestFormat::test_keywordcase_invalid_option", + "tests/test_format.py::TestFormat::test_identifiercase_invalid_option", + "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_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_preserve_ws", + "tests/test_format.py::TestFormatReindentAligned::test_joins", + "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::TestFormatReindent::test_option", + "tests/test_format.py::TestFormatReindent::test_keywords_between", + "tests/test_format.py::TestFormatReindent::test_join", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "tests/test_grouping.py::test_grouping_identifiers_with_operators", + "tests/test_grouping.py::test_statement_get_type", + "tests/test_grouping.py::test_keyword_followed_by_parenthesis", + "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_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_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_single_quotes_are_strings", + "tests/test_parse.py::test_single_quotes_with_linebreaks", + "tests/test_parse.py::test_get_token_at_offset", + "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_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_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_issue38", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "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_issue190_open_file", + "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_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "tests/test_regressions.py::test_as_in_parentheses_indents", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_regressions.py::test_copy_issue672", + "tests/test_regressions.py::test_primary_key_issue740", + "tests/test_split.py::test_split_backslash", + "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_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_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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/engine/filter_stack.py b/sqlparse/engine/filter_stack.py +index 4375ef06a6b39ab152758ec011d8f528c9b20b74..3feba377b891631655e8ab9fe0ea01ff1028c202 100644 +--- a/sqlparse/engine/filter_stack.py ++++ b/sqlparse/engine/filter_stack.py +@@ -18,12 +18,12 @@ + self.preprocess = [] + self.stmtprocess = [] + self.postprocess = [] +- self._grouping = True +- if not strip_semicolon: ++ self._grouping = False ++ if strip_semicolon: + self.stmtprocess.append(StripTrailingSemicolonFilter()) + + def enable_grouping(self): +- self._grouping = False ++ self._grouping = True + + def run(self, sql, encoding=None): + stream = lexer.tokenize(sql, encoding) +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__w8nu5ojp/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..98ab28e075cb4868501da007c34cbc16ff42285d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "f3cdc2a1521cb7125c4c08d3386941056b22a267aa995183813895efdcfa6cbe", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "a7500e345daf286ceb4fc056de8294e6c0562c39cd768917bbbf8959b09e35e3", + "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": true, + "partial_repair_sha256": "5ed8cc6ca466b28704fac57877da37e9bfe6e687ed83e9d1e7b9ccec3e746999", + "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": "73c64fe9d4fdfad1f4eef7a7e205734104207b65", + "source_completion_sha256": "6b69e327a0c5710d3e4f6060e164fa0702d3c87e9f945408d4704d3df69c8177", + "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_module__x9bxhim7", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "40ca0b8da4a11c1c5ad6ce07432a610f455c1576dcedd7faf1da3529e0692c9d", + "is_fork": true, + "learner_path": "tasks/c2e7787a170a29361790b06e/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/73c64fe9d4fdfad1f4eef7a7e205734104207b65/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": "ab774e0804d8b79ed9037211b82efb67089c3b21bdb48c68830562476a3652dd", + "provenance_path": "tasks/c2e7787a170a29361790b06e/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "73c64fe9d4fdfad1f4eef7a7e205734104207b65", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "cd309d74f4c402c0d7aef588c4424be8cf76ccfa", + "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_module__x9bxhim7", + "task_sha256": "34960e457a8f66d37c9d1990b753f036cf5749a589f25baeb25b28535eadcede", + "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_module__x9bxhim7", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d9a1f7accaede7a739ac5d60a5c5dbefe3ac1c20 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/instruction.md @@ -0,0 +1,51 @@ +# SQL formatting broken after recent changes + +I was trying to format some SQL queries and noticed that the formatting is completely broken. The indentation and alignment are not working correctly anymore. + +## Steps to Reproduce + +```python +import sqlparse + +# Example 1: Basic formatting +sql = 'select * from foo where bar = 1 limit 1' +print(sqlparse.format(sql, reindent=True)) + +# Example 2: Query with functions +sql = "select 'abc' as foo, coalesce(col1, col2)||col3 as bar, col3 from my_table" +print(sqlparse.format(sql, reindent=True)) + +# Example 3: Query with CASE statement +sql = ''' +SELECT + CASE WHEN a = 1 THEN 'one' + WHEN a = 2 THEN 'two' + ELSE 'other' + END AS result +FROM table +''' +print(sqlparse.format(sql, reindent=True)) +``` + +## Expected Output + +For Example 1, I expect: +``` +select * +from foo +where bar = 1 +limit 1 +``` + +But instead I get an AttributeError. Similar errors occur with the other examples. + +## Environment + +- sqlparse version: 0.4.3 +- Python version: 3.10.8 + +This used to work in previous versions. I think something broke in the reindent and aligned indent filters. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..46eeac9c9aeb575845d5b92c47105f2044a648af --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/metadata.json @@ -0,0 +1,534 @@ +{ + "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_cli.py::test_valid_args", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "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" + ], + "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_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_joins", + "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::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "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_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": "cd309d74f4c402c0d7aef588c4424be8cf76ccfa", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "73c64fe9d4fdfad1f4eef7a7e205734104207b65" + }, + "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_grouping.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_parse.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_cli.py", + "tests/test_format.py", + "tests/test_regressions.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/aligned_indent.py", + "sqlparse/filters/reindent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 894984, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7", + "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_module__x9bxhim7", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "40ca0b8da4a11c1c5ad6ce07432a610f455c1576dcedd7faf1da3529e0692c9d", + "is_fork": true, + "learner_path": "tasks/c2e7787a170a29361790b06e/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/73c64fe9d4fdfad1f4eef7a7e205734104207b65/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": "ab774e0804d8b79ed9037211b82efb67089c3b21bdb48c68830562476a3652dd", + "provenance_path": "tasks/c2e7787a170a29361790b06e/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "73c64fe9d4fdfad1f4eef7a7e205734104207b65", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "cd309d74f4c402c0d7aef588c4424be8cf76ccfa", + "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_module__x9bxhim7", + "task_sha256": "34960e457a8f66d37c9d1990b753f036cf5749a589f25baeb25b28535eadcede", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..6b8ce0dc3c76660e608e3235a9e9d89749fa9fd4 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "f3cdc2a1521cb7125c4c08d3386941056b22a267aa995183813895efdcfa6cbe", + "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/73c64fe9d4fdfad1f4eef7a7e205734104207b65/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "6b69e327a0c5710d3e4f6060e164fa0702d3c87e9f945408d4704d3df69c8177", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "d3fed644b97ee463e0765e1ce423666fc839662be22878288e36877339c53fca", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "40ca0b8da4a11c1c5ad6ce07432a610f455c1576dcedd7faf1da3529e0692c9d", + "is_fork": true, + "learner_path": "tasks/c2e7787a170a29361790b06e/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/73c64fe9d4fdfad1f4eef7a7e205734104207b65/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": "ab774e0804d8b79ed9037211b82efb67089c3b21bdb48c68830562476a3652dd", + "provenance_path": "tasks/c2e7787a170a29361790b06e/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "73c64fe9d4fdfad1f4eef7a7e205734104207b65", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "cd309d74f4c402c0d7aef588c4424be8cf76ccfa", + "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_module__x9bxhim7", + "task_sha256": "34960e457a8f66d37c9d1990b753f036cf5749a589f25baeb25b28535eadcede", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..30cbbcd7f17aed7e4096932fc38b1cff37d411ea --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/provided-gold.diff @@ -0,0 +1,72 @@ +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index f94d220e5149e8a82fa784731fe94fa18a293bd8..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -87,25 +87,15 @@ + tlist.insert_after(cond[-1], ws) + + def _next_token(self, tlist, idx=-1): +- """Find the next token matching the split_words criteria. +- +- Args: +- tlist: The token list to search in +- idx: The index to start searching from +- +- Returns: +- A tuple of (token_index, token) if found, or (None, None) if not found +- """ +- idx += 1 +- while idx < len(tlist.tokens): +- token = tlist.tokens[idx] +- if token.is_keyword and ( +- token.normalized in self.split_words or +- token.match(T.Keyword, self.split_words, regex=True) +- ): +- return idx, token +- idx += 1 +- return None, None ++ split_words = T.Keyword, self.split_words, True ++ tidx, token = tlist.token_next_by(m=split_words, idx=idx) ++ # treat "BETWEEN x and y" as a single statement ++ if token and token.normalized == 'BETWEEN': ++ tidx, token = self._next_token(tlist, tidx) ++ if token and token.normalized == 'AND': ++ tidx, token = self._next_token(tlist, tidx) ++ return tidx, token ++ + def _split_kwds(self, tlist): + tidx, token = self._next_token(tlist) + while token: +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 438ce7a4ea29719775c40737b3555bf5341eae39..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', +@@ -97,8 +98,8 @@ + + def _process(self, tlist): + func_name = '_process_{cls}'.format(cls=type(tlist).__name__) +- func = getattr(self, func_name.upper(), self._process_default) +- func(tlist[::-1]) ++ func = getattr(self, func_name.lower(), self._process_default) ++ func(tlist) + + def _process_where(self, tlist): + tidx, token = tlist.token_next_by(m=(T.Keyword, 'WHERE')) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f40996c1ab6039a1c6fd90ee9bcc1e973734d349 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/solution/solve.sh @@ -0,0 +1,78 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index f94d220e5149e8a82fa784731fe94fa18a293bd8..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -87,25 +87,15 @@ + tlist.insert_after(cond[-1], ws) + + def _next_token(self, tlist, idx=-1): +- """Find the next token matching the split_words criteria. +- +- Args: +- tlist: The token list to search in +- idx: The index to start searching from +- +- Returns: +- A tuple of (token_index, token) if found, or (None, None) if not found +- """ +- idx += 1 +- while idx < len(tlist.tokens): +- token = tlist.tokens[idx] +- if token.is_keyword and ( +- token.normalized in self.split_words or +- token.match(T.Keyword, self.split_words, regex=True) +- ): +- return idx, token +- idx += 1 +- return None, None ++ split_words = T.Keyword, self.split_words, True ++ tidx, token = tlist.token_next_by(m=split_words, idx=idx) ++ # treat "BETWEEN x and y" as a single statement ++ if token and token.normalized == 'BETWEEN': ++ tidx, token = self._next_token(tlist, tidx) ++ if token and token.normalized == 'AND': ++ tidx, token = self._next_token(tlist, tidx) ++ return tidx, token ++ + def _split_kwds(self, tlist): + tidx, token = self._next_token(tlist) + while token: +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 438ce7a4ea29719775c40737b3555bf5341eae39..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', +@@ -97,8 +98,8 @@ + + def _process(self, tlist): + func_name = '_process_{cls}'.format(cls=type(tlist).__name__) +- func = getattr(self, func_name.upper(), self._process_default) +- func(tlist[::-1]) ++ func = getattr(self, func_name.lower(), self._process_default) ++ func(tlist) + + def _process_where(self, tlist): + tidx, token = tlist.token_next_by(m=(T.Keyword, 'WHERE')) +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..29754a7eb292426d28dc3dbb06bc437f403fb560 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:0c6bc3e14cb5ad2cfb1452d1ae9094b6288dd38e3e7e9165184bafcd5b170821" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..782fc1f0ae5750d43c7c2a79afc1b39a17150658 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_cli.py::test_valid_args", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement", + "tests/test_format.py::TestFormatReindentAligned::test_case_statement_with_between", + "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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "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" + ], + "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_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_joins", + "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::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index f94d220e5149e8a82fa784731fe94fa18a293bd8..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -87,25 +87,15 @@ + tlist.insert_after(cond[-1], ws) + + def _next_token(self, tlist, idx=-1): +- """Find the next token matching the split_words criteria. +- +- Args: +- tlist: The token list to search in +- idx: The index to start searching from +- +- Returns: +- A tuple of (token_index, token) if found, or (None, None) if not found +- """ +- idx += 1 +- while idx < len(tlist.tokens): +- token = tlist.tokens[idx] +- if token.is_keyword and ( +- token.normalized in self.split_words or +- token.match(T.Keyword, self.split_words, regex=True) +- ): +- return idx, token +- idx += 1 +- return None, None ++ split_words = T.Keyword, self.split_words, True ++ tidx, token = tlist.token_next_by(m=split_words, idx=idx) ++ # treat "BETWEEN x and y" as a single statement ++ if token and token.normalized == 'BETWEEN': ++ tidx, token = self._next_token(tlist, tidx) ++ if token and token.normalized == 'AND': ++ tidx, token = self._next_token(tlist, tidx) ++ return tidx, token ++ + def _split_kwds(self, tlist): + tidx, token = self._next_token(tlist) + while token: +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__x9bxhim7/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..77665852e08192b5200d827515d526ee5cec2fc2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "a022de07b2b8524a9887c8d6f2e3ee74bc8c4bd388f6291562712c06b9cf3cb0", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "d242a91388418c7a65dc069f2c54f7c48f40768b66c01506f77ca22f4651f603", + "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": true, + "partial_repair_sha256": "87be326c1d70826c2e93e3928335afb152983f3b8ac61f81e1b08b0119a364f4", + "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": "4e49104cceb472ae1123e297e03f4ed842d379a6", + "source_completion_sha256": "8e5ae86d6c4ca9bbfc7a6772d9bd3e9fb31335e32fbe286faa12c0ff8535e0b4", + "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_module__ytdlfcl6", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "8c35d65cadf5d520c5735187e73a92407ead6de8258ff6d21297ce2e17be813f", + "is_fork": true, + "learner_path": "tasks/67cb807a848e350aa770bb5f/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/4e49104cceb472ae1123e297e03f4ed842d379a6/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": "693f1f15e49d285725dd6d16279499f7c88a437457ebd17eba7816977295c447", + "provenance_path": "tasks/67cb807a848e350aa770bb5f/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "4e49104cceb472ae1123e297e03f4ed842d379a6", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "206cab5d273ebb07c67669ca7b0812f5199be7d1", + "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_module__ytdlfcl6", + "task_sha256": "60586435c91fb4b316c450aa1fe600cb6fef3f4b6c6a9e28240c841db8c1fe06", + "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_module__ytdlfcl6", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ba48e3be43623d4082f64572123115ff8d885b15 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/instruction.md @@ -0,0 +1,31 @@ +SQL formatting produces incorrect output with extra " processed" suffix + +#### Description + +When using sqlparse to format SQL statements, the formatted output includes an unexpected " processed" suffix appended to the result. This affects all formatting operations including reindent and aligned indent filters. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Basic formatting +sql = 'select * from foo' +formatted = sqlparse.format(sql, reindent=True) +print(repr(formatted)) +# Expected: 'select *\nfrom foo' +# Actual: 'select *\nfrom foo processed' + +# Also affects other formatting options +sql2 = 'SELECT NULL AS c1, NULL AS c2 FROM t1' +formatted2 = sqlparse.format(sql2, reindent=True) +print(repr(formatted2)) +# Expected: 'SELECT NULL AS c1,\n NULL AS c2\nFROM t1' +# Actual: 'SELECT NULL AS c1,\n NULL AS c2\nFROM t1 processed' +``` + +The issue appears to affect all SQL formatting operations, causing the formatted SQL to have an unwanted " processed" string appended to the end of the output. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1c2f430bdd3f034b666e09f81e9bb529c5cd7feb --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/metadata.json @@ -0,0 +1,534 @@ +{ + "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_cli.py::test_valid_args", + "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::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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue562_tzcasts" + ], + "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_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::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::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "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_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": "206cab5d273ebb07c67669ca7b0812f5199be7d1", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "4e49104cceb472ae1123e297e03f4ed842d379a6" + }, + "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_grouping.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_parse.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_cli.py", + "tests/test_format.py", + "tests/test_regressions.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/aligned_indent.py", + "sqlparse/filters/reindent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 894768, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6", + "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_module__ytdlfcl6", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "8c35d65cadf5d520c5735187e73a92407ead6de8258ff6d21297ce2e17be813f", + "is_fork": true, + "learner_path": "tasks/67cb807a848e350aa770bb5f/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/4e49104cceb472ae1123e297e03f4ed842d379a6/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": "693f1f15e49d285725dd6d16279499f7c88a437457ebd17eba7816977295c447", + "provenance_path": "tasks/67cb807a848e350aa770bb5f/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "4e49104cceb472ae1123e297e03f4ed842d379a6", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "206cab5d273ebb07c67669ca7b0812f5199be7d1", + "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_module__ytdlfcl6", + "task_sha256": "60586435c91fb4b316c450aa1fe600cb6fef3f4b6c6a9e28240c841db8c1fe06", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..c30d91c18609ac8902c3427d2936d8b7695aa098 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "a022de07b2b8524a9887c8d6f2e3ee74bc8c4bd388f6291562712c06b9cf3cb0", + "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/4e49104cceb472ae1123e297e03f4ed842d379a6/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "8e5ae86d6c4ca9bbfc7a6772d9bd3e9fb31335e32fbe286faa12c0ff8535e0b4", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "50d484ad4e7f8d5ce9735ee6bfe6de8e129cfee8f96cc3b8c71c1bd8859247cb", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "8c35d65cadf5d520c5735187e73a92407ead6de8258ff6d21297ce2e17be813f", + "is_fork": true, + "learner_path": "tasks/67cb807a848e350aa770bb5f/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/4e49104cceb472ae1123e297e03f4ed842d379a6/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": "693f1f15e49d285725dd6d16279499f7c88a437457ebd17eba7816977295c447", + "provenance_path": "tasks/67cb807a848e350aa770bb5f/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "4e49104cceb472ae1123e297e03f4ed842d379a6", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "206cab5d273ebb07c67669ca7b0812f5199be7d1", + "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_module__ytdlfcl6", + "task_sha256": "60586435c91fb4b316c450aa1fe600cb6fef3f4b6c6a9e28240c841db8c1fe06", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..692aa932d15ff745b207f625380f21a7c3b4c5b5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/provided-gold.diff @@ -0,0 +1,36 @@ +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index 2a8ea25dcba20e86d1c14cd0f89400f7d2af7ef6..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -131,5 +131,5 @@ + func(tlist) + + def process(self, stmt): +- processed_stmt = self._process(stmt) +- return processed_stmt + " processed" ++ self._process(stmt) ++ return stmt +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 1a7d5502b6fde20937794c6959ef27d2477498e6..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -49,7 +49,7 @@ + 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', +@@ -123,8 +123,8 @@ + self._process_default(tlist, not is_dml_dll) + + def _process_function(self, tlist): +- self._last_func = tlist[-1] +- self._process_default(reversed(tlist)) ++ self._last_func = tlist[0] ++ self._process_default(tlist) + + def _process_identifierlist(self, tlist): + identifiers = list(tlist.get_identifiers()) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5582b41a949231a60c5037e22d5087a13033555a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/solution/solve.sh @@ -0,0 +1,42 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index 2a8ea25dcba20e86d1c14cd0f89400f7d2af7ef6..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -131,5 +131,5 @@ + func(tlist) + + def process(self, stmt): +- processed_stmt = self._process(stmt) +- return processed_stmt + " processed" ++ self._process(stmt) ++ return stmt +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 1a7d5502b6fde20937794c6959ef27d2477498e6..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -49,7 +49,7 @@ + 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', +@@ -123,8 +123,8 @@ + self._process_default(tlist, not is_dml_dll) + + def _process_function(self, tlist): +- self._last_func = tlist[-1] +- self._process_default(reversed(tlist)) ++ self._last_func = tlist[0] ++ self._process_default(tlist) + + def _process_identifierlist(self, tlist): + identifiers = list(tlist.get_identifiers()) +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0df62e6d0bcb8cf9b39d8e94069c5e1b6539db6c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:c034138a2fd9cddad63375f957f23a5a3ec13ed965cb06bab06d77deeff564aa" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..39b1bea4f882d617f62acec6577e03ec5b2698f3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_cli.py::test_valid_args", + "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::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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "tests/test_regressions.py::test_issue562_tzcasts" + ], + "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_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::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::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index 2a8ea25dcba20e86d1c14cd0f89400f7d2af7ef6..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -131,5 +131,5 @@ + func(tlist) + + def process(self, stmt): +- processed_stmt = self._process(stmt) +- return processed_stmt + " processed" ++ self._process(stmt) ++ return stmt +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__ytdlfcl6/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..4e081b2f7e7fef7ad22981722f1b179fe09c4819 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "aaba44115a977c571b25b92c8701236fbe5d671634402bc59367bf3a47d5b05a", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "573f00248f5a6c07bacd2c424782275821e658ea59e939bacf5d0ac18716d777", + "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": true, + "partial_repair_sha256": "2d515125445a6abdc41d3c2f7593c852ebb3a793f2e5ed4b38f1cbfe562af688", + "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": "d891f1f0526f666af690b18f1bc97c069580c9f9", + "source_completion_sha256": "382d69ea88e45a107efce3e8ed11094d86f6c57459e8618e20e3ad4a62f2cc3b", + "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_module__z994yg2s", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "2ea3289727fde5eddcf98d6bb87f9540789eda7b4c552781a9fd7de3e333ffc1", + "is_fork": true, + "learner_path": "tasks/6c23d20373184e8ccb852715/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/d891f1f0526f666af690b18f1bc97c069580c9f9/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": "eb4dd02c2cfbec10054b30fa8ed1b3685301e01264f141f3e685e4d498064f90", + "provenance_path": "tasks/6c23d20373184e8ccb852715/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d891f1f0526f666af690b18f1bc97c069580c9f9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "508a46168a354ef1c6699fd72d6775b1f8e0bad8", + "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_module__z994yg2s", + "task_sha256": "82982cb6318180f02272e7be7933fda1d695be0b4311a7b6419905794038b44e", + "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_module__z994yg2s", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..afface8cfa3d034a2810798df3a283e337dca5a5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/instruction.md @@ -0,0 +1,37 @@ +SQL formatting broken after recent changes + +#### Description + +The SQL formatter is producing incorrect output and throwing errors when trying to format basic SQL statements. Multiple formatting operations that previously worked are now failing. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Basic reindent formatting fails +sql = 'select * from foo where bar = 1 and baz = 2 or bzz = 3;' +formatted = sqlparse.format(sql, reindent=True) +print("Expected:") +print('\n'.join(['select *', 'from foo', 'where bar = 1', ' and baz = 2', ' or bzz = 3;'])) +print("Actual:") +print(repr(formatted)) + +# Comment stripping produces wrong output +sql_with_comment = 'select * from foo -- this is a comment' +stripped = sqlparse.format(sql_with_comment, strip_comments=True) +print("Comment stripped result:") +print(repr(stripped)) + +# Spaces around operators returns None instead of formatted SQL +sql_ops = 'select a+b from table' +spaced = sqlparse.format(sql_ops, use_space_around_operators=True) +print("Spaces around operators result:") +print(repr(spaced)) +``` + +The formatter seems to be inserting incorrect whitespace characters, handling comment removal improperly, and in some cases returning None instead of the formatted SQL string. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..fecf4fa47212ecc49b0fffd8654f8fb6b189f964 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/metadata.json @@ -0,0 +1,534 @@ +{ + "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::TestFormat::test_strip_comments_single", + "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_preserve_ws", + "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_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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue213_leadingws", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "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" + ], + "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_invalid_option", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_issue227_gettype_cte", + "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_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_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": "508a46168a354ef1c6699fd72d6775b1f8e0bad8", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "d891f1f0526f666af690b18f1bc97c069580c9f9" + }, + "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_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", + "tests/test_regressions.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/others.py", + "sqlparse/filters/reindent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 896447, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s", + "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_module__z994yg2s", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "2ea3289727fde5eddcf98d6bb87f9540789eda7b4c552781a9fd7de3e333ffc1", + "is_fork": true, + "learner_path": "tasks/6c23d20373184e8ccb852715/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/d891f1f0526f666af690b18f1bc97c069580c9f9/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": "eb4dd02c2cfbec10054b30fa8ed1b3685301e01264f141f3e685e4d498064f90", + "provenance_path": "tasks/6c23d20373184e8ccb852715/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d891f1f0526f666af690b18f1bc97c069580c9f9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "508a46168a354ef1c6699fd72d6775b1f8e0bad8", + "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_module__z994yg2s", + "task_sha256": "82982cb6318180f02272e7be7933fda1d695be0b4311a7b6419905794038b44e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..96c82f6821c4da028ea3052ed4012c5dfeddb0db --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "aaba44115a977c571b25b92c8701236fbe5d671634402bc59367bf3a47d5b05a", + "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/d891f1f0526f666af690b18f1bc97c069580c9f9/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "382d69ea88e45a107efce3e8ed11094d86f6c57459e8618e20e3ad4a62f2cc3b", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "0402942b29d3955c9a69f40ac12a159200bd01370581d00fadca354d3d5ba1ca", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "2ea3289727fde5eddcf98d6bb87f9540789eda7b4c552781a9fd7de3e333ffc1", + "is_fork": true, + "learner_path": "tasks/6c23d20373184e8ccb852715/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/d891f1f0526f666af690b18f1bc97c069580c9f9/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": "eb4dd02c2cfbec10054b30fa8ed1b3685301e01264f141f3e685e4d498064f90", + "provenance_path": "tasks/6c23d20373184e8ccb852715/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d891f1f0526f666af690b18f1bc97c069580c9f9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "508a46168a354ef1c6699fd72d6775b1f8e0bad8", + "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_module__z994yg2s", + "task_sha256": "82982cb6318180f02272e7be7933fda1d695be0b4311a7b6419905794038b44e", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..8446dbd4e8ff96e81ef3e97e022cd5a52cd329ca --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/provided-gold.diff @@ -0,0 +1,149 @@ +diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py +index 5b251a70025b58252902149a321556bef8de30ca..6c1680ec4a8cbba52b30c25868b4b849d5b3a935 100644 +--- a/sqlparse/filters/others.py ++++ b/sqlparse/filters/others.py +@@ -15,45 +15,62 @@ + + @staticmethod + def _process(tlist): +- def get_next_comment(idx=0): ++ def get_next_comment(idx=-1): ++ # TODO(andi) Comment types should be unified, see related issue38 + return tlist.token_next_by(i=sql.Comment, t=T.Comment, idx=idx) + + def _get_insert_token(token): +- m = re.search(r'([\r\n]*) *$', token.value) ++ """Returns either a whitespace or the line breaks from token.""" ++ # See issue484 why line breaks should be preserved. ++ # Note: The actual value for a line break is replaced by \n ++ # in SerializerUnicode which will be executed in the ++ # postprocessing state. ++ m = re.search(r'([\r\n]+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: +- return sql.Token(T.Whitespace, '\t') ++ return sql.Token(T.Whitespace, ' ') + +- sql_hints = (T.Comment.Multiline.Hint,) ++ sql_hints = (T.Comment.Multiline.Hint, T.Comment.Single.Hint) + tidx, token = get_next_comment() + while token: ++ # skipping token remove if token is a SQL-Hint. issue262 + is_sql_hint = False + if token.ttype in sql_hints: + is_sql_hint = True + elif isinstance(token, sql.Comment): + comment_tokens = token.tokens +- if len(comment_tokens) >= 0: ++ if len(comment_tokens) > 0: + if comment_tokens[0].ttype in sql_hints: + is_sql_hint = True + + if is_sql_hint: ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + continue + +- pidx, prev_ = tlist.token_prev(tidx, skip_ws=True) +- nidx, next_ = tlist.token_next(tidx, skip_ws=True) ++ pidx, prev_ = tlist.token_prev(tidx, skip_ws=False) ++ nidx, next_ = tlist.token_next(tidx, skip_ws=False) ++ # Replace by whitespace if prev and next exist and if they're not ++ # whitespaces. This doesn't apply if prev or next is a parenthesis. + if ( + prev_ is None or next_ is None +- or prev_.is_whitespace or prev_.match(T.Punctuation, ')') +- or next_.is_whitespace or next_.match(T.Punctuation, '(') ++ or prev_.is_whitespace or prev_.match(T.Punctuation, '(') ++ or next_.is_whitespace or next_.match(T.Punctuation, ')') + ): ++ # Insert a whitespace to ensure the following SQL produces ++ # a valid SQL (see #425). + if prev_ is not None and not prev_.match(T.Punctuation, '('): +- tlist.tokens.insert(tidx + 1, _get_insert_token(token)) ++ tlist.tokens.insert(tidx, _get_insert_token(token)) + tlist.tokens.remove(token) + else: +- tlist.tokens[tidx - 1] = _get_insert_token(token) ++ tlist.tokens[tidx] = _get_insert_token(token) + ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + + def process(self, stmt): +@@ -71,10 +88,12 @@ + @staticmethod + def _stripws_default(tlist): + last_was_ws = False +- for i, token in enumerate(tlist.tokens): ++ is_first_char = True ++ for token in tlist.tokens: + if token.is_whitespace: +- token.value = '' if last_was_ws or i == len(tlist.tokens) - 1 else ' ' ++ token.value = '' if last_was_ws or is_first_char else ' ' + last_was_ws = token.is_whitespace ++ is_first_char = False + + def _stripws_identifierlist(self, tlist): + # Removes newlines before commas, see issue140 +@@ -102,10 +121,10 @@ + self._stripws_default(tlist) + + def process(self, stmt, depth=0): +- [self.process(sgroup, depth) for sgroup in stmt.get_sublists()] # removed + 1 ++ [self.process(sgroup, depth + 1) for sgroup in stmt.get_sublists()] + self._stripws(stmt) +- if depth == 0 or (stmt.tokens and stmt.tokens[0].is_whitespace): # changed 'and' to 'or' and check first token +- stmt.tokens.pop(0) # pop the first token instead of the last ++ if depth == 0 and stmt.tokens and stmt.tokens[-1].is_whitespace: ++ stmt.tokens.pop(-1) + return stmt + + +@@ -129,9 +148,9 @@ + tidx, token = tlist.token_next_by(t=ttypes, idx=tidx) + + def process(self, stmt): +- [self.process(sgroup) for sgroup in reversed(stmt.get_sublists())] ++ [self.process(sgroup) for sgroup in stmt.get_sublists()] + SpacesAroundOperatorsFilter._process(stmt) +- return None ++ return stmt + + + class StripTrailingSemicolonFilter: +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 85fd11af1b0aa9577b5d1412fbde7a2857d74669..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -13,17 +13,17 @@ + def __init__(self, width=2, char=' ', wrap_after=0, n='\n', + comma_first=False, indent_after_first=False, + indent_columns=False, compact=False): +- self.n = char # Incorrectly assign char instead of n ++ self.n = n + self.width = width +- self.char = n # Incorrectly assign n instead of char +- self.indent = 1 if not indent_after_first else 0 # Incorrect logic change +- self.offset = 1 # Change default offset value +- self.wrap_after = wrap_after + 1 # Introduce off-by-one error +- self.comma_first = not comma_first # Flip the boolean logic ++ self.char = char ++ self.indent = 1 if indent_after_first else 0 ++ self.offset = 0 ++ self.wrap_after = wrap_after ++ self.comma_first = comma_first + self.indent_columns = indent_columns + self.compact = compact +- self._curr_stmt = '' +- self._last_stmt = '' ++ self._curr_stmt = None ++ self._last_stmt = None + self._last_func = None + + def _flatten_up_to_token(self, token): diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2d604da42e4040bd5eb7ea6c84cd6bf3de7ed12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/solution/solve.sh @@ -0,0 +1,155 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py +index 5b251a70025b58252902149a321556bef8de30ca..6c1680ec4a8cbba52b30c25868b4b849d5b3a935 100644 +--- a/sqlparse/filters/others.py ++++ b/sqlparse/filters/others.py +@@ -15,45 +15,62 @@ + + @staticmethod + def _process(tlist): +- def get_next_comment(idx=0): ++ def get_next_comment(idx=-1): ++ # TODO(andi) Comment types should be unified, see related issue38 + return tlist.token_next_by(i=sql.Comment, t=T.Comment, idx=idx) + + def _get_insert_token(token): +- m = re.search(r'([\r\n]*) *$', token.value) ++ """Returns either a whitespace or the line breaks from token.""" ++ # See issue484 why line breaks should be preserved. ++ # Note: The actual value for a line break is replaced by \n ++ # in SerializerUnicode which will be executed in the ++ # postprocessing state. ++ m = re.search(r'([\r\n]+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: +- return sql.Token(T.Whitespace, '\t') ++ return sql.Token(T.Whitespace, ' ') + +- sql_hints = (T.Comment.Multiline.Hint,) ++ sql_hints = (T.Comment.Multiline.Hint, T.Comment.Single.Hint) + tidx, token = get_next_comment() + while token: ++ # skipping token remove if token is a SQL-Hint. issue262 + is_sql_hint = False + if token.ttype in sql_hints: + is_sql_hint = True + elif isinstance(token, sql.Comment): + comment_tokens = token.tokens +- if len(comment_tokens) >= 0: ++ if len(comment_tokens) > 0: + if comment_tokens[0].ttype in sql_hints: + is_sql_hint = True + + if is_sql_hint: ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + continue + +- pidx, prev_ = tlist.token_prev(tidx, skip_ws=True) +- nidx, next_ = tlist.token_next(tidx, skip_ws=True) ++ pidx, prev_ = tlist.token_prev(tidx, skip_ws=False) ++ nidx, next_ = tlist.token_next(tidx, skip_ws=False) ++ # Replace by whitespace if prev and next exist and if they're not ++ # whitespaces. This doesn't apply if prev or next is a parenthesis. + if ( + prev_ is None or next_ is None +- or prev_.is_whitespace or prev_.match(T.Punctuation, ')') +- or next_.is_whitespace or next_.match(T.Punctuation, '(') ++ or prev_.is_whitespace or prev_.match(T.Punctuation, '(') ++ or next_.is_whitespace or next_.match(T.Punctuation, ')') + ): ++ # Insert a whitespace to ensure the following SQL produces ++ # a valid SQL (see #425). + if prev_ is not None and not prev_.match(T.Punctuation, '('): +- tlist.tokens.insert(tidx + 1, _get_insert_token(token)) ++ tlist.tokens.insert(tidx, _get_insert_token(token)) + tlist.tokens.remove(token) + else: +- tlist.tokens[tidx - 1] = _get_insert_token(token) ++ tlist.tokens[tidx] = _get_insert_token(token) + ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + + def process(self, stmt): +@@ -71,10 +88,12 @@ + @staticmethod + def _stripws_default(tlist): + last_was_ws = False +- for i, token in enumerate(tlist.tokens): ++ is_first_char = True ++ for token in tlist.tokens: + if token.is_whitespace: +- token.value = '' if last_was_ws or i == len(tlist.tokens) - 1 else ' ' ++ token.value = '' if last_was_ws or is_first_char else ' ' + last_was_ws = token.is_whitespace ++ is_first_char = False + + def _stripws_identifierlist(self, tlist): + # Removes newlines before commas, see issue140 +@@ -102,10 +121,10 @@ + self._stripws_default(tlist) + + def process(self, stmt, depth=0): +- [self.process(sgroup, depth) for sgroup in stmt.get_sublists()] # removed + 1 ++ [self.process(sgroup, depth + 1) for sgroup in stmt.get_sublists()] + self._stripws(stmt) +- if depth == 0 or (stmt.tokens and stmt.tokens[0].is_whitespace): # changed 'and' to 'or' and check first token +- stmt.tokens.pop(0) # pop the first token instead of the last ++ if depth == 0 and stmt.tokens and stmt.tokens[-1].is_whitespace: ++ stmt.tokens.pop(-1) + return stmt + + +@@ -129,9 +148,9 @@ + tidx, token = tlist.token_next_by(t=ttypes, idx=tidx) + + def process(self, stmt): +- [self.process(sgroup) for sgroup in reversed(stmt.get_sublists())] ++ [self.process(sgroup) for sgroup in stmt.get_sublists()] + SpacesAroundOperatorsFilter._process(stmt) +- return None ++ return stmt + + + class StripTrailingSemicolonFilter: +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 85fd11af1b0aa9577b5d1412fbde7a2857d74669..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -13,17 +13,17 @@ + def __init__(self, width=2, char=' ', wrap_after=0, n='\n', + comma_first=False, indent_after_first=False, + indent_columns=False, compact=False): +- self.n = char # Incorrectly assign char instead of n ++ self.n = n + self.width = width +- self.char = n # Incorrectly assign n instead of char +- self.indent = 1 if not indent_after_first else 0 # Incorrect logic change +- self.offset = 1 # Change default offset value +- self.wrap_after = wrap_after + 1 # Introduce off-by-one error +- self.comma_first = not comma_first # Flip the boolean logic ++ self.char = char ++ self.indent = 1 if indent_after_first else 0 ++ self.offset = 0 ++ self.wrap_after = wrap_after ++ self.comma_first = comma_first + self.indent_columns = indent_columns + self.compact = compact +- self._curr_stmt = '' +- self._last_stmt = '' ++ self._curr_stmt = None ++ self._last_stmt = None + self._last_func = None + + def _flatten_up_to_token(self, token): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..523a3bf82518683386e13fec8d0e4c4b4f25a632 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:376d95e9947480035630343be562d724b1a6f013f81e1b1f917f9a78d0b7bfab" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..628bfa9da8ce713450df0f8064d34d3326e3694a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormat::test_strip_comments_single", + "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_preserve_ws", + "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_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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue38", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue213_leadingws", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "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" + ], + "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_invalid_option", + "tests/test_format.py::TestFormat::test_strip_ws_invalid_option", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "tests/test_format.py::TestFormatReindent::test_option", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_issue227_gettype_cte", + "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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py +index 5b251a70025b58252902149a321556bef8de30ca..6c1680ec4a8cbba52b30c25868b4b849d5b3a935 100644 +--- a/sqlparse/filters/others.py ++++ b/sqlparse/filters/others.py +@@ -15,45 +15,62 @@ + + @staticmethod + def _process(tlist): +- def get_next_comment(idx=0): ++ def get_next_comment(idx=-1): ++ # TODO(andi) Comment types should be unified, see related issue38 + return tlist.token_next_by(i=sql.Comment, t=T.Comment, idx=idx) + + def _get_insert_token(token): +- m = re.search(r'([\r\n]*) *$', token.value) ++ """Returns either a whitespace or the line breaks from token.""" ++ # See issue484 why line breaks should be preserved. ++ # Note: The actual value for a line break is replaced by \n ++ # in SerializerUnicode which will be executed in the ++ # postprocessing state. ++ m = re.search(r'([\r\n]+) *$', token.value) + if m is not None: + return sql.Token(T.Whitespace.Newline, m.groups()[0]) + else: +- return sql.Token(T.Whitespace, '\t') ++ return sql.Token(T.Whitespace, ' ') + +- sql_hints = (T.Comment.Multiline.Hint,) ++ sql_hints = (T.Comment.Multiline.Hint, T.Comment.Single.Hint) + tidx, token = get_next_comment() + while token: ++ # skipping token remove if token is a SQL-Hint. issue262 + is_sql_hint = False + if token.ttype in sql_hints: + is_sql_hint = True + elif isinstance(token, sql.Comment): + comment_tokens = token.tokens +- if len(comment_tokens) >= 0: ++ if len(comment_tokens) > 0: + if comment_tokens[0].ttype in sql_hints: + is_sql_hint = True + + if is_sql_hint: ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + continue + +- pidx, prev_ = tlist.token_prev(tidx, skip_ws=True) +- nidx, next_ = tlist.token_next(tidx, skip_ws=True) ++ pidx, prev_ = tlist.token_prev(tidx, skip_ws=False) ++ nidx, next_ = tlist.token_next(tidx, skip_ws=False) ++ # Replace by whitespace if prev and next exist and if they're not ++ # whitespaces. This doesn't apply if prev or next is a parenthesis. + if ( + prev_ is None or next_ is None +- or prev_.is_whitespace or prev_.match(T.Punctuation, ')') +- or next_.is_whitespace or next_.match(T.Punctuation, '(') ++ or prev_.is_whitespace or prev_.match(T.Punctuation, '(') ++ or next_.is_whitespace or next_.match(T.Punctuation, ')') + ): ++ # Insert a whitespace to ensure the following SQL produces ++ # a valid SQL (see #425). + if prev_ is not None and not prev_.match(T.Punctuation, '('): +- tlist.tokens.insert(tidx + 1, _get_insert_token(token)) ++ tlist.tokens.insert(tidx, _get_insert_token(token)) + tlist.tokens.remove(token) + else: +- tlist.tokens[tidx - 1] = _get_insert_token(token) ++ tlist.tokens[tidx] = _get_insert_token(token) + ++ # using current index as start index to search next token for ++ # preventing infinite loop in cases when token type is a ++ # "SQL-Hint" and has to be skipped + tidx, token = get_next_comment(idx=tidx) + + def process(self, stmt): +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__z994yg2s/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..6cb5249f743e4c6cf7c37c66661ec3308b1b0c82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "e1ac11e436ca86585d36f9721d67214aa782784cef89684ff12163655502bd1e", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "93e202f7f57835409830518f26767201a956db53e426abbb1109893bf16e8def", + "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": true, + "partial_repair_sha256": "623c673183870e905e478eda342da5a204ec078c1559ddd8cadadfb2c31cbcf6", + "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": "31a76475a6e61f9b422a90e62ee8e205ef339d37", + "source_completion_sha256": "117a63387474cf8db9b6a669586b24e32031b6934d5d2ef0338823f5eff43974", + "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_module__zqrr80g2", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "e0967a3f7a8af15a9ed0cd6b40de8963ad1385406b6e83543240b1b2abbe8020", + "is_fork": true, + "learner_path": "tasks/d4772a4a98f9e4fa61ebe175/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/31a76475a6e61f9b422a90e62ee8e205ef339d37/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": "c75ef4264b9f65faffcc8e6b24705c25be4bcfc5cd11f3c1cf6a706dae370d0a", + "provenance_path": "tasks/d4772a4a98f9e4fa61ebe175/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "31a76475a6e61f9b422a90e62ee8e205ef339d37", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "feb3fccc57d5fcc352b456c453e03fd5636e6c33", + "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_module__zqrr80g2", + "task_sha256": "afd72c0f525f84fc891b1ef59c3b29690475397674fbe0faf1ef0eed120d7e4a", + "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_module__zqrr80g2", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f71778042c2dcc1d709d2d9e44a75ac54fba7ef4 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/instruction.md @@ -0,0 +1,41 @@ +SQL formatting produces incorrect output with reindent=True + +#### Description + +When using `sqlparse.format()` with `reindent=True`, the formatted SQL output is completely broken and produces unexpected results. The formatting appears to be processing tokens in reverse order and using incorrect method names. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Simple SELECT statement +sql = "select * from foo where bar = 'test'" +formatted = sqlparse.format(sql, reindent=True) +print("Formatted:", repr(formatted)) +print("Expected: 'select *\\nfrom foo\\nwhere bar = 'test''") + +# Identifier list formatting +sql2 = "select 'abc' as foo, coalesce(col1, col2)||col3 as bar,col3 from my_table" +formatted2 = sqlparse.format(sql2, reindent=True) +print("Formatted:", repr(formatted2)) +``` + +The above code raises `AttributeError: 'list' object has no attribute 'lower'` instead of producing properly formatted SQL. + +#### Expected Behavior + +The formatter should produce properly indented SQL with newlines and appropriate spacing, such as: +```sql +select * +from foo +where bar = 'test' +``` + +#### Actual Behavior + +The code raises an AttributeError and fails to format the SQL properly. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..ba8d075a626870714259bd56596a192c33d3e8fa --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/metadata.json @@ -0,0 +1,534 @@ +{ + "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_cli.py::test_valid_args", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "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::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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "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" + ], + "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_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_joins", + "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::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "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_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": "feb3fccc57d5fcc352b456c453e03fd5636e6c33", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "31a76475a6e61f9b422a90e62ee8e205ef339d37" + }, + "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_grouping.py", + "/testbed/tests/test_keywords.py", + "/testbed/tests/test_parse.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_cli.py", + "tests/test_format.py", + "tests/test_regressions.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/aligned_indent.py", + "sqlparse/filters/reindent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 894452, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2", + "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_module__zqrr80g2", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "e0967a3f7a8af15a9ed0cd6b40de8963ad1385406b6e83543240b1b2abbe8020", + "is_fork": true, + "learner_path": "tasks/d4772a4a98f9e4fa61ebe175/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/31a76475a6e61f9b422a90e62ee8e205ef339d37/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": "c75ef4264b9f65faffcc8e6b24705c25be4bcfc5cd11f3c1cf6a706dae370d0a", + "provenance_path": "tasks/d4772a4a98f9e4fa61ebe175/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "31a76475a6e61f9b422a90e62ee8e205ef339d37", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "feb3fccc57d5fcc352b456c453e03fd5636e6c33", + "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_module__zqrr80g2", + "task_sha256": "afd72c0f525f84fc891b1ef59c3b29690475397674fbe0faf1ef0eed120d7e4a", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..f20d8afcfb4c25da749de4ea6c8ed8f0648f196d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "e1ac11e436ca86585d36f9721d67214aa782784cef89684ff12163655502bd1e", + "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/31a76475a6e61f9b422a90e62ee8e205ef339d37/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "117a63387474cf8db9b6a669586b24e32031b6934d5d2ef0338823f5eff43974", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "9c6801fcefdc5969f906be09017d1c28ff257ca8100170da221c182a8415f78a", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "e0967a3f7a8af15a9ed0cd6b40de8963ad1385406b6e83543240b1b2abbe8020", + "is_fork": true, + "learner_path": "tasks/d4772a4a98f9e4fa61ebe175/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/31a76475a6e61f9b422a90e62ee8e205ef339d37/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": "c75ef4264b9f65faffcc8e6b24705c25be4bcfc5cd11f3c1cf6a706dae370d0a", + "provenance_path": "tasks/d4772a4a98f9e4fa61ebe175/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "31a76475a6e61f9b422a90e62ee8e205ef339d37", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "feb3fccc57d5fcc352b456c453e03fd5636e6c33", + "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_module__zqrr80g2", + "task_sha256": "afd72c0f525f84fc891b1ef59c3b29690475397674fbe0faf1ef0eed120d7e4a", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..4794d8d68669b67f6a625cd50cea96bd06c3abde --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/provided-gold.diff @@ -0,0 +1,44 @@ +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index fc274e0691e915a694147afe60b7e00c8d600a4e..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -58,9 +58,10 @@ + tlist.insert_before(tlist[-1], self.nl()) + + def _process_identifierlist(self, tlist): ++ # columns being selected + identifiers = list(tlist.get_identifiers()) +- identifiers.pop() +- [tlist.insert_after(token, self.nl()) for token in identifiers] ++ identifiers.pop(0) ++ [tlist.insert_before(token, self.nl()) for token in identifiers] + self._process_default(tlist) + + def _process_case(self, tlist): +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index b6b65d77d91d6f2b93139a628379984389d500e3..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -42,8 +42,9 @@ + + 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( +@@ -97,8 +98,8 @@ + + def _process(self, tlist): + func_name = '_process_{cls}'.format(cls=type(tlist).__name__) +- func = getattr(self, func_name.upper(), self._process_default) +- func(tlist[::-1]) ++ func = getattr(self, func_name.lower(), self._process_default) ++ func(tlist) + + def _process_where(self, tlist): + tidx, token = tlist.token_next_by(m=(T.Keyword, 'WHERE')) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..db97a812f059ae98c897c6382894e3a5202c50c9 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/solution/solve.sh @@ -0,0 +1,50 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index fc274e0691e915a694147afe60b7e00c8d600a4e..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -58,9 +58,10 @@ + tlist.insert_before(tlist[-1], self.nl()) + + def _process_identifierlist(self, tlist): ++ # columns being selected + identifiers = list(tlist.get_identifiers()) +- identifiers.pop() +- [tlist.insert_after(token, self.nl()) for token in identifiers] ++ identifiers.pop(0) ++ [tlist.insert_before(token, self.nl()) for token in identifiers] + self._process_default(tlist) + + def _process_case(self, tlist): +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index b6b65d77d91d6f2b93139a628379984389d500e3..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -42,8 +42,9 @@ + + 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( +@@ -97,8 +98,8 @@ + + def _process(self, tlist): + func_name = '_process_{cls}'.format(cls=type(tlist).__name__) +- func = getattr(self, func_name.upper(), self._process_default) +- func(tlist[::-1]) ++ func = getattr(self, func_name.lower(), self._process_default) ++ func(tlist) + + def _process_where(self, tlist): + tidx, token = tlist.token_next_by(m=(T.Keyword, 'WHERE')) +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f14c258cf6909a9072b882395e3ef9206f9ec7d5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:2dc4b417742eda624a039290e74f022f8a02b8ccb4851cefb3234bc52a75f886" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..37b6fbaded96af6644f1a5a7fef46541e6ba24f8 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_cli.py::test_valid_args", + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "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::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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "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" + ], + "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_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_joins", + "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::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_token_next_doesnt_ignore_skip_cm", + "tests/test_regressions.py::test_issue284_as_grouping[AS]", + "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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index fc274e0691e915a694147afe60b7e00c8d600a4e..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -58,9 +58,10 @@ + tlist.insert_before(tlist[-1], self.nl()) + + def _process_identifierlist(self, tlist): ++ # columns being selected + identifiers = list(tlist.get_identifiers()) +- identifiers.pop() +- [tlist.insert_after(token, self.nl()) for token in identifiers] ++ identifiers.pop(0) ++ [tlist.insert_before(token, self.nl()) for token in identifiers] + self._process_default(tlist) + + def _process_case(self, tlist): +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zqrr80g2/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..7c95bcab53c6c58ce2fff74006c79823455bca26 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "822f5dc0b66dc4f55ed96fa6359e00eb0c09f6b467fc4f3dcb4b4ad927616839", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "506a8d91cef599eaed0a69afb52e289ac4ee5f45efbd3112c2fe5d00f834a036", + "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": true, + "partial_repair_sha256": "d50058c60b92436ab523f5600023742c0017514e075aedf850a3ad1bb1ffc798", + "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": "ba488e35122860e5a1e0f3032071eca0bb871e90", + "source_completion_sha256": "84556344ebd8bd41ac228de3ea0bd1b3cbc9f6558691b687b23b352e19da854f", + "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_module__zzigv9fs", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "984468da38f2baf0aa2d9b95d740e1188ce9c2e9ba1e251f6d60beed00ad281f", + "is_fork": true, + "learner_path": "tasks/a689bd049d2cbe216143d657/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/ba488e35122860e5a1e0f3032071eca0bb871e90/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": "575bf8ed8aa0b8395eaf31bd170dbc66ca7ae0c084096282c60f32a2ab80fe44", + "provenance_path": "tasks/a689bd049d2cbe216143d657/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ba488e35122860e5a1e0f3032071eca0bb871e90", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "2740bc8e0c9b6b7511c36ccc3b7414a30ea9e377", + "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_module__zzigv9fs", + "task_sha256": "40fdf2bb0f944601ce36842f209149688123035004e30cc92393d4d780a16764", + "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_module__zzigv9fs", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dadc9cf62a8c06adede92c4c483c89d6f4a463a4 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/instruction.md @@ -0,0 +1,43 @@ +# SQL formatting is broken with recent changes + +**Describe the bug** +The SQL formatting functionality is broken after recent changes. The indentation is completely wrong in many SQL statements, especially with GROUP BY, ORDER BY, and nested queries. + +**To Reproduce** +Try formatting a SQL query with GROUP BY or nested queries: + +```python +import sqlparse + +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 +""" + +print(sqlparse.format(sql, reindent=True)) +``` + +**Expected behavior** +The SQL should be properly indented with aligned columns and proper indentation for nested queries. + +**Actual behavior** +The indentation is completely wrong. The output has incorrect offsets, especially after keywords like GROUP BY, ORDER BY, etc. Nested queries and parenthesized expressions are also not indented correctly. + +**Your project** +No + +**Environment info** +- OS: Linux +- Python version: 3.10 +- sqlparse version: latest + +**Additional context** +This seems to be related to changes in the indentation calculation in the reindent and aligned_indent filters. The issue affects both the regular reindent and the aligned indentation modes. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..5469e81edc887a9d08b8938665aadcdb2526622c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/metadata.json @@ -0,0 +1,534 @@ +{ + "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::TestFormatReindentAligned::test_basic", + "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::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "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_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_issue207_runaway_format" + ], + "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_joins", + "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_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "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::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_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_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_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_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": "2740bc8e0c9b6b7511c36ccc3b7414a30ea9e377", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "ba488e35122860e5a1e0f3032071eca0bb871e90" + }, + "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_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", + "tests/test_regressions.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/aligned_indent.py", + "sqlparse/filters/reindent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 897893, + "task_id": "andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs", + "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_module__zzigv9fs", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "984468da38f2baf0aa2d9b95d740e1188ce9c2e9ba1e251f6d60beed00ad281f", + "is_fork": true, + "learner_path": "tasks/a689bd049d2cbe216143d657/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/ba488e35122860e5a1e0f3032071eca0bb871e90/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": "575bf8ed8aa0b8395eaf31bd170dbc66ca7ae0c084096282c60f32a2ab80fe44", + "provenance_path": "tasks/a689bd049d2cbe216143d657/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ba488e35122860e5a1e0f3032071eca0bb871e90", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "2740bc8e0c9b6b7511c36ccc3b7414a30ea9e377", + "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_module__zzigv9fs", + "task_sha256": "40fdf2bb0f944601ce36842f209149688123035004e30cc92393d4d780a16764", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..d9d320b302019afc903d4f76b35301870481317a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "822f5dc0b66dc4f55ed96fa6359e00eb0c09f6b467fc4f3dcb4b4ad927616839", + "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/ba488e35122860e5a1e0f3032071eca0bb871e90/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "84556344ebd8bd41ac228de3ea0bd1b3cbc9f6558691b687b23b352e19da854f", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "050e5986704e5a987be6fc74dc7adc97396e837a6ce7f59bc45c2e71b9d5ea41", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "984468da38f2baf0aa2d9b95d740e1188ce9c2e9ba1e251f6d60beed00ad281f", + "is_fork": true, + "learner_path": "tasks/a689bd049d2cbe216143d657/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/ba488e35122860e5a1e0f3032071eca0bb871e90/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": "575bf8ed8aa0b8395eaf31bd170dbc66ca7ae0c084096282c60f32a2ab80fe44", + "provenance_path": "tasks/a689bd049d2cbe216143d657/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ba488e35122860e5a1e0f3032071eca0bb871e90", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "2740bc8e0c9b6b7511c36ccc3b7414a30ea9e377", + "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_module__zzigv9fs", + "task_sha256": "40fdf2bb0f944601ce36842f209149688123035004e30cc92393d4d780a16764", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..9869bc91ca4a52146c64d134197b7e7524a7f10c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/provided-gold.diff @@ -0,0 +1,33 @@ +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index ad4e292448ecb2258eb5d77369ac9d883f0605e6..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -118,9 +118,10 @@ + for sgroup in tlist.get_sublists(): + idx = tlist.token_index(sgroup) + pidx, prev_ = tlist.token_prev(idx) +- offset_ = 2 if ( ++ # HACK: make "group/order by" work. Longer than max_len. ++ offset_ = 3 if ( + prev_ and prev_.match(T.Keyword, self.by_words, regex=True) +- ) else 1 ++ ) else 0 + with offset(self, offset_): + self._process(sgroup) + +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index f8125d7815f7b21e33137562964d054197ea07dd..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -42,8 +42,9 @@ + + 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( diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4619c5266ad2bc24a30b24ff01399a9130607e90 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/solution/solve.sh @@ -0,0 +1,39 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index ad4e292448ecb2258eb5d77369ac9d883f0605e6..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -118,9 +118,10 @@ + for sgroup in tlist.get_sublists(): + idx = tlist.token_index(sgroup) + pidx, prev_ = tlist.token_prev(idx) +- offset_ = 2 if ( ++ # HACK: make "group/order by" work. Longer than max_len. ++ offset_ = 3 if ( + prev_ and prev_.match(T.Keyword, self.by_words, regex=True) +- ) else 1 ++ ) else 0 + with offset(self, offset_): + self._process(sgroup) + +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index f8125d7815f7b21e33137562964d054197ea07dd..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -42,8 +42,9 @@ + + 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( +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ea290be76c3ae46aee46d369c7d031407eb5591f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:1858fb7a9dcf2be889854a9304a73bfc5eea69d77b52356fbd6f4a562c95a174" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..b8255cd34233e85b7ae6d5f1ce2faa35e27c2e25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "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::TestFormatReindent::test_parenthesis", + "tests/test_format.py::TestFormatReindent::test_where", + "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_long_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_nested_identifier_list", + "tests/test_format.py::TestFormatReindent::test_insert_values", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_issue207_runaway_format" + ], + "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_joins", + "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_join", + "tests/test_format.py::TestFormatReindent::test_identifier_list_with_functions", + "tests/test_format.py::TestFormatReindent::test_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "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::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_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_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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/filters/aligned_indent.py b/sqlparse/filters/aligned_indent.py +index ad4e292448ecb2258eb5d77369ac9d883f0605e6..dc60926390781758f50c0e01e190a60b1b794443 100644 +--- a/sqlparse/filters/aligned_indent.py ++++ b/sqlparse/filters/aligned_indent.py +@@ -118,9 +118,10 @@ + for sgroup in tlist.get_sublists(): + idx = tlist.token_index(sgroup) + pidx, prev_ = tlist.token_prev(idx) +- offset_ = 2 if ( ++ # HACK: make "group/order by" work. Longer than max_len. ++ offset_ = 3 if ( + prev_ and prev_.match(T.Keyword, self.by_words, regex=True) +- ) else 1 ++ ) else 0 + with offset(self, offset_): + self._process(sgroup) + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.combine_module__zzigv9fs/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..8be6c8cb6fb3cfc187c5cafaf02865032b7e1dea --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "8a2b396e80f593bf660def72e65a7e7b0ac3f009044ecc109f020198e91f6199", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "ca56cd9baee96c887f4cfec1ac71a532998a9f974d24415766d29643b8734c91", + "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": "64ad2a5f5cb9fef03c5f135dbace9d314ca32ed2", + "source_completion_sha256": "384d67ac2d518b9a9b64c30f4aeaf34c112191ab1828703b1a134abb106bb5ea", + "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.func_basic__07jpr8n3", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "fb010d4f72c39960bcd6a864fc713f97dca9b395824de94940de568b3bef101a", + "is_fork": true, + "learner_path": "tasks/4dcf07eb1727bb4fd4016ad7/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/64ad2a5f5cb9fef03c5f135dbace9d314ca32ed2/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": "18fbc7f0bb05f3762df2418a23a61545f34e89aae25931945dd398185752d73a", + "provenance_path": "tasks/4dcf07eb1727bb4fd4016ad7/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "64ad2a5f5cb9fef03c5f135dbace9d314ca32ed2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a3fc2d74540e7165ffa397798f7b4b0d16f82f43", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3", + "task_sha256": "2ef2a32427df8041b4711458af9b6fffe9ca15e787171577abf047a9f5114796", + "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.func_basic__07jpr8n3", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e54e0c0b2ccea5d114d67135d318ee8c761631f4 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/instruction.md @@ -0,0 +1,33 @@ +Comment grouping broken for single-line comments + +#### Description + +Single-line comments (both `--` and `#` style) are not being properly grouped or parsed, causing various operations to fail with `TypeError: unsupported operand type(s)` errors. + +#### Steps/Code to Reproduce + +```python +import sqlparse +from sqlparse import tokens as T + +# This should parse a single comment token but fails +sql = "--hello" +parsed = sqlparse.parse(sql)[0] +print(f"Number of tokens: {len(parsed.tokens)}") +print(f"Token type: {parsed.tokens[0].ttype}") + +# Strip comments also fails +sql = "SELECT foo; -- comment" +result = sqlparse.format(sql, strip_comments=True) +print(f"Result: {result}") +``` + +Expected behavior: Single-line comments should be grouped into single Comment tokens and strip_comments should work properly. + +Actual behavior: Various TypeError exceptions are raised during comment processing. + +The issue affects both dash-style (`--`) and hash-style (`#`) single-line comments, with and without trailing newlines. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..5587419b0b540a0ce9c0a4443a843702e56191c3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/metadata.json @@ -0,0 +1,533 @@ +{ + "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::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "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_issue38", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_split.py::test_split_comment_end_of_line" + ], + "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_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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_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_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "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_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_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": "a3fc2d74540e7165ffa397798f7b4b0d16f82f43", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "64ad2a5f5cb9fef03c5f135dbace9d314ca32ed2" + }, + "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_keywords.py", + "/testbed/tests/test_parse.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", + "tests/test_grouping.py", + "tests/test_regressions.py", + "tests/test_split.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/engine/grouping.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 868063, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3", + "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.func_basic__07jpr8n3", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "fb010d4f72c39960bcd6a864fc713f97dca9b395824de94940de568b3bef101a", + "is_fork": true, + "learner_path": "tasks/4dcf07eb1727bb4fd4016ad7/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/64ad2a5f5cb9fef03c5f135dbace9d314ca32ed2/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": "18fbc7f0bb05f3762df2418a23a61545f34e89aae25931945dd398185752d73a", + "provenance_path": "tasks/4dcf07eb1727bb4fd4016ad7/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "64ad2a5f5cb9fef03c5f135dbace9d314ca32ed2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a3fc2d74540e7165ffa397798f7b4b0d16f82f43", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3", + "task_sha256": "2ef2a32427df8041b4711458af9b6fffe9ca15e787171577abf047a9f5114796", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..8ee589ecd8ccca8a97c0a7afb6d9bd7da6cacb76 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "8a2b396e80f593bf660def72e65a7e7b0ac3f009044ecc109f020198e91f6199", + "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/64ad2a5f5cb9fef03c5f135dbace9d314ca32ed2/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "384d67ac2d518b9a9b64c30f4aeaf34c112191ab1828703b1a134abb106bb5ea", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "cc32e1a98637496a5311cd3658501e2d16d7e56ee47663def97bc4d98f3f459d", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "fb010d4f72c39960bcd6a864fc713f97dca9b395824de94940de568b3bef101a", + "is_fork": true, + "learner_path": "tasks/4dcf07eb1727bb4fd4016ad7/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/64ad2a5f5cb9fef03c5f135dbace9d314ca32ed2/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": "18fbc7f0bb05f3762df2418a23a61545f34e89aae25931945dd398185752d73a", + "provenance_path": "tasks/4dcf07eb1727bb4fd4016ad7/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "64ad2a5f5cb9fef03c5f135dbace9d314ca32ed2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a3fc2d74540e7165ffa397798f7b4b0d16f82f43", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3", + "task_sha256": "2ef2a32427df8041b4711458af9b6fffe9ca15e787171577abf047a9f5114796", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..faae06b4741c2f800b03b41d512ffd529d77f161 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/provided-gold.diff @@ -0,0 +1,21 @@ +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index 7924c6057013a5dbfe6debc5d83c26d0e3fd4000..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -314,12 +314,12 @@ + tidx, token = tlist.token_next_by(t=T.Comment) + while token: + eidx, end = tlist.token_not_matching( +- lambda tk: imt(tk, t=T.Comment) and not tk.is_newline, idx=tidx) +- if end is None: +- eidx, end = tlist.token_next(eidx, skip_ws=True) ++ lambda tk: imt(tk, t=T.Comment) or tk.is_newline, idx=tidx) ++ if end is not None: ++ eidx, end = tlist.token_prev(eidx, skip_ws=False) + tlist.group_tokens(sql.Comment, tidx, eidx) + +- tidx, token = tlist.token_next_by(t=T.Comment, idx=eidx) ++ tidx, token = tlist.token_next_by(t=T.Comment, idx=tidx) + + + @recurse(sql.Where) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..57ab0535b586eb3054d600b777cad29678ad3e51 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/solution/solve.sh @@ -0,0 +1,27 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index 7924c6057013a5dbfe6debc5d83c26d0e3fd4000..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -314,12 +314,12 @@ + tidx, token = tlist.token_next_by(t=T.Comment) + while token: + eidx, end = tlist.token_not_matching( +- lambda tk: imt(tk, t=T.Comment) and not tk.is_newline, idx=tidx) +- if end is None: +- eidx, end = tlist.token_next(eidx, skip_ws=True) ++ lambda tk: imt(tk, t=T.Comment) or tk.is_newline, idx=tidx) ++ if end is not None: ++ eidx, end = tlist.token_prev(eidx, skip_ws=False) + tlist.group_tokens(sql.Comment, tidx, eidx) + +- tidx, token = tlist.token_next_by(t=T.Comment, idx=eidx) ++ tidx, token = tlist.token_next_by(t=T.Comment, idx=tidx) + + + @recurse(sql.Where) +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f280fa174f723a080340a51445e788ee155df066 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:2760e15c0188de249d63a27400c062505feb50d9414bd33830c0f9fbec337f51" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..025e44feac3d1b2716ec80d93daa4a7978a2fe5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "tests/test_grouping.py::test_grouping_identifier_list_with_inline_comments", + "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_issue38", + "tests/test_regressions.py::test_format_accepts_encoding", + "tests/test_split.py::test_split_comment_end_of_line" + ], + "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_preserves_linebreak", + "tests/test_format.py::TestFormat::test_strip_comments_preserves_whitespace", + "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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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_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_issue34[create]", + "tests/test_regressions.py::test_issue34[CREATE]", + "tests/test_regressions.py::test_issue35", + "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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__07jpr8n3/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..5bcd924b1112fb53f68a52bb75b88ed84f93b01a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "c2081d9a05118fb25f0b5f850de86b23e9dcd12b2a2a12628b54b810f1bcbba2", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "b6acde72ebbbe6f48fa2f50699fb122d279eb7cca553af7d1f0d1bce5b265d0a", + "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": "d8a21e56d4b9abbc81055a93a2e027498fb79b4e", + "source_completion_sha256": "44243f1813d39c04b6ce38f2844b1f871a06674cd1b3440d5dff8285a9c1f6c2", + "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.func_basic__0k84oqtu", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "c1e683debd0a21a540b949a6b3284811d14c56672d451f00c7c586ab4780aa49", + "is_fork": true, + "learner_path": "tasks/914b47d959370b2b2751c40c/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/d8a21e56d4b9abbc81055a93a2e027498fb79b4e/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": "56afe83e0ebc496901777f3a52b800e2ee1dc5a0569a1da4f6de0afcb384b0a9", + "provenance_path": "tasks/914b47d959370b2b2751c40c/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d8a21e56d4b9abbc81055a93a2e027498fb79b4e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "653fa8887d9748bf32e73e0e9d52f120951b08b2", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu", + "task_sha256": "efd448136f5e1324b740fd4df4428ed7045cf7e6d6b0426047a1a1cb853ecf6e", + "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.func_basic__0k84oqtu", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..40e97ce932c831cc437ddb0fb1e4038fceedd100 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/instruction.md @@ -0,0 +1,29 @@ +SQL formatting with reindent returns None instead of formatted string + +#### Description + +When using `sqlparse.format()` with `reindent=True`, the function returns `None` instead of the expected formatted SQL string. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Simple single statement +sql = 'select foo' +result = sqlparse.format(sql, reindent=True) +print(f"Result: {result}") +print(f"Expected: select foo") + +# Multiple statements +sql = 'select foo; select bar' +result = sqlparse.format(sql, reindent=True) +print(f"Result: {result}") +print(f"Expected: select foo;\n\nselect bar") +``` + +The code above prints `None` for both cases instead of the formatted SQL strings. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..774c2281a6db18876274966fdf56ce6c24d5b351 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/metadata.json @@ -0,0 +1,533 @@ +{ + "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::TestFormatReindent::test_stmts" + ], + "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_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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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": "653fa8887d9748bf32e73e0e9d52f120951b08b2", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "d8a21e56d4b9abbc81055a93a2e027498fb79b4e" + }, + "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/reindent.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 913057, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu", + "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.func_basic__0k84oqtu", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "c1e683debd0a21a540b949a6b3284811d14c56672d451f00c7c586ab4780aa49", + "is_fork": true, + "learner_path": "tasks/914b47d959370b2b2751c40c/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/d8a21e56d4b9abbc81055a93a2e027498fb79b4e/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": "56afe83e0ebc496901777f3a52b800e2ee1dc5a0569a1da4f6de0afcb384b0a9", + "provenance_path": "tasks/914b47d959370b2b2751c40c/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d8a21e56d4b9abbc81055a93a2e027498fb79b4e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "653fa8887d9748bf32e73e0e9d52f120951b08b2", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu", + "task_sha256": "efd448136f5e1324b740fd4df4428ed7045cf7e6d6b0426047a1a1cb853ecf6e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..b6e2d1614e8c9d01e4580f724b7afd62f3da0935 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "c2081d9a05118fb25f0b5f850de86b23e9dcd12b2a2a12628b54b810f1bcbba2", + "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/d8a21e56d4b9abbc81055a93a2e027498fb79b4e/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "44243f1813d39c04b6ce38f2844b1f871a06674cd1b3440d5dff8285a9c1f6c2", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "5223f2078b645ba5cecff2ed5f6242dd7de7532695da1d438e0e82f34ff90f70", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "c1e683debd0a21a540b949a6b3284811d14c56672d451f00c7c586ab4780aa49", + "is_fork": true, + "learner_path": "tasks/914b47d959370b2b2751c40c/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/d8a21e56d4b9abbc81055a93a2e027498fb79b4e/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": "56afe83e0ebc496901777f3a52b800e2ee1dc5a0569a1da4f6de0afcb384b0a9", + "provenance_path": "tasks/914b47d959370b2b2751c40c/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d8a21e56d4b9abbc81055a93a2e027498fb79b4e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "653fa8887d9748bf32e73e0e9d52f120951b08b2", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu", + "task_sha256": "efd448136f5e1324b740fd4df4428ed7045cf7e6d6b0426047a1a1cb853ecf6e", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..d64a0f648d2cf88db66fb15a9f8f3d1193cd44da --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/provided-gold.diff @@ -0,0 +1,16 @@ +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 551be26703346076d56022c568c53d69920508a5..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -240,8 +240,8 @@ + self._process(stmt) + + if self._last_stmt is not None: +- nl = '\n' if str(stmt).endswith('\n') else '\n\n' ++ nl = '\n' if str(self._last_stmt).endswith('\n') else '\n\n' + stmt.tokens.insert(0, sql.Token(T.Whitespace, nl)) + +- self._last_stmt = None +- return None ++ self._last_stmt = stmt ++ return stmt diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ffa15fd56a6305a6cb9173fb1e713a1ad8452cb1 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/solution/solve.sh @@ -0,0 +1,22 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py +index 551be26703346076d56022c568c53d69920508a5..7dc2b82a37b19694b3c22ab3e98d3ffefa88ed12 100644 +--- a/sqlparse/filters/reindent.py ++++ b/sqlparse/filters/reindent.py +@@ -240,8 +240,8 @@ + self._process(stmt) + + if self._last_stmt is not None: +- nl = '\n' if str(stmt).endswith('\n') else '\n\n' ++ nl = '\n' if str(self._last_stmt).endswith('\n') else '\n\n' + stmt.tokens.insert(0, sql.Token(T.Whitespace, nl)) + +- self._last_stmt = None +- return None ++ self._last_stmt = stmt ++ return stmt +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2659dda34e8b4392383d5b689a8c661ae77ed278 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:667c5ed3c8d9b8571f4ea0536e416e88ceada53fc90215bd4dda42c18cc8c12c" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..6c90bb2e2ff16dd398b887b6ce5ddd29adfb76a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormatReindent::test_stmts" + ], + "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_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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0k84oqtu/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..0d835d9c4ac3f3469c01f9b064b15389d820785a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "710844b262b15b10fd4e91ada33dc539279000d4aff2abb7aac3b17dc1ad307f", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "f7785d8b08df102acf8fa247ec6280cb71e2839f205fa6f5c16fbd4a0de8db3f", + "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": "ba7b24b1144fe13a7c1f6199ecb602009521d9d7", + "source_completion_sha256": "730aced9ed19365be2944a540af628ef4d89d596921a4692d65f5ed3c15f5919", + "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.func_basic__0mum3b07", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "41412821505861e6c0c110706347c93e0394ccf4d32f6e1cd27504bf7ff1113f", + "is_fork": true, + "learner_path": "tasks/3b97daa0ef5057a8a1856aff/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/ba7b24b1144fe13a7c1f6199ecb602009521d9d7/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": "616dd5ea9b61a3cabff3cc425d239e2cc2cde7fdb164b30ecb1efd16a964be2d", + "provenance_path": "tasks/3b97daa0ef5057a8a1856aff/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ba7b24b1144fe13a7c1f6199ecb602009521d9d7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "0a5e5fbe20b16c2b3d5b8757e8acf1dd0278d9de", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07", + "task_sha256": "1d751ce173d4fee61af5b9f554b98de641124a09bb0f14776ddf3036cdb4c097", + "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.func_basic__0mum3b07", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1ac3fd41d6c08305592868859abf47b62dbc772b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/instruction.md @@ -0,0 +1,39 @@ +Recurse decorator not working correctly for sublists + +Description + +The `recurse` decorator in `utils.py` is not properly traversing sublists. When using functions decorated with `@recurse`, the recursion logic appears to be inverted - it's only processing sublists that match the specified class types instead of processing all sublists except those types. + +Steps/Code to Reproduce + +```python +import sqlparse + +# Simple function call should be grouped as Function +sql = 'foo()' +parsed = sqlparse.parse(sql)[0] +print(f"Token type: {type(parsed.tokens[0])}") +# Expected: +# Actual: + +# Parenthesis grouping also affected +sql = '(where 1)' +parsed = sqlparse.parse(sql)[0] +print(f"Number of tokens: {len(parsed.tokens)}") +print(f"Token type: {type(parsed.tokens[0])}") +# Expected: 1 token of type Parenthesis +# Actual: Multiple tokens, not properly grouped + +# Nested structures not being processed +sql = 'select (select (x3) x2) and (y2) bar' +parsed = sqlparse.parse(sql)[0] +print(f"Parsed correctly: {str(parsed) == sql}") +# Expected: True +# Actual: False +``` + +The issue affects various SQL parsing operations including function grouping, parenthesis grouping, and identifier parsing. Complex nested structures are particularly impacted. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..6825e1ee9c41e49a877796d389f226a3588bd4df --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/metadata.json @@ -0,0 +1,533 @@ +{ + "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_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_grouping_function", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_pprint", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue39" + ], + "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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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_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_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_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_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_param_single_literal", + "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_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_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_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": "0a5e5fbe20b16c2b3d5b8757e8acf1dd0278d9de", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "ba7b24b1144fe13a7c1f6199ecb602009521d9d7" + }, + "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_format.py", + "/testbed/tests/test_keywords.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_grouping.py", + "tests/test_parse.py", + "tests/test_regressions.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/utils.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 884305, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07", + "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.func_basic__0mum3b07", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "41412821505861e6c0c110706347c93e0394ccf4d32f6e1cd27504bf7ff1113f", + "is_fork": true, + "learner_path": "tasks/3b97daa0ef5057a8a1856aff/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/ba7b24b1144fe13a7c1f6199ecb602009521d9d7/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": "616dd5ea9b61a3cabff3cc425d239e2cc2cde7fdb164b30ecb1efd16a964be2d", + "provenance_path": "tasks/3b97daa0ef5057a8a1856aff/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ba7b24b1144fe13a7c1f6199ecb602009521d9d7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "0a5e5fbe20b16c2b3d5b8757e8acf1dd0278d9de", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07", + "task_sha256": "1d751ce173d4fee61af5b9f554b98de641124a09bb0f14776ddf3036cdb4c097", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..62f0b258f238809769238b36104c246b490b1249 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "710844b262b15b10fd4e91ada33dc539279000d4aff2abb7aac3b17dc1ad307f", + "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/ba7b24b1144fe13a7c1f6199ecb602009521d9d7/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "730aced9ed19365be2944a540af628ef4d89d596921a4692d65f5ed3c15f5919", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "b3f5dcc08acb00d5db942e79fa44b59a743ede148d961ce013697747305a0697", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "41412821505861e6c0c110706347c93e0394ccf4d32f6e1cd27504bf7ff1113f", + "is_fork": true, + "learner_path": "tasks/3b97daa0ef5057a8a1856aff/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/ba7b24b1144fe13a7c1f6199ecb602009521d9d7/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": "616dd5ea9b61a3cabff3cc425d239e2cc2cde7fdb164b30ecb1efd16a964be2d", + "provenance_path": "tasks/3b97daa0ef5057a8a1856aff/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ba7b24b1144fe13a7c1f6199ecb602009521d9d7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "0a5e5fbe20b16c2b3d5b8757e8acf1dd0278d9de", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07", + "task_sha256": "1d751ce173d4fee61af5b9f554b98de641124a09bb0f14776ddf3036cdb4c097", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..03b9e9c199cb7ffbf77a1b62d448dc69720461cd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/provided-gold.diff @@ -0,0 +1,13 @@ +diff --git a/sqlparse/utils.py b/sqlparse/utils.py +index 508fc7a9afc71d8902fcb31952d2525ce49edbfa..58c0245a7566c14102fa921b0fee35d7f8fa061c 100644 +--- a/sqlparse/utils.py ++++ b/sqlparse/utils.py +@@ -69,7 +69,7 @@ + def wrap(f): + def wrapped_f(tlist): + for sgroup in tlist.get_sublists(): +- if isinstance(sgroup, cls): ++ if not isinstance(sgroup, cls): + wrapped_f(sgroup) + f(tlist) + diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c05aa977ac9a3ae4ce9cbf8e88092b20323f0c02 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/solution/solve.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/utils.py b/sqlparse/utils.py +index 508fc7a9afc71d8902fcb31952d2525ce49edbfa..58c0245a7566c14102fa921b0fee35d7f8fa061c 100644 +--- a/sqlparse/utils.py ++++ b/sqlparse/utils.py +@@ -69,7 +69,7 @@ + def wrap(f): + def wrapped_f(tlist): + for sgroup in tlist.get_sublists(): +- if isinstance(sgroup, cls): ++ if not isinstance(sgroup, cls): + wrapped_f(sgroup) + f(tlist) + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f7de3dd5524fdc52434de293b2454edcaf9a0157 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:7b1b9a93a27cb54703176ddef4bccb33b3302644b5915b01954c6eeada69d619" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..4050de0c2f433f2dc4d24e58be26fb6e866e2661 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_grouping.py::test_grouping_parenthesis", + "tests/test_grouping.py::test_grouping_identifier_function", + "tests/test_grouping.py::test_grouping_nested_identifier_with_order", + "tests/test_grouping.py::test_grouping_where", + "tests/test_grouping.py::test_grouping_function", + "tests/test_parse.py::test_parse_function_parameter", + "tests/test_parse.py::test_parse_nested_function", + "tests/test_parse.py::test_pprint", + "tests/test_regressions.py::test_issue9", + "tests/test_regressions.py::test_issue39" + ], + "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_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "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_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_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_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_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_param_single_literal", + "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_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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0mum3b07/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..b7a2985dc81c90842f005ab50544260b4626946a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "741e79468e4a2637689d821f8bf46d5aa36ad68c790e6bcebf6183f7b5a2a409", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "057f61a3251ab4c1d5e7166b148b74c3947a52d284ed1f75e7d1120490ff8334", + "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": true, + "partial_repair_sha256": "f0d0f742e7f19303800cb91da50434fc0535fb7158719f9111c497bfab8e0a1d", + "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": "f0dc168f4595815f6f5f8a489d9d225a779f2704", + "source_completion_sha256": "25c422b477ef89a2af450865173d1430fa7a3d650761b7ece1b1fe720bc57ecb", + "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.func_basic__0p5g34u4", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f4f53111f5630fd42915b063b8ee6577d0ec2ebc0ad121d26d34a8007356370c", + "is_fork": true, + "learner_path": "tasks/e7481b05930fc68174015ac1/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/f0dc168f4595815f6f5f8a489d9d225a779f2704/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": "94257bb4646d3e22e587e37b3899bb90f21b0c339271ba28aae53de6a528f3e8", + "provenance_path": "tasks/e7481b05930fc68174015ac1/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f0dc168f4595815f6f5f8a489d9d225a779f2704", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "89b8e741ea4f1f8c49cebc741e915505988ef94b", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4", + "task_sha256": "31ca9303f9b196294da7ab39087f72784151f54de257a4d0b2f9f8e9aef5b183", + "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.func_basic__0p5g34u4", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4033d5deb86777e78992181defd2095cc53f4171 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/instruction.md @@ -0,0 +1,38 @@ +Output format options broken - python format returns PHP and spaces around operators inverted + +#### Description + +The SQL formatter is not working correctly for output format options and spaces around operators. When using `output_format='python'`, it returns PHP-formatted output instead. Also, the `use_space_around_operators` option appears to be inverted - it adds spaces when set to False and doesn't add spaces when set to True. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Python output format returns PHP format instead +sql = 'select * from foo;' +result = sqlparse.format(sql, output_format='python') +print("Expected: sql = 'select * from foo;'") +print(f"Got: {result}") + +# PHP output format doesn't work at all +result_php = sqlparse.format(sql, output_format='php') +print("Expected: $sql = \"select * from foo;\";") +print(f"Got: {result_php}") + +# Spaces around operators inverted behavior +sql2 = 'select a*b-c from table' +result_spaces = sqlparse.format(sql2, use_space_around_operators=True) +print("Expected with spaces: select a * b - c from table") +print(f"Got: {result_spaces}") + +result_no_spaces = sqlparse.format(sql2, use_space_around_operators=False) +print("Expected without spaces: select a*b-c from table") +print(f"Got: {result_no_spaces}") +``` + +The output shows that python format returns PHP syntax, PHP format returns unformatted SQL, and the spaces option works backwards from what you'd expect. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..5be188859d1417008d752451d7ea3c6284f38eae --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/metadata.json @@ -0,0 +1,533 @@ +{ + "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::TestFormat::test_strip_comments_preserves_hint", + "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_identifier_list_with_functions", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_json_ops" + ], + "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_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::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_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_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": "89b8e741ea4f1f8c49cebc741e915505988ef94b", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "f0dc168f4595815f6f5f8a489d9d225a779f2704" + }, + "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/formatter.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 913143, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4", + "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.func_basic__0p5g34u4", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f4f53111f5630fd42915b063b8ee6577d0ec2ebc0ad121d26d34a8007356370c", + "is_fork": true, + "learner_path": "tasks/e7481b05930fc68174015ac1/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/f0dc168f4595815f6f5f8a489d9d225a779f2704/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": "94257bb4646d3e22e587e37b3899bb90f21b0c339271ba28aae53de6a528f3e8", + "provenance_path": "tasks/e7481b05930fc68174015ac1/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f0dc168f4595815f6f5f8a489d9d225a779f2704", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "89b8e741ea4f1f8c49cebc741e915505988ef94b", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4", + "task_sha256": "31ca9303f9b196294da7ab39087f72784151f54de257a4d0b2f9f8e9aef5b183", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..5790b1b7b013ac329b3469fca6a91c9f9c24f285 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "741e79468e4a2637689d821f8bf46d5aa36ad68c790e6bcebf6183f7b5a2a409", + "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/f0dc168f4595815f6f5f8a489d9d225a779f2704/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "25c422b477ef89a2af450865173d1430fa7a3d650761b7ece1b1fe720bc57ecb", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "7198f404efe31c43ee2844a6f6fc6b5021caeed21a0b926fade543627ddecd4f", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "f4f53111f5630fd42915b063b8ee6577d0ec2ebc0ad121d26d34a8007356370c", + "is_fork": true, + "learner_path": "tasks/e7481b05930fc68174015ac1/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/f0dc168f4595815f6f5f8a489d9d225a779f2704/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": "94257bb4646d3e22e587e37b3899bb90f21b0c339271ba28aae53de6a528f3e8", + "provenance_path": "tasks/e7481b05930fc68174015ac1/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "f0dc168f4595815f6f5f8a489d9d225a779f2704", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "89b8e741ea4f1f8c49cebc741e915505988ef94b", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4", + "task_sha256": "31ca9303f9b196294da7ab39087f72784151f54de257a4d0b2f9f8e9aef5b183", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..8faef4f867e4dd6890acb0ab24cff21a3606724d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/provided-gold.diff @@ -0,0 +1,35 @@ +diff --git a/sqlparse/formatter.py b/sqlparse/formatter.py +index 5cfd80d2cad96bf673ef23fa03a255565cb094dd..72f2c19edc371a993b7e7a6481826cf22d5b3d9f 100644 +--- a/sqlparse/formatter.py ++++ b/sqlparse/formatter.py +@@ -154,13 +154,13 @@ + stack.preprocess.append(filters.TruncateStringFilter( + width=options['truncate_strings'], char=options['truncate_char'])) + +- # Altered the condition to unchecked state +- if not options.get('use_space_around_operators', False): ++ if options.get('use_space_around_operators', False): + stack.enable_grouping() + stack.stmtprocess.append(filters.SpacesAroundOperatorsFilter()) + +- # Removed enable_grouping() call for strip_comments ++ # After grouping + if options.get('strip_comments'): ++ stack.enable_grouping() + stack.stmtprocess.append(filters.StripCommentsFilter()) + + if options.get('strip_whitespace') or options.get('reindent'): +@@ -192,9 +192,10 @@ + # Serializer + if options.get('output_format'): + frmt = options['output_format'] +- # Removed case for 'php' +- if frmt.lower() == 'python': +- fltr = filters.OutputPHPFilter() # Intentional misassignment ++ if frmt.lower() == 'php': ++ fltr = filters.OutputPHPFilter() ++ elif frmt.lower() == 'python': ++ fltr = filters.OutputPythonFilter() + else: + fltr = None + if fltr is not None: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..701e040238fed1221206f2f7974788d281844684 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/solution/solve.sh @@ -0,0 +1,41 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/formatter.py b/sqlparse/formatter.py +index 5cfd80d2cad96bf673ef23fa03a255565cb094dd..72f2c19edc371a993b7e7a6481826cf22d5b3d9f 100644 +--- a/sqlparse/formatter.py ++++ b/sqlparse/formatter.py +@@ -154,13 +154,13 @@ + stack.preprocess.append(filters.TruncateStringFilter( + width=options['truncate_strings'], char=options['truncate_char'])) + +- # Altered the condition to unchecked state +- if not options.get('use_space_around_operators', False): ++ if options.get('use_space_around_operators', False): + stack.enable_grouping() + stack.stmtprocess.append(filters.SpacesAroundOperatorsFilter()) + +- # Removed enable_grouping() call for strip_comments ++ # After grouping + if options.get('strip_comments'): ++ stack.enable_grouping() + stack.stmtprocess.append(filters.StripCommentsFilter()) + + if options.get('strip_whitespace') or options.get('reindent'): +@@ -192,9 +192,10 @@ + # Serializer + if options.get('output_format'): + frmt = options['output_format'] +- # Removed case for 'php' +- if frmt.lower() == 'python': +- fltr = filters.OutputPHPFilter() # Intentional misassignment ++ if frmt.lower() == 'php': ++ fltr = filters.OutputPHPFilter() ++ elif frmt.lower() == 'python': ++ fltr = filters.OutputPythonFilter() + else: + fltr = None + if fltr is not None: +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..13c14df866da63c42915eb635d8a8b6558444b76 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:b1b60719b0d9fb94075cc8479354c6d22fce79af1dfec1d95f57ac5f06c18fd4" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..ee831a67c2d15565d2d3364f6bfc895300b4f32d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormat::test_strip_comments_preserves_hint", + "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_identifier_list_with_functions", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_json_ops" + ], + "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_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::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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/sqlparse/formatter.py b/sqlparse/formatter.py +index 5cfd80d2cad96bf673ef23fa03a255565cb094dd..72f2c19edc371a993b7e7a6481826cf22d5b3d9f 100644 +--- a/sqlparse/formatter.py ++++ b/sqlparse/formatter.py +@@ -154,13 +154,13 @@ + stack.preprocess.append(filters.TruncateStringFilter( + width=options['truncate_strings'], char=options['truncate_char'])) + +- # Altered the condition to unchecked state +- if not options.get('use_space_around_operators', False): ++ if options.get('use_space_around_operators', False): + stack.enable_grouping() + stack.stmtprocess.append(filters.SpacesAroundOperatorsFilter()) + +- # Removed enable_grouping() call for strip_comments ++ # After grouping + if options.get('strip_comments'): ++ stack.enable_grouping() + stack.stmtprocess.append(filters.StripCommentsFilter()) + + if options.get('strip_whitespace') or options.get('reindent'): +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/validation/canaries/original-bug.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/validation/openenv.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0p5g34u4/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "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" + ] + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/LICENSE.source b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..de414c55796725b86b89c2a5d1aa34e72ff4b258 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/LICENSE.source @@ -0,0 +1,25 @@ +Copyright (c) 2016, Andi Albrecht +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..c3ec20acdb7306dd7483f8908f6c722a02a03bf8 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "d5c8bd23b9d0b3e2c365da2a6429032cd66f6c098cecb4fa7121886f510f5c71", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "55c26a155df9cc5515397720f47a23b465d26256abf013c44e9f36f57c966f4a", + "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": "18a8e2e447a2e73e6c54d40443cd951a8e7fcd61", + "source_completion_sha256": "9cc3a89b33abc8f4a0e1af33de03d193a79e8f15c2477d700a952a40a9a4a99a", + "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.func_basic__0q0uf0jj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "3a5f26584416c157f9569870dcc423e696f2fbc6308579ab408c1fd6c2ee8769", + "is_fork": true, + "learner_path": "tasks/168b93734be86047b351c185/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/18a8e2e447a2e73e6c54d40443cd951a8e7fcd61/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": "4f36891d961fad28e90774bbfc7fec8c1ea9fafd8af2b8265e8820191865e83b", + "provenance_path": "tasks/168b93734be86047b351c185/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "18a8e2e447a2e73e6c54d40443cd951a8e7fcd61", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "49ab444ba0f774983a699cf3db54e9b260a2f9e1", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj", + "task_sha256": "0c36ecb349805bbab57ffe99b680e4b3e0c9078270db08bfec1aa0759cfc1d9c", + "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.func_basic__0q0uf0jj", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cc285b6bcb86abaeab6c627bc743d2afc16342e0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/instruction.md @@ -0,0 +1,39 @@ +IdentifierList grouping returns wrong token indices + +#### Description + +When parsing SQL with identifier lists, the grouping function returns incorrect token indices, causing IndexError when trying to access tokens during formatting operations. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Simple identifier list +sql = "select foo, bar from table" +parsed = sqlparse.parse(sql)[0] +print(parsed.tokens) + +# This will cause issues during formatting +formatted = sqlparse.format(sql, reindent=True) +print(formatted) +``` + +The issue also occurs with more complex queries: + +```python +sql = "select a, b, c from table group by a, b, c" +formatted = sqlparse.format(sql, reindent=True) +``` + +#### Expected Behavior + +The formatter should properly handle identifier lists and return correctly formatted SQL without raising IndexError. + +#### Actual Behavior + +IndexError: pop from empty list is raised during formatting operations involving identifier lists. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..b213e9d12af8fe07d09ca07dd705ae7cc84aaddd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/metadata.json @@ -0,0 +1,533 @@ +{ + "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::TestFormatReindentAligned::test_basic", + "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::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_nested_identifier_list", + "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::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "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_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_pprint", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_tokenize.py::test_tokenlist_repr" + ], + "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_joins", + "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_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_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_identifiers_with_operators", + "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_comparison_exclude", + "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_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_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_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_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_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_except_formatting", + "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_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_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_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": "49ab444ba0f774983a699cf3db54e9b260a2f9e1", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "18a8e2e447a2e73e6c54d40443cd951a8e7fcd61" + }, + "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_keywords.py", + "/testbed/tests/test_split.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", + "tests/test_grouping.py", + "tests/test_parse.py", + "tests/test_regressions.py", + "tests/test_tokenize.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/engine/grouping.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 849511, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj", + "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.func_basic__0q0uf0jj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "3a5f26584416c157f9569870dcc423e696f2fbc6308579ab408c1fd6c2ee8769", + "is_fork": true, + "learner_path": "tasks/168b93734be86047b351c185/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/18a8e2e447a2e73e6c54d40443cd951a8e7fcd61/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": "4f36891d961fad28e90774bbfc7fec8c1ea9fafd8af2b8265e8820191865e83b", + "provenance_path": "tasks/168b93734be86047b351c185/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "18a8e2e447a2e73e6c54d40443cd951a8e7fcd61", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "49ab444ba0f774983a699cf3db54e9b260a2f9e1", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj", + "task_sha256": "0c36ecb349805bbab57ffe99b680e4b3e0c9078270db08bfec1aa0759cfc1d9c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..e7040a0e89842c10da183a9c0eeba1fe698b85c0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "d5c8bd23b9d0b3e2c365da2a6429032cd66f6c098cecb4fa7121886f510f5c71", + "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/18a8e2e447a2e73e6c54d40443cd951a8e7fcd61/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "9cc3a89b33abc8f4a0e1af33de03d193a79e8f15c2477d700a952a40a9a4a99a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "afddf2add87d37994b1f0e06c5d0f7c1aa22a69338e5c24a8915995c6125c9b7", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "3a5f26584416c157f9569870dcc423e696f2fbc6308579ab408c1fd6c2ee8769", + "is_fork": true, + "learner_path": "tasks/168b93734be86047b351c185/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/18a8e2e447a2e73e6c54d40443cd951a8e7fcd61/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": "4f36891d961fad28e90774bbfc7fec8c1ea9fafd8af2b8265e8820191865e83b", + "provenance_path": "tasks/168b93734be86047b351c185/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "18a8e2e447a2e73e6c54d40443cd951a8e7fcd61", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "49ab444ba0f774983a699cf3db54e9b260a2f9e1", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj", + "task_sha256": "0c36ecb349805bbab57ffe99b680e4b3e0c9078270db08bfec1aa0759cfc1d9c", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..7039d5f3b8f36c3f4ac297cdb8b73912f1206679 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/provided-gold.diff @@ -0,0 +1,13 @@ +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index ec0c8d38a33479ce825dd11575fb7a4925b3c6c3..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -302,7 +302,7 @@ + return imt(token, i=sqlcls, m=m_role, t=ttypes) + + def post(tlist, pidx, tidx, nidx): +- return nidx, pidx ++ return pidx, nidx + + valid_prev = valid_next = valid + _group(tlist, sql.IdentifierList, match, diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5bc85e0e560381f804923dc6fdf8d2da98c1762a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/solution/solve.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/engine/grouping.py b/sqlparse/engine/grouping.py +index ec0c8d38a33479ce825dd11575fb7a4925b3c6c3..a63f4da2c52e23024524be280eb7198f1dae8e58 100644 +--- a/sqlparse/engine/grouping.py ++++ b/sqlparse/engine/grouping.py +@@ -302,7 +302,7 @@ + return imt(token, i=sqlcls, m=m_role, t=ttypes) + + def post(tlist, pidx, tidx, nidx): +- return nidx, pidx ++ return pidx, nidx + + valid_prev = valid_next = valid + _group(tlist, sql.IdentifierList, match, +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8c60fdb27e14bf77399896a878daf4cb882646b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:049d4069f7cc3e4f2274a839eccf8ff42cdbcbc8aba832b557796c2a1b053bb1" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..9cb26b6999d5739c73853b904c5fd9eca9109f67 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormatReindentAligned::test_basic", + "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::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_nested_identifier_list", + "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::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_grouping.py::test_grouping_identifiers", + "tests/test_grouping.py::test_grouping_identifier_wildcard", + "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_identifier_list_with_order", + "tests/test_grouping.py::test_grouping_idlist_function", + "tests/test_grouping.py::test_grouping_function", + "tests/test_grouping.py::test_identifier_consumes_ordering", + "tests/test_parse.py::test_parse_square_brackets_notation_isnt_too_greedy", + "tests/test_parse.py::test_sqlite_identifiers", + "tests/test_parse.py::test_pprint", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_issue90", + "tests/test_regressions.py::test_null_with_as", + "tests/test_regressions.py::test_issue227_gettype_cte", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_format_invalid_where_clause", + "tests/test_tokenize.py::test_tokenlist_repr" + ], + "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_joins", + "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_case", + "tests/test_format.py::TestFormatReindent::test_case2", + "tests/test_format.py::TestFormatReindent::test_duplicate_linebreaks", + "tests/test_format.py::TestOutputFormat::test_python", + "tests/test_format.py::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_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_identifiers_with_operators", + "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_comparison_exclude", + "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_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_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_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_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_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_except_formatting", + "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_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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted-inventory.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..83b02a3a53553c0e8e3575436ca87d51176f6b9e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted-inventory.json @@ -0,0 +1,152 @@ +{ + "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" + } + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_split.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f1429ed7edacd5cf6e5da5ef1efeb6ca1f3ad3 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_split.py @@ -0,0 +1,210 @@ +# Tests splitting functions. + +import types +from 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) == 1 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_tokenize.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec12d8341f50b410f74a09091ae32ea6158dc9b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0q0uf0jj/tests/trusted/tests/test_tokenize.py @@ -0,0 +1,247 @@ +import types +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import lexer +from 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 = " +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" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/adapter.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..289d33003931a8c833936890c20cf258254aa316 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/adapter.json @@ -0,0 +1,126 @@ +{ + "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": "241d80a31afd269b8953a99473540dd226ba8b7c72d1b13e26a0d42bf4831878", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "e13015d66834756d892a4ffca6bf6abe05afa7aab8834788a940d5acf72d9218", + "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": "387d245c860638cf258e876012cfff8a80866b3e", + "source_completion_sha256": "90f65b49ef42595cc5faa162779b23a78a370a3de6b189f5b994cdf35ca30d2e", + "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.func_basic__0ytgxfff", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "a512fddf4b763a6520897b68915e6735c8b847b97c440fc9afcebd92ada78d20", + "is_fork": true, + "learner_path": "tasks/2b31a5f1dd2027c06a7a3a2c/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/387d245c860638cf258e876012cfff8a80866b3e/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": "f0e1db7cb7b6ac9635d1a8e2f96393c9171ec0e775e86f19755bfb7caed8271a", + "provenance_path": "tasks/2b31a5f1dd2027c06a7a3a2c/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "387d245c860638cf258e876012cfff8a80866b3e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "1622b3e85fd0572c020a8159427676af8890cc48", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff", + "task_sha256": "dafcd9630720c93428f92fc2a002b45bd02205a0bc8e1f2d895e5bc47a2cbb81", + "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.func_basic__0ytgxfff", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "andialbrecht/sqlparse" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/dependency-setup.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a96f4a95c3e8a02a91bbd0297b071a6558fdf82 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install pytest diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/environment/Dockerfile b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/instruction.md b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..06979e8a532972973e3762c5d7b7d51b05d18e39 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/instruction.md @@ -0,0 +1,27 @@ +StripWhitespaceFilter removes first token instead of trailing whitespace + +When using sqlparse formatting with whitespace stripping, the filter incorrectly removes the first token from SQL statements instead of properly handling trailing whitespace. This causes SQL queries to be malformed and lose their initial keywords or identifiers. + +#### Steps/Code to Reproduce + +```python +import sqlparse + +# Simple SELECT statement +sql = "SELECT id, name FROM table" +formatted = sqlparse.format(sql, strip_whitespace=True) +print("Expected:", sql) +print("Actual :", formatted) + +# With reindent option +sql2 = "SELECT id, name FROM (SELECT id, name FROM bar) as foo" +formatted2 = sqlparse.format(sql2, reindent=True) +print("Expected: proper formatting") +print("Actual :", formatted2) +``` + +The output shows that the first token (like "SELECT") gets removed from the statement, breaking the SQL syntax completely. + +## 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 `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/metadata.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..594bb1e1f0648c51f78d20e7c859a064002c2a64 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/metadata.json @@ -0,0 +1,533 @@ +{ + "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::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_preserve_ws", + "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::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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue213_leadingws", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "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" + ], + "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_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_invalid_option", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "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::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_issue227_gettype_cte", + "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_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_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": "1622b3e85fd0572c020a8159427676af8890cc48", + "healthy": "d802518f3673051449163fc84fe1455448f79b3b", + "learner": "387d245c860638cf258e876012cfff8a80866b3e" + }, + "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_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", + "tests/test_regressions.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/others.py" + ], + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_stages_bytes": 898383, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff", + "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.func_basic__0ytgxfff", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "a512fddf4b763a6520897b68915e6735c8b847b97c440fc9afcebd92ada78d20", + "is_fork": true, + "learner_path": "tasks/2b31a5f1dd2027c06a7a3a2c/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/387d245c860638cf258e876012cfff8a80866b3e/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": "f0e1db7cb7b6ac9635d1a8e2f96393c9171ec0e775e86f19755bfb7caed8271a", + "provenance_path": "tasks/2b31a5f1dd2027c06a7a3a2c/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "387d245c860638cf258e876012cfff8a80866b3e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "1622b3e85fd0572c020a8159427676af8890cc48", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff", + "task_sha256": "dafcd9630720c93428f92fc2a002b45bd02205a0bc8e1f2d895e5bc47a2cbb81", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "andialbrecht/sqlparse", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/provenance.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..589b8e69714c648594e078b47959501dad7aee08 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "241d80a31afd269b8953a99473540dd226ba8b7c72d1b13e26a0d42bf4831878", + "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/387d245c860638cf258e876012cfff8a80866b3e/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "90f65b49ef42595cc5faa162779b23a78a370a3de6b189f5b994cdf35ca30d2e", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "94ac5f9f02e6d9c0e51173f58e081cb6ccee4aa32602c4e3184b7922436f12aa", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "d802518f3673051449163fc84fe1455448f79b3b", + "instruction_sha256": "a512fddf4b763a6520897b68915e6735c8b847b97c440fc9afcebd92ada78d20", + "is_fork": true, + "learner_path": "tasks/2b31a5f1dd2027c06a7a3a2c/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/387d245c860638cf258e876012cfff8a80866b3e/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": "f0e1db7cb7b6ac9635d1a8e2f96393c9171ec0e775e86f19755bfb7caed8271a", + "provenance_path": "tasks/2b31a5f1dd2027c06a7a3a2c/source-proof.json", + "repository_lineage": [ + "swesmith/andialbrecht__sqlparse.e57923b3", + "andialbrecht/sqlparse" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "387d245c860638cf258e876012cfff8a80866b3e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "1622b3e85fd0572c020a8159427676af8890cc48", + "source_kind": "mutation", + "source_repo": "swesmith/andialbrecht__sqlparse.e57923b3", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff", + "task_sha256": "dafcd9630720c93428f92fc2a002b45bd02205a0bc8e1f2d895e5bc47a2cbb81", + "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" +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/provided-gold.diff b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..4820fcae3f5f167a628d9c17ff032896fe131657 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/provided-gold.diff @@ -0,0 +1,18 @@ +diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py +index b2fa8075e27fd95ff558b19a6046296d055674e3..6c1680ec4a8cbba52b30c25868b4b849d5b3a935 100644 +--- a/sqlparse/filters/others.py ++++ b/sqlparse/filters/others.py +@@ -121,10 +121,10 @@ + self._stripws_default(tlist) + + def process(self, stmt, depth=0): +- [self.process(sgroup, depth) for sgroup in stmt.get_sublists()] # removed + 1 ++ [self.process(sgroup, depth + 1) for sgroup in stmt.get_sublists()] + self._stripws(stmt) +- if depth == 0 or (stmt.tokens and stmt.tokens[0].is_whitespace): # changed 'and' to 'or' and check first token +- stmt.tokens.pop(0) # pop the first token instead of the last ++ if depth == 0 and stmt.tokens and stmt.tokens[-1].is_whitespace: ++ stmt.tokens.pop(-1) + return stmt + + diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/solution/solve.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..cdc1da6a1c84d86cf34923fae1719b470b01f679 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/solution/solve.sh @@ -0,0 +1,24 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/sqlparse/filters/others.py b/sqlparse/filters/others.py +index b2fa8075e27fd95ff558b19a6046296d055674e3..6c1680ec4a8cbba52b30c25868b4b849d5b3a935 100644 +--- a/sqlparse/filters/others.py ++++ b/sqlparse/filters/others.py +@@ -121,10 +121,10 @@ + self._stripws_default(tlist) + + def process(self, stmt, depth=0): +- [self.process(sgroup, depth) for sgroup in stmt.get_sublists()] # removed + 1 ++ [self.process(sgroup, depth + 1) for sgroup in stmt.get_sublists()] + self._stripws(stmt) +- if depth == 0 or (stmt.tokens and stmt.tokens[0].is_whitespace): # changed 'and' to 'or' and check first token +- stmt.tokens.pop(0) # pop the first token instead of the last ++ if depth == 0 and stmt.tokens and stmt.tokens[-1].is_whitespace: ++ stmt.tokens.pop(-1) + return stmt + + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/task.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b90ae057188ab15fa42e47446d0bd0f568f003cc --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:59d1bbaf22aaad8f5f40734b51800bf721f5fa29656e2ea9243de2916cc6323c" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/check_pytest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3977e41867a5171bd0ba40de1f1c904875c55e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/check_pytest.py @@ -0,0 +1,91 @@ +"""Distinguish real pytest failures from missing/setup/verifier evidence.""" + +import argparse +import json +import re +import xml.etree.ElementTree as ET +from 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" 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" + ) diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/expected-panels.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..47200ea800f3db79ffb747b9d17d1d59bd4140f8 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/expected-panels.json @@ -0,0 +1,337 @@ +{ + "fail-to-pass": [ + "tests/test_format.py::TestFormat::test_strip_comments_multi", + "tests/test_format.py::TestFormat::test_strip_ws", + "tests/test_format.py::TestFormat::test_preserve_ws", + "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::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_python", + "tests/test_format.py::TestOutputFormat::test_php", + "tests/test_format.py::test_format_column_ordering", + "tests/test_format.py::test_having_produces_newline", + "tests/test_format.py::test_format_json_ops", + "tests/test_format.py::test_strip_ws_removes_trailing_ws_in_groups", + "tests/test_regressions.py::test_issue35", + "tests/test_regressions.py::test_issue40", + "tests/test_regressions.py::test_comment_encoding_when_reindent", + "tests/test_regressions.py::test_parse_sql_with_binary", + "tests/test_regressions.py::test_format_accepts_encoding", + "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_issue213_leadingws", + "tests/test_regressions.py::test_issue207_runaway_format", + "tests/test_regressions.py::test_issue315_utf8_by_default", + "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" + ], + "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_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_invalid_option", + "tests/test_format.py::TestFormat::test_notransform_of_quoted_crlf", + "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::TestOutputFormat::test_python_multiple_statements", + "tests/test_format.py::TestOutputFormat::test_sql", + "tests/test_format.py::TestOutputFormat::test_invalid_option", + "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_format_right_margin_invalid_option[ten]", + "tests/test_format.py::test_format_right_margin_invalid_option[2]", + "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_issue38", + "tests/test_regressions.py::test_issue39", + "tests/test_regressions.py::test_issue83", + "tests/test_regressions.py::test_dont_alias_keywords", + "tests/test_regressions.py::test_stream", + "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_issue227_gettype_cte", + "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_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_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]" + ] +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/grade.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from 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") diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/panel-config.json b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..0300198d40af683c40bf078966b1387596186f25 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/panel-config.json @@ -0,0 +1,22 @@ +{ + "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" + } +} diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/test.sh b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/pyproject.toml b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..229f344d3650805f40ebd76567d116f8ab8af683 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/pyproject.toml @@ -0,0 +1,104 @@ +[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 = true +parallel = true +omit = [ + "sqlparse/__main__.py", +] + +[tool.coverage.paths] +sqlparse = ["sqlparse"] +tests = ["tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/__init__.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/conftest.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..939c481d3a172b2737a4029288650bc028b08e2d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/conftest.py @@ -0,0 +1,47 @@ +"""Helpers for testing.""" + +import io +import 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_stream diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/_Make_DirEntry.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/_Make_DirEntry.sql new file mode 100644 index 0000000000000000000000000000000000000000..e877bf123833736b2c90c509dcb3dd71444d08e5 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/_Make_DirEntry.sql @@ -0,0 +1,6 @@ +-- Make a new dir entry +-- and return its inode + + +INSERT INTO dir_entries(type) + VALUES(:type) \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/begintag.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/begintag.sql new file mode 100644 index 0000000000000000000000000000000000000000..699b3659631264867cadb15a3a4c92bbc7306973 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/begintag.sql @@ -0,0 +1,4 @@ +begin; +update foo + set bar = 1; +commit; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/begintag_2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/begintag_2.sql new file mode 100644 index 0000000000000000000000000000000000000000..0de26d666d2d8a403b6ed5030cbf148f47593713 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/begintag_2.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/casewhen_procedure.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/casewhen_procedure.sql new file mode 100644 index 0000000000000000000000000000000000000000..e590d49b8bb11a3b2e5e66fb9240900ed1d66055 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/casewhen_procedure.sql @@ -0,0 +1,8 @@ +create procedure procName() +begin + select case when column = 'value' then column else 0 end; +end; +create procedure procName() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/dashcomment.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/dashcomment.sql new file mode 100644 index 0000000000000000000000000000000000000000..0d5ac62c66b4e5cb9ef3e3e6dca64a94c674b548 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/dashcomment.sql @@ -0,0 +1,5 @@ +select * from user; +--select * from host; +select * from user; +select * -- foo; +from foo; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/encoding_gbk.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/encoding_gbk.sql new file mode 100644 index 0000000000000000000000000000000000000000..a61322965963077f90bdcb4c73376f98f843fc0a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/encoding_gbk.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '²»ÒÔÎïϲ£¬²»ÒԼº±¯' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/encoding_utf8.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/encoding_utf8.sql new file mode 100644 index 0000000000000000000000000000000000000000..26e7ad45fe04af709b1d7b13f9ef1cd27491f8fd --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/encoding_utf8.sql @@ -0,0 +1,3 @@ +select * +from foo +where bar = '齐天大圣.カラフルな雲.사랑해요' \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function.sql new file mode 100644 index 0000000000000000000000000000000000000000..d19227f0f3186b3f8f79ca53f5c16547275fe9a7 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function.sql @@ -0,0 +1,13 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql.sql new file mode 100644 index 0000000000000000000000000000000000000000..e485f7a121e43c99c9c646103e88bfce9f92a245 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql.sql @@ -0,0 +1,72 @@ +CREATE 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; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql2.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql2.sql new file mode 100644 index 0000000000000000000000000000000000000000..b5d494cc484b2222e9da2583605cc25b4af82a77 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql2.sql @@ -0,0 +1,7 @@ +CREATE OR REPLACE FUNCTION update_something() RETURNS void AS +$body$ +BEGIN + raise notice 'foo'; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql3.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql3.sql new file mode 100644 index 0000000000000000000000000000000000000000..b25d81892e69e60d4345a5e94112df600da8d28e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql3.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION foo() RETURNS integer AS +$body$ +DECLARE +BEGIN + select * from foo; +END; +$body$ +LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql4.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql4.sql new file mode 100644 index 0000000000000000000000000000000000000000..02900a6f262d46945f5a0765823e31e330e6019d --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/function_psql4.sql @@ -0,0 +1,12 @@ +CREATE FUNCTION doubledollarinbody(var1 text) RETURNS text +/* see issue277 */ +LANGUAGE plpgsql +AS $_$ +DECLARE + str text; + BEGIN + str = $$'foo'$$||var1; + execute 'select '||str into str; + return str; + END +$_$; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/huge_select.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/huge_select.sql new file mode 100644 index 0000000000000000000000000000000000000000..ab39823b6fc4e6301af6e23119a600427aa10466 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/huge_select.sql @@ -0,0 +1 @@ +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 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 \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/multiple_case_in_begin.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/multiple_case_in_begin.sql new file mode 100644 index 0000000000000000000000000000000000000000..6cbb3864e043e7c0d1fa6928ca2b44a21dc552d0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/multiple_case_in_begin.sql @@ -0,0 +1,8 @@ +CREATE TRIGGER mytrig +AFTER UPDATE OF vvv ON mytable +BEGIN + UPDATE aa + SET mycola = (CASE WHEN (A=1) THEN 2 END); + UPDATE bb + SET mycolb = (CASE WHEN (B=1) THEN 5 END); +END; \ No newline at end of file diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/mysql_handler.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/mysql_handler.sql new file mode 100644 index 0000000000000000000000000000000000000000..702374ef71b339ca51ef82f62e58667b68ffef5f --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/mysql_handler.sql @@ -0,0 +1,10 @@ +create procedure proc1() +begin + declare handler for foo begin end; + select 1; +end; + +create procedure proc2() +begin + select 1; +end; diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/stream.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/stream.sql new file mode 100644 index 0000000000000000000000000000000000000000..c1b73b03abc9b14aa957bf936dcfba5406112001 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/stream.sql @@ -0,0 +1,2 @@ +-- this file is streamed in +insert into foo diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/test_cp1251.sql b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/test_cp1251.sql new file mode 100644 index 0000000000000000000000000000000000000000..6c0228b7d194ff72bb64b0523107aa160c196c3e --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/files/test_cp1251.sql @@ -0,0 +1 @@ +insert into foo values (1); -- Ïåñíÿ ïðî íàäåæäó diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_cli.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c1f2b040b4829e3a2159b0132a1afd286f7d8c --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_cli.py @@ -0,0 +1,122 @@ +import subprocess +import 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_format.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..4dae299de80828cf9b25b03d038ddadde0a51828 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_format.py @@ -0,0 +1,774 @@ +import pytest + +import sqlparse +from 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 == expected diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_grouping.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..88b762cd64eb888ca6e445f6afbef540f441ae8b --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_grouping.py @@ -0,0 +1,679 @@ +import pytest + +import sqlparse +from 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" diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_keywords.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..b26e9b45ae815b7789ae4717eb58766ed47032a0 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_keywords.py @@ -0,0 +1,13 @@ +import pytest + +from sqlparse import tokens +from 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 == ttype diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_parse.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..b49dcca3718169d11edbc10762241926ef1ddd60 --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_parse.py @@ -0,0 +1,595 @@ +"""Tests sqlparse.parse().""" +from io import StringIO + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T, keywords +from 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.Operator diff --git a/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_regressions.py b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_regressions.py new file mode 100644 index 0000000000000000000000000000000000000000..b32889018b4720ba2e95768f2cb8030eb97fe12a --- /dev/null +++ b/tasks/andialbrecht__sqlparse.e57923b3.func_basic__0ytgxfff/tests/trusted/tests/test_regressions.py @@ -0,0 +1,467 @@ +import copy +import sys + +import pytest + +import sqlparse +from sqlparse import sql, tokens as T +from 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 INSERT +TO public.ruled_tab +DO 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.fixture +def 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)