diff --git a/.github/dependabot.yml b/.github/dependabot.yml index e870ec5..3b39bf5 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -10,6 +10,8 @@ updates: commit-message: prefix: "deps" open-pull-requests-limit: 10 + cooldown: + default-days: 7 groups: rust-dependencies: patterns: @@ -25,6 +27,8 @@ updates: commit-message: prefix: "ci" open-pull-requests-limit: 5 + cooldown: + default-days: 7 groups: github-actions: patterns: diff --git a/.github/workflows/_audit.yml b/.github/workflows/_audit.yml index 8e5b80b..ca2adbd 100644 --- a/.github/workflows/_audit.yml +++ b/.github/workflows/_audit.yml @@ -3,6 +3,9 @@ name: Security Audit +permissions: + contents: read + on: workflow_call: inputs: diff --git a/.github/workflows/_build.yml b/.github/workflows/_build.yml index bbd49d5..9005029 100644 --- a/.github/workflows/_build.yml +++ b/.github/workflows/_build.yml @@ -3,6 +3,9 @@ name: Build Release +permissions: + contents: read + on: workflow_call: inputs: @@ -19,7 +22,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/_changelog.yml b/.github/workflows/_changelog.yml deleted file mode 100644 index 44344ab..0000000 --- a/.github/workflows/_changelog.yml +++ /dev/null @@ -1,38 +0,0 @@ -# SPDX-FileCopyrightText: 2025 RAprogramm -# SPDX-License-Identifier: MIT - -name: Update Changelog - -on: - workflow_call: - -jobs: - changelog: - name: Update Changelog - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - token: ${{ secrets.GITHUB_TOKEN }} - - - name: Generate changelog - uses: orhun/git-cliff-action@a9a95522b26fe6403f7bb24031f21fb573d0f5ff # v4.9.1 - with: - config: cliff.toml - args: --verbose - env: - OUTPUT: CHANGELOG.md - - - name: Commit changelog - run: | - git config user.name "github-actions[bot]" - git config user.email "github-actions[bot]@users.noreply.github.com" - git add CHANGELOG.md - if git diff --staged --quiet; then - echo "No changes to commit" - else - git commit -m "docs: update changelog [skip ci]" - git pull --rebase origin main - git push - fi diff --git a/.github/workflows/_clippy.yml b/.github/workflows/_clippy.yml index 1b564ee..7d373ca 100644 --- a/.github/workflows/_clippy.yml +++ b/.github/workflows/_clippy.yml @@ -3,6 +3,9 @@ name: Clippy +permissions: + contents: read + on: workflow_call: inputs: @@ -19,7 +22,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable components: clippy diff --git a/.github/workflows/_deny.yml b/.github/workflows/_deny.yml index fb96167..f1ee2bb 100644 --- a/.github/workflows/_deny.yml +++ b/.github/workflows/_deny.yml @@ -3,6 +3,9 @@ name: Dependency Check +permissions: + contents: read + on: workflow_call: inputs: diff --git a/.github/workflows/_detect.yml b/.github/workflows/_detect.yml index 1c932ac..015e555 100644 --- a/.github/workflows/_detect.yml +++ b/.github/workflows/_detect.yml @@ -3,6 +3,9 @@ name: Detect Changes +permissions: + contents: read + on: workflow_call: outputs: diff --git a/.github/workflows/_doc.yml b/.github/workflows/_doc.yml index 0b79c98..f8c8d78 100644 --- a/.github/workflows/_doc.yml +++ b/.github/workflows/_doc.yml @@ -3,6 +3,9 @@ name: Documentation +permissions: + contents: read + on: workflow_call: inputs: @@ -19,7 +22,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/_doctest.yml b/.github/workflows/_doctest.yml index 611283f..2c62977 100644 --- a/.github/workflows/_doctest.yml +++ b/.github/workflows/_doctest.yml @@ -3,6 +3,9 @@ name: Doctests +permissions: + contents: read + on: workflow_call: inputs: @@ -19,7 +22,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/_fmt.yml b/.github/workflows/_fmt.yml index d9456b6..e10527d 100644 --- a/.github/workflows/_fmt.yml +++ b/.github/workflows/_fmt.yml @@ -3,6 +3,9 @@ name: Format +permissions: + contents: read + on: workflow_call: inputs: @@ -19,7 +22,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: nightly components: rustfmt diff --git a/.github/workflows/_machete.yml b/.github/workflows/_machete.yml index db2e950..7b5837d 100644 --- a/.github/workflows/_machete.yml +++ b/.github/workflows/_machete.yml @@ -3,6 +3,9 @@ name: Unused Dependencies +permissions: + contents: read + on: workflow_call: inputs: @@ -19,7 +22,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/_msrv.yml b/.github/workflows/_msrv.yml index 362639e..8659a3f 100644 --- a/.github/workflows/_msrv.yml +++ b/.github/workflows/_msrv.yml @@ -3,6 +3,9 @@ name: MSRV +permissions: + contents: read + on: workflow_call: inputs: @@ -21,8 +24,8 @@ jobs: persist-credentials: false - name: Get MSRV from Cargo.toml id: msrv - run: echo "version=$(grep '^rust-version' Cargo.toml | sed 's/.*= *\"\([^\"]*\)\".*/\1/')" >> $GITHUB_OUTPUT - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + run: echo "version=$(grep '^rust-version' Cargo.toml | sed 's/.*= *\"\([^\"]*\)\".*/\1/')" >> "$GITHUB_OUTPUT" + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: ${{ steps.msrv.outputs.version }} - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/_pr-size.yml b/.github/workflows/_pr-size.yml index 7537f3e..54f2d91 100644 --- a/.github/workflows/_pr-size.yml +++ b/.github/workflows/_pr-size.yml @@ -3,6 +3,9 @@ name: PR Size Check +permissions: + contents: read + on: workflow_call: inputs: @@ -15,6 +18,9 @@ jobs: name: PR Size Check runs-on: ubuntu-latest if: github.event_name == 'pull_request' && inputs.rust_changed == 'true' + permissions: + contents: read + pull-requests: write steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: diff --git a/.github/workflows/_publish.yml b/.github/workflows/_publish.yml deleted file mode 100644 index 1a461f4..0000000 --- a/.github/workflows/_publish.yml +++ /dev/null @@ -1,38 +0,0 @@ -# SPDX-FileCopyrightText: 2025 RAprogramm -# SPDX-License-Identifier: MIT - -name: Publish to crates.io - -on: - workflow_call: - inputs: - new_tag: - required: true - type: string - secrets: - CRATES_IO_TOKEN: - required: true - -jobs: - publish: - name: Publish to crates.io - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master - with: - toolchain: stable - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 - - name: Publish - run: | - output=$(cargo publish --token ${{ secrets.CRATES_IO_TOKEN }} --allow-dirty 2>&1) || { - if echo "$output" | grep -q "already exists"; then - echo "::notice::Version already published to crates.io" - exit 0 - else - echo "$output" - exit 1 - fi - } diff --git a/.github/workflows/_qual.yml b/.github/workflows/_qual.yml index 38a0ca4..8693163 100644 --- a/.github/workflows/_qual.yml +++ b/.github/workflows/_qual.yml @@ -3,6 +3,9 @@ name: Quality Check +permissions: + contents: read + on: workflow_call: inputs: diff --git a/.github/workflows/_release-build.yml b/.github/workflows/_release-build.yml deleted file mode 100644 index c85c19d..0000000 --- a/.github/workflows/_release-build.yml +++ /dev/null @@ -1,86 +0,0 @@ -# SPDX-FileCopyrightText: 2025 RAprogramm -# SPDX-License-Identifier: MIT - -name: Release Build - -on: - workflow_call: - inputs: - new_tag: - required: true - type: string - -jobs: - release-build: - name: Release Build ${{ matrix.target }} - runs-on: ${{ matrix.os }} - strategy: - fail-fast: false - matrix: - include: - - target: x86_64-unknown-linux-gnu - os: ubuntu-latest - archive: tar.gz - cross: false - - target: x86_64-unknown-linux-musl - os: ubuntu-latest - archive: tar.gz - cross: true - - target: aarch64-unknown-linux-gnu - os: ubuntu-latest - archive: tar.gz - cross: true - - target: x86_64-apple-darwin - os: macos-latest - archive: tar.gz - cross: false - - target: aarch64-apple-darwin - os: macos-latest - archive: tar.gz - cross: false - - target: x86_64-pc-windows-msvc - os: windows-latest - archive: zip - cross: false - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master - with: - toolchain: stable - targets: ${{ matrix.target }} - - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 - with: - key: release-${{ matrix.target }} - - - name: Install cross - if: matrix.cross - run: cargo install cross --git https://github.com/cross-rs/cross - - - name: Build with cross - if: matrix.cross - run: cross build --release --target ${{ matrix.target }} - - - name: Build with cargo - if: ${{ !matrix.cross }} - run: cargo build --release --target ${{ matrix.target }} - - - name: Package (Unix) - if: matrix.os != 'windows-latest' - run: | - cd target/${{ matrix.target }}/release - tar czf ../../../sql-query-analyzer-${{ matrix.target }}.tar.gz sql-query-analyzer - - - name: Package (Windows) - if: matrix.os == 'windows-latest' - run: | - cd target/${{ matrix.target }}/release - Compress-Archive -Path sql-query-analyzer.exe -DestinationPath ../../../sql-query-analyzer-${{ matrix.target }}.zip - - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: sql-query-analyzer-${{ matrix.target }} - path: sql-query-analyzer-${{ matrix.target }}.${{ matrix.archive }} diff --git a/.github/workflows/_release.yml b/.github/workflows/_release.yml deleted file mode 100644 index 46601a7..0000000 --- a/.github/workflows/_release.yml +++ /dev/null @@ -1,87 +0,0 @@ -# SPDX-FileCopyrightText: 2025 RAprogramm -# SPDX-License-Identifier: MIT - -name: Create Release - -on: - workflow_call: - inputs: - new_tag: - required: true - type: string - version: - required: true - type: string - -jobs: - release: - name: Create Release - runs-on: ubuntu-latest - permissions: - contents: write - id-token: write - attestations: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Generate release notes - uses: orhun/git-cliff-action@a9a95522b26fe6403f7bb24031f21fb573d0f5ff # v4.9.1 - with: - config: cliff.toml - args: --verbose --latest --strip header - env: - OUTPUT: RELEASE_NOTES.md - - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - path: artifacts - - - name: Package crate - run: cargo package --no-verify --allow-dirty - - - name: Locate .crate file - id: artefact - run: | - set -euo pipefail - crate=$(find target/package -maxdepth 1 -name '*.crate' -print -quit) - if [ -z "$crate" ]; then - echo "::error::No .crate file produced under target/package" >&2 - exit 1 - fi - echo "path=$crate" >> "$GITHUB_OUTPUT" - - - name: Generate CycloneDX SBOM - uses: anchore/sbom-action@66cbf4bc1f1c0d2edc94016e65bc221b6bb0ad6c # v0.24.3 - with: - path: ./ - format: cyclonedx-json - output-file: sql-query-analyzer-sbom.cdx.json - upload-artifact: false - upload-release-assets: false - - - name: Generate build provenance attestation - id: attest - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 - with: - subject-path: | - ${{ steps.artefact.outputs.path }} - sql-query-analyzer-sbom.cdx.json - - - name: Stage provenance bundle - env: - BUNDLE: ${{ steps.attest.outputs.bundle-path }} - run: cp "$BUNDLE" sql-query-analyzer-provenance.sigstore.json - - - name: Create Release - uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4 - with: - tag_name: v${{ inputs.version }} - body_path: RELEASE_NOTES.md - files: | - artifacts/**/* - sql-query-analyzer-sbom.cdx.json - sql-query-analyzer-provenance.sigstore.json - ${{ steps.artefact.outputs.path }} diff --git a/.github/workflows/_reuse.yml b/.github/workflows/_reuse.yml index abaece8..9458828 100644 --- a/.github/workflows/_reuse.yml +++ b/.github/workflows/_reuse.yml @@ -3,6 +3,9 @@ name: REUSE Compliance +permissions: + contents: read + on: workflow_call: inputs: diff --git a/.github/workflows/_semver.yml b/.github/workflows/_semver.yml index 614fb4c..c32a00c 100644 --- a/.github/workflows/_semver.yml +++ b/.github/workflows/_semver.yml @@ -3,6 +3,9 @@ name: Semver Check +permissions: + contents: read + on: workflow_call: inputs: @@ -20,7 +23,7 @@ jobs: with: fetch-depth: 0 persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/_tag.yml b/.github/workflows/_tag.yml deleted file mode 100644 index 054e5a0..0000000 --- a/.github/workflows/_tag.yml +++ /dev/null @@ -1,50 +0,0 @@ -# SPDX-FileCopyrightText: 2025 RAprogramm -# SPDX-License-Identifier: MIT - -name: Create Version Tag - -on: - workflow_call: - outputs: - new_tag: - description: "Whether a new tag was created" - value: ${{ jobs.tag-release.outputs.new_tag }} - version: - description: "The version from Cargo.toml" - value: ${{ jobs.tag-release.outputs.version }} - -jobs: - tag-release: - name: Create Version Tag - runs-on: ubuntu-latest - outputs: - new_tag: ${{ steps.check.outputs.new_tag }} - version: ${{ steps.check.outputs.version }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - - - name: Check for new version - id: check - run: | - VERSION=$(grep '^version' Cargo.toml | head -1 | sed 's/.*"\(.*\)".*/\1/') - TAG="v${VERSION}" - echo "version=${VERSION}" >> $GITHUB_OUTPUT - if git rev-parse "$TAG" >/dev/null 2>&1; then - echo "Tag $TAG already exists" - echo "new_tag=false" >> $GITHUB_OUTPUT - else - echo "New version detected: $VERSION" - echo "new_tag=true" >> $GITHUB_OUTPUT - fi - - - name: Create and push tag - if: steps.check.outputs.new_tag == 'true' - run: | - git config user.name "github-actions[bot]" - git config user.email "github-actions[bot]@users.noreply.github.com" - git tag -a "v${STEPS_CHECK_OUTPUTS_VERSION}" -m "Release v${STEPS_CHECK_OUTPUTS_VERSION}" - git push origin "v${STEPS_CHECK_OUTPUTS_VERSION}" - env: - STEPS_CHECK_OUTPUTS_VERSION: ${{ steps.check.outputs.version }} diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index 8c54d80..a8c0f1c 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -3,6 +3,9 @@ name: Test +permissions: + contents: read + on: workflow_call: inputs: @@ -22,7 +25,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable components: llvm-tools-preview diff --git a/.github/workflows/cargo-update.yml b/.github/workflows/cargo-update.yml index ec95c5a..f96592c 100644 --- a/.github/workflows/cargo-update.yml +++ b/.github/workflows/cargo-update.yml @@ -22,7 +22,7 @@ jobs: with: persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 15dabc3..f2750ea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,7 +20,7 @@ env: RUSTFLAGS: -D warnings jobs: - # Stage 1: PR size check (blocks everything on failure) + # Stage 1: PR size check (advisory report, does not gate the pipeline) pr-size: name: PR Size Check runs-on: ubuntu-latest @@ -44,10 +44,6 @@ jobs: # Stage 2: Detect changes detect: - needs: pr-size - if: | - always() && - (github.event_name == 'push' || needs.pr-size.result == 'success') uses: ./.github/workflows/_detect.yml # Stage 3: All checks (parallel) @@ -165,86 +161,15 @@ jobs: with: rust_changed: ${{ needs.detect.outputs.rust }} - # Stage 5: Changelog (only on main after build) - changelog: - needs: build - if: always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.build.result == 'success' - permissions: - contents: write - uses: ./.github/workflows/_changelog.yml - - # Stage 6: Tag release (after changelog) - tag: - needs: [build, changelog] - if: | - always() && - github.event_name == 'push' && - github.ref == 'refs/heads/main' && - needs.build.result == 'success' && - (needs.changelog.result == 'success' || needs.changelog.result == 'skipped') - permissions: - contents: write - uses: ./.github/workflows/_tag.yml - - # Check if release should proceed - should-release: - needs: tag - if: always() && needs.tag.result == 'success' - runs-on: ubuntu-latest - outputs: - release: ${{ steps.check.outputs.release }} - version: ${{ needs.tag.outputs.version }} - steps: - - name: Check if new tag - id: check - run: | - echo "new_tag='${NEEDS_TAG_OUTPUTS_NEW_TAG}'" - echo "version='${NEEDS_TAG_OUTPUTS_VERSION}'" - if [ "${NEEDS_TAG_OUTPUTS_NEW_TAG}" = "true" ]; then - echo "release=true" >> $GITHUB_OUTPUT - else - echo "release=false" >> $GITHUB_OUTPUT - fi - env: - NEEDS_TAG_OUTPUTS_NEW_TAG: ${{ needs.tag.outputs.new_tag }} - NEEDS_TAG_OUTPUTS_VERSION: ${{ needs.tag.outputs.version }} - - # Stage 7: Release builds (only if new tag) - release-build: - needs: should-release - if: always() && needs.should-release.result == 'success' && needs.should-release.outputs.release == 'true' - uses: ./.github/workflows/_release-build.yml - with: - new_tag: ${{ needs.should-release.outputs.release }} - - # Stage 8: Create release and publish (after release builds) - release: - needs: [should-release, release-build] - if: always() && needs.should-release.result == 'success' && needs.should-release.outputs.release == 'true' && needs.release-build.result == 'success' - permissions: - contents: write - id-token: write - attestations: write - uses: ./.github/workflows/_release.yml - with: - new_tag: ${{ needs.should-release.outputs.release }} - version: ${{ needs.should-release.outputs.version }} - - publish: - needs: [should-release, release-build] - if: always() && needs.should-release.result == 'success' && needs.should-release.outputs.release == 'true' && needs.release-build.result == 'success' - uses: ./.github/workflows/_publish.yml - with: - new_tag: ${{ needs.should-release.outputs.release }} - secrets: - CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }} + # Releases are not part of CI: they are driven by the `Release-plz` + # workflow (release PR -> merge -> publish), with binary assets and + # attestations attached by `Release binaries` and `Release attestations`. # Aggregate gate: single required status context for branch protection ci-success: name: CI Success needs: [ - pr-size, detect, fmt, clippy, diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 38afa22..e155a4b 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -39,7 +39,7 @@ jobs: persist-credentials: false - name: Setup Rust toolchain - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index 9c536e9..81d4d0e 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -31,7 +31,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + - uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master with: toolchain: stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/publish-version.yml b/.github/workflows/publish-version.yml deleted file mode 100644 index 3de7980..0000000 --- a/.github/workflows/publish-version.yml +++ /dev/null @@ -1,48 +0,0 @@ -# SPDX-FileCopyrightText: 2026 RAprogramm -# SPDX-License-Identifier: MIT - -name: Publish Tagged Version - -on: - workflow_dispatch: - inputs: - tag: - description: "Tag to publish to crates.io (e.g. v0.6.0)" - required: true - type: string - -permissions: - contents: read - -concurrency: - group: publish-version - cancel-in-progress: false - -jobs: - publish: - name: Publish ${{ inputs.tag }} to crates.io - runs-on: ubuntu-latest - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ inputs.tag }} - persist-credentials: false - - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master - with: - toolchain: stable - - - name: Publish - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }} - run: | - output=$(cargo publish --allow-dirty 2>&1) || { - if echo "$output" | grep -q "already exists"; then - echo "::notice::Version already published to crates.io" - exit 0 - else - echo "$output" - exit 1 - fi - } diff --git a/.github/workflows/release-attestations.yml b/.github/workflows/release-attestations.yml new file mode 100644 index 0000000..412a7a3 --- /dev/null +++ b/.github/workflows/release-attestations.yml @@ -0,0 +1,104 @@ +# SPDX-FileCopyrightText: 2026 RAprogramm +# SPDX-License-Identifier: MIT + +# On every published GitHub release, generate a CycloneDX SBOM and a +# signed SLSA build-provenance attestation for the `.crate` artefact +# that release-plz published to crates.io, then attach the SBOM, the +# Sigstore provenance bundle, and the crate itself to the release so +# consumers can run `gh attestation verify` against them and supply-chain +# scanners (e.g. OpenSSF Scorecard Signed-Releases) can see the signature. +# +# `workflow_dispatch` is the escape hatch for re-attesting an older tag. + +name: Release attestations + +on: + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: "Tag to re-attest (e.g. v0.16.0)" + required: true + type: string + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.release.tag_name || inputs.tag }} + cancel-in-progress: false + +jobs: + attest: + name: Generate SBOM and provenance + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: write + id-token: write + attestations: write + steps: + - name: Checkout tagged commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.release.tag_name || inputs.tag }} + fetch-depth: 0 + persist-credentials: false + + - name: Setup Rust toolchain + uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master + with: + toolchain: stable + + # No dependency cache here on purpose: this workflow publishes + # runtime artefacts, and a restored cache is an unverified input to + # them (zizmor cache-poisoning). Release builds are rare enough that + # a cold build is the right trade. + + - name: Package crate + run: cargo package --no-verify --allow-dirty + + - name: Locate .crate file + id: artefact + run: | + set -euo pipefail + crate=$(find target/package -maxdepth 1 -name '*.crate' -print -quit) + if [ -z "$crate" ]; then + echo "::error::No .crate file produced under target/package" >&2 + exit 1 + fi + echo "path=$crate" >> "$GITHUB_OUTPUT" + echo "name=$(basename "$crate")" >> "$GITHUB_OUTPUT" + + - name: Generate CycloneDX SBOM + uses: anchore/sbom-action@66cbf4bc1f1c0d2edc94016e65bc221b6bb0ad6c # v0.24.3 + with: + path: ./ + format: cyclonedx-json + output-file: sql-query-analyzer-sbom.cdx.json + upload-artifact: false + upload-release-assets: false + + - name: Generate build provenance attestation + id: attest + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: | + ${{ steps.artefact.outputs.path }} + sql-query-analyzer-sbom.cdx.json + + - name: Attach SBOM, provenance bundle, and crate to GitHub release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: ${{ github.event.release.tag_name || inputs.tag }} + BUNDLE: ${{ steps.attest.outputs.bundle-path }} + CRATE: ${{ steps.artefact.outputs.path }} + run: | + set -euo pipefail + cp "$BUNDLE" sql-query-analyzer-provenance.sigstore.json + gh release upload "$TAG" \ + sql-query-analyzer-sbom.cdx.json \ + sql-query-analyzer-provenance.sigstore.json \ + "$CRATE" \ + --clobber diff --git a/.github/workflows/release-binaries.yml b/.github/workflows/release-binaries.yml new file mode 100644 index 0000000..8008003 --- /dev/null +++ b/.github/workflows/release-binaries.yml @@ -0,0 +1,123 @@ +# SPDX-FileCopyrightText: 2026 RAprogramm +# SPDX-License-Identifier: MIT + +# release-plz creates the GitHub release and its changelog body when it +# pushes the `vX.Y.Z` tag. This workflow only attaches per-platform binary +# archives to that existing release — it never recreates or rewrites the +# release notes — and signs each archive with a SLSA build-provenance +# attestation verifiable via `gh attestation verify`. +# +# The tag push fires while release-plz is still finishing the release +# creation; the builds take minutes, so the release always exists by the +# time the upload step runs. `workflow_dispatch` re-builds assets for an +# existing tag on demand. + +name: Release binaries + +on: + push: + tags: + - "v[0-9]*" + workflow_dispatch: + inputs: + tag: + description: "Existing release tag to (re)build assets for (e.g. v0.16.0)" + required: true + type: string + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.release.tag_name || github.ref_name || inputs.tag }} + cancel-in-progress: false + +jobs: + build: + name: Build ${{ matrix.target }} + runs-on: ${{ matrix.os }} + permissions: + contents: write # upload release assets + id-token: write # mint Sigstore signing certificate for attestations + attestations: write # persist build provenance attestations + strategy: + fail-fast: false + matrix: + include: + - target: x86_64-unknown-linux-gnu + os: ubuntu-latest + archive: tar.gz + cross: false + - target: x86_64-unknown-linux-musl + os: ubuntu-latest + archive: tar.gz + cross: true + - target: aarch64-unknown-linux-gnu + os: ubuntu-latest + archive: tar.gz + cross: true + - target: x86_64-apple-darwin + os: macos-latest + archive: tar.gz + cross: false + - target: aarch64-apple-darwin + os: macos-latest + archive: tar.gz + cross: false + - target: x86_64-pc-windows-msvc + os: windows-latest + archive: zip + cross: false + steps: + - name: Checkout tagged commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.tag || github.ref_name }} + persist-credentials: false + + - name: Setup Rust toolchain + uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master + with: + toolchain: stable + targets: ${{ matrix.target }} + + # No dependency cache here on purpose: this workflow publishes + # runtime artefacts, and a restored cache is an unverified input to + # them (zizmor cache-poisoning). Release builds are rare enough that + # a cold build is the right trade. + + - name: Install cross + if: matrix.cross + run: cargo install cross --git https://github.com/cross-rs/cross + + - name: Build with cross + if: matrix.cross + run: cross build --release --target ${{ matrix.target }} + + - name: Build with cargo + if: ${{ !matrix.cross }} + run: cargo build --release --target ${{ matrix.target }} + + - name: Package (Unix) + if: matrix.os != 'windows-latest' + run: | + cd target/${{ matrix.target }}/release + tar czf ../../../sql-query-analyzer-${{ matrix.target }}.tar.gz sql-query-analyzer + + - name: Package (Windows) + if: matrix.os == 'windows-latest' + shell: pwsh + run: | + Compress-Archive -Path target/${{ matrix.target }}/release/sql-query-analyzer.exe ` + -DestinationPath sql-query-analyzer-${{ matrix.target }}.zip + + - name: Generate build provenance attestation + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: sql-query-analyzer-${{ matrix.target }}.${{ matrix.archive }} + + - name: Attach archive to the release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_TAG: ${{ inputs.tag || github.ref_name }} + run: gh release upload "$RELEASE_TAG" "sql-query-analyzer-${{ matrix.target }}.${{ matrix.archive }}" --clobber diff --git a/.github/workflows/release-plz.yml b/.github/workflows/release-plz.yml new file mode 100644 index 0000000..0df4194 --- /dev/null +++ b/.github/workflows/release-plz.yml @@ -0,0 +1,127 @@ +# SPDX-FileCopyrightText: 2026 RAprogramm +# SPDX-License-Identifier: MIT + +# Release automation driven by release-plz, with publishing deliberately +# kept out of the automatic path: +# +# push to `main` -> `release-pr` ONLY: it reads the conventional +# commits since the last tag and opens (or updates) +# the single open release PR that bumps +# `Cargo.toml` and prepends a section to +# `CHANGELOG.md`. Nothing is tagged, nothing is +# published. +# workflow_dispatch -> opt-in `release` (checkbox, off by default): +# the only way anything reaches crates.io. A human +# must merge the release PR AND explicitly run this +# workflow; `release-plz release` then tags the +# commit, publishes to crates.io, and creates the +# GitHub release with the curated changelog as its +# body. The command is idempotent. +# +# Authentication is via a dedicated GitHub App (`RELEASE_PLZ_APP_ID` + +# `RELEASE_PLZ_APP_PRIVATE_KEY` repository secrets). The App identity is +# required, not optional: PRs and releases created with the default +# `secrets.GITHUB_TOKEN` do not trigger downstream workflows (the `CI` +# checks on the release PR, `Release binaries`, `Release attestations`). +# +# See `release-plz.toml` for the configuration and `RELEASE.md` for the +# human-facing flow. + +name: Release-plz + +on: + push: + branches: + - main + workflow_dispatch: + inputs: + publish: + description: "Publish the merged release: tag, crates.io, GitHub release (release-plz release)" + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + release-pr: + name: Release-plz PR + runs-on: ubuntu-latest + if: ${{ github.event_name == 'push' && github.repository_owner == 'RAprogramm' }} + timeout-minutes: 30 + steps: + - name: Mint GitHub App token + id: app_token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ secrets.RELEASE_PLZ_APP_ID }} + private-key: ${{ secrets.RELEASE_PLZ_APP_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + token: ${{ steps.app_token.outputs.token }} + + - name: Setup Rust toolchain + uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master + with: + toolchain: stable + + # release-plz applies `pr_labels` but never creates the labels, so the + # workflow guarantees its own prerequisite instead of failing silently + # on a fresh clone of the repository. + - name: Ensure the release label exists + env: + GH_TOKEN: ${{ steps.app_token.outputs.token }} + run: gh label create release --repo "$GITHUB_REPOSITORY" --color B60205 --description "Release pull request" --force + + - name: Run release-plz release-pr + uses: release-plz/action@66b324fd6c72d05d2a08568492ecdd62bfb8a62b # v0.5.148 + with: + command: release-pr + env: + GITHUB_TOKEN: ${{ steps.app_token.outputs.token }} + CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }} + + publish: + name: Publish merged release + runs-on: ubuntu-latest + if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish && github.repository_owner == 'RAprogramm' }} + timeout-minutes: 30 + steps: + - name: Mint GitHub App token + id: app_token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ secrets.RELEASE_PLZ_APP_ID }} + private-key: ${{ secrets.RELEASE_PLZ_APP_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + token: ${{ steps.app_token.outputs.token }} + + - name: Setup Rust toolchain + uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master + with: + toolchain: stable + + - name: Run release-plz release + uses: release-plz/action@66b324fd6c72d05d2a08568492ecdd62bfb8a62b # v0.5.148 + with: + command: release + env: + GITHUB_TOKEN: ${{ steps.app_token.outputs.token }} + CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }} diff --git a/.github/zizmor.yml b/.github/zizmor.yml index 3f5d550..7de0049 100644 --- a/.github/zizmor.yml +++ b/.github/zizmor.yml @@ -6,22 +6,9 @@ rules: # crates.io trusted publishing is not configured for this crate yet; - # publishing authenticates with a scoped CRATES_IO_TOKEN secret. + # publishing authenticates with a scoped CRATES_IO_TOKEN secret, which + # the manual publish step of the Release-plz workflow passes to + # release-plz. use-trusted-publishing: ignore: - - _publish.yml - - publish-version.yml - - # softprops/action-gh-release creates the release from generated notes - # and attaches multiple asset globs in a single declarative step; the - # equivalent gh-cli script adds more surface than it removes. - superfluous-actions: - ignore: - - _release.yml - - # These two jobs push with git (the release tag and the regenerated - # CHANGELOG.md), so their checkouts must keep credentials. - artipacked: - ignore: - - _tag.yml - - _changelog.yml + - release-plz.yml diff --git a/.gitignore b/.gitignore index 19f9055..f892416 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target .claude +.opencode diff --git a/CHANGELOG.md b/CHANGELOG.md index b672b81..e66e6db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,16 +5,6 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] - -### Added - -- Add PERF017 rule detecting correlated subqueries ([#110](https://github.com/RAprogramm/sql-query-analyzer/issues/110)) ([b0e47bc](https://github.com/RAprogramm/sql-query-analyzer/commit/b0e47bceb5357302d5001e14e6ba59a72a648957)) - -### Documentation - -- Update changelog [skip ci] ([3ffe437](https://github.com/RAprogramm/sql-query-analyzer/commit/3ffe4372b5481088fc85fff61bbef681ce8e9b7a)) - ## [0.15.0] - 2026-07-14 ### Added @@ -333,7 +323,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Use rustls instead of openssl for cross-compilation ([2bdf030](https://github.com/RAprogramm/sql-query-analyzer/commit/2bdf03097c563bce1c7b70eb613f6d58bc52b0c2)) -[Unreleased]: https://github.com/RAprogramm/sql-query-analyzer/compare/v0.15.0...HEAD [0.15.0]: https://github.com/RAprogramm/sql-query-analyzer/compare/v0.14.0...v0.15.0 [0.14.0]: https://github.com/RAprogramm/sql-query-analyzer/compare/v0.13.0...v0.14.0 [0.13.0]: https://github.com/RAprogramm/sql-query-analyzer/compare/v0.12.0...v0.13.0 @@ -349,7 +338,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [0.4.0]: https://github.com/RAprogramm/sql-query-analyzer/compare/v0.3.0...v0.4.0 [0.3.0]: https://github.com/RAprogramm/sql-query-analyzer/compare/v0.2.0...v0.3.0 [0.2.0]: https://github.com/RAprogramm/sql-query-analyzer/compare/v0.1.1...v0.2.0 -[0.1.1]: https://github.com/RAprogramm/sql-query-analyzer/compare/v1...v0.1.1 -[1]: https://github.com/RAprogramm/sql-query-analyzer/compare/v0.1.0...v1 +[0.1.1]: https://github.com/RAprogramm/sql-query-analyzer/compare/v0.1.0...v0.1.1 [0.1.0]: https://github.com/RAprogramm/sql-query-analyzer/releases/tag/v0.1.0 diff --git a/Cargo.lock b/Cargo.lock index 3505b10..99aa01c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "aho-corasick" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" dependencies = [ "memchr", ] @@ -78,9 +78,9 @@ dependencies = [ [[package]] name = "ar_archive_writer" -version = "0.5.2" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4087686b4b0a3427190bae57a1d9a478dbb2d40c5dc1bd6e2b6d797913bdd348" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" dependencies = [ "object", ] @@ -114,9 +114,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.17.1" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4342d8937fc7e5dd9b1c60292261c0670c882a2cd1719cfc11b1af41731e32ad" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" dependencies = [ "aws-lc-sys", "zeroize", @@ -124,9 +124,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.42.0" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d9ceb1da931507a12f4fccea479dccd00da1943e1b4ae72d8e502d707361444" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" dependencies = [ "cc", "cmake", @@ -135,12 +135,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - [[package]] name = "base64" version = "0.23.1" @@ -149,9 +143,9 @@ checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" [[package]] name = "bitflags" -version = "2.13.0" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "block-buffer" @@ -164,9 +158,9 @@ dependencies = [ [[package]] name = "bstr" -version = "1.12.3" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79" +checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214" dependencies = [ "memchr", "regex-automata", @@ -175,15 +169,15 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.3" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" [[package]] name = "bytes" -version = "1.12.1" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" [[package]] name = "castaway" @@ -196,9 +190,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.67" +version = "1.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" dependencies = [ "find-msvc-tools", "jobserver", @@ -208,9 +202,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cfg_aliases" @@ -220,9 +214,9 @@ checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chacha20" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", "cpufeatures", @@ -231,9 +225,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.9" +version = "4.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" dependencies = [ "clap_builder", "clap_derive", @@ -241,9 +235,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.7" +version = "4.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" dependencies = [ "anstream", "anstyle", @@ -266,9 +260,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "1.1.0" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" [[package]] name = "cmake" @@ -320,7 +314,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] @@ -355,9 +349,9 @@ dependencies = [ [[package]] name = "combine" -version = "4.6.7" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -385,9 +379,9 @@ checksum = "baf0a07a401f374238ab8e2f11a104d2851bf9ce711ec69804834de8af45c7af" [[package]] name = "console" -version = "0.16.4" +version = "0.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fe5f465a4f6fee88fad41b85d990f84c835335e85b5d9e6e63e0d06d28cba7c" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" dependencies = [ "encode_unicode", "libc", @@ -397,9 +391,9 @@ dependencies = [ [[package]] name = "const-oid" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" [[package]] name = "core-foundation" @@ -419,18 +413,18 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" dependencies = [ "libc", ] [[package]] name = "crossbeam-deque" -version = "0.8.7" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -438,18 +432,18 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.20" +version = "0.9.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.22" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "crypto-common" @@ -479,13 +473,13 @@ dependencies = [ [[package]] name = "displaydoc" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] @@ -496,7 +490,7 @@ checksum = "8dc51d98e636f5e3b0759a39257458b22619cac7e96d932da6eeb052891bb67c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] @@ -507,9 +501,9 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "either" -version = "1.16.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "encode_unicode" @@ -519,15 +513,15 @@ checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", "windows-sys 0.61.2", @@ -535,15 +529,15 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "find-msvc-tools" -version = "0.1.9" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "float-cmp" @@ -556,9 +550,9 @@ dependencies = [ [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -571,53 +565,53 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "futures-channel" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", ] [[package]] name = "futures-core" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] name = "futures-io" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" [[package]] name = "futures-macro" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] name = "futures-sink" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" [[package]] name = "futures-task" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] name = "futures-util" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", "futures-io", @@ -664,9 +658,9 @@ checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" [[package]] name = "hashbrown" -version = "0.17.1" +version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" [[package]] name = "heck" @@ -676,9 +670,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "http" -version = "1.4.2" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" dependencies = [ "bytes", "itoa", @@ -696,9 +690,9 @@ dependencies = [ [[package]] name = "http-body-util" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", @@ -715,22 +709,21 @@ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "hybrid-array" -version = "0.4.13" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ "typenum", ] [[package]] name = "hyper" -version = "1.10.1" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" dependencies = [ "atomic-waker", "bytes", - "futures-channel", "futures-core", "http", "http-body", @@ -744,9 +737,9 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.9" +version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ "http", "hyper", @@ -759,16 +752,17 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.20" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64 0.22.1", + "base64", "bytes", "futures-channel", "futures-util", "http", "http-body", + "httparse", "hyper", "ipnet", "libc", @@ -782,9 +776,9 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -796,9 +790,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -809,9 +803,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -823,16 +817,17 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ + "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", @@ -843,15 +838,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -910,9 +905,9 @@ dependencies = [ [[package]] name = "ipnet" -version = "2.12.0" +version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" [[package]] name = "is_terminal_polyfill" @@ -931,9 +926,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "jni" @@ -962,7 +957,7 @@ dependencies = [ "quote", "rustc_version", "simd_cesu8", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] @@ -981,7 +976,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" dependencies = [ "quote", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] @@ -996,9 +991,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.103" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -1007,9 +1002,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.186" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "linux-raw-sys" @@ -1019,9 +1014,9 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litemap" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] name = "lock_api" @@ -1034,21 +1029,21 @@ dependencies = [ [[package]] name = "log" -version = "0.4.33" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "lru-slab" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" [[package]] name = "masterror" -version = "0.29.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e856b98b2569d0186c833d8a369af5ea2f37ff399a11fe2702798f7d0a97970" +checksum = "c84f6c983b337a166b1b8d9028fef5efbfa07c2305ba2b0a8c1e7e07a6cd14b3" dependencies = [ "http", "itoa", @@ -1063,21 +1058,21 @@ dependencies = [ [[package]] name = "masterror-derive" -version = "0.12.0" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "821b3dfc91c3aab149eb185d831d1b5ed350a39575ce6b21389d38ea2bddbc90" +checksum = "0e0cf256bb91d6b80df4256f0be16ab02831ef6027bbdd00cf45776902fb8ccb" dependencies = [ "masterror-template", "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] name = "masterror-template" -version = "0.4.2" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa90f9eaa68a5c3a60b2322bd19d16ac5cf54e0dba3fdca6cc649fa1317b27d1" +checksum = "32029235c1d9cb2220065380208dee3bd31452e26d67b71a32e4f0306c0c9e23" [[package]] name = "memchr" @@ -1087,9 +1082,9 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "mio" -version = "1.2.2" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi", @@ -1125,9 +1120,9 @@ dependencies = [ [[package]] name = "object" -version = "0.37.3" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" dependencies = [ "memchr", ] @@ -1146,9 +1141,9 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "openssl-probe" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" [[package]] name = "parking_lot" @@ -1181,27 +1176,27 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" [[package]] name = "pkg-config" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "portable-atomic" -version = "1.13.1" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] name = "potential_utf" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ "zerovec", ] @@ -1256,9 +1251,9 @@ dependencies = [ [[package]] name = "psm" -version = "0.1.31" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "645dbe486e346d9b5de3ef16ede18c26e6c70ad97418f4874b8b1889d6e761ea" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" dependencies = [ "ar_archive_writer", "cc", @@ -1266,9 +1261,9 @@ dependencies = [ [[package]] name = "quinn" -version = "0.11.11" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ "bytes", "cfg_aliases", @@ -1286,9 +1281,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.16" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "aws-lc-rs", "bytes", @@ -1309,9 +1304,9 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", @@ -1338,9 +1333,9 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.10.2" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ "chacha20", "getrandom 0.4.3", @@ -1355,9 +1350,9 @@ checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" [[package]] name = "rand_pcg" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" dependencies = [ "rand_core", ] @@ -1399,7 +1394,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b" dependencies = [ "quote", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] @@ -1452,7 +1447,7 @@ version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ - "base64 0.23.1", + "base64", "bytes", "futures-core", "futures-util", @@ -1517,9 +1512,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", @@ -1530,9 +1525,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.43" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "once_cell", @@ -1544,9 +1539,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" dependencies = [ "openssl-probe", "rustls-pki-types", @@ -1556,9 +1551,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "web-time", "zeroize", @@ -1566,9 +1561,9 @@ dependencies = [ [[package]] name = "rustls-platform-verifier" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" dependencies = [ "core-foundation", "core-foundation-sys", @@ -1587,15 +1582,15 @@ dependencies = [ [[package]] name = "rustls-platform-verifier-android" -version = "0.1.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.13" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "aws-lc-rs", "ring", @@ -1626,9 +1621,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -1720,24 +1715,11 @@ dependencies = [ "serde_core", ] -[[package]] -name = "serde_yaml" -version = "0.9.34+deprecated" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" -dependencies = [ - "indexmap", - "itoa", - "ryu", - "serde", - "unsafe-libyaml", -] - [[package]] name = "sha2" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", "cpufeatures", @@ -1819,7 +1801,6 @@ dependencies = [ "reqwest", "serde", "serde_json", - "serde_yaml", "smallvec", "sqlparser", "tempfile", @@ -1845,9 +1826,9 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "stacker" -version = "0.1.24" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "640c8cdd92b6b12f5bcb1803ca3bbf5ab96e5e6b6b96b9ab77dabe9e880b3190" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" dependencies = [ "cc", "cfg-if", @@ -1886,9 +1867,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.118" +version = "2.0.119" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" dependencies = [ "proc-macro2", "quote", @@ -1917,13 +1898,13 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] @@ -1957,29 +1938,29 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] name = "tinystr" -version = "0.8.3" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "zerovec", @@ -1987,18 +1968,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" @@ -2019,20 +1991,20 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.7.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] name = "tokio-rustls" -version = "0.26.4" +version = "0.26.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" dependencies = [ "rustls", "tokio", @@ -2040,9 +2012,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.18" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", @@ -2053,9 +2025,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.2.1+spec-1.1.0" +version = "1.2.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073" dependencies = [ "indexmap", "serde_core", @@ -2077,9 +2049,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.19+spec-1.1.0" +version = "0.25.21+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" dependencies = [ "indexmap", "toml_datetime", @@ -2089,9 +2061,9 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.1.5+spec-1.1.0" +version = "1.1.7+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" dependencies = [ "winnow", ] @@ -2180,15 +2152,15 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-width" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "unit-prefix" @@ -2196,12 +2168,6 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" -[[package]] -name = "unsafe-libyaml" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" - [[package]] name = "untrusted" version = "0.9.0" @@ -2210,9 +2176,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -2222,9 +2188,12 @@ dependencies = [ [[package]] name = "utf8_iter" -version = "1.0.4" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] [[package]] name = "utf8parse" @@ -2232,11 +2201,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "uuid" -version = "1.23.5" +version = "1.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea5fab0d6c3c01ae70085a09cb03d4c7a1d6314e2b3e075392783396d724ca0a" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" dependencies = [ "js-sys", "wasm-bindgen", @@ -2253,9 +2228,9 @@ dependencies = [ [[package]] name = "walkdir" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" dependencies = [ "same-file", "winapi-util", @@ -2263,9 +2238,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -2278,12 +2253,11 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasm-bindgen" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -2291,19 +2265,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.76" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2311,22 +2286,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] @@ -2346,9 +2321,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.103" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -2366,9 +2341,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.8" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] @@ -2472,24 +2447,24 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" dependencies = [ "memchr", ] [[package]] name = "writeable" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -2498,13 +2473,13 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", "synstructure", ] @@ -2519,27 +2494,27 @@ dependencies = [ [[package]] name = "zerofrom-derive" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", "synstructure", ] [[package]] name = "zeroize" -version = "1.9.0" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" [[package]] name = "zerotrie" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" dependencies = [ "displaydoc", "yoke", @@ -2548,9 +2523,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.6" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "yoke", "zerofrom", @@ -2559,13 +2534,13 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.3" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 6c346e2..1a9c000 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,13 +6,12 @@ authors = ["RAprogramm "] description = "Static analysis tool for SQL queries with 35 built-in rules for performance, security, and style" license = "MIT" repository = "https://github.com/RAprogramm/sql-query-analyzer" -homepage = "https://github.com/RAprogramm/sql-query-analyzer" documentation = "https://docs.rs/sql-query-analyzer" readme = "README.md" keywords = ["sql", "analyzer", "linter", "performance", "database"] categories = ["development-tools", "command-line-utilities", "database"] exclude = [".github", "target", ".git"] -rust-version = "1.97" +rust-version = "1.100" [lib] name = "sql_query_analyzer" @@ -32,9 +31,8 @@ reqwest = { version = "0.13", default-features = false, features = [ ] } serde = { version = "1", features = ["derive"] } serde_json = "1" -serde_yaml = "0.9" toml = "1" -masterror = "0.29" +masterror = "0.32" sqlparser = "0.64" smallvec = { version = "1", features = ["serde"] } indexmap = { version = "2", features = ["serde"] } @@ -45,7 +43,9 @@ rayon = "1" regex = "1" [dev-dependencies] +serde_json = "1" tempfile = "3" +tokio = { version = "1", features = ["rt-multi-thread", "macros"] } assert_cmd = "2" predicates = "3" divan = { version = "6.1.0", package = "codspeed-divan-compat" } diff --git a/README.md b/README.md index c2cf1b3..4b6b508 100644 --- a/README.md +++ b/README.md @@ -475,7 +475,7 @@ sql-query-analyzer analyze -s schema.sql -q queries.sql ## ClickHouse Support -The analyzer includes a preprocessor that handles ClickHouse-specific DDL constructs not supported by the underlying SQL parser: +The analyzer includes a preprocessor that handles ClickHouse-specific DDL constructs not supported by the underlying SQL parser, plus a dedicated set of ClickHouse best-practice rules that activate only with `--dialect clickhouse`. ### Supported Constructs @@ -485,6 +485,38 @@ The analyzer includes a preprocessor that handles ClickHouse-specific DDL constr | `TTL` | `TTL event_date + INTERVAL 90 DAY` | Data expiration rules | | `SETTINGS` | `SETTINGS index_granularity = 8192` | Table-level settings | | `PARTITION BY` | `PARTITION BY toYYYYMM(date)` | Partitioning expressions | +| `SAMPLE BY` | `SAMPLE BY intHash32(id)` | Sampling key | +| Skipping index | `INDEX idx col TYPE minmax GRANULARITY 4` | Data skipping indexes | +| Projection | `PROJECTION p (SELECT ... ORDER BY ...)` | Pre-aggregated views of a table | +| Dictionary | `CREATE DICTIONARY d (...)` | Key-value lookup dictionaries | +| Materialized view | `CREATE MATERIALIZED VIEW mv TO dest AS SELECT ...` | Incremental views (engine clause stripped) | +| Mutation | `ALTER TABLE t UPDATE/DELETE ...` | Rewritten to standard statements for analysis | +| Query clauses | `PREWHERE`, `FINAL`, `WITH TOTALS`, `WITH FILL` | ClickHouse query modifiers | + +### ClickHouse Rules + +When the ClickHouse dialect is selected, the OLTP index-suggestion rules are replaced by ClickHouse-aware rules that reason about the sparse primary key, partition pruning, and columnar storage: + +| Rule | Severity | Description | +|------|----------|-------------| +| `CH001` | Info | `SELECT *` reads every column file | +| `CH002` | Warning | WHERE does not use the sort key prefix | +| `CH003` | Warning | WHERE does not match `PARTITION BY` | +| `CH004` | Warning | Function on a date column disables the index | +| `CH005` | Info | Filter column has no sort key or skipping index | +| `CH006` | Info | `LowCardinality` on a likely high-cardinality column | +| `CH007` | Info | `Nullable` column used in a hot filter path | +| `CH009` | Info | `uniqExact` where approximate `uniq` suffices | +| `CH010` | Info | Multiple count subqueries replaceable by `countIf` | +| `CH011` | Warning | `ORDER BY` in a subquery without `LIMIT` | +| `CH012` | Info | `GROUP BY` prefix differs from the sort key | +| `CH016` | Info | Multi-table JOIN (prefer dictionary/denormalization) | +| `CH019` | Warning | `FINAL` forces read-time deduplication | +| `CH021` | Info | `WHERE` filter that could use `PREWHERE` | +| `CH022` | Warning | `ALTER UPDATE/DELETE` mutation is heavy | +| `CH023` | Warning | Manual `OPTIMIZE TABLE ... FINAL` | +| `CH024` | Info | JOIN against a table that exists as a dictionary | +| `CH025` | Info | `GROUP BY` on a plain `String` key (prefer `LowCardinality`) | ### Example diff --git a/RELEASE.md b/RELEASE.md new file mode 100644 index 0000000..6edb604 --- /dev/null +++ b/RELEASE.md @@ -0,0 +1,104 @@ + + +# Release process + +Releases of `sql_query_analyzer` are driven by [release-plz][rplz]. +Conventional commits land on `main`; release-plz reads them and opens (or +updates) a "release PR" that bumps `Cargo.toml` and prepends a section to +`CHANGELOG.md`. That is all the automatic path ever does — **the workflow +never publishes anything by itself**. + +Publishing requires two deliberate human actions: + +1. **merge the release PR** — the reviewed changelog lands on `main`; +2. **run the `Release-plz` workflow manually** (`workflow_dispatch`) with + the `publish` checkbox enabled — only then does `release-plz release` + tag the commit, publish to crates.io, and create the GitHub release. + +`release_always = false` in `release-plz.toml` makes the `release` +command act only on commits that belong to a merged `release-plz-*` +branch, so even a manual run cannot publish a version that never came +through a reviewed release PR. A feature PR that bumps the version +manually (breaking changes must, to satisfy the `Semver Checks` gate) +does not publish on merge either — the bumped, unpublished version simply +flows into the next release PR. Publish promptly after merging: until the +publish run tags the version, `release-pr` keeps the release PR open for +that same version. + +[rplz]: https://release-plz.dev + +## Versioning policy + +The crate follows [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html) +with Cargo's `0.x` interpretation: + +- While the major is `0`, **breaking changes** (`feat!:`) bump the minor. +- **New features** (`feat:`) also bump the minor — `features_always_increment_minor = true`, + matching the established cadence where every batch of new rules shipped + as a minor (`0.14 -> 0.15 -> 0.16`). +- **Bug fixes** and other non-feature commits bump the patch. + +After 1.0 the standard major/minor/patch rules apply. + +`Semver Checks` (`cargo semver-checks`, the `_semver.yml` job of `ci.yml`) +runs on every PR and blocks a release whose API change exceeds the +version bump. release-plz reads the same conventional commits to decide +the bump, so by the time a release PR exists the version and the API diff +already agree. + +## How a release happens + +``` +conventional commit on main + | + v +Release-plz workflow (on push to main) + `release-pr` only -- opens or updates the single open release PR; + nothing is tagged, nothing is published + | + v +release PR -- Cargo.toml bump + CHANGELOG.md section (label: release) + | + v (maintainer reviews, CI runs, semver gate passes) +merge [human action 1] + | + v +Release-plz workflow_dispatch with `publish` checked [human action 2] + `release` publishes to crates.io, tags vX.Y.Z, creates the GitHub release + | + +--> Release binaries -- per-platform archives + provenance + +--> Release attestations -- .crate + CycloneDX SBOM + provenance +``` + +If a publish run fails partway, re-run the `Release-plz` workflow with +`publish` checked — `release-plz release` is idempotent. Binary assets can +be rebuilt for an existing tag via `workflow_dispatch` on `Release +binaries`; attestations likewise on `Release attestations`. + +## One-time setup + +The `Release-plz` workflow authenticates as a dedicated GitHub App +(`RELEASE_PLZ_APP_ID` + `RELEASE_PLZ_APP_PRIVATE_KEY` repository +secrets), not as the default `GITHUB_TOKEN`: PRs and releases created +with the default token do not trigger downstream workflows, so the +release would not be fully automatic. The App needs exactly two +permissions — `Contents: read & write` and `Pull requests: read & +write` — and is installed on this repository only. `CRATES_IO_TOKEN` +must also be set as a repository secret. + +Everything else the pipeline needs is self-service: the `release` label +is created by the workflow itself before release-plz runs. The only +manual steps are the two secrets above — GitHub deliberately keeps +App-key provisioning outside automation — and they are set once. + +## Changelog style + +`CHANGELOG.md` follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) +and the section headings (`Added`, `Fixed`, `Changed`, ...) are produced +by the `[changelog]` table of `release-plz.toml`, which mirrors the +previous git-cliff configuration. Commit subjects must be Conventional +Commits (`feat:`/`fix:`/`docs:`/...); merge commits carrying `(#123)` +get an automatic issue link. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..d763416 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,54 @@ +# Security Policy + +This document describes how to report security vulnerabilities in +`sql-query-analyzer` and what you can expect in return. + +## Supported Versions + +Security fixes are provided for the latest released version and for the +current `main` branch. Older versions are not actively patched; update to +the latest release before reporting. + +| Version | Supported | +| ------- | ------------------ | +| latest | :white_check_mark: | +| main | :white_check_mark: | +| older | :x: | + +## Reporting a Vulnerability + +Report security vulnerabilities privately — do **not** open a public issue. + +Use [GitHub Private Vulnerability Reporting](https://github.com/RAprogramm/sql-query-analyzer/security/advisories/new) +to submit a report. Every report is acknowledged within 5 business days. + +Include, when possible: + +- the affected version or commit; +- a minimal reproduction (the SQL input and the CLI invocation are usually + enough — this tool parses untrusted SQL, so parser crashes, unbounded + memory growth, and rule bypasses all count as security issues); +- the impact you observed or expect. + +## Scope + +In scope: + +- memory-safety, crash, or resource-exhaustion issues reachable from + SQL input (schema files, query files, stdin); +- logic flaws that make security rules (`SEC*`) silently pass dangerous SQL; +- credential handling in the LLM integrations (API keys, tokens); +- vulnerabilities in the shipped GitHub Action (`action.yml`). + +Out of scope: + +- findings that require the user to deliberately run the tool on + attacker-controlled configuration files; +- social engineering of maintainers; +- third-party services (Ollama/OpenAI/Anthropic endpoints). + +## Disclosure Policy + +- We prepare a fix and a security advisory before any public disclosure. +- Coordinated disclosure: the advisory is published as soon as a patched + version is released, or after 90 days, whichever comes first. diff --git a/action.yml b/action.yml index dfaa7a5..0c8bf8a 100644 --- a/action.yml +++ b/action.yml @@ -72,18 +72,21 @@ runs: curl -sL "$URL" | tar xz -C /tmp chmod +x /tmp/sql_query_analyzer - echo "/tmp" >> $GITHUB_PATH + echo "/tmp" >> "$GITHUB_PATH" - name: Run analysis id: analyze shell: bash + env: + INPUT_SCHEMA: ${{ inputs.schema }} + INPUT_QUERIES: ${{ inputs.queries }} + INPUT_DIALECT: ${{ inputs.dialect }} + INPUT_FORMAT: ${{ inputs.format }} run: | - ARGS="analyze -s ${{ inputs.schema }} -q ${{ inputs.queries }}" - ARGS="$ARGS --dialect ${{ inputs.dialect }}" - ARGS="$ARGS -f ${{ inputs.format }}" - ARGS="$ARGS --no-color" + ARGS=(analyze -s "$INPUT_SCHEMA" -q "$INPUT_QUERIES") + ARGS+=(--dialect "$INPUT_DIALECT" -f "$INPUT_FORMAT" --no-color) - OUTPUT=$(sql_query_analyzer $ARGS 2>&1) || EXIT_CODE=$? + OUTPUT=$(sql_query_analyzer "${ARGS[@]}" 2>&1) || EXIT_CODE=$? EXIT_CODE=${EXIT_CODE:-0} echo "$OUTPUT" @@ -91,30 +94,34 @@ runs: ERROR_COUNT=$(echo "$OUTPUT" | grep -oP '\d+(?= error)' | head -1 || echo "0") WARNING_COUNT=$(echo "$OUTPUT" | grep -oP '\d+(?= warning)' | head -1 || echo "0") - echo "exit_code=$EXIT_CODE" >> $GITHUB_OUTPUT - echo "error_count=${ERROR_COUNT:-0}" >> $GITHUB_OUTPUT - echo "warning_count=${WARNING_COUNT:-0}" >> $GITHUB_OUTPUT + echo "exit_code=$EXIT_CODE" >> "$GITHUB_OUTPUT" + echo "error_count=${ERROR_COUNT:-0}" >> "$GITHUB_OUTPUT" + echo "warning_count=${WARNING_COUNT:-0}" >> "$GITHUB_OUTPUT" { echo "analysis<> $GITHUB_OUTPUT + } >> "$GITHUB_OUTPUT" - name: Generate SARIF id: sarif if: inputs.upload-sarif == 'true' shell: bash + env: + INPUT_SCHEMA: ${{ inputs.schema }} + INPUT_QUERIES: ${{ inputs.queries }} + INPUT_DIALECT: ${{ inputs.dialect }} run: | sql_query_analyzer analyze \ - -s ${{ inputs.schema }} \ - -q ${{ inputs.queries }} \ - --dialect ${{ inputs.dialect }} \ + -s "$INPUT_SCHEMA" \ + -q "$INPUT_QUERIES" \ + --dialect "$INPUT_DIALECT" \ -f sarif > results.sarif || true - name: Upload SARIF if: inputs.upload-sarif == 'true' - uses: github/codeql-action/upload-sarif@v4 + uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4 with: sarif_file: results.sarif category: sql-query-analyzer @@ -124,15 +131,19 @@ runs: shell: bash env: GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + REPOSITORY: ${{ github.repository }} + UPDATE_COMMENT: ${{ inputs.update-comment }} + INPUT_SCHEMA: ${{ inputs.schema }} + INPUT_QUERIES: ${{ inputs.queries }} + INPUT_DIALECT: ${{ inputs.dialect }} + ERROR_COUNT: ${{ steps.analyze.outputs.error_count }} + WARNING_COUNT: ${{ steps.analyze.outputs.warning_count }} + EXIT_CODE: ${{ steps.analyze.outputs.exit_code }} + ANALYSIS: ${{ steps.analyze.outputs.analysis }} run: | MARKER="" - PR_NUMBER=${{ github.event.pull_request.number }} - - ERROR_COUNT=${{ steps.analyze.outputs.error_count }} - WARNING_COUNT=${{ steps.analyze.outputs.warning_count }} - EXIT_CODE=${{ steps.analyze.outputs.exit_code }} - # Build verdict section if [ "$EXIT_CODE" = "0" ]; then VERDICT="> [!TIP] > **All SQL checks passed.** No issues found in your queries!" @@ -146,11 +157,9 @@ runs: > - Run \`sql_query_analyzer analyze\` locally for detailed output" fi - # Status icons if [ "${ERROR_COUNT:-0}" -eq 0 ]; then ERROR_STATUS="✅"; else ERROR_STATUS="❌"; fi if [ "${WARNING_COUNT:-0}" -eq 0 ]; then WARNING_STATUS="✅"; else WARNING_STATUS="⚠️"; fi - # Build comment COMMENT="${MARKER} ## SQL Query Analysis @@ -172,7 +181,7 @@ runs: Analysis Details — full output \`\`\` - ${{ steps.analyze.outputs.analysis }} + ${ANALYSIS} \`\`\` @@ -184,40 +193,42 @@ runs: | Setting | Value | |:--------|:------| - | Dialect | \`${{ inputs.dialect }}\` | - | Schema | \`${{ inputs.schema }}\` | - | Queries | \`${{ inputs.queries }}\` | + | Dialect | \`${INPUT_DIALECT}\` | + | Schema | \`${INPUT_SCHEMA}\` | + | Queries | \`${INPUT_QUERIES}\` | --- [SQL Query Analyzer](https://github.com/RAprogramm/sql-query-analyzer)" - if [ "${{ inputs.update-comment }}" = "true" ]; then - EXISTING=$(gh api repos/${{ github.repository }}/issues/${PR_NUMBER}/comments \ + if [ "$UPDATE_COMMENT" = "true" ]; then + EXISTING=$(gh api "repos/${REPOSITORY}/issues/${PR_NUMBER}/comments" \ --jq ".[] | select(.body | contains(\"${MARKER}\")) | .id" | head -1) if [ -n "$EXISTING" ]; then - gh api repos/${{ github.repository }}/issues/comments/${EXISTING} \ + gh api "repos/${REPOSITORY}/issues/comments/${EXISTING}" \ -X PATCH -f body="$COMMENT" else - gh pr comment $PR_NUMBER --body "$COMMENT" + gh pr comment "$PR_NUMBER" --body "$COMMENT" fi else - gh pr comment $PR_NUMBER --body "$COMMENT" + gh pr comment "$PR_NUMBER" --body "$COMMENT" fi - name: Check result shell: bash + env: + EXIT_CODE: ${{ steps.analyze.outputs.exit_code }} + FAIL_ON_ERROR: ${{ inputs.fail-on-error }} + FAIL_ON_WARNING: ${{ inputs.fail-on-warning }} run: | - EXIT_CODE=${{ steps.analyze.outputs.exit_code }} - - if [ "$EXIT_CODE" = "2" ] && [ "${{ inputs.fail-on-error }}" = "true" ]; then + if [ "$EXIT_CODE" = "2" ] && [ "$FAIL_ON_ERROR" = "true" ]; then echo "::error::SQL analysis found errors" exit 1 fi - if [ "$EXIT_CODE" = "1" ] && [ "${{ inputs.fail-on-warning }}" = "true" ]; then + if [ "$EXIT_CODE" = "1" ] && [ "$FAIL_ON_WARNING" = "true" ]; then echo "::warning::SQL analysis found warnings" exit 1 fi diff --git a/benches/analyzer.rs b/benches/analyzer.rs index c76ba2d..f680b2a 100644 --- a/benches/analyzer.rs +++ b/benches/analyzer.rs @@ -4,6 +4,8 @@ //! Benchmarks for the static analysis pipeline: schema parsing, query //! parsing, rule execution and report formatting. +use std::fmt::Write; + use divan::{Bencher, black_box}; use sql_query_analyzer::{ config::RulesConfig, @@ -54,40 +56,46 @@ const QUERY_TEMPLATES: &[&str] = &[ ]; fn queries_sql(count: usize) -> String { - (0..count) - .map(|i| { - let template = QUERY_TEMPLATES[i % QUERY_TEMPLATES.len()]; - let table_suffix = (i / QUERY_TEMPLATES.len()) % SCHEMA_TABLES; - format!("{};\n", template.replace("{n}", &table_suffix.to_string())) - }) - .collect() + let mut sql = String::new(); + for i in 0..count { + let template = QUERY_TEMPLATES[i % QUERY_TEMPLATES.len()]; + let table_suffix = (i / QUERY_TEMPLATES.len()) % SCHEMA_TABLES; + let _ = writeln!( + sql, + "{};", + template.replace("{n}", &table_suffix.to_string()) + ); + } + sql } fn schema_sql(tables: usize) -> String { let mut sql = String::new(); for n in 0..tables { - sql.push_str(&format!( + let _ = write!( + sql, "CREATE TABLE users{n} (id INT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, status VARCHAR(32), created_at TIMESTAMP, last_login TIMESTAMP);\n\ CREATE TABLE orders{n} (id INT PRIMARY KEY, user_id INT NOT NULL, total DECIMAL(10, 2), status VARCHAR(32), created_at TIMESTAMP);\n\ CREATE TABLE products{n} (id INT PRIMARY KEY, name VARCHAR(255), price DECIMAL(10, 2), category_id INT);\n\ CREATE UNIQUE INDEX idx_users{n}_email ON users{n}(email);\n\ CREATE INDEX idx_orders{n}_user ON orders{n}(user_id, created_at);\n" - )); + ); } sql } fn clickhouse_schema_sql(tables: usize) -> String { - (0..tables) - .map(|n| { - format!( - "CREATE TABLE events{n} (id UInt64, user_id UInt64, ts DateTime CODEC(Delta, ZSTD), payload String CODEC(ZSTD(3))) \ - ENGINE = MergeTree PARTITION BY toYYYYMM(ts) ORDER BY (user_id, ts);\n\ - CREATE TABLE metrics{n} (name LowCardinality(String), ts DateTime CODEC(DoubleDelta), value Float64 CODEC(Gorilla, LZ4)) \ - ENGINE = MergeTree ORDER BY (name, ts) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;\n" - ) - }) - .collect() + let mut sql = String::new(); + for n in 0..tables { + let _ = write!( + sql, + "CREATE TABLE events{n} (id UInt64, user_id UInt64, ts DateTime CODEC(Delta, ZSTD), payload String CODEC(ZSTD(3))) \ + ENGINE = MergeTree PARTITION BY toYYYYMM(ts) ORDER BY (user_id, ts);\n\ + CREATE TABLE metrics{n} (name LowCardinality(String), ts DateTime CODEC(DoubleDelta), value Float64 CODEC(Gorilla, LZ4)) \ + ENGINE = MergeTree ORDER BY (name, ts) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;\n" + ); + } + sql } fn parsed_schema() -> Schema { @@ -99,11 +107,15 @@ fn parsed_queries(count: usize) -> Vec { } fn report(count: usize) -> AnalysisReport { - let runner = RuleRunner::with_schema_and_config(parsed_schema(), RulesConfig::default()); + let runner = RuleRunner::with_schema_and_config_and_dialect( + SqlDialect::Generic, + parsed_schema(), + &RulesConfig::default() + ); runner.analyze(&parsed_queries(count)) } -fn output_options(format: OutputFormat) -> OutputOptions { +const fn output_options(format: OutputFormat) -> OutputOptions { OutputOptions { format, colored: false, @@ -151,7 +163,11 @@ fn analyze_rules(bencher: Bencher, count: usize) { #[divan::bench(args = SIZES)] fn analyze_rules_with_schema(bencher: Bencher, count: usize) { - let runner = RuleRunner::with_schema_and_config(parsed_schema(), RulesConfig::default()); + let runner = RuleRunner::with_schema_and_config_and_dialect( + SqlDialect::Generic, + parsed_schema(), + &RulesConfig::default() + ); let queries = parsed_queries(count); bencher.bench(|| runner.analyze(black_box(&queries))); } @@ -160,7 +176,11 @@ fn analyze_rules_with_schema(bencher: Bencher, count: usize) { fn build_rule_runner_with_schema(bencher: Bencher) { let schema = parsed_schema(); bencher.bench(|| { - RuleRunner::with_schema_and_config(black_box(schema.clone()), RulesConfig::default()) + RuleRunner::with_schema_and_config_and_dialect( + SqlDialect::Generic, + black_box(schema.clone()), + &RulesConfig::default() + ) }); } @@ -185,7 +205,11 @@ fn full_static_pipeline(bencher: Bencher, count: usize) { bencher.bench(|| { let schema = Schema::parse(black_box(&schema), SqlDialect::Generic).unwrap(); let queries = parse_queries(black_box(&queries), SqlDialect::Generic).unwrap(); - let runner = RuleRunner::with_schema_and_config(schema, RulesConfig::default()); + let runner = RuleRunner::with_schema_and_config_and_dialect( + SqlDialect::Generic, + schema, + &RulesConfig::default() + ); let report = runner.analyze(&queries); format_static_analysis(&report, &opts) }); diff --git a/cliff.toml b/cliff.toml deleted file mode 100644 index 071726b..0000000 --- a/cliff.toml +++ /dev/null @@ -1,81 +0,0 @@ -# SPDX-FileCopyrightText: 2025 RAprogramm -# SPDX-License-Identifier: MIT - -[changelog] -header = """ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -""" -body = """ -{%- macro remote_url() -%} - https://github.com/RAprogramm/sql-query-analyzer -{%- endmacro -%} - -{% if version -%} -## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }} -{% else -%} -## [Unreleased] -{% endif -%} - -{% for group, commits in commits | group_by(attribute="group") %} -### {{ group | striptags | trim | upper_first }} -{% for commit in commits %} -- {% if commit.scope %}**{{ commit.scope }}**: {% endif %}{{ commit.message | upper_first }} \ -([{{ commit.id | truncate(length=7, end="") }}]({{ self::remote_url() }}/commit/{{ commit.id }}))\ -{% if commit.breaking %} **BREAKING**{% endif %} -{%- endfor %} -{% endfor %} - -""" -footer = """ -{%- set repo_url = "https://github.com/RAprogramm/sql-query-analyzer" -%} -{% for release in releases -%} -{% if release.version -%} -{% if release.previous.version -%} -[{{ release.version | trim_start_matches(pat="v") }}]: {{ repo_url }}/compare/{{ release.previous.version }}...{{ release.version }} -{% else -%} -[{{ release.version | trim_start_matches(pat="v") }}]: {{ repo_url }}/releases/tag/{{ release.version }} -{% endif -%} -{% else -%} -{% if release.previous.version -%} -[Unreleased]: {{ repo_url }}/compare/{{ release.previous.version }}...HEAD -{% endif -%} -{% endif -%} -{% endfor %} -""" -trim = true - -[git] -conventional_commits = true -filter_unconventional = true -split_commits = false -commit_preprocessors = [ - { pattern = '^#[0-9]+ ', replace = "" }, - { pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/RAprogramm/sql-query-analyzer/issues/${2}))" }, -] -commit_parsers = [ - { message = "^feat", group = "Added" }, - { message = "^fix", group = "Fixed" }, - { message = "^doc", group = "Documentation" }, - { message = "^perf", group = "Performance" }, - { message = "^refactor", group = "Changed" }, - { message = "^style", group = "Changed" }, - { message = "^test", group = "Testing" }, - { message = "^build", group = "Build" }, - { message = "^ci", group = "CI/CD" }, - { message = "^chore\\(release\\)", skip = true }, - { message = "^chore\\(deps\\)", group = "Dependencies" }, - { message = "^deps", group = "Dependencies" }, - { message = "^chore", group = "Miscellaneous" }, - { message = "^revert", group = "Reverted" }, -] -protect_breaking_commits = false -filter_commits = false -topo_order = false -sort_commits = "newest" -tag_pattern = "v[0-9].*" diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 14751d6..0469492 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -22,6 +22,7 @@ SPDX-License-Identifier: MIT - [Style](rules/style.md) - [Security](rules/security.md) - [Schema-Aware](rules/schema.md) +- [ClickHouse](rules/clickhouse.md) # Integrations diff --git a/docs/src/rules/clickhouse.md b/docs/src/rules/clickhouse.md new file mode 100644 index 0000000..5ad1e47 --- /dev/null +++ b/docs/src/rules/clickhouse.md @@ -0,0 +1,111 @@ + + +# ClickHouse Rules + +These rules activate only with `--dialect clickhouse`. They replace the OLTP +index-suggestion rules (`SCHEMA001`, `SCHEMA003`, `SCHEMA004`) with checks that +understand ClickHouse's sparse primary index, partition pruning, and columnar +storage. The OLTP rules assume `CREATE INDEX`, which does not exist in +ClickHouse, so they are skipped for this dialect. + +## CH001 — SELECT * on a columnar store (Info) + +`SELECT *` reads and decompresses every column file. List only the columns you +need. + +## CH002 — Filter does not use the sort key (Warning) + +`WHERE` does not reference any `ORDER BY`/`PRIMARY KEY` column, so no granules +are pruned. + +```sql +-- schema.sql +CREATE TABLE t (d Date, x UInt64) ENGINE = MergeTree ORDER BY d; + +-- Flagged: x is not part of the sort key +SELECT d FROM t WHERE x = 1; +``` + +## CH003 — Partition pruning missed (Warning) + +`WHERE` does not match the `PARTITION BY` expression, so whole partitions are +scanned. + +## CH004 — Function on a date column in WHERE (Warning) + +Wrapping a date column in `toDate`/`toYear`/... disables the sparse index. Use a +range predicate instead. + +## CH005 — No skipping index for filter column (Info) + +The filter column is in neither the sort key nor a skipping index. Suggests an +`ADD INDEX ... TYPE minmax/bloom_filter`. + +## CH006 — LowCardinality on a high-cardinality column (Info) + +`LowCardinality` helps below roughly 10k distinct values; on `id`/`uuid`/`url` +columns it usually hurts. + +## CH007 — Nullable column in a hot path (Info) + +`Nullable` adds a null-mask read and blocks optimizations; prefer a sentinel +default. + +## CH009 — uniqExact usage (Info) + +`uniqExact` tracks every distinct value. Prefer `uniq`/`uniqCombined` for +analytics. + +## CH010 — Conditional counts via subqueries (Info) + +Several `count()` subqueries scan the table separately; `countIf(condition)` +does it in one pass. + +## CH011 — ORDER BY in a subquery without LIMIT (Warning) + +Sorting a subquery result is wasted work when the outer query re-sorts. + +## CH012 — GROUP BY does not match the sort key (Info) + +Aligning the `GROUP BY` prefix with `ORDER BY` enables streaming aggregation +without a hash table. + +## CH016 — Multi-table JOIN (Info) + +ClickHouse builds an in-memory hash table per join. Keep the large table on the +left or replace dimension joins with a dictionary. + +## CH019 — FINAL modifier usage (Warning) + +`FINAL` merges parts at read time. Prefer `argMax`/`argMin` or +`ReplacingMergeTree` with background merges. + +## CH021 — PREWHERE opportunity (Info) + +A `WHERE` filter reads all selected columns before filtering. Moving the +selective filter columns to `PREWHERE` lets ClickHouse read them first and skip +granules early. + +## CH022 — Heavy mutation (Warning) + +`ALTER TABLE ... UPDATE/DELETE` rewrites whole parts asynchronously and is +expensive. Prefer a `ReplacingMergeTree` with a version column, or drop whole +partitions. + +## CH023 — Manual OPTIMIZE FINAL (Warning) + +`OPTIMIZE TABLE ... FINAL` rewrites parts synchronously. Rely on background +merges and reserve `OPTIMIZE FINAL` for maintenance windows. + +## CH024 — Dictionary lookup opportunity (Info) + +A `JOIN` against a table that is also defined as a dictionary pays full-table +cost. Use `dictGet`/`dictHas` on the dictionary instead. + +## CH025 — GROUP BY on a plain String key (Info) + +Grouping on a plain `String` builds large hash tables. Use +`LowCardinality(String)` for low-cardinality grouping keys. diff --git a/docs/src/rules/index.md b/docs/src/rules/index.md index e8cec07..a641e5b 100644 --- a/docs/src/rules/index.md +++ b/docs/src/rules/index.md @@ -5,7 +5,8 @@ SPDX-License-Identifier: MIT # Rules Overview -35 built-in rules across four categories. Every rule has a stable ID, a default +35 built-in rules across four categories, plus ClickHouse-specific rules that +activate only with `--dialect clickhouse`. Every rule has a stable ID, a default severity, and a suggestion attached to each violation. Rules can be disabled or re-weighted via [configuration](../configuration.md). @@ -15,6 +16,7 @@ re-weighted via [configuration](../configuration.md). | [Style](style.md) | `STYLE001`–`STYLE004` | Readability and maintainability | | [Security](security.md) | `SEC001`–`SEC008` | Destructive statements without guards | | [Schema-Aware](schema.md) | `SCHEMA001`–`SCHEMA004` | Cross-checking queries against DDL | +| [ClickHouse](clickhouse.md) | `CH001`–`CH019` | Sparse index, partition pruning, columnar anti-patterns | ## Severities diff --git a/fuzz/.gitignore b/fuzz/.gitignore new file mode 100644 index 0000000..258328e --- /dev/null +++ b/fuzz/.gitignore @@ -0,0 +1,4 @@ +target +artifacts +corpus +quarantine diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock new file mode 100644 index 0000000..5711d6b --- /dev/null +++ b/fuzz/Cargo.lock @@ -0,0 +1,2256 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "clap" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "colored" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "compact_str" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79fcda08c33bb58b97008b2cdada6622500e949e060f5913361763121abd2416" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "serde", + "static_assertions", + "zmij", +] + +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "unicode-width", + "windows-sys 0.61.2", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "fuzz" +version = "0.0.0" +dependencies = [ + "libfuzzer-sys", + "sql_query_analyzer", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "indicatif" +version = "0.18.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9433806cd6b4ec1aba79c021c7e4c58fb4c3b9977c085062e611ac929998fb0c" +dependencies = [ + "console", + "portable-atomic", + "unicode-width", + "unit-prefix", + "web-time", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "masterror" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c84f6c983b337a166b1b8d9028fef5efbfa07c2305ba2b0a8c1e7e07a6cd14b3" +dependencies = [ + "http", + "itoa", + "masterror-derive", + "masterror-template", + "ryu", + "serde", + "sha2", + "toml", + "uuid", +] + +[[package]] +name = "masterror-derive" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0cf256bb91d6b80df4256f0be16ab02831ef6027bbdd00cf45776902fb8ccb" +dependencies = [ + "masterror-template", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "masterror-template" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32029235c1d9cb2220065380208dee3bd31452e26d67b71a32e4f0306c0c9e23" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "recursive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0786a43debb760f491b1bc0269fe5e84155353c67482b9e60d0cfb596054b43e" +dependencies = [ + "recursive-proc-macro-impl", + "stacker", +] + +[[package]] +name = "recursive-proc-macro-impl" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "sql_query_analyzer" +version = "0.16.0" +dependencies = [ + "clap", + "colored", + "compact_str", + "indexmap", + "indicatif", + "masterror", + "rayon", + "regex", + "reqwest", + "serde", + "serde_json", + "smallvec", + "sqlparser", + "tokio", + "toml", +] + +[[package]] +name = "sqlparser" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e0d273b4f8ddd14a35ed36862acbc9cc96cec578e36ee1881a9d42e0e0f2c8" +dependencies = [ + "log", + "recursive", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "1.2.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.7+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "unit-prefix" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml new file mode 100644 index 0000000..3de808f --- /dev/null +++ b/fuzz/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "fuzz" +version = "0.0.0" +publish = false +edition = "2024" + +[workspace] + +[package.metadata] +cargo-fuzz = true + +[dependencies] +libfuzzer-sys = "0.4" + +[dependencies.sql_query_analyzer] +path = ".." + +[[bin]] +name = "fuzz_preprocess" +path = "fuzz_targets/fuzz_preprocess.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "fuzz_parse_queries" +path = "fuzz_targets/fuzz_parse_queries.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "fuzz_schema_parse" +path = "fuzz_targets/fuzz_schema_parse.rs" +test = false +doc = false +bench = false diff --git a/fuzz/fuzz_targets/fuzz_parse_queries.rs b/fuzz/fuzz_targets/fuzz_parse_queries.rs new file mode 100644 index 0000000..a769caf --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_parse_queries.rs @@ -0,0 +1,21 @@ +#![no_main] + +//! Fuzzes SQL query parsing for crashes on attacker-controlled input. + +use libfuzzer_sys::fuzz_target; +use sql_query_analyzer::query::parse_queries; +use sql_query_analyzer::query::SqlDialect; + +fuzz_target!(|data: &[u8]| { + if let Ok(sql) = std::str::from_utf8(data) { + for dialect in [ + SqlDialect::Generic, + SqlDialect::ClickHouse, + SqlDialect::MySQL, + SqlDialect::PostgreSQL, + SqlDialect::SQLite, + ] { + let _ = parse_queries(sql, dialect); + } + } +}); diff --git a/fuzz/fuzz_targets/fuzz_preprocess.rs b/fuzz/fuzz_targets/fuzz_preprocess.rs new file mode 100644 index 0000000..21234b2 --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_preprocess.rs @@ -0,0 +1,23 @@ +#![no_main] + +//! Fuzzes the dialect-aware SQL preprocessor for crashes and unbounded +//! resource growth on attacker-controlled SQL. + +use libfuzzer_sys::fuzz_target; +use sql_query_analyzer::preprocessor::Preprocessor; +use sql_query_analyzer::query::SqlDialect; + +fuzz_target!(|data: &[u8]| { + if let Ok(sql) = std::str::from_utf8(data) { + for dialect in [ + SqlDialect::Generic, + SqlDialect::ClickHouse, + SqlDialect::MySQL, + SqlDialect::PostgreSQL, + SqlDialect::SQLite, + ] { + let preprocessor = Preprocessor::new(dialect); + let _ = preprocessor.process(sql); + } + } +}); diff --git a/fuzz/fuzz_targets/fuzz_schema_parse.rs b/fuzz/fuzz_targets/fuzz_schema_parse.rs new file mode 100644 index 0000000..03d5428 --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_schema_parse.rs @@ -0,0 +1,21 @@ +#![no_main] + +//! Fuzzes schema DDL parsing for crashes on attacker-controlled input. + +use libfuzzer_sys::fuzz_target; +use sql_query_analyzer::query::SqlDialect; +use sql_query_analyzer::schema::Schema; + +fuzz_target!(|data: &[u8]| { + if let Ok(sql) = std::str::from_utf8(data) { + for dialect in [ + SqlDialect::Generic, + SqlDialect::ClickHouse, + SqlDialect::MySQL, + SqlDialect::PostgreSQL, + SqlDialect::SQLite, + ] { + let _ = Schema::parse(sql, dialect); + } + } +}); diff --git a/release-plz.toml b/release-plz.toml new file mode 100644 index 0000000..477d46a --- /dev/null +++ b/release-plz.toml @@ -0,0 +1,106 @@ +# SPDX-FileCopyrightText: 2026 RAprogramm +# SPDX-License-Identifier: MIT + +# release-plz configuration — https://release-plz.dev/docs/config +# +# Releases are driven by Conventional Commits on `main`: release-plz opens +# (and keeps updating) a single release PR that bumps `Cargo.toml` and +# prepends a section to `CHANGELOG.md`; merging that PR tags `vX.Y.Z`, +# publishes to crates.io, and creates the GitHub release. +# +# See `RELEASE.md` for the human-facing flow. + +[workspace] +allow_dirty = false +changelog_update = true +git_release_enable = true +git_tag_enable = true +publish = true +publish_allow_dirty = false +release = true +# Publish only when the pushed commit belongs to a release PR (a branch +# named `release-plz-*`). Without this, `release-plz release` publishes on +# ANY push where Cargo.toml is ahead of crates.io — a feature PR that bumps +# the version manually (breaking changes must, to satisfy the semver gate) +# would ship straight to crates.io with no curated CHANGELOG section and +# wrong release notes. With `release_always = false` such a merge instead +# flows into the next release PR, and publishing happens only when that PR +# merges. +release_always = false +# The repository history releases every batch of new rules as a minor +# (0.14 -> 0.15 -> 0.16), so a `feat:` commit must bump the minor already +# on the 0.x line. release-plz defaults this to `false` (feat bumps patch +# until 1.0), which contradicts the established cadence. +features_always_increment_minor = true +# The semver gate lives in the repository CI (`Semver Checks` job of +# `ci.yml`, workflow `_semver.yml`), which always runs the fresh upstream +# cargo-semver-checks. The version bundled into release-plz lags the stable +# rustdoc JSON format and cannot parse its output, so the bundled check is +# disabled here rather than duplicating a broken copy of the gate. +semver_check = false +pr_labels = ["release"] +pr_draft = false + +[changelog] +# Keep the Keep a Changelog + SemVer preamble verbatim so a regenerated +# file continues the curated history byte-identically. +header = """ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +""" +# Produce, per release: +# ## [x.y.z](compare/vA...vB) - DATE +# ### Added / Fixed / Changed / ... +# - **scope**: message ([#PR](pull/PR) or [sha](commit/sha)) +# The section headings mirror the previous git-cliff output (`cliff.toml` +# heritage) so the CHANGELOG keeps one consistent style across releases. +body = """ + +## [{{ version | trim_start_matches(pat="v") }}]\ +{% if release_link %}({{ release_link }}){% endif %} - {{ timestamp | date(format="%Y-%m-%d") }} +{% for group, commits in commits | group_by(attribute="group") %} +### {{ group | striptags | trim | upper_first }} +{% for commit in commits %} +- {% if commit.scope %}**{{ commit.scope }}**: {% endif %}\ +{% if commit.breaking %}**BREAKING:** {% endif %}\ +{{ commit.message | upper_first }} \ +{% if commit.remote.pr_number %}([#{{ commit.remote.pr_number }}](https://github.com/RAprogramm/sql-query-analyzer/pull/{{ commit.remote.pr_number }}))\ +{% else %}([{{ commit.id | truncate(length=7, end="") }}](https://github.com/RAprogramm/sql-query-analyzer/commit/{{ commit.id }}))\ +{% endif %} +{% endfor %} +{% endfor %} +""" +# Merge-commit subjects carry a trailing `(#123)`; turn it into an issue +# link before the conventional-commit parsers classify the type. +commit_preprocessors = [ + { pattern = '\(#(\d+)\)', replace = "([#${1}](https://github.com/RAprogramm/sql-query-analyzer/issues/${1}))" }, +] +# Same grouping table the previous git-cliff configuration used. +commit_parsers = [ + { message = "^feat", group = "Added" }, + { message = "^fix", group = "Fixed" }, + { message = "^doc", group = "Documentation" }, + { message = "^perf", group = "Performance" }, + { message = "^refactor", group = "Changed" }, + { message = "^style", group = "Changed" }, + { message = "^test", group = "Testing" }, + { message = "^build", group = "Build" }, + { message = "^ci", group = "CI/CD" }, + { message = "^chore\\(release\\)", skip = true }, + { message = "^chore\\(deps\\)", group = "Dependencies" }, + { message = "^deps", group = "Dependencies" }, + { message = "^chore", group = "Miscellaneous" }, + { message = "^revert", group = "Reverted" }, +] +# Keep breaking changes in the changelog even if their type would be skipped. +protect_breaking_commits = true +sort_commits = "newest" + +[[package]] +name = "sql_query_analyzer" +git_release_name = "v{{ version }}" +git_tag_name = "v{{ version }}" diff --git a/src/app.rs b/src/app.rs index 8fcc241..6d08756 100644 --- a/src/app.rs +++ b/src/app.rs @@ -252,7 +252,7 @@ mod tests { let config = Config::default(); let result = execute_command(command, config).await.unwrap(); assert_eq!(result.exit_code, 0); - assert!(!result.stdout.is_empty()); + assert_ne!(result.stdout, [] as [std::string::String; 0]); } #[tokio::test] @@ -348,7 +348,7 @@ mod tests { let config = Config::default(); let result = execute_command(command, config).await.unwrap(); let output = result.stdout.join(""); - assert!(output.contains("{") || output.contains("queries_analyzed")); + assert!(output.contains('{') || output.contains("queries_analyzed")); } #[tokio::test] @@ -372,7 +372,7 @@ mod tests { }; let config = Config::default(); let result = execute_command(command, config).await.unwrap(); - assert!(!result.stdout.is_empty()); + assert_ne!(result.stdout, [] as [std::string::String; 0]); } #[tokio::test] @@ -396,7 +396,7 @@ mod tests { }; let config = Config::default(); let result = execute_command(command, config).await.unwrap(); - assert!(!result.stdout.is_empty()); + assert_ne!(result.stdout, [] as [std::string::String; 0]); } #[tokio::test] diff --git a/src/app/analyze.rs b/src/app/analyze.rs index 241a14d..b5a45c2 100644 --- a/src/app/analyze.rs +++ b/src/app/analyze.rs @@ -86,14 +86,18 @@ use crate::{ /// ``` pub async fn run_analyze(params: AnalyzeParams, config: Config) -> AppResult { let schema_sql = read_to_string(¶ms.schema_path) - .map_err(|e| file_read_error(¶ms.schema_path, e))?; + .map_err(|e| file_read_error(¶ms.schema_path, &e))?; let queries_sql = read_queries_input(¶ms.queries_path)?; let sql_dialect = convert_dialect(params.dialect); let parsed_schema = Schema::parse(&schema_sql, sql_dialect)?; let parsed_queries = parse_queries_cached(&queries_sql, sql_dialect)?; let schema_summary = parsed_schema.to_summary(); let output_opts = create_output_options(params.output_format, params.no_color, params.verbose); - let runner = RuleRunner::with_schema_and_config(parsed_schema.clone(), config.rules.clone()); + let runner = RuleRunner::with_schema_and_config_and_dialect( + sql_dialect, + parsed_schema.clone(), + &config.rules + ); let static_report = runner.analyze(&parsed_queries); let static_output = format_static_analysis(&static_report, &output_opts); let exit_code = calculate_exit_code(&static_report); @@ -109,10 +113,10 @@ pub async fn run_analyze(params: AnalyzeParams, config: Config) -> AppResult AppResult AppResult SqlDialect { +#[must_use] +pub const fn convert_dialect(dialect: Dialect) -> SqlDialect { match dialect { Dialect::Generic => SqlDialect::Generic, Dialect::Mysql => SqlDialect::MySQL, @@ -62,7 +63,8 @@ pub fn convert_dialect(dialect: Dialect) -> SqlDialect { /// let format = convert_format(Format::Json); /// assert!(matches!(format, OutputFormat::Json)); /// ``` -pub fn convert_format(format: Format) -> OutputFormat { +#[must_use] +pub const fn convert_format(format: Format) -> OutputFormat { match format { Format::Text => OutputFormat::Text, Format::Json => OutputFormat::Json, diff --git a/src/app/helpers.rs b/src/app/helpers.rs index 3645098..e3c894a 100644 --- a/src/app/helpers.rs +++ b/src/app/helpers.rs @@ -5,6 +5,7 @@ //! providers, and managing configuration defaults. use std::{ + env, fs::read_to_string, io::{self, Read} }; @@ -44,6 +45,7 @@ use crate::{ /// let report = AnalysisReport::new(1, 0); /// assert_eq!(calculate_exit_code(&report), 0); /// ``` +#[must_use] pub fn calculate_exit_code(report: &AnalysisReport) -> i32 { if report .violations @@ -51,14 +53,13 @@ pub fn calculate_exit_code(report: &AnalysisReport) -> i32 { .any(|v| v.severity == Severity::Error) { 2 - } else if report - .violations - .iter() - .any(|v| v.severity == Severity::Warning) - { - 1 } else { - 0 + i32::from( + report + .violations + .iter() + .any(|v| v.severity == Severity::Warning) + ) } } @@ -83,10 +84,10 @@ pub fn read_queries_input(path: &str) -> AppResult { let mut buffer = String::new(); io::stdin() .read_to_string(&mut buffer) - .map_err(|e| file_read_error("stdin", e))?; + .map_err(|e| file_read_error("stdin", &e))?; Ok(buffer) } else { - read_to_string(path).map_err(|e| file_read_error(path, e)) + read_to_string(path).map_err(|e| file_read_error(path, &e)) } } @@ -132,7 +133,12 @@ pub fn parse_queries_cached(sql: &str, dialect: SqlDialect) -> AppResult OutputOptions { +#[must_use] +pub const fn create_output_options( + format: Format, + no_color: bool, + verbose: bool +) -> OutputOptions { OutputOptions { format: convert_format(format), colored: !no_color, @@ -143,7 +149,7 @@ pub fn create_output_options(format: Format, no_color: bool, verbose: bool) -> O /// Builds an LLM provider configuration from CLI parameters. /// /// Constructs the appropriate `LlmProvider` variant based on the -/// selected provider type. For cloud providers (OpenAI, Anthropic), +/// selected provider type. For cloud providers (`OpenAI`, Anthropic), /// an API key is required. /// /// # Arguments @@ -173,7 +179,8 @@ pub fn build_llm_provider( })?; Ok(LlmProvider::OpenAI { api_key: key, - model + model, + base_url: env_base_url("OPENAI_BASE_URL") }) } Provider::Anthropic => { @@ -182,7 +189,8 @@ pub fn build_llm_provider( })?; Ok(LlmProvider::Anthropic { api_key: key, - model + model, + base_url: env_base_url("ANTHROPIC_BASE_URL") }) } Provider::Ollama => Ok(LlmProvider::Ollama { @@ -192,6 +200,15 @@ pub fn build_llm_provider( } } +/// Reads an optional non-empty base URL override from the environment. +/// +/// Used to point cloud providers at Azure `OpenAI`, gateways, or +/// OpenAI-compatible proxies. Returns `None` when the variable is unset or +/// blank. +fn env_base_url(var: &str) -> Option { + env::var(var).ok().filter(|value| !value.trim().is_empty()) +} + /// Checks if LLM access is available. /// /// Determines whether LLM analysis can be performed based on the @@ -206,7 +223,8 @@ pub fn build_llm_provider( /// # Returns /// /// `true` if LLM access is available, `false` otherwise. -pub fn has_llm_access(api_key: &Option, provider: &Provider) -> bool { +#[must_use] +pub const fn has_llm_access(api_key: Option<&String>, provider: Provider) -> bool { api_key.is_some() || matches!(provider, Provider::Ollama) } @@ -226,10 +244,11 @@ pub fn has_llm_access(api_key: &Option, provider: &Provider) -> bool { /// # Returns /// /// The resolved model name. +#[must_use] pub fn get_effective_model( model: Option, config_model: Option, - provider: &Provider + provider: Provider ) -> String { model .or(config_model) @@ -249,6 +268,7 @@ pub fn get_effective_model( /// # Returns /// /// The resolved Ollama URL. +#[must_use] pub fn get_effective_ollama_url(url: String, config_url: Option) -> String { if url == "http://localhost:11434" { config_url.unwrap_or(url) @@ -339,39 +359,39 @@ mod tests { #[test] fn test_has_llm_access_with_api_key() { - assert!(has_llm_access(&Some("key".to_string()), &Provider::OpenAI)); + assert!(has_llm_access(Some(&"key".to_string()), Provider::OpenAI)); } #[test] fn test_has_llm_access_ollama_no_key() { - assert!(has_llm_access(&None, &Provider::Ollama)); + assert!(has_llm_access(None, Provider::Ollama)); } #[test] fn test_has_llm_access_openai_no_key() { - assert!(!has_llm_access(&None, &Provider::OpenAI)); + assert!(!has_llm_access(None, Provider::OpenAI)); } #[test] fn test_has_llm_access_anthropic_no_key() { - assert!(!has_llm_access(&None, &Provider::Anthropic)); + assert!(!has_llm_access(None, Provider::Anthropic)); } #[test] fn test_get_effective_model_explicit() { - let model = get_effective_model(Some("gpt-4o".to_string()), None, &Provider::OpenAI); + let model = get_effective_model(Some("gpt-4o".to_string()), None, Provider::OpenAI); assert_eq!(model, "gpt-4o"); } #[test] fn test_get_effective_model_from_config() { - let model = get_effective_model(None, Some("claude-3".to_string()), &Provider::Anthropic); + let model = get_effective_model(None, Some("claude-3".to_string()), Provider::Anthropic); assert_eq!(model, "claude-3"); } #[test] fn test_get_effective_model_default() { - let model = get_effective_model(None, None, &Provider::OpenAI); + let model = get_effective_model(None, None, Provider::OpenAI); assert_eq!(model, "gpt-4"); } diff --git a/src/app/types.rs b/src/app/types.rs index ca54ea7..4d234aa 100644 --- a/src/app/types.rs +++ b/src/app/types.rs @@ -42,7 +42,7 @@ pub struct AnalyzeParams { pub queries_path: String, /// LLM provider for AI-powered analysis. pub provider: Provider, - /// API key for cloud LLM providers (OpenAI, Anthropic). + /// API key for cloud LLM providers (`OpenAI`, Anthropic). pub api_key: Option, /// Model name to use for LLM analysis. pub model: Option, @@ -137,7 +137,7 @@ mod tests { dry_run: false, no_color: false }; - assert!(format!("{:?}", params).contains("AnalyzeParams")); + assert!(format!("{params:?}").contains("AnalyzeParams")); } #[test] @@ -167,7 +167,7 @@ mod tests { llm_output: None, dry_run_info: None }; - assert!(format!("{:?}", result).contains("AnalyzeResult")); + assert!(format!("{result:?}").contains("AnalyzeResult")); } #[test] @@ -176,7 +176,7 @@ mod tests { schema_summary: "schema".to_string(), queries_summary: "queries".to_string() }; - assert!(format!("{:?}", info).contains("DryRunInfo")); + assert!(format!("{info:?}").contains("DryRunInfo")); } #[test] @@ -185,7 +185,7 @@ mod tests { exit_code: 0, stdout: vec!["line1".to_string()] }; - assert!(format!("{:?}", output).contains("CommandOutput")); + assert!(format!("{output:?}").contains("CommandOutput")); } #[test] @@ -194,7 +194,7 @@ mod tests { exit_code: 1, stdout: vec!["error".to_string()] }; - let cloned = output.clone(); + let cloned = output; assert_eq!(cloned.exit_code, 1); assert_eq!(cloned.stdout.len(), 1); } diff --git a/src/cache.rs b/src/cache.rs index 3ec2c7e..1b87de1 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -47,6 +47,7 @@ pub struct QueryCache { } impl QueryCache { + #[must_use] pub fn new(max_size: usize) -> Self { Self { cache: HashMap::with_capacity(max_size), @@ -60,6 +61,7 @@ impl QueryCache { hasher.finish() } + #[must_use] pub fn get(&self, sql: &str) -> Option> { let key = Self::hash_key(sql); self.cache.get(&key).cloned() diff --git a/src/cli.rs b/src/cli.rs index a17bb34..0f27e97 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -27,7 +27,7 @@ pub enum Commands { #[arg(short, long, value_enum, default_value = "ollama")] provider: Provider, - /// API key for OpenAI or Anthropic + /// API key for `OpenAI` or Anthropic #[arg(short, long, env = "LLM_API_KEY", hide_env_values = true)] api_key: Option, @@ -61,7 +61,7 @@ pub enum Commands { } } -#[derive(Debug, Clone, ValueEnum)] +#[derive(Debug, Clone, Copy, ValueEnum)] pub enum Provider { OpenAI, Anthropic, @@ -70,7 +70,8 @@ pub enum Provider { impl Provider { /// Get default model for provider - pub fn default_model(&self) -> &str { + #[must_use] + pub const fn default_model(&self) -> &str { match self { Self::OpenAI => "gpt-4", Self::Anthropic => "claude-sonnet-4-20250514", @@ -79,7 +80,7 @@ impl Provider { } } -#[derive(Debug, Clone, ValueEnum)] +#[derive(Debug, Clone, Copy, ValueEnum)] #[non_exhaustive] pub enum Dialect { Generic, @@ -89,7 +90,7 @@ pub enum Dialect { Clickhouse } -#[derive(Debug, Clone, ValueEnum)] +#[derive(Debug, Clone, Copy, ValueEnum)] pub enum Format { Text, Json, diff --git a/src/config.rs b/src/config.rs index d435b4b..7cc448b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -22,7 +22,7 @@ //! max_retries = 3 //! initial_delay_ms = 1000 //! max_delay_ms = 30000 -//! backoff_factor = 2.0 +//! backoff_factor = 2 //! //! [rules] //! disabled = ["STYLE001", "PERF011"] @@ -64,7 +64,7 @@ pub struct RulesConfig { /// Disabled rule IDs #[serde(default)] pub disabled: Vec, - /// Severity overrides (rule_id -> severity) + /// Severity overrides (`rule_id` -> severity) #[serde(default)] pub severity: HashMap } @@ -95,7 +95,7 @@ pub struct RetryConfig { pub max_retries: u32, pub initial_delay_ms: u64, pub max_delay_ms: u64, - pub backoff_factor: f64 + pub backoff_factor: u32 } impl Default for RetryConfig { @@ -104,7 +104,7 @@ impl Default for RetryConfig { max_retries: 3, initial_delay_ms: 1000, max_delay_ms: 30000, - backoff_factor: 2.0 + backoff_factor: 2 } } } @@ -117,6 +117,11 @@ impl Config { /// 2. Config file in current directory (.sql-analyzer.toml) /// 3. Config file in home directory (~/.config/sql-analyzer/config.toml) /// 4. Default values + /// + /// # Errors + /// + /// Returns [`crate::AppError`] if a configuration file exists but cannot be + /// read or is not valid TOML. pub fn load() -> AppResult { let mut config = Self::default(); if let Some(home) = env::var_os("HOME") { @@ -126,17 +131,17 @@ impl Config { .join("config.toml"); if home_config.exists() { let content = fs::read_to_string(&home_config) - .map_err(|e| config_error(format!("Failed to read config file: {}", e)))?; + .map_err(|e| config_error(format!("Failed to read config file: {e}")))?; config = toml::from_str(&content) - .map_err(|e| config_error(format!("Invalid config file: {}", e)))?; + .map_err(|e| config_error(format!("Invalid config file: {e}")))?; } } let local_config = PathBuf::from(".sql-analyzer.toml"); if local_config.exists() { let content = fs::read_to_string(&local_config) - .map_err(|e| config_error(format!("Failed to read config file: {}", e)))?; + .map_err(|e| config_error(format!("Failed to read config file: {e}")))?; config = toml::from_str(&content) - .map_err(|e| config_error(format!("Invalid config file: {}", e)))?; + .map_err(|e| config_error(format!("Invalid config file: {e}")))?; } if let Ok(api_key) = env::var("LLM_API_KEY") { config.llm.api_key = Some(api_key); diff --git a/src/error.rs b/src/error.rs index e320f53..960bbbd 100644 --- a/src/error.rs +++ b/src/error.rs @@ -18,8 +18,9 @@ pub use masterror::{AppError, AppResult}; /// /// * `path` - The file path that failed to read /// * `source` - The underlying IO error -pub fn file_read_error(path: &str, source: std::io::Error) -> AppError { - AppError::internal(format!("Failed to read file '{}': {}", path, source)) +#[must_use] +pub fn file_read_error(path: &str, source: &std::io::Error) -> AppError { + AppError::internal(format!("Failed to read file '{path}': {source}")) } /// Create schema parse error with optional position info @@ -40,11 +41,12 @@ pub fn llm_api_error(message: impl Into) -> AppError { } /// Create HTTP error -pub fn http_error(err: reqwest::Error) -> AppError { +#[must_use] +pub fn http_error(err: &reqwest::Error) -> AppError { let msg = if err.is_timeout() { - format!("Request timeout: {}", err) + format!("Request timeout: {err}") } else if err.is_connect() { - format!("Connection failed: {}", err) + format!("Connection failed: {err}") } else if err.is_status() { format!("HTTP error {}: {}", err.status().unwrap_or_default(), err) } else { @@ -65,17 +67,18 @@ pub fn config_error(message: impl Into) -> AppError { /// - Attempts to extract line and column information from sqlparser errors /// - Uses "Line: X, Column Y" pattern matching fn format_sql_error(prefix: &str, message: &str) -> String { - if let Some(pos) = extract_position(message) { - format!( - "{prefix} at line {line}, column {column}:\n {message}", - prefix = prefix, - line = pos.line, - column = pos.column, - message = message - ) - } else { - format!("{}:\n {}", prefix, message) - } + extract_position(message).map_or_else( + || format!("{prefix}:\n {message}"), + |pos| { + format!( + "{prefix} at line {line}, column {column}:\n {message}", + prefix = prefix, + line = pos.line, + column = pos.column, + message = message + ) + } + ) } struct SqlPosition { diff --git a/src/llm.rs b/src/llm.rs index a7a07d7..7b3cdcc 100644 --- a/src/llm.rs +++ b/src/llm.rs @@ -6,12 +6,24 @@ //! //! # Supported Providers //! -//! | Provider | Endpoint | Authentication | -//! |----------|----------|----------------| -//! | OpenAI | `api.openai.com` | Bearer token | -//! | Anthropic | `api.anthropic.com` | x-api-key header | +//! | Provider | Default Endpoint | Authentication | +//! |----------|------------------|----------------| +//! | `OpenAI` | `api.openai.com` (overridable) | Bearer token | +//! | Anthropic | `api.anthropic.com` (overridable) | x-api-key header | //! | Ollama | Local (configurable) | None | //! +//! # Custom Endpoints +//! +//! `OpenAI` and Anthropic accept an optional `base_url` override, enabling +//! Azure `OpenAI`, self-hosted gateways, OpenAI-compatible proxies, and local +//! servers (llama.cpp, Ollama, vLLM, LM Studio, `LocalAI`). When `base_url` is +//! `None` the official endpoint is used. +//! +//! The override accepts either convention used across the ecosystem: a bare +//! host (`http://127.0.0.1:8080`) or one that already ends in `/v1` +//! (`http://127.0.0.1:8080/v1`, the form used by the `OpenAI` SDK and most local +//! servers). A duplicated `/v1` segment is never produced. +//! //! # Retry Behavior //! //! The client automatically retries on transient errors: @@ -44,29 +56,53 @@ use tokio::time::sleep; use crate::{ config::RetryConfig, - error::{AppResult, http_error, llm_api_error} + error::{AppResult, http_error, llm_api_error}, + query::SqlDialect }; +/// Prompt guidance for generic/OLTP dialects. +const GENERIC_PROMPT: &str = "You are a database performance expert. Analyze the following SQL \ + queries for potential performance issues, especially regarding index \ + usage."; + +/// Prompt guidance for the `ClickHouse` dialect. +const CLICKHOUSE_PROMPT: &str = "You are a ClickHouse performance expert. Analyze the following \ + queries against a columnar OLAP store. Focus on: ORDER BY / \ + primary-key prefix usage, partition pruning (PARTITION BY), data \ + skipping indexes, avoiding SELECT * and FINAL, LowCardinality and \ + Nullable choices, uniq vs uniqExact, countIf vs subqueries, and \ + JOIN strategy (dictionaries/denormalization)."; + +/// Default `OpenAI` API base URL used when no override is provided. +const OPENAI_BASE_URL: &str = "https://api.openai.com"; + +/// Default Anthropic API base URL used when no override is provided. +const ANTHROPIC_BASE_URL: &str = "https://api.anthropic.com"; + /// LLM provider configuration with authentication credentials. #[derive(Debug, Clone)] pub enum LlmProvider { - /// OpenAI API (GPT-4, GPT-3.5, etc.) + /// `OpenAI` API (GPT-4, GPT-3.5, etc.) OpenAI { /// API key (sk-...) - api_key: String, + api_key: String, /// Model identifier (e.g., "gpt-4", "gpt-3.5-turbo") - model: String + model: String, + /// Optional base URL override for Azure/proxy/compatible endpoints. + base_url: Option }, /// Anthropic API (Claude models) Anthropic { /// API key - api_key: String, + api_key: String, /// Model identifier (e.g., "claude-sonnet-4-20250514") - model: String + model: String, + /// Optional base URL override for gateways and test servers. + base_url: Option }, /// Local Ollama instance Ollama { - /// Base URL (e.g., "http://localhost:11434") + /// Base URL (e.g., "") base_url: String, /// Model name (e.g., "llama3.2", "codellama") model: String @@ -145,14 +181,49 @@ struct OllamaResponse { response: String } +/// Joins a base URL with an endpoint path without duplicating a `/v1` segment. +/// +/// Accepts both ecosystem conventions: a bare host (`http://host:port`) or one +/// already ending in `/v1` (`http://host:port/v1`). Trailing slashes are ignored. +fn join_endpoint(base: &str, path: &str) -> String { + let base = base.trim_end_matches('/'); + let path = path.trim_start_matches('/'); + if let Some(rest) = path.strip_prefix("v1/") + && base.ends_with("/v1") + { + return format!("{base}/{rest}"); + } + format!("{base}/{path}") +} + +/// Build the analysis prompt for a dialect, embedding schema and query +/// summaries. +fn build_prompt(schema_summary: &str, queries_summary: &str, dialect: SqlDialect) -> String { + let guidance = match dialect { + SqlDialect::ClickHouse => CLICKHOUSE_PROMPT, + _ => GENERIC_PROMPT + }; + format!( + "{guidance}\n\n{schema_summary}\n\n{queries_summary}\n\n\ + For each query, identify:\n\ + 1. Whether the existing schema design is used effectively\n\ + 2. Missing schema features that would improve performance\n\ + 3. Full scans or inefficient operations\n\ + 4. Suggestions for query optimization\n\ + Provide specific, actionable recommendations." + ) +} + impl LlmClient { /// Create new LLM client with default retry configuration #[allow(dead_code)] + #[must_use] pub fn new(provider: LlmProvider) -> Self { Self::with_retry_config(provider, RetryConfig::default()) } /// Create new LLM client with custom retry configuration + #[must_use] pub fn with_retry_config(provider: LlmProvider, retry_config: RetryConfig) -> Self { let client = reqwest::Client::builder() .timeout(Duration::from_secs(120)) @@ -166,20 +237,18 @@ impl LlmClient { } /// Analyze SQL queries using LLM with automatic retry - pub async fn analyze(&self, schema_summary: &str, queries_summary: &str) -> AppResult { - let prompt = format!( - "You are a database performance expert. Analyze the following SQL queries \ - for potential performance issues, especially regarding index usage.\n\n\ - {schema}\n\n{queries}\n\n\ - For each query, identify:\n\ - 1. Whether existing indexes can be used effectively\n\ - 2. Missing indexes that would improve performance\n\ - 3. Full table scans or inefficient operations\n\ - 4. Suggestions for query optimization\n\ - Provide specific, actionable recommendations.", - schema = schema_summary, - queries = queries_summary - ); + /// + /// # Errors + /// + /// Returns [`crate::AppError`] if the provider request fails after all + /// retry attempts, or if the response cannot be parsed. + pub async fn analyze( + &self, + schema_summary: &str, + queries_summary: &str, + dialect: SqlDialect + ) -> AppResult { + let prompt = build_prompt(schema_summary, queries_summary, dialect); self.call_with_retry(&prompt).await } @@ -195,13 +264,14 @@ impl LlmClient { delay ); sleep(Duration::from_millis(delay)).await; - delay = ((delay as f64 * self.retry_config.backoff_factor) as u64) + delay = delay + .saturating_mul(u64::from(self.retry_config.backoff_factor)) .min(self.retry_config.max_delay_ms); } match self.call_provider(prompt).await { Ok(result) => return Ok(result), Err(e) => { - if self.is_retryable_error(&e) { + if Self::is_retryable_error(&e) { last_error = Some(e); continue; } @@ -212,7 +282,7 @@ impl LlmClient { Err(last_error.unwrap_or_else(|| llm_api_error("All retry attempts failed"))) } - fn is_retryable_error(&self, error: &masterror::AppError) -> bool { + fn is_retryable_error(error: &masterror::AppError) -> bool { let msg = error.to_string().to_lowercase(); msg.contains("timeout") || msg.contains("connection") @@ -228,12 +298,20 @@ impl LlmClient { match &self.provider { LlmProvider::OpenAI { api_key, - model - } => self.call_openai(api_key, model, prompt).await, + model, + base_url + } => { + self.call_openai(api_key, model, base_url.as_deref(), prompt) + .await + } LlmProvider::Anthropic { api_key, - model - } => self.call_anthropic(api_key, model, prompt).await, + model, + base_url + } => { + self.call_anthropic(api_key, model, base_url.as_deref(), prompt) + .await + } LlmProvider::Ollama { base_url, model @@ -241,7 +319,14 @@ impl LlmClient { } } - async fn call_openai(&self, api_key: &str, model: &str, prompt: &str) -> AppResult { + async fn call_openai( + &self, + api_key: &str, + model: &str, + base_url: Option<&str>, + prompt: &str + ) -> AppResult { + let base = base_url.unwrap_or(OPENAI_BASE_URL); let request = OpenAIRequest { model: model.to_string(), messages: vec![OpenAIRequestMessage { @@ -251,21 +336,18 @@ impl LlmClient { }; let response = self .client - .post("https://api.openai.com/v1/chat/completions") - .header("Authorization", format!("Bearer {}", api_key)) + .post(join_endpoint(base, "v1/chat/completions")) + .header("Authorization", format!("Bearer {api_key}")) .json(&request) .send() .await - .map_err(http_error)?; + .map_err(|e| http_error(&e))?; if !response.status().is_success() { let status = response.status(); let text = response.text().await.unwrap_or_default(); - return Err(llm_api_error(format!( - "OpenAI API error {}: {}", - status, text - ))); + return Err(llm_api_error(format!("OpenAI API error {status}: {text}"))); } - let result: OpenAIResponse = response.json().await.map_err(http_error)?; + let result: OpenAIResponse = response.json().await.map_err(|e| http_error(&e))?; result .choices .first() @@ -273,7 +355,14 @@ impl LlmClient { .ok_or_else(|| llm_api_error("Empty response from OpenAI")) } - async fn call_anthropic(&self, api_key: &str, model: &str, prompt: &str) -> AppResult { + async fn call_anthropic( + &self, + api_key: &str, + model: &str, + base_url: Option<&str>, + prompt: &str + ) -> AppResult { + let base = base_url.unwrap_or(ANTHROPIC_BASE_URL); let request = AnthropicRequest { model: model.to_string(), max_tokens: 4096, @@ -284,22 +373,21 @@ impl LlmClient { }; let response = self .client - .post("https://api.anthropic.com/v1/messages") + .post(join_endpoint(base, "v1/messages")) .header("x-api-key", api_key) .header("anthropic-version", "2023-06-01") .json(&request) .send() .await - .map_err(http_error)?; + .map_err(|e| http_error(&e))?; if !response.status().is_success() { let status = response.status(); let text = response.text().await.unwrap_or_default(); return Err(llm_api_error(format!( - "Anthropic API error {}: {}", - status, text + "Anthropic API error {status}: {text}" ))); } - let result: AnthropicResponse = response.json().await.map_err(http_error)?; + let result: AnthropicResponse = response.json().await.map_err(|e| http_error(&e))?; result .content .first() @@ -320,16 +408,363 @@ impl LlmClient { .json(&request) .send() .await - .map_err(http_error)?; + .map_err(|e| http_error(&e))?; if !response.status().is_success() { let status = response.status(); let text = response.text().await.unwrap_or_default(); - return Err(llm_api_error(format!( - "Ollama API error {}: {}", - status, text - ))); + return Err(llm_api_error(format!("Ollama API error {status}: {text}"))); } - let result: OllamaResponse = response.json().await.map_err(http_error)?; + let result: OllamaResponse = response.json().await.map_err(|e| http_error(&e))?; Ok(result.response) } } + +#[cfg(test)] +mod tests { + use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpListener + }; + + use super::*; + + fn no_retry() -> RetryConfig { + RetryConfig { + max_retries: 0, + initial_delay_ms: 1, + max_delay_ms: 1, + backoff_factor: 1 + } + } + + /// Start a one-shot mock HTTP server returning `status` and `body`. + async fn mock_server(status: &'static str, body: &'static str) -> String { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + if let Ok((mut sock, _)) = listener.accept().await { + let mut buf = [0u8; 8192]; + let _ = sock.read(&mut buf).await; + let resp = format!( + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = sock.write_all(resp.as_bytes()).await; + let _ = sock.shutdown().await; + } + }); + format!("http://{addr}") + } + + #[test] + fn build_prompt_clickhouse_has_columnar_guidance() { + let p = build_prompt("schema", "queries", SqlDialect::ClickHouse); + assert!(p.contains("ClickHouse")); + assert!(p.contains("schema")); + assert!(p.contains("queries")); + } + + #[test] + fn build_prompt_generic_uses_oltp_guidance() { + let p = build_prompt("s", "q", SqlDialect::Generic); + assert!(p.contains("index")); + assert!(!p.contains("columnar")); + } + + #[test] + fn retryable_error_detection() { + assert!(LlmClient::is_retryable_error(&llm_api_error( + "connection refused" + ))); + assert!(LlmClient::is_retryable_error(&llm_api_error( + "HTTP 429 rate limit" + ))); + assert!(LlmClient::is_retryable_error(&llm_api_error("server 503"))); + assert!(!LlmClient::is_retryable_error(&llm_api_error( + "bad request 400" + ))); + } + + #[test] + fn response_structs_parse() { + let o: OllamaResponse = serde_json::from_str(r#"{"response":"hi"}"#).unwrap(); + assert_eq!(o.response, "hi"); + let a: OpenAIResponse = + serde_json::from_str(r#"{"choices":[{"message":{"content":"yo"}}]}"#).unwrap(); + assert_eq!(a.choices[0].message.content, "yo"); + let an: AnthropicResponse = + serde_json::from_str(r#"{"content":[{"text":"hey"}]}"#).unwrap(); + assert_eq!(an.content[0].text, "hey"); + } + + #[tokio::test] + async fn ollama_success_returns_text() { + let base = mock_server("200 OK", r#"{"response":"analysis result"}"#).await; + let client = LlmClient::with_retry_config( + LlmProvider::Ollama { + base_url: base, + model: "m".into() + }, + no_retry() + ); + let out = client + .analyze("schema", "queries", SqlDialect::ClickHouse) + .await + .unwrap(); + assert_eq!(out, "analysis result"); + } + + #[tokio::test] + async fn ollama_error_status_is_returned() { + let base = mock_server("500 Internal Server Error", "boom").await; + let client = LlmClient::with_retry_config( + LlmProvider::Ollama { + base_url: base, + model: "m".into() + }, + no_retry() + ); + let err = client + .analyze("s", "q", SqlDialect::Generic) + .await + .unwrap_err(); + assert!(err.to_string().contains("500")); + } + + #[tokio::test] + async fn connection_failure_is_reported() { + let client = LlmClient::with_retry_config( + LlmProvider::Ollama { + base_url: "http://127.0.0.1:1".into(), + model: "m".into() + }, + no_retry() + ); + assert!(client.analyze("s", "q", SqlDialect::Generic).await.is_err()); + } + + #[test] + fn join_endpoint_handles_both_base_url_conventions() { + assert_eq!( + join_endpoint("http://h:8080", "v1/chat/completions"), + "http://h:8080/v1/chat/completions" + ); + assert_eq!( + join_endpoint("http://h:8080/v1", "v1/chat/completions"), + "http://h:8080/v1/chat/completions" + ); + assert_eq!( + join_endpoint("http://h:8080/v1/", "v1/chat/completions"), + "http://h:8080/v1/chat/completions" + ); + assert_eq!( + join_endpoint("http://h:8080", "v1/messages"), + "http://h:8080/v1/messages" + ); + assert_eq!( + join_endpoint("http://h:8080/v1", "v1/messages"), + "http://h:8080/v1/messages" + ); + } + + #[tokio::test] + async fn openai_success_via_base_url_override() { + let base = mock_server( + "200 OK", + r#"{"choices":[{"message":{"content":"openai result"}}]}"# + ) + .await; + let client = LlmClient::with_retry_config( + LlmProvider::OpenAI { + api_key: "sk-test".into(), + model: "gpt-4".into(), + base_url: Some(base) + }, + no_retry() + ); + let out = client.analyze("s", "q", SqlDialect::Generic).await.unwrap(); + assert_eq!(out, "openai result"); + } + + #[tokio::test] + async fn openai_error_status_is_returned() { + let base = mock_server("401 Unauthorized", r#"{"error":"bad key"}"#).await; + let client = LlmClient::with_retry_config( + LlmProvider::OpenAI { + api_key: "sk-bad".into(), + model: "gpt-4".into(), + base_url: Some(base) + }, + no_retry() + ); + let err = client + .analyze("s", "q", SqlDialect::Generic) + .await + .unwrap_err(); + assert!(err.to_string().contains("401")); + } + + #[tokio::test] + async fn anthropic_success_via_base_url_override() { + let base = mock_server("200 OK", r#"{"content":[{"text":"anthropic result"}]}"#).await; + let client = LlmClient::with_retry_config( + LlmProvider::Anthropic { + api_key: "sk-ant".into(), + model: "claude-3".into(), + base_url: Some(base) + }, + no_retry() + ); + let out = client.analyze("s", "q", SqlDialect::Generic).await.unwrap(); + assert_eq!(out, "anthropic result"); + } + + #[tokio::test] + async fn anthropic_error_status_is_returned() { + let base = mock_server("429 Too Many Requests", "slow down").await; + let client = LlmClient::with_retry_config( + LlmProvider::Anthropic { + api_key: "sk-ant".into(), + model: "claude-3".into(), + base_url: Some(base) + }, + no_retry() + ); + let err = client + .analyze("s", "q", SqlDialect::Generic) + .await + .unwrap_err(); + assert!(err.to_string().contains("429")); + } + + #[test] + fn new_uses_default_retry_config() { + let client = LlmClient::new(LlmProvider::Ollama { + base_url: "http://127.0.0.1:1".into(), + model: "m".into() + }); + assert_eq!(client.retry_config.max_retries, 3); + } + + #[tokio::test] + async fn openai_success_returns_message_content() { + let base = mock_server( + "200 OK", + r#"{"choices":[{"message":{"content":"openai answer"}}]}"# + ) + .await; + let client = LlmClient::with_retry_config( + LlmProvider::OpenAI { + api_key: "sk-test".into(), + model: "gpt-4".into(), + base_url: Some(base) + }, + no_retry() + ); + let out = client + .analyze("schema", "queries", SqlDialect::Generic) + .await + .unwrap(); + assert_eq!(out, "openai answer"); + } + + #[tokio::test] + async fn openai_empty_choices_is_error() { + let base = mock_server("200 OK", r#"{"choices":[]}"#).await; + let client = LlmClient::with_retry_config( + LlmProvider::OpenAI { + api_key: "sk-test".into(), + model: "gpt-4".into(), + base_url: Some(base) + }, + no_retry() + ); + let err = client + .analyze("s", "q", SqlDialect::Generic) + .await + .unwrap_err(); + assert!(err.to_string().contains("Empty response from OpenAI")); + } + + #[tokio::test] + async fn anthropic_success_returns_text() { + let base = mock_server("200 OK", r#"{"content":[{"text":"claude answer"}]}"#).await; + let client = LlmClient::with_retry_config( + LlmProvider::Anthropic { + api_key: "sk-ant".into(), + model: "claude-3".into(), + base_url: Some(base) + }, + no_retry() + ); + let out = client + .analyze("schema", "queries", SqlDialect::PostgreSQL) + .await + .unwrap(); + assert_eq!(out, "claude answer"); + } + + #[tokio::test] + async fn anthropic_empty_content_is_error() { + let base = mock_server("200 OK", r#"{"content":[]}"#).await; + let client = LlmClient::with_retry_config( + LlmProvider::Anthropic { + api_key: "sk-ant".into(), + model: "claude-3".into(), + base_url: Some(base) + }, + no_retry() + ); + let err = client + .analyze("s", "q", SqlDialect::Generic) + .await + .unwrap_err(); + assert!(err.to_string().contains("Empty response from Anthropic")); + } + + /// Start a mock HTTP server answering successive connections in order. + async fn mock_server_seq(responses: &[(&'static str, &'static str)]) -> String { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let responses = responses.to_vec(); + tokio::spawn(async move { + for (status, body) in responses { + let Ok((mut sock, _)) = listener.accept().await else { + continue; + }; + let mut buf = [0u8; 8192]; + let _ = sock.read(&mut buf).await; + let resp = format!( + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = sock.write_all(resp.as_bytes()).await; + let _ = sock.shutdown().await; + } + }); + format!("http://{addr}") + } + + #[tokio::test] + async fn retry_recovers_after_transient_server_error() { + let base = mock_server_seq(&[ + ("500 Internal Server Error", "boom"), + ("200 OK", r#"{"response":"recovered"}"#) + ]) + .await; + let client = LlmClient::with_retry_config( + LlmProvider::Ollama { + base_url: base, + model: "m".into() + }, + RetryConfig { + max_retries: 1, + initial_delay_ms: 1, + max_delay_ms: 2, + backoff_factor: 2 + } + ); + let out = client.analyze("s", "q", SqlDialect::Generic).await.unwrap(); + assert_eq!(out, "recovered"); + } +} diff --git a/src/main.rs b/src/main.rs index f40bdcb..7b4c51b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,7 +17,7 @@ //! Style, or Security, each with configurable severity levels. //! //! 2. **LLM Analysis** (optional) - When API credentials are provided, queries -//! are sent to OpenAI, Anthropic, or a local Ollama instance for deeper +//! are sent to `OpenAI`, Anthropic, or a local Ollama instance for deeper //! semantic analysis and optimization suggestions. //! //! # Quick Start @@ -128,7 +128,7 @@ //! - [`rules`] - Static analysis rule engine and built-in rules //! - [`query`] - SQL parsing and query metadata extraction //! - [`schema`] - Database schema parsing and representation -//! - [`llm`] - LLM provider integrations (OpenAI, Anthropic, Ollama) +//! - [`llm`] - LLM provider integrations (`OpenAI`, Anthropic, Ollama) //! - [`config`] - Configuration loading and validation //! - [`output`] - Result formatting for various output formats //! - [`cache`] - Query parsing cache for performance @@ -181,7 +181,7 @@ async fn run(command: Commands) -> AppResult { fn print_output(output: &CommandOutput) { for line in &output.stdout { - println!("{}", line); + println!("{line}"); } } diff --git a/src/output.rs b/src/output.rs index 6512fdb..0c58136 100644 --- a/src/output.rs +++ b/src/output.rs @@ -1,6 +1,10 @@ +use std::fmt::Write; + use colored::Colorize; use serde::Serialize; +pub mod yaml; + use crate::{ query::Query, rules::{AnalysisReport, Severity} @@ -47,7 +51,7 @@ pub fn format_queries_summary(queries: &[Query], opts: &OutputOptions) -> String OutputFormat::Json | OutputFormat::Sarif => { serde_json::to_string_pretty(queries).unwrap_or_default() } - OutputFormat::Yaml => serde_yaml::to_string(queries).unwrap_or_default(), + OutputFormat::Yaml => yaml::to_string(&queries).unwrap_or_default(), OutputFormat::Text => format_text_summary(queries, opts) } } @@ -67,7 +71,7 @@ pub fn format_analysis_result(queries: &[Query], analysis: &str, opts: &OutputOp queries: queries.to_vec(), analysis: analysis.to_string() }; - serde_yaml::to_string(&result).unwrap_or_default() + yaml::to_string(&result).unwrap_or_default() } OutputFormat::Text => { let mut output = String::new(); @@ -85,49 +89,77 @@ pub fn format_analysis_result(queries: &[Query], analysis: &str, opts: &OutputOp fn format_text_summary(queries: &[Query], opts: &OutputOptions) -> String { let mut summary = String::from("SQL Queries:\n\n"); for (i, query) in queries.iter().enumerate() { - let header = format!("Query #{} ({}):", i + 1, query.query_type); + let header = format!("Query #{} ({}):", i + 1, query.kind); if opts.colored { summary.push_str(&header.cyan().bold().to_string()); } else { summary.push_str(&header); } summary.push('\n'); - summary.push_str(&format!("{}\n", query.raw)); + let _ = writeln!(summary, "{}", query.raw); if !query.cte_names.is_empty() { - let ctes: Vec<&str> = query.cte_names.iter().map(|s| s.as_str()).collect(); - summary.push_str(&format!("CTEs: {}\n", ctes.join(", "))); + let ctes: Vec<&str> = query + .cte_names + .iter() + .map(compact_str::CompactString::as_str) + .collect(); + let _ = writeln!(summary, "CTEs: {}", ctes.join(", ")); } - let tables: Vec<&str> = query.tables.iter().map(|s| s.as_str()).collect(); - summary.push_str(&format!("Tables: {}\n", tables.join(", "))); + let tables: Vec<&str> = query + .tables + .iter() + .map(compact_str::CompactString::as_str) + .collect(); + let _ = writeln!(summary, "Tables: {}", tables.join(", ")); if !query.where_cols.is_empty() { - let cols: Vec<&str> = query.where_cols.iter().map(|s| s.as_str()).collect(); - summary.push_str(&format!("WHERE columns: {}\n", cols.join(", "))); + let cols: Vec<&str> = query + .where_cols + .iter() + .map(compact_str::CompactString::as_str) + .collect(); + let _ = writeln!(summary, "WHERE columns: {}", cols.join(", ")); } if !query.join_cols.is_empty() { - let cols: Vec<&str> = query.join_cols.iter().map(|s| s.as_str()).collect(); - summary.push_str(&format!("JOIN columns: {}\n", cols.join(", "))); + let cols: Vec<&str> = query + .join_cols + .iter() + .map(compact_str::CompactString::as_str) + .collect(); + let _ = writeln!(summary, "JOIN columns: {}", cols.join(", ")); } if !query.order_cols.is_empty() { - let cols: Vec<&str> = query.order_cols.iter().map(|s| s.as_str()).collect(); - summary.push_str(&format!("ORDER BY columns: {}\n", cols.join(", "))); + let cols: Vec<&str> = query + .order_cols + .iter() + .map(compact_str::CompactString::as_str) + .collect(); + let _ = writeln!(summary, "ORDER BY columns: {}", cols.join(", ")); } if !query.group_cols.is_empty() { - let cols: Vec<&str> = query.group_cols.iter().map(|s| s.as_str()).collect(); - summary.push_str(&format!("GROUP BY columns: {}\n", cols.join(", "))); + let cols: Vec<&str> = query + .group_cols + .iter() + .map(compact_str::CompactString::as_str) + .collect(); + let _ = writeln!(summary, "GROUP BY columns: {}", cols.join(", ")); } if !query.having_cols.is_empty() { - let cols: Vec<&str> = query.having_cols.iter().map(|s| s.as_str()).collect(); - summary.push_str(&format!("HAVING columns: {}\n", cols.join(", "))); + let cols: Vec<&str> = query + .having_cols + .iter() + .map(compact_str::CompactString::as_str) + .collect(); + let _ = writeln!(summary, "HAVING columns: {}", cols.join(", ")); } if !query.window_funcs.is_empty() { let funcs: Vec<&str> = query.window_funcs.iter().map(|w| w.name.as_str()).collect(); - summary.push_str(&format!("Window functions: {}\n", funcs.join(", "))); + let _ = writeln!(summary, "Window functions: {}", funcs.join(", ")); } if let Some(limit) = query.limit { - summary.push_str(&format!("LIMIT: {}\n", limit)); + let _ = writeln!(summary, "LIMIT: {limit}"); } if let Some(offset) = query.offset { - summary.push_str(&format!("OFFSET: {}\n", offset)); + let _ = writeln!(summary, "OFFSET: {offset}"); } if query.has_distinct { summary.push_str("Has DISTINCT: yes\n"); @@ -139,39 +171,44 @@ fn format_text_summary(queries: &[Query], opts: &OutputOptions) -> String { summary.push_str("Has subquery: yes\n"); } if opts.verbose { - let c = query.complexity(); - let complexity_label = if c.score < 5 { - if opts.colored { - "Low".green().to_string() - } else { - "Low".to_string() - } - } else if c.score < 15 { - if opts.colored { - "Medium".yellow().to_string() - } else { - "Medium".to_string() - } - } else if opts.colored { - "High".red().to_string() - } else { - "High".to_string() - }; - summary.push_str(&format!( - "Complexity: {} (score: {})\n", - complexity_label, c.score - )); + write_complexity(&mut summary, query, opts); } summary.push('\n'); } summary } -/// Format static analysis report +/// Append the colored complexity line for a query to `summary`. +fn write_complexity(summary: &mut String, query: &Query, opts: &OutputOptions) { + let c = query.complexity(); + let complexity_label = if c.score < 5 { + if opts.colored { + "Low".green().to_string() + } else { + "Low".to_string() + } + } else if c.score < 15 { + if opts.colored { + "Medium".yellow().to_string() + } else { + "Medium".to_string() + } + } else if opts.colored { + "High".red().to_string() + } else { + "High".to_string() + }; + let _ = writeln!( + summary, + "Complexity: {} (score: {})", + complexity_label, c.score + ); +} +#[must_use] pub fn format_static_analysis(report: &AnalysisReport, opts: &OutputOptions) -> String { match opts.format { OutputFormat::Json => serde_json::to_string_pretty(report).unwrap_or_default(), - OutputFormat::Yaml => serde_yaml::to_string(report).unwrap_or_default(), + OutputFormat::Yaml => yaml::to_string(report).unwrap_or_default(), OutputFormat::Text => format_text_analysis(report, opts), OutputFormat::Sarif => format_sarif(report) } @@ -280,14 +317,15 @@ fn format_text_analysis(report: &AnalysisReport, opts: &OutputOptions) -> String } } }; - output.push_str(&format!( - " [{severity:>5}] {rule_id}: {message}\n", + let _ = writeln!( + output, + " [{severity:>5}] {rule_id}: {message}", severity = severity_str, rule_id = violation.rule_id, message = violation.message - )); + ); if let Some(suggestion) = &violation.suggestion { - let suggestion_line = format!(" → {}\n", suggestion); + let suggestion_line = format!(" → {suggestion}\n"); if opts.colored { output.push_str(&suggestion_line.dimmed().to_string()); } else { diff --git a/src/output/yaml.rs b/src/output/yaml.rs new file mode 100644 index 0000000..e71cd93 --- /dev/null +++ b/src/output/yaml.rs @@ -0,0 +1,276 @@ +//! Minimal, dependency-free YAML serializer for analysis output. +//! +//! Serializes any [`serde::Serialize`] value to YAML by routing through +//! [`serde_json::Value`]. It intentionally avoids the unmaintained +//! `libyaml`-backed crates while covering the data shapes the analyzer emits: +//! maps, sequences, strings, numbers, booleans, and null. + +use std::fmt::Write; + +use serde::Serialize; +use serde_json::Value; + +/// Serialize a value to a YAML document string. +/// +/// # Errors +/// +/// Returns the serialization error when the value cannot be represented as +/// JSON, which is the intermediate representation used for emission. +pub fn to_string(value: &T) -> Result { + let json = serde_json::to_value(value)?; + let mut out = String::new(); + match &json { + Value::Object(map) => emit_object(map, 0, true, &mut out), + Value::Array(items) => emit_array(items, 0, true, &mut out), + _ => emit_scalar(&json, &mut out) + } + if !out.ends_with('\n') { + out.push('\n'); + } + Ok(out) +} + +/// Emit a scalar JSON value on the current line. +fn emit_scalar(value: &Value, out: &mut String) { + match value { + Value::Null => out.push_str("null\n"), + Value::Bool(b) => { + let _ = writeln!(out, "{b}"); + } + Value::Number(n) => { + let _ = writeln!(out, "{n}"); + } + Value::String(s) => { + out.push_str(&format_scalar(s)); + out.push('\n'); + } + Value::Array(items) if items.is_empty() => out.push_str("[]\n"), + Value::Object(map) if map.is_empty() => out.push_str("{}\n"), + _ => out.push('\n') + } +} + +/// Emit a JSON array as a YAML sequence. +/// +/// When `first_on_current_line` is set, the cursor already sits where the first +/// `- ` marker belongs (e.g. right after a parent `- `), so no leading newline +/// or indent is written for the first item. +fn emit_array(items: &[Value], indent: usize, first_on_current_line: bool, out: &mut String) { + if items.is_empty() { + out.push_str("[]\n"); + return; + } + for (i, item) in items.iter().enumerate() { + if i == 0 && first_on_current_line { + // cursor already positioned for the dash + } else { + push_indent(out, indent); + } + out.push_str("- "); + match item { + Value::Object(map) => emit_object(map, indent + 2, true, out), + Value::Array(inner) => emit_array(inner, indent + 2, true, out), + _ => emit_scalar(item, out) + } + } +} + +/// Emit a JSON object as a YAML mapping. +/// +/// When `first_on_current_line` is set, the first key is written at the current +/// cursor position (used after a `- ` marker); otherwise every key is indented. +fn emit_object( + map: &serde_json::Map, + indent: usize, + first_on_current_line: bool, + out: &mut String +) { + if map.is_empty() { + out.push_str("{}\n"); + return; + } + for (i, (key, value)) in map.iter().enumerate() { + if !(i == 0 && first_on_current_line) { + push_indent(out, indent); + } + out.push_str(&format_key(key)); + out.push(':'); + match value { + Value::Object(inner) if inner.is_empty() => out.push_str(" {}\n"), + Value::Array(inner) if inner.is_empty() => out.push_str(" []\n"), + Value::Object(inner) => emit_object(inner, indent + 2, false, out), + Value::Array(inner) => emit_array(inner, indent + 2, false, out), + _ => { + out.push(' '); + emit_scalar(value, out); + } + } + } +} + +/// Append `indent` spaces to the output. +fn push_indent(out: &mut String, indent: usize) { + for _ in 0..indent { + out.push(' '); + } +} + +/// Format a mapping key, quoting it when it is not a plain-safe scalar. +fn format_key(key: &str) -> String { + if is_plain_safe(key) { + key.to_string() + } else { + quote(key) + } +} + +/// Format a string scalar, choosing plain or double-quoted style. +fn format_scalar(s: &str) -> String { + if is_plain_safe(s) { + s.to_string() + } else { + quote(s) + } +} + +/// Decide whether a string can be emitted as a plain YAML scalar. +fn is_plain_safe(s: &str) -> bool { + if s.is_empty() { + return false; + } + if s.chars().any(char::is_control) { + return false; + } + if s.starts_with([' ', '-']) || s.ends_with(' ') { + return false; + } + if s.contains(": ") || s.contains(" #") { + return false; + } + if s.contains([ + ':', '#', '[', ']', '{', '}', ',', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`' + ]) { + return false; + } + !matches!( + s.to_lowercase().as_str(), + "null" | "~" | "true" | "false" | "yes" | "no" | "on" | "off" + ) && !looks_numeric(s) +} + +/// Detect strings that YAML would reinterpret as numbers or booleans. +fn looks_numeric(s: &str) -> bool { + !s.is_empty() && s.parse::().is_ok() +} + +/// Emit a double-quoted YAML scalar with escapes. +fn quote(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if c.is_control() => { + let _ = write!(out, "\\u{:04x}", c as u32); + } + c => out.push(c) + } + } + out.push('"'); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn yaml(v: &T) -> String { + to_string(v).unwrap() + } + + #[test] + fn scalar_map() { + let mut map = serde_json::Map::new(); + map.insert("a".into(), Value::from(1)); + map.insert("b".into(), Value::from(true)); + map.insert("c".into(), Value::Null); + assert_eq!(yaml(&Value::Object(map)), "a: 1\nb: true\nc: null\n"); + } + + #[test] + fn nested_object_and_array() { + let v: Value = serde_json::json!({ + "violations": [{"rule": "CH001", "severity": "Info"}], + "count": 1 + }); + let out = yaml(&v); + assert!(out.contains("violations:")); + assert!(out.contains("- rule: CH001")); + assert!(out.contains("severity: Info")); + assert!(out.contains("count: 1")); + } + + #[test] + fn empty_containers() { + let v: Value = serde_json::json!({"list": [], "obj": {}}); + let out = yaml(&v); + assert!(out.contains("list: []")); + assert!(out.contains("obj: {}")); + } + + #[test] + fn quotes_ambiguous_strings() { + let v: Value = serde_json::json!({"n": "42", "b": "true", "s": "a: b", "e": ""}); + let out = yaml(&v); + assert!(out.contains("n: \"42\"")); + assert!(out.contains("b: \"true\"")); + assert!(out.contains("s: \"a: b\"")); + assert!(out.contains("e: \"\"")); + } + + #[test] + fn escapes_newlines() { + let v: Value = serde_json::json!({"text": "line1\nline2"}); + assert!(yaml(&v).contains("text: \"line1\\nline2\"")); + } + + #[test] + fn array_of_scalars() { + let v: Value = serde_json::json!(["x", "y"]); + assert_eq!(yaml(&v), "- x\n- y\n"); + } + + #[test] + fn top_level_array_of_objects() { + let v: Value = serde_json::json!([{"a": 1}, {"a": 2}]); + assert_eq!(yaml(&v), "- a: 1\n- a: 2\n"); + } + + #[test] + fn nested_array_in_array() { + let v: Value = serde_json::json!([[1, 2], [3]]); + assert!(yaml(&v).contains("- - 1")); + } + + #[test] + fn quotes_special_keys() { + let mut map = serde_json::Map::new(); + map.insert("a: b".into(), Value::from(1)); + assert!(yaml(&Value::Object(map)).contains("\"a: b\": 1")); + } + + #[test] + fn escapes_control_characters() { + let v: Value = serde_json::json!({"s": "a\tb"}); + assert!(yaml(&v).contains("s: \"a\\tb\"")); + } + + #[test] + fn top_level_scalar() { + assert_eq!(yaml(&Value::from(7)), "7\n"); + } +} diff --git a/src/preprocessor.rs b/src/preprocessor.rs index 0626842..8159ba4 100644 --- a/src/preprocessor.rs +++ b/src/preprocessor.rs @@ -6,7 +6,7 @@ //! //! # Supported Dialects //! -//! - **ClickHouse**: Handles `CODEC`, `TTL`, `SETTINGS` clauses +//! - **`ClickHouse`**: Handles `CODEC`, `TTL`, `SETTINGS` clauses //! //! # Architecture //! @@ -38,17 +38,29 @@ pub struct Preprocessor { dialect: SqlDialect } +pub use crate::preprocessor::clickhouse::{MaterializedViewInfo, ProjectionInfo, SkipIndexInfo}; + /// Metadata extracted during preprocessing. #[derive(Debug, Default, Clone)] pub struct PreprocessorMetadata { - /// Column codecs: column_name -> codec_expression - pub codecs: HashMap, + /// Column codecs: `column_name` -> `codec_expression` + pub codecs: HashMap, /// TTL expressions extracted from table definitions - pub ttl_expressions: Vec, - /// Table settings: setting_name -> value - pub settings: HashMap, - /// Partition expressions (ClickHouse PARTITION BY) - pub partition_by: Vec + pub ttl_expressions: Vec, + /// Table settings: `setting_name` -> value + pub settings: HashMap, + /// Partition expressions (`ClickHouse` PARTITION BY) + pub partition_by: Vec, + /// Sample by expressions (`ClickHouse` SAMPLE BY) + pub sample_by: Vec, + /// Data skipping indexes (`ClickHouse` INDEX ... TYPE ... GRANULARITY) + pub skip_indexes: Vec, + /// Projections (`ClickHouse` PROJECTION ... AS SELECT) + pub projections: Vec, + /// Dictionary names (`ClickHouse` CREATE DICTIONARY) + pub dictionaries: Vec, + /// Materialized views (`ClickHouse` CREATE MATERIALIZED VIEW) + pub materialized_views: Vec } /// Result of SQL preprocessing. @@ -63,7 +75,7 @@ pub struct PreprocessorResult { impl Preprocessor { /// Create a new preprocessor for the specified dialect. #[must_use] - pub fn new(dialect: SqlDialect) -> Self { + pub const fn new(dialect: SqlDialect) -> Self { Self { dialect } diff --git a/src/preprocessor/clickhouse.rs b/src/preprocessor/clickhouse.rs index 99050c7..248e6b8 100644 --- a/src/preprocessor/clickhouse.rs +++ b/src/preprocessor/clickhouse.rs @@ -1,13 +1,13 @@ //! ClickHouse-specific SQL preprocessing. //! -//! Handles ClickHouse DDL constructs not supported by sqlparser: +//! Handles `ClickHouse` DDL constructs not supported by sqlparser: //! - `CODEC(...)` - Column compression codecs //! - `TTL ...` - Data expiration rules //! - `SETTINGS ...` - Table-level settings //! //! # Codec Syntax //! -//! ClickHouse supports various compression codecs: +//! `ClickHouse` supports various compression codecs: //! ```sql //! CREATE TABLE t ( //! col1 String CODEC(ZSTD), @@ -30,6 +30,42 @@ use regex::Regex; use super::{PreprocessorMetadata, PreprocessorResult}; +/// Metadata for a `ClickHouse` data skipping index. +#[derive(Debug, Clone)] +pub struct SkipIndexInfo { + /// Index name + pub name: String, + /// Indexed expression (column or expression) + pub expr: String, + /// Index type (minmax, set, `bloom_filter`, `ngrambf_v1`, `tokenbf_v1`, + /// text) + pub type_name: String, + /// Optional type arguments (e.g. "100" for set, "0.01" for `bloom_filter`) + pub type_args: Option, + /// Granularity in granules + pub granularity: usize +} + +/// Metadata for a `ClickHouse` projection. +#[derive(Debug, Clone)] +pub struct ProjectionInfo { + /// Projection name + pub name: String, + /// Inner `SELECT` definition (without the surrounding parentheses) + pub query: String +} + +/// Metadata for a `ClickHouse` materialized view. +#[derive(Debug, Clone)] +pub struct MaterializedViewInfo { + /// View name + pub name: String, + /// Destination table (`TO target`), when present + pub target: Option, + /// Source `SELECT` feeding the view + pub query: String +} + /// Regex for matching CODEC clauses with optional nested parentheses. /// Matches: `CODEC(ZSTD)`, `CODEC(Delta, LZ4)`, `CODEC(ZSTD(3))` static CODEC_REGEX: LazyLock = LazyLock::new(|| { @@ -46,36 +82,123 @@ static COLUMN_CODEC_REGEX: LazyLock = LazyLock::new(|| { /// Regex for matching TTL clauses. /// Matches: `TTL expr + INTERVAL n UNIT` up to SETTINGS or end static TTL_REGEX: LazyLock = - LazyLock::new(|| Regex::new(r"(?i)\bTTL\s+(.+?)(?:\s+SETTINGS\b|;|$)").expect("valid regex")); + LazyLock::new(|| Regex::new(r"(?i)\bTTL\s+(.+?)(\s+SETTINGS\b|;|$)").expect("valid regex")); /// Regex for matching SETTINGS clauses. /// Matches: `SETTINGS key = value, key2 = value2` static SETTINGS_REGEX: LazyLock = LazyLock::new(|| Regex::new(r"(?i)\bSETTINGS\s+([^;]+)").expect("valid regex")); -/// Regex for matching PARTITION BY clauses (ClickHouse DDL). +/// Regex for matching PARTITION BY clauses (`ClickHouse` DDL). static PARTITION_BY_REGEX: LazyLock = LazyLock::new(|| { Regex::new(r"(?i)\bPARTITION\s+BY\s+(\S+(?:\([^)]*\))?)").expect("valid regex") }); +/// Regex for matching SAMPLE BY clauses (`ClickHouse` DDL). +static SAMPLE_BY_REGEX: LazyLock = LazyLock::new(|| { + Regex::new(r"(?is)\bSAMPLE\s+BY\s+(.+?)(\s+SETTINGS\b|\s+TTL\b|;|$)").expect("valid regex") +}); + /// Regex for individual setting key-value pairs. static SETTING_PAIR_REGEX: LazyLock = LazyLock::new(|| Regex::new(r"(\w+)\s*=\s*('[^']*'|\d+)").expect("valid regex")); -/// Preprocess ClickHouse SQL. +/// Regex for matching `ClickHouse` skipping index definitions. +/// Matches: `INDEX name expr TYPE type(args) GRANULARITY n` +static SKIP_INDEX_REGEX: LazyLock = LazyLock::new(|| { + Regex::new( + r"(?is)\bINDEX\s+(\w+)\s+(.+?)\s+TYPE\s+(\w+)(?:\s*\(([^)]*)\))?\s+GRANULARITY\s+(\d+)" + ) + .expect("valid regex") +}); + +/// Regex for removing skipping index definitions (including optional leading +/// comma). +static SKIP_INDEX_REMOVE_REGEX: LazyLock = LazyLock::new(|| { + Regex::new(r"(?is),?\s*\bINDEX\s+\w+\s+.+?\s+TYPE\s+\w+(?:\s*\([^)]*\))?\s+GRANULARITY\s+\d+") + .expect("valid regex") +}); + +/// Regex for matching a `CREATE DICTIONARY` header. +/// Captures the dictionary name (group 1). +static DICTIONARY_REGEX: LazyLock = LazyLock::new(|| { + Regex::new( + r"(?i)\bCREATE\s+(?:OR\s+REPLACE\s+)?DICTIONARY\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w.]+)" + ) + .expect("valid regex") +}); + +/// Regex for removing a whole `CREATE DICTIONARY` statement (up to `;` or end). +static DICTIONARY_REMOVE_REGEX: LazyLock = LazyLock::new(|| { + Regex::new(r"(?is)\bCREATE\s+(?:OR\s+REPLACE\s+)?DICTIONARY\b[^;]*;?").expect("valid regex") +}); + +/// Regex for matching a `CREATE MATERIALIZED VIEW` header. +/// Captures the view name (group 1) and optional `TO target` (group 2). +static MATERIALIZED_VIEW_REGEX: LazyLock = LazyLock::new(|| { + Regex::new( + r"(?i)\bCREATE\s+MATERIALIZED\s+VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w.]+)(?:\s+TO\s+([\w.]+))?" + ) + .expect("valid regex") +}); + +/// Regex for stripping the `ClickHouse` engine clause between a materialized +/// view header and its `AS SELECT` body, so the statement becomes parseable. +/// Group 1 keeps the header, group 3 keeps the `AS SELECT` keyword. +static MATERIALIZED_VIEW_ENGINE_REGEX: LazyLock = LazyLock::new(|| { + Regex::new(r"(?is)(\bCREATE\s+MATERIALIZED\s+VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?[\w.]+(?:\s+TO\s+[\w.]+)?)(.*?)(\bAS\s+SELECT\b)") + .expect("valid regex") +}); + +/// Regex for a `ClickHouse` `ALTER TABLE ... UPDATE ... WHERE ...` mutation. +static MUTATION_UPDATE_REGEX: LazyLock = LazyLock::new(|| { + Regex::new(r"(?is)\bALTER\s+TABLE\s+([\w.]+)\s+UPDATE\s+(.+?)\s+WHERE\s+(.+?)(;|$)") + .expect("valid regex") +}); + +/// Regex for a `ClickHouse` `ALTER TABLE ... DELETE WHERE ...` mutation. +static MUTATION_DELETE_REGEX: LazyLock = LazyLock::new(|| { + Regex::new(r"(?is)\bALTER\s+TABLE\s+([\w.]+)\s+DELETE\s+WHERE\s+(.+?)(;|$)") + .expect("valid regex") +}); + +/// Rewrite `ClickHouse` mutation statements into standard `UPDATE`/`DELETE` so +/// `sqlparser` can parse them. +/// +/// `ClickHouse` expresses row mutations as `ALTER TABLE ... UPDATE/DELETE`, +/// which the parser rejects. Rewriting them to the standard form keeps the +/// statement analysable (and lets the mutation rule flag it). +pub fn rewrite_mutations(sql: &str) -> String { + let step = MUTATION_UPDATE_REGEX.replace_all(sql, "UPDATE ${1} SET ${2} WHERE ${3}${4}"); + MUTATION_DELETE_REGEX + .replace_all(&step, "DELETE FROM ${1} WHERE ${2}${3}") + .to_string() +} + +/// Preprocess `ClickHouse` SQL. /// /// Removes unsupported constructs and extracts metadata. +#[must_use] pub fn preprocess(sql: &str) -> PreprocessorResult { let mut metadata = PreprocessorMetadata::default(); - let mut result = sql.to_string(); - extract_codecs(&result, &mut metadata); - extract_ttl(&result, &mut metadata); - extract_settings(&result, &mut metadata); - extract_partition_by(&result, &mut metadata); - result = remove_codecs(&result); + extract_codecs(sql, &mut metadata); + extract_ttl(sql, &mut metadata); + extract_settings(sql, &mut metadata); + extract_partition_by(sql, &mut metadata); + extract_sample_by(sql, &mut metadata); + extract_skip_indexes(sql, &mut metadata); + extract_projections(sql, &mut metadata); + extract_dictionaries(sql, &mut metadata); + extract_materialized_views(sql, &mut metadata); + let mut result = remove_codecs(sql); result = remove_ttl(&result); result = remove_settings(&result); result = remove_partition_by(&result); + result = remove_sample_by(&result); + result = remove_skip_indexes(&result); + result = remove_projections(&result); + result = remove_dictionaries(&result); + result = remove_materialized_view_engine(&result); result = normalize_whitespace(&result); PreprocessorResult { sql: result, @@ -131,30 +254,286 @@ fn extract_partition_by(sql: &str, metadata: &mut PreprocessorMetadata) { } } +/// Extract SAMPLE BY expressions from SQL. +fn extract_sample_by(sql: &str, metadata: &mut PreprocessorMetadata) { + for cap in SAMPLE_BY_REGEX.captures_iter(sql) { + if let Some(expr) = cap.get(1) { + metadata.sample_by.push(expr.as_str().trim().to_string()); + } + } +} + +/// Remove SAMPLE BY clauses from SQL. +fn remove_sample_by(sql: &str) -> String { + SAMPLE_BY_REGEX.replace_all(sql, "${2}").into_owned() +} + +/// Extract data skipping indexes from SQL. +fn extract_skip_indexes(sql: &str, metadata: &mut PreprocessorMetadata) { + for cap in SKIP_INDEX_REGEX.captures_iter(sql) { + let name = cap.get(1).map(|m| m.as_str().to_string()); + let expr = cap.get(2).map(|m| m.as_str().trim().to_string()); + let type_name = cap.get(3).map(|m| m.as_str().to_string()); + let type_args = cap.get(4).map(|m| m.as_str().trim().to_string()); + let granularity = cap + .get(5) + .and_then(|m| m.as_str().parse::().ok()) + .unwrap_or(1); + if let (Some(n), Some(e), Some(t)) = (name, expr, type_name) { + metadata.skip_indexes.push(SkipIndexInfo { + name: n, + expr: e, + type_name: t, + type_args: type_args.filter(|s| !s.is_empty()), + granularity + }); + } + } +} + +/// Remove data skipping index definitions from SQL. +fn remove_skip_indexes(sql: &str) -> String { + SKIP_INDEX_REMOVE_REGEX.replace_all(sql, "").into_owned() +} + +/// Locate every `PROJECTION` definition and its byte span. +/// +/// Supports both `PROJECTION name (SELECT ...)` and `PROJECTION name AS SELECT +/// ...`. Parentheses and commas inside single-quoted strings are ignored when +/// finding the definition boundary. +fn find_projections(sql: &str) -> Vec<(usize, usize, ProjectionInfo)> { + let bytes = sql.as_bytes(); + let keyword = b"PROJECTION"; + let mut found = Vec::new(); + let mut search = 0; + while let Some(start) = find_keyword_ignore_case(bytes, keyword, search) { + let after = start + keyword.len(); + search = after; + let mut idx = after; + while idx < bytes.len() && (bytes[idx] as char).is_whitespace() { + idx += 1; + } + let name_start = idx; + while idx < bytes.len() && (bytes[idx] as char).is_alphanumeric() + || (idx < bytes.len() && bytes[idx] == b'_') + { + idx += 1; + } + if name_start == idx { + continue; + } + let name = sql[name_start..idx].to_string(); + while idx < bytes.len() && (bytes[idx] as char).is_whitespace() { + idx += 1; + } + if idx >= bytes.len() { + continue; + } + if bytes[idx] == b'(' { + if let Some(end) = matching_paren(bytes, idx) { + let query = sql[idx + 1..end].trim().to_string(); + found.push(( + start, + end + 1, + ProjectionInfo { + name, + query + } + )); + search = end + 1; + } + } else if bytes + .get(idx..idx + 2) + .is_some_and(|two| two.eq_ignore_ascii_case(b"AS")) + { + let body_start = idx + 2; + if let Some(end) = projection_as_end(bytes, body_start) { + let query = sql[body_start..end].trim().to_string(); + found.push(( + start, + end, + ProjectionInfo { + name, + query + } + )); + search = end; + } + } + } + found +} + +/// Return the byte index of the `)` matching the `(` at `open`. +const fn matching_paren(bytes: &[u8], open: usize) -> Option { + let mut depth = 0; + let mut in_str = false; + let mut i = open; + while i < bytes.len() { + let c = bytes[i]; + if in_str { + if c == b'\'' { + in_str = false; + } + } else { + match c { + b'\'' => in_str = true, + b'(' => depth += 1, + b')' => { + depth -= 1; + if depth == 0 { + return Some(i); + } + } + _ => {} + } + } + i += 1; + } + None +} + +/// Find the end of a `PROJECTION name AS SELECT ...` body: the first top-level +/// comma or closing parenthesis outside of strings and nested parentheses. +const fn projection_as_end(bytes: &[u8], start: usize) -> Option { + let mut depth = 0; + let mut in_str = false; + let mut i = start; + while i < bytes.len() { + let c = bytes[i]; + if in_str { + if c == b'\'' { + in_str = false; + } + } else { + match c { + b'\'' => in_str = true, + b'(' => depth += 1, + b')' | b',' if depth == 0 => return Some(i), + b')' => depth -= 1, + _ => {} + } + } + i += 1; + } + None +} + +/// Extract projection definitions into metadata. +fn extract_projections(sql: &str, metadata: &mut PreprocessorMetadata) { + for (_, _, projection) in find_projections(sql) { + metadata.projections.push(projection); + } +} + +/// Remove projection definitions (and a leading comma) from SQL. +fn remove_projections(sql: &str) -> String { + let mut spans: Vec<(usize, usize)> = find_projections(sql) + .into_iter() + .map(|(start, end, _)| (start, end)) + .collect(); + spans.sort_by_key(|(start, _)| *start); + let mut out = String::with_capacity(sql.len()); + let mut cursor = 0; + for (start, end) in spans { + let mut cut_start = start; + let prefix = sql[cursor..start].trim_end(); + if prefix.ends_with(',') { + cut_start = sql[..start].trim_end().len() - 1; + } + out.push_str(&sql[cursor..cut_start]); + cursor = end; + } + out.push_str(&sql[cursor..]); + out +} + +/// Extract `CREATE DICTIONARY` names into metadata. +fn extract_dictionaries(sql: &str, metadata: &mut PreprocessorMetadata) { + for cap in DICTIONARY_REGEX.captures_iter(sql) { + if let Some(name) = cap.get(1) { + metadata.dictionaries.push(name.as_str().to_string()); + } + } +} + +/// Remove whole `CREATE DICTIONARY` statements from SQL. +fn remove_dictionaries(sql: &str) -> String { + DICTIONARY_REMOVE_REGEX.replace_all(sql, "").into_owned() +} + +/// Extract `CREATE MATERIALIZED VIEW` metadata into metadata. +fn extract_materialized_views(sql: &str, metadata: &mut PreprocessorMetadata) { + for cap in MATERIALIZED_VIEW_REGEX.captures_iter(sql) { + let whole = cap.get(0).map_or(0, |m| m.end()); + let name = cap.get(1).map_or_default(|m| m.as_str().to_string()); + let target = cap.get(2).map(|m| m.as_str().to_string()); + let query = sql[whole..] + .split(';') + .next() + .and_then(|seg| { + find_keyword_ignore_case(seg.as_bytes(), b"SELECT", 0) + .map(|i| seg[i..].trim().to_string()) + }) + .unwrap_or_default(); + metadata.materialized_views.push(MaterializedViewInfo { + name, + target, + query + }); + } +} + +/// Strip the engine clause between a materialized view header and its body so +/// the statement parses with `sqlparser`. +fn remove_materialized_view_engine(sql: &str) -> String { + MATERIALIZED_VIEW_ENGINE_REGEX + .replace_all(sql, |caps: ®ex::Captures| { + format!("{} {}", &caps[1], &caps[3]) + }) + .to_string() +} + /// Remove CODEC clauses from SQL. fn remove_codecs(sql: &str) -> String { - CODEC_REGEX.replace_all(sql, "").to_string() + CODEC_REGEX.replace_all(sql, "").into_owned() } /// Remove TTL clauses from SQL. fn remove_ttl(sql: &str) -> String { - TTL_REGEX.replace_all(sql, "").to_string() + TTL_REGEX.replace_all(sql, "${2}").into_owned() } /// Remove SETTINGS clauses from SQL. fn remove_settings(sql: &str) -> String { - SETTINGS_REGEX.replace_all(sql, "").to_string() + SETTINGS_REGEX.replace_all(sql, "").into_owned() } /// Remove PARTITION BY clauses from SQL. fn remove_partition_by(sql: &str) -> String { - PARTITION_BY_REGEX.replace_all(sql, "").to_string() + PARTITION_BY_REGEX.replace_all(sql, "").into_owned() } +/// Regex for collapsing whitespace runs. +static WHITESPACE_REGEX: LazyLock = + LazyLock::new(|| Regex::new(r"\s+").expect("valid regex")); + /// Normalize excessive whitespace. fn normalize_whitespace(sql: &str) -> String { - let re = Regex::new(r"\s+").expect("valid regex"); - re.replace_all(sql.trim(), " ").to_string() + WHITESPACE_REGEX.replace_all(sql.trim(), " ").into_owned() +} + +/// Find an ASCII case-insensitive `needle` in `haystack` at or after `from`. +fn find_keyword_ignore_case(haystack: &[u8], needle: &[u8], from: usize) -> Option { + if needle.is_empty() || haystack.len() < from + needle.len() { + return None; + } + (from..=haystack.len() - needle.len()).find(|&i| { + haystack[i..i + needle.len()] + .iter() + .zip(needle) + .all(|(h, n)| h.eq_ignore_ascii_case(n)) + }) } #[cfg(test)] @@ -178,12 +557,12 @@ mod tests { #[test] fn test_multiple_codecs() { - let sql = r#" + let sql = r" CREATE TABLE t ( col1 String CODEC(ZSTD), col2 UInt64 CODEC(Delta, LZ4) ) ENGINE = MergeTree ORDER BY col1 - "#; + "; let result = preprocess(sql); assert!(!result.sql.contains("CODEC")); assert_eq!( @@ -229,7 +608,7 @@ mod tests { #[test] fn test_complex_clickhouse_ddl() { - let sql = r#" + let sql = r" CREATE TABLE events ON CLUSTER default ( event_date Date, event_time DateTime CODEC(Delta, ZSTD), @@ -240,11 +619,12 @@ mod tests { ORDER BY (event_date, user_id) TTL event_date + INTERVAL 90 DAY SETTINGS index_granularity = 8192 - "#; + "; let result = preprocess(sql); assert!(!result.sql.contains("CODEC")); assert!(!result.sql.contains("TTL")); assert!(!result.sql.contains("SETTINGS")); + assert!(!result.sql.contains("index_granularity")); assert!(result.sql.contains("ENGINE = ReplicatedMergeTree")); assert!(result.sql.contains("ORDER BY")); assert_eq!(result.metadata.codecs.len(), 3); @@ -255,13 +635,91 @@ mod tests { ); } + #[test] + fn test_ttl_followed_by_settings_keeps_no_body() { + let sql = "CREATE TABLE t (d Date) ENGINE = MergeTree ORDER BY d \ + TTL d + INTERVAL 7 DAY SETTINGS index_granularity = 4096"; + let result = preprocess(sql); + assert!(!result.sql.contains("index_granularity")); + assert!(!result.sql.contains("SETTINGS")); + assert_eq!( + result.metadata.settings.get("index_granularity"), + Some(&"4096".to_string()) + ); + } + + #[test] + fn test_sample_by_followed_by_settings() { + let sql = "CREATE TABLE t (id UInt64) ENGINE = MergeTree ORDER BY id \ + SAMPLE BY id SETTINGS index_granularity = 4096"; + let result = preprocess(sql); + assert!(!result.sql.contains("SAMPLE")); + assert!(!result.sql.contains("index_granularity")); + assert_eq!(result.metadata.sample_by.len(), 1); + } + + #[test] + fn test_projection_extraction() { + let sql = "CREATE TABLE t (a UInt64, b String, PROJECTION p (SELECT a, sum(b) ORDER BY a)) \ + ENGINE = MergeTree ORDER BY a"; + let result = preprocess(sql); + assert!(!result.sql.contains("PROJECTION")); + assert_eq!(result.metadata.projections.len(), 1); + assert_eq!(result.metadata.projections[0].name, "p"); + assert!(result.metadata.projections[0].query.contains("sum(b)")); + } + + #[test] + fn test_projection_as_select_form() { + let sql = "CREATE TABLE t (a UInt64, PROJECTION p AS SELECT a ORDER BY a) \ + ENGINE = MergeTree ORDER BY a"; + let result = preprocess(sql); + assert!(!result.sql.contains("PROJECTION")); + assert_eq!(result.metadata.projections.len(), 1); + } + + #[test] + fn test_dictionary_removal() { + let sql = "CREATE DICTIONARY d (id UInt64) PRIMARY KEY id SOURCE(NULL()) LAYOUT(FLAT()); \ + CREATE TABLE x (id UInt64) ENGINE = MergeTree ORDER BY id"; + let result = preprocess(sql); + assert!(!result.sql.contains("DICTIONARY")); + assert_eq!(result.metadata.dictionaries, vec!["d".to_string()]); + assert!(result.sql.contains("CREATE TABLE x")); + } + + #[test] + fn test_materialized_view_engine_strip() { + let sql = "CREATE MATERIALIZED VIEW mv TO dest ENGINE = MergeTree ORDER BY a \ + AS SELECT a FROM src"; + let result = preprocess(sql); + assert!(!result.sql.contains("ENGINE")); + assert!(result.sql.contains("AS SELECT a FROM src")); + assert_eq!(result.metadata.materialized_views.len(), 1); + let mv = &result.metadata.materialized_views[0]; + assert_eq!(mv.name, "mv"); + assert_eq!(mv.target.as_deref(), Some("dest")); + assert!(mv.query.contains("SELECT a FROM src")); + } + + #[test] + fn test_rewrite_mutations() { + let upd = rewrite_mutations("ALTER TABLE t UPDATE x = 0 WHERE d = today()"); + assert_eq!(upd, "UPDATE t SET x = 0 WHERE d = today()"); + let del = rewrite_mutations("ALTER TABLE t DELETE WHERE d = today();"); + assert_eq!(del, "DELETE FROM t WHERE d = today();"); + } + #[test] fn test_no_modification_without_special_syntax() { let sql = "CREATE TABLE t (id UInt64) ENGINE = MergeTree ORDER BY id"; let result = preprocess(sql); assert_eq!(result.sql, sql); assert!(result.metadata.codecs.is_empty()); - assert!(result.metadata.ttl_expressions.is_empty()); + assert_eq!( + result.metadata.ttl_expressions, + [] as [std::string::String; 0] + ); assert!(result.metadata.settings.is_empty()); } } diff --git a/src/query.rs b/src/query.rs index 372ca98..2e1963b 100644 --- a/src/query.rs +++ b/src/query.rs @@ -4,6 +4,7 @@ mod types; use extract::{ExtractionContext, extract_columns_from_expr, extract_from_set_expr}; use indexmap::IndexSet; use rayon::prelude::*; +use regex::Regex; use sqlparser::{ dialect::{ ClickHouseDialect, Dialect, GenericDialect, MySqlDialect, PostgreSqlDialect, SQLiteDialect @@ -15,7 +16,7 @@ pub use types::{Query, QueryType}; use crate::error::{AppResult, query_parse_error}; /// SQL dialect for parsing -#[derive(Debug, Clone, Copy, Default)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[non_exhaustive] pub enum SqlDialect { #[default] @@ -28,6 +29,7 @@ pub enum SqlDialect { impl SqlDialect { /// Convert to sqlparser dialect for parsing + #[must_use] pub fn into_parser_dialect(self) -> Box { match self { Self::Generic => Box::new(GenericDialect {}), @@ -44,23 +46,38 @@ impl SqlDialect { /// # Notes /// /// - Parses statements in parallel for better performance +/// +/// # Errors +/// +/// Returns [`crate::AppError`] if the SQL cannot be parsed by the underlying +/// parser for the selected dialect. pub fn parse_queries(sql: &str, dialect: SqlDialect) -> AppResult> { let parser_dialect = dialect.into_parser_dialect(); - let statements = Parser::parse_sql(parser_dialect.as_ref(), sql) + let sql = if dialect == SqlDialect::ClickHouse { + std::borrow::Cow::Owned(crate::preprocessor::clickhouse::rewrite_mutations(sql)) + } else { + std::borrow::Cow::Borrowed(sql) + }; + let statements = Parser::parse_sql(parser_dialect.as_ref(), sql.as_ref()) .map_err(|e| query_parse_error(e.to_string()))?; - let queries: Result, _> = statements.into_par_iter().map(parse_statement).collect(); - queries + let mut queries: Vec = statements.into_par_iter().map(parse_statement).collect(); + if dialect == SqlDialect::ClickHouse { + for q in &mut queries { + enrich_clickhouse_query(q); + } + } + Ok(queries) } -fn parse_statement(stmt: sqlparser::ast::Statement) -> AppResult { +fn parse_statement(stmt: sqlparser::ast::Statement) -> Query { use sqlparser::ast::Statement; let raw = stmt.to_string(); match stmt { - Statement::Query(query) => parse_select_query(raw, *query), + Statement::Query(query) => parse_select_query(raw, &query), Statement::Insert(insert) => { let mut q = Query::new(raw, QueryType::Insert); q.tables.push(insert.table.to_string().into()); - Ok(q) + q } Statement::Update(update) => { let mut q = Query::new(raw, QueryType::Update); @@ -70,7 +87,7 @@ fn parse_statement(stmt: sqlparser::ast::Statement) -> AppResult { extract_columns_from_expr(&sel, &mut cols); q.where_cols = cols.into_iter().collect(); } - Ok(q) + q } Statement::Delete(delete) => { let mut q = Query::new(raw, QueryType::Delete); @@ -84,14 +101,14 @@ fn parse_statement(stmt: sqlparser::ast::Statement) -> AppResult { q.tables.push(item.relation.to_string().into()); } } - Ok(q) + q } Statement::Truncate(truncate) => { let mut q = Query::new(raw, QueryType::Truncate); for table in truncate.table_names { q.tables.push(table.name.to_string().into()); } - Ok(q) + q } Statement::Drop { names, @@ -103,14 +120,14 @@ fn parse_statement(stmt: sqlparser::ast::Statement) -> AppResult { q.tables.push(name.to_string().into()); } q.cte_names - .push(format!("{:?}", object_type).to_lowercase().into()); - Ok(q) + .push(format!("{object_type:?}").to_lowercase().into()); + q } - _ => Ok(Query::new(raw, QueryType::Other)) + _ => Query::new(raw, QueryType::Other) } } -fn parse_select_query(raw: String, query: sqlparser::ast::Query) -> AppResult { +fn parse_select_query(raw: String, query: &sqlparser::ast::Query) -> Query { let mut q = Query::new(raw, QueryType::Select); for cte in &query .with @@ -190,5 +207,22 @@ fn parse_select_query(raw: String, query: sqlparser::ast::Query) -> AppResult ) { - use sqlparser::ast::{Expr, InTarget}; + use sqlparser::ast::Expr; match expr { Expr::Identifier(ident) => { columns.insert(ident.value.as_str().into()); @@ -27,30 +27,27 @@ pub fn extract_columns_from_expr( } Expr::UnaryOp { expr, .. - } => { - extract_columns_from_expr(expr, columns); } - Expr::In { - expr, - target: InTarget::List(list), - .. + | Expr::Cast { + expr, .. + } + | Expr::Extract { + expr, .. } => { extract_columns_from_expr(expr, columns); - for item in list { - extract_columns_from_expr(item, columns); - } } Expr::In { expr, - target: InTarget::Subquery(_), + target, .. } => { extract_columns_from_expr(expr, columns); + if let sqlparser::ast::InTarget::List(list) = target { + for item in list { + extract_columns_from_expr(item, columns); + } + } } - Expr::Subquery(_) - | Expr::Exists { - .. - } => {} Expr::Between { expr, low, @@ -61,10 +58,7 @@ pub fn extract_columns_from_expr( extract_columns_from_expr(low, columns); extract_columns_from_expr(high, columns); } - Expr::IsNull(e) | Expr::IsNotNull(e) => { - extract_columns_from_expr(e, columns); - } - Expr::Nested(e) => { + Expr::IsNull(e) | Expr::IsNotNull(e) | Expr::Nested(e) => { extract_columns_from_expr(e, columns); } Expr::Function(func) => { @@ -96,16 +90,6 @@ pub fn extract_columns_from_expr( extract_columns_from_expr(else_res, columns); } } - Expr::Cast { - expr, .. - } => { - extract_columns_from_expr(expr, columns); - } - Expr::Extract { - expr, .. - } => { - extract_columns_from_expr(expr, columns); - } _ => {} } } @@ -185,27 +169,30 @@ pub fn extract_window_functions(expr: &sqlparser::ast::Expr, windows: &mut Vec bool { - use sqlparser::ast::{Expr, InTarget}; + use sqlparser::ast::Expr; match expr { Expr::Subquery(_) - | Expr::In { - target: InTarget::Subquery(_), - .. - } | Expr::Exists { .. } => true, + Expr::In { + expr, + target, + .. + } => { + contains_subquery(expr) + || match target { + sqlparser::ast::InTarget::List(list) => list.iter().any(contains_subquery), + sqlparser::ast::InTarget::Subquery(_) => true, + _ => false + } + } Expr::BinaryOp { left, right, .. } => contains_subquery(left) || contains_subquery(right), Expr::Nested(e) => contains_subquery(e), - Expr::In { - expr, - target: InTarget::List(list), - .. - } => contains_subquery(expr) || list.iter().any(contains_subquery), Expr::Case { operand, conditions, diff --git a/src/query/extract/set_expr.rs b/src/query/extract/set_expr.rs index ea1f20c..e2566f2 100644 --- a/src/query/extract/set_expr.rs +++ b/src/query/extract/set_expr.rs @@ -24,8 +24,14 @@ pub fn extract_from_set_expr(set_expr: &sqlparser::ast::SetExpr, ctx: &mut Extra } } for table in &select.from { + if matches!(table.relation, sqlparser::ast::TableFactor::Derived { .. }) { + *ctx.has_subquery = true; + } extract_from_table_factor(&table.relation, ctx.tables); for join in &table.joins { + if matches!(join.relation, sqlparser::ast::TableFactor::Derived { .. }) { + *ctx.has_subquery = true; + } extract_from_table_factor(&join.relation, ctx.tables); match &join.join_operator { sqlparser::ast::JoinOperator::Join(constraint) diff --git a/src/query/extract/table.rs b/src/query/extract/table.rs index 101430c..90033a3 100644 --- a/src/query/extract/table.rs +++ b/src/query/extract/table.rs @@ -43,9 +43,6 @@ pub fn extract_from_table_factor( }; extract_from_set_expr(&subquery.body, &mut ctx); } - TableFactor::TableFunction { - .. - } => {} TableFactor::NestedJoin { table_with_joins, .. } => { diff --git a/src/query/types.rs b/src/query/types.rs index 62f49df..2cda76f 100644 --- a/src/query/types.rs +++ b/src/query/types.rs @@ -10,23 +10,39 @@ pub type ColumnVec = SmallVec<[CompactString; 8]>; /// Parsed SQL query with metadata #[derive(Debug, Clone, Serialize)] pub struct Query { - pub raw: String, - pub query_type: QueryType, - pub tables: Vec, - pub cte_names: Vec, - pub where_cols: ColumnVec, - pub join_cols: ColumnVec, - pub order_cols: ColumnVec, - pub group_cols: ColumnVec, - pub having_cols: ColumnVec, - pub window_funcs: Vec, - pub limit: Option, - pub offset: Option, - pub has_union: bool, - pub has_distinct: bool, - pub has_subquery: bool, + pub raw: String, + pub kind: QueryType, + pub tables: Vec, + pub cte_names: Vec, + pub where_cols: ColumnVec, + pub prewhere_cols: ColumnVec, + pub join_cols: ColumnVec, + pub order_cols: ColumnVec, + pub group_cols: ColumnVec, + pub having_cols: ColumnVec, + pub window_funcs: Vec, + pub limit: Option, + pub offset: Option, + pub has_union: bool, + pub has_distinct: bool, + pub has_subquery: bool, + pub clickhouse: ClickHouseFlags, #[serde(skip)] - complexity_cell: OnceLock + complexity_cell: OnceLock +} + +/// ClickHouse-specific query modifiers detected in the raw SQL text. +/// +/// These flags describe optional query clauses that only `ClickHouse` supports +/// and that influence the dialect-specific rules. +#[derive(Debug, Clone, Default, Serialize)] +pub struct ClickHouseFlags { + /// Query uses the `FINAL` table modifier. + pub has_final: bool, + /// Query uses `WITH TOTALS` on an aggregation. + pub has_totals: bool, + /// Query uses `WITH FILL` on a window/ordering. + pub has_fill: bool } impl Query { @@ -74,10 +90,11 @@ impl Default for Query { fn default() -> Self { Self { raw: String::new(), - query_type: QueryType::Other, + kind: QueryType::Other, tables: Vec::new(), cte_names: Vec::new(), where_cols: ColumnVec::new(), + prewhere_cols: ColumnVec::new(), join_cols: ColumnVec::new(), order_cols: ColumnVec::new(), group_cols: ColumnVec::new(), @@ -88,16 +105,18 @@ impl Default for Query { has_union: false, has_distinct: false, has_subquery: false, + clickhouse: ClickHouseFlags::default(), complexity_cell: OnceLock::new() } } } impl Query { - pub fn new(raw: String, query_type: QueryType) -> Self { + #[must_use] + pub fn new(raw: String, kind: QueryType) -> Self { Self { raw, - query_type, + kind, ..Default::default() } } @@ -119,12 +138,14 @@ impl std::fmt::Display for QueryType { /// Calculate complexity score for a query pub fn calculate_complexity(query: &Query) -> QueryComplexity { - let table_count = query.tables.len() as u32; - let join_count = query.join_cols.len() as u32; - let condition_count = query.where_cols.len() as u32 + query.having_cols.len() as u32; - let window_count = query.window_funcs.len() as u32; - let subquery_count = if query.has_subquery { 1 } else { 0 }; - let aggregation_count = query.group_cols.len() as u32; + let table_count = u32::try_from(query.tables.len()).unwrap_or(u32::MAX); + let join_count = u32::try_from(query.join_cols.len()).unwrap_or(u32::MAX); + let condition_count = u32::try_from(query.where_cols.len()) + .unwrap_or(u32::MAX) + .saturating_add(u32::try_from(query.having_cols.len()).unwrap_or(u32::MAX)); + let window_count = u32::try_from(query.window_funcs.len()).unwrap_or(u32::MAX); + let subquery_count = u32::from(query.has_subquery); + let aggregation_count = u32::try_from(query.group_cols.len()).unwrap_or(u32::MAX); let score = table_count + join_count * 3 + condition_count @@ -132,7 +153,7 @@ pub fn calculate_complexity(query: &Query) -> QueryComplexity { + subquery_count * 4 + aggregation_count * 2 + if query.has_union { 3 } else { 0 } - + if query.has_distinct { 1 } else { 0 }; + + u32::from(query.has_distinct); QueryComplexity { score, table_count, diff --git a/src/rules.rs b/src/rules.rs index 1b477f5..d731bfc 100644 --- a/src/rules.rs +++ b/src/rules.rs @@ -66,6 +66,7 @@ //! } //! ``` +mod clickhouse; mod performance; pub mod schema_aware; mod security; @@ -75,7 +76,11 @@ mod types; use rayon::prelude::*; pub use types::{AnalysisReport, RuleCategory, RuleInfo, Severity, Violation}; -use crate::{config::RulesConfig, query::Query, schema::Schema}; +use crate::{ + config::RulesConfig, + query::{Query, SqlDialect}, + schema::Schema +}; /// Trait for implementing SQL analysis rules. /// @@ -156,7 +161,7 @@ pub trait Rule: Send + Sync { /// ..Default::default() /// }; /// -/// let runner = RuleRunner::with_config(config); +/// let runner = RuleRunner::with_config(&config); /// let queries = parse_queries("SELECT id FROM users", SqlDialect::Generic).unwrap(); /// let report = runner.analyze(&queries); /// @@ -175,8 +180,9 @@ impl Default for RuleRunner { impl RuleRunner { /// Create a new runner with all default rules + #[must_use] pub fn new() -> Self { - Self::with_config(RulesConfig::default()) + Self::with_config(&RulesConfig::default()) } /// Create a new runner with configuration @@ -186,8 +192,19 @@ impl RuleRunner { /// - Performance rules (PERF001-PERF020) detect query optimization issues /// - Style rules (STYLE001-STYLE004) enforce best practices /// - Security rules (SEC001-SEC008) detect dangerous operations - pub fn with_config(config: RulesConfig) -> Self { - let all_rules: Vec> = vec![ + #[must_use] + pub fn with_config(config: &RulesConfig) -> Self { + Self::with_dialect_and_config(SqlDialect::Generic, config) + } + + /// Create a new runner for a specific dialect with configuration. + /// + /// When the dialect is [`SqlDialect::ClickHouse`], ClickHouse-specific + /// query rules (CH001, CH004, CH009-CH011, CH013-CH014, CH016, CH019) are + /// registered in addition to the generic rules. + #[must_use] + pub fn with_dialect_and_config(dialect: SqlDialect, config: &RulesConfig) -> Self { + let mut all_rules: Vec> = vec![ Box::new(performance::SelectStarWithoutLimit), Box::new(performance::LeadingWildcard), Box::new(performance::OrInsteadOfIn), @@ -219,6 +236,21 @@ impl RuleRunner { Box::new(security::PrivilegeChange), Box::new(security::DynamicSqlExecution), ]; + if dialect == SqlDialect::ClickHouse { + let ch_rules: Vec> = vec![ + Box::new(clickhouse::SelectStarWideTable), + Box::new(clickhouse::FunctionOnKeyColumn), + Box::new(clickhouse::UniqExactUsage), + Box::new(clickhouse::CountIfOpportunity), + Box::new(clickhouse::OrderByInSubquery), + Box::new(clickhouse::JoinBigTables), + Box::new(clickhouse::FinalUsage), + Box::new(clickhouse::PrewhereOpportunity), + Box::new(clickhouse::HeavyMutation), + Box::new(clickhouse::ManualOptimizeFinal), + ]; + all_rules.extend(ch_rules); + } let rules: Vec> = all_rules .into_iter() .filter(|r| { @@ -243,23 +275,63 @@ impl RuleRunner { } } - /// Create runner with schema-aware rules and configuration + /// Create runner with schema-aware rules for a specific dialect. /// - /// # Notes - /// - /// - Adds schema-aware rules (SCHEMA001-SCHEMA004) if not disabled - /// - Updates severity cache for schema rules - pub fn with_schema_and_config(schema: Schema, config: RulesConfig) -> Self { - let mut runner = Self::with_config(config.clone()); - let schema_rules: Vec> = vec![ - Box::new(schema_aware::MissingIndexOnFilterColumn::new( - schema.clone() - )), + /// When the dialect is [`SqlDialect::ClickHouse`], `ClickHouse` + /// schema-aware rules (CH002-CH003, CH005-CH007, CH012) are registered too. + #[must_use] + pub fn with_schema_and_config_and_dialect( + dialect: SqlDialect, + schema: Schema, + config: &RulesConfig + ) -> Self { + let mut runner = Self::with_dialect_and_config(dialect, config); + let mut schema_rules: Vec> = vec![ Box::new(schema_aware::ColumnNotInSchema::new(schema.clone())), - Box::new(schema_aware::SuggestIndex::new(schema.clone())), - Box::new(schema_aware::JoinOnNonIndexedColumn::new(schema.clone())), - Box::new(schema_aware::ImplicitTypeConversion::new(schema)), + Box::new(schema_aware::ImplicitTypeConversion::new(schema.clone())), ]; + // OLTP-style index suggestions (CREATE INDEX) do not apply to + // ClickHouse's sparse primary key; the CH002/CH005 rules cover that + // dialect instead. + if dialect != SqlDialect::ClickHouse { + let oltp_rules: Vec> = vec![ + Box::new(schema_aware::MissingIndexOnFilterColumn::new( + schema.clone() + )), + Box::new(schema_aware::SuggestIndex::new(schema.clone())), + Box::new(schema_aware::JoinOnNonIndexedColumn::new(schema.clone())), + ]; + schema_rules.extend(oltp_rules); + } + if dialect == SqlDialect::ClickHouse { + let ch_schema_rules: Vec> = vec![ + Box::new(clickhouse::FilterNotUsingPrimaryKey { + schema: schema.clone() + }), + Box::new(clickhouse::PartitionPruningMissed { + schema: schema.clone() + }), + Box::new(clickhouse::MissingSkipIndex { + schema: schema.clone() + }), + Box::new(clickhouse::LowCardinalityHighCardinality { + schema: schema.clone() + }), + Box::new(clickhouse::NullableHotPath { + schema: schema.clone() + }), + Box::new(clickhouse::GroupByOrderMismatch { + schema: schema.clone() + }), + Box::new(clickhouse::DictionaryLookupOpportunity { + schema: schema.clone() + }), + Box::new(clickhouse::GroupByStringKey { + schema + }), + ]; + schema_rules.extend(ch_schema_rules); + } for rule in schema_rules { if !config .disabled diff --git a/src/rules/clickhouse.rs b/src/rules/clickhouse.rs new file mode 100644 index 0000000..b836fdb --- /dev/null +++ b/src/rules/clickhouse.rs @@ -0,0 +1,869 @@ +//! ClickHouse-specific analysis rules. +//! +//! These rules encode `ClickHouse` best practices: sparse primary index usage, +//! partition pruning, data skipping indexes, columnar-storage anti-patterns, +//! and OLTP-style misuse. They are registered only when the `ClickHouse` +//! dialect is selected. + +use super::{Rule, RuleCategory, RuleInfo, Severity, Violation}; +use crate::{ + query::{Query, QueryType}, + schema::{Schema, TableInfo} +}; + +/// Returns the table in the schema whose name matches a query table reference, +/// ignoring an optional database prefix and case. +fn find_table<'a>(schema: &'a Schema, name: &str) -> Option<&'a TableInfo> { + let bare = name.rsplit('.').next().unwrap_or(name); + schema + .tables + .values() + .find(|t| t.name.eq_ignore_ascii_case(bare)) +} + +/// Extracts bare identifiers from a `ClickHouse` expression such as +/// `toYYYYMM(event_date)` or `(event_date, user_id)`. +fn identifiers_in(expr: &str) -> Vec { + let mut out = Vec::new(); + let mut current = String::new(); + for ch in expr.chars() { + if ch.is_ascii_alphanumeric() || ch == '_' { + current.push(ch); + } else if !current.is_empty() { + out.push(current.clone()); + current.clear(); + } + } + if !current.is_empty() { + out.push(current); + } + out +} + +/// Returns the effective sort key columns for a table (PRIMARY KEY or ORDER +/// BY). +fn sort_key(table: &TableInfo) -> Vec { + table + .primary_key + .clone() + .or_else(|| table.order_by.clone()) + .unwrap_or_default() +} + +/// SELECT * on a columnar store reads every column file. +pub struct SelectStarWideTable; + +impl Rule for SelectStarWideTable { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH001", + name: "SELECT * on columnar store", + severity: Severity::Info, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.kind != QueryType::Select { + return vec![]; + } + let upper = query.raw.to_uppercase(); + if !(upper.contains("SELECT *") || upper.contains("SELECT *")) { + return vec![]; + } + let info = self.info(); + vec![Violation { + rule_id: info.id, + rule_name: info.name, + message: "SELECT * reads every column file in a columnar store".to_string(), + severity: info.severity, + category: info.category, + suggestion: Some( + "List only the columns you need; ClickHouse reads and decompresses each selected column" + .to_string() + ), + query_index + }] + } +} + +/// WHERE clause does not touch the primary key, so no granules are pruned. +pub struct FilterNotUsingPrimaryKey { + pub schema: Schema +} + +impl Rule for FilterNotUsingPrimaryKey { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH002", + name: "Filter does not use primary key", + severity: Severity::Warning, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.kind != QueryType::Select || query.where_cols.is_empty() { + return vec![]; + } + let mut violations = Vec::new(); + for table_name in &query.tables { + let Some(table) = find_table(&self.schema, table_name) else { + continue; + }; + let key = sort_key(table); + if key.is_empty() { + continue; + } + let uses_key = query + .where_cols + .iter() + .any(|c| key.iter().any(|k| k.eq_ignore_ascii_case(c))); + if !uses_key { + let info = self.info(); + violations.push(Violation { + rule_id: info.id, + rule_name: info.name, + message: format!( + "WHERE on '{}' does not reference the sort key ({})", + table.name, + key.join(", ") + ), + severity: info.severity, + category: info.category, + suggestion: Some( + "Filter on a prefix of the ORDER BY key, or add a data skipping index" + .to_string() + ), + query_index + }); + } + } + violations + } +} + +/// WHERE does not match the partition expression, so partitions are not pruned. +pub struct PartitionPruningMissed { + pub schema: Schema +} + +impl Rule for PartitionPruningMissed { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH003", + name: "Partition pruning missed", + severity: Severity::Warning, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.kind != QueryType::Select || query.where_cols.is_empty() { + return vec![]; + } + let mut violations = Vec::new(); + for table_name in &query.tables { + let Some(table) = find_table(&self.schema, table_name) else { + continue; + }; + let Some(partition) = &table.partition_by else { + continue; + }; + let part_cols = identifiers_in(partition); + let prunes = query + .where_cols + .iter() + .any(|c| part_cols.iter().any(|p| p.eq_ignore_ascii_case(c))); + if !prunes { + let info = self.info(); + violations.push(Violation { + rule_id: info.id, + rule_name: info.name, + message: format!( + "WHERE does not match PARTITION BY ({}) on '{}'", + partition, table.name + ), + severity: info.severity, + category: info.category, + suggestion: Some( + "Filter on the partition expression (e.g. toYYYYMM(date) = 202401) to skip whole partitions" + .to_string() + ), + query_index + }); + } + } + violations + } +} + +/// Function call on a date/time column in WHERE prevents index usage. +pub struct FunctionOnKeyColumn; + +const CH_DATE_FUNCTIONS: [&str; 11] = [ + "TODATE(", + "TODATETIME(", + "TOYEAR(", + "TOMONTH(", + "TOSTARTOFDAY(", + "TOSTARTOFMONTH(", + "TOSTARTOFWEEK(", + "TOSTARTOFHOUR(", + "TODAYOFWEEK(", + "TODAYOFYEAR(", + "TOSTARTOFQUARTER(" +]; + +impl Rule for FunctionOnKeyColumn { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH004", + name: "Function on date column in WHERE", + severity: Severity::Warning, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.kind != QueryType::Select { + return vec![]; + } + let upper = query.raw.to_uppercase(); + let Some(pos) = upper.find("WHERE") else { + return vec![]; + }; + let where_part = &upper[pos..]; + if !CH_DATE_FUNCTIONS.iter().any(|f| where_part.contains(f)) { + return vec![]; + } + let info = self.info(); + vec![Violation { + rule_id: info.id, + rule_name: info.name, + message: "Wrapping a date column in a function disables the primary index".to_string(), + severity: info.severity, + category: info.category, + suggestion: Some( + "Use a range predicate (col >= '...' AND col < '...') so the sparse index can prune granules" + .to_string() + ), + query_index + }] + } +} + +/// WHERE column is neither in the sort key nor covered by a skipping index. +pub struct MissingSkipIndex { + pub schema: Schema +} + +impl Rule for MissingSkipIndex { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH005", + name: "No skipping index for filter column", + severity: Severity::Info, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.kind != QueryType::Select || query.where_cols.is_empty() { + return vec![]; + } + let mut violations = Vec::new(); + for table_name in &query.tables { + let Some(table) = find_table(&self.schema, table_name) else { + continue; + }; + let key = sort_key(table); + for col in &query.where_cols { + let in_key = key.iter().any(|k| k.eq_ignore_ascii_case(col)); + let in_skip = table.skip_indexes.iter().any(|si| { + identifiers_in(&si.expr) + .iter() + .any(|e| e.eq_ignore_ascii_case(col)) + }); + if !in_key && !in_skip { + let info = self.info(); + violations.push(Violation { + rule_id: info.id, + rule_name: info.name, + message: format!( + "Column '{}' on '{}' is not in the sort key or a skipping index", + col, table.name + ), + severity: info.severity, + category: info.category, + suggestion: Some(format!( + "ADD INDEX idx_{col} {col} TYPE minmax GRANULARITY 4 (or bloom_filter for high-cardinality)" + )), + query_index + }); + } + } + } + violations + } +} + +/// `LowCardinality` applied to a likely high-cardinality column. +pub struct LowCardinalityHighCardinality { + pub schema: Schema +} + +const HIGH_CARDINALITY_HINTS: [&str; 6] = ["ID", "UUID", "URL", "HASH", "TOKEN", "TRACE"]; + +impl Rule for LowCardinalityHighCardinality { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH006", + name: "LowCardinality on high-cardinality column", + severity: Severity::Info, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + let mut violations = Vec::new(); + for table_name in &query.tables { + let Some(table) = find_table(&self.schema, table_name) else { + continue; + }; + for col in &table.columns { + let ty = col.data_type.to_uppercase(); + if !ty.contains("LOWCARDINALITY") { + continue; + } + let upper_name = col.name.to_uppercase(); + if HIGH_CARDINALITY_HINTS + .iter() + .any(|h| upper_name.contains(h)) + { + let info = self.info(); + violations.push(Violation { + rule_id: info.id, + rule_name: info.name, + message: format!( + "Column '{}' on '{}' uses LowCardinality but looks high-cardinality", + col.name, table.name + ), + severity: info.severity, + category: info.category, + suggestion: Some( + "LowCardinality helps below ~10k distinct values; verify with uniqExact before keeping it" + .to_string() + ), + query_index + }); + } + } + } + violations + } +} + +/// Nullable column used in a hot filter path. +pub struct NullableHotPath { + pub schema: Schema +} + +impl Rule for NullableHotPath { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH007", + name: "Nullable column in hot path", + severity: Severity::Info, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.where_cols.is_empty() && query.join_cols.is_empty() { + return vec![]; + } + let mut violations = Vec::new(); + for table_name in &query.tables { + let Some(table) = find_table(&self.schema, table_name) else { + continue; + }; + for col in &table.columns { + if !col.is_nullable { + continue; + } + let used = query + .where_cols + .iter() + .chain(query.join_cols.iter()) + .any(|c| c.eq_ignore_ascii_case(&col.name)); + if used { + let info = self.info(); + violations.push(Violation { + rule_id: info.id, + rule_name: info.name, + message: format!( + "Nullable column '{}' on '{}' is used in a filter", + col.name, table.name + ), + severity: info.severity, + category: info.category, + suggestion: Some( + "Nullable adds a null-mask read and blocks optimizations; prefer a sentinel default" + .to_string() + ), + query_index + }); + } + } + } + violations + } +} + +/// uniqExact used where approximate uniq is usually acceptable. +pub struct UniqExactUsage; + +impl Rule for UniqExactUsage { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH009", + name: "uniqExact usage", + severity: Severity::Info, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if !query.raw.to_uppercase().contains("UNIQEXACT(") { + return vec![]; + } + let info = self.info(); + vec![Violation { + rule_id: info.id, + rule_name: info.name, + message: "uniqExact tracks every distinct value and is memory-heavy".to_string(), + severity: info.severity, + category: info.category, + suggestion: Some( + "Use uniq() or uniqCombined() for approximate distinct counts in analytics" + .to_string() + ), + query_index + }] + } +} + +/// Several count subqueries that a single countIf scan can replace. +pub struct CountIfOpportunity; + +impl Rule for CountIfOpportunity { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH010", + name: "Conditional counts via subqueries", + severity: Severity::Info, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + let upper = query.raw.to_uppercase(); + let count_subqueries = upper.matches("(SELECT COUNT(").count(); + if count_subqueries < 2 { + return vec![]; + } + let info = self.info(); + vec![Violation { + rule_id: info.id, + rule_name: info.name, + message: format!("{count_subqueries} count subqueries scan the table separately"), + severity: info.severity, + category: info.category, + suggestion: Some( + "Use countIf(condition) columns in a single scan instead of separate subqueries" + .to_string() + ), + query_index + }] + } +} + +/// ORDER BY inside a subquery without LIMIT wastes CPU. +pub struct OrderByInSubquery; + +impl Rule for OrderByInSubquery { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH011", + name: "ORDER BY in subquery without LIMIT", + severity: Severity::Warning, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.kind != QueryType::Select || !query.has_subquery { + return vec![]; + } + let upper = query.raw.to_uppercase(); + if upper.contains("ORDER BY") && query.limit.is_none() { + let info = self.info(); + return vec![Violation { + rule_id: info.id, + rule_name: info.name, + message: "Sorting a subquery result is wasted work when the outer query re-sorts" + .to_string(), + severity: info.severity, + category: info.category, + suggestion: Some( + "Remove ORDER BY from the subquery unless it is paired with LIMIT".to_string() + ), + query_index + }]; + } + vec![] + } +} + +/// GROUP BY order does not match the sort key, blocking stream aggregation. +pub struct GroupByOrderMismatch { + pub schema: Schema +} + +impl Rule for GroupByOrderMismatch { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH012", + name: "GROUP BY does not match sort key", + severity: Severity::Info, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.kind != QueryType::Select || query.group_cols.is_empty() { + return vec![]; + } + let mut violations = Vec::new(); + for table_name in &query.tables { + let Some(table) = find_table(&self.schema, table_name) else { + continue; + }; + let key = sort_key(table); + if key.is_empty() { + continue; + } + let first_group = query + .group_cols + .first() + .map(compact_str::CompactString::to_lowercase); + let matches = first_group + .as_ref() + .is_some_and(|g| key.first().is_some_and(|k| k.eq_ignore_ascii_case(g))); + if !matches { + let info = self.info(); + violations.push(Violation { + rule_id: info.id, + rule_name: info.name, + message: format!( + "GROUP BY prefix differs from the sort key of '{}'", + table.name + ), + severity: info.severity, + category: info.category, + suggestion: Some( + "Align GROUP BY with the ORDER BY prefix to enable streaming aggregation without a hash table" + .to_string() + ), + query_index + }); + } + } + violations + } +} + +/// Joining multiple tables where a dictionary or denormalization is cheaper. +pub struct JoinBigTables; + +impl Rule for JoinBigTables { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH016", + name: "Multi-table JOIN", + severity: Severity::Info, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.kind != QueryType::Select || query.join_cols.is_empty() { + return vec![]; + } + if query.tables.len() < 2 { + return vec![]; + } + let info = self.info(); + vec![Violation { + rule_id: info.id, + rule_name: info.name, + message: format!( + "Query joins {} tables; ClickHouse builds an in-memory hash table per join", + query.tables.len() + ), + severity: info.severity, + category: info.category, + suggestion: Some( + "Keep the large table on the left, or replace small dimension joins with a dictionary or denormalized columns" + .to_string() + ), + query_index + }] + } +} + +/// FINAL forces read-time deduplication. +pub struct FinalUsage; + +impl Rule for FinalUsage { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH019", + name: "FINAL modifier usage", + severity: Severity::Warning, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if !query.clickhouse.has_final { + return vec![]; + } + let info = self.info(); + vec![Violation { + rule_id: info.id, + rule_name: info.name, + message: "FINAL merges parts at read time, which is expensive on large tables" + .to_string(), + severity: info.severity, + category: info.category, + suggestion: Some( + "Prefer argMax/argMin or ReplacingMergeTree with eventual merges over FINAL" + .to_string() + ), + query_index + }] + } +} + +/// A `WHERE` filter without `PREWHERE` reads every column before filtering. +pub struct PrewhereOpportunity; + +impl Rule for PrewhereOpportunity { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH021", + name: "PREWHERE opportunity", + severity: Severity::Info, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.kind != QueryType::Select + || query.where_cols.is_empty() + || !query.prewhere_cols.is_empty() + { + return vec![]; + } + let info = self.info(); + vec![Violation { + rule_id: info.id, + rule_name: info.name, + message: "Filtering in WHERE reads all selected columns before applying the filter" + .to_string(), + severity: info.severity, + category: info.category, + suggestion: Some( + "Move the selective filter columns to PREWHERE so ClickHouse reads them first and skips granules" + .to_string() + ), + query_index + }] + } +} + +/// `ALTER TABLE ... UPDATE/DELETE` mutations are asynchronous and heavy. +pub struct HeavyMutation; + +impl Rule for HeavyMutation { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH022", + name: "Heavy mutation (ALTER UPDATE/DELETE)", + severity: Severity::Warning, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.kind != QueryType::Update && query.kind != QueryType::Delete { + return vec![]; + } + let info = self.info(); + vec![Violation { + rule_id: info.id, + rule_name: info.name, + message: "ALTER UPDATE/DELETE rewrites whole parts and runs asynchronously in the background" + .to_string(), + severity: info.severity, + category: info.category, + suggestion: Some( + "Prefer a ReplacingMergeTree with a version column, or delete by partition via DROP PART" + .to_string() + ), + query_index + }] + } +} + +/// Manual `OPTIMIZE TABLE ... FINAL` forces expensive merges. +pub struct ManualOptimizeFinal; + +impl Rule for ManualOptimizeFinal { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH023", + name: "Manual OPTIMIZE FINAL", + severity: Severity::Warning, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + let upper = query.raw.to_uppercase(); + if !(upper.contains("OPTIMIZE TABLE") && upper.contains("FINAL")) { + return vec![]; + } + let info = self.info(); + vec![Violation { + rule_id: info.id, + rule_name: info.name, + message: "OPTIMIZE TABLE ... FINAL rewrites parts synchronously and is expensive" + .to_string(), + severity: info.severity, + category: info.category, + suggestion: Some( + "Rely on background merges; run OPTIMIZE FINAL only for targeted maintenance windows" + .to_string() + ), + query_index + }] + } +} + +/// A `JOIN` against a table that also exists as a dictionary can use a lookup. +pub struct DictionaryLookupOpportunity { + pub schema: Schema +} + +impl Rule for DictionaryLookupOpportunity { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH024", + name: "Dictionary lookup opportunity", + severity: Severity::Info, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if self.schema.dictionaries.is_empty() || query.join_cols.is_empty() { + return vec![]; + } + let mut violations = Vec::new(); + for table_name in &query.tables { + let bare = table_name.rsplit('.').next().unwrap_or(table_name); + if self + .schema + .dictionaries + .iter() + .any(|d| d.rsplit('.').next().unwrap_or(d).eq_ignore_ascii_case(bare)) + { + let info = self.info(); + violations.push(Violation { + rule_id: info.id, + rule_name: info.name, + message: format!( + "'{bare}' is defined as a dictionary; a JOIN pays full-table cost" + ), + severity: info.severity, + category: info.category, + suggestion: Some( + "Use dictGet/dictHas on the dictionary instead of joining the source table" + .to_string() + ), + query_index + }); + } + } + violations + } +} + +/// `GROUP BY` on a plain `String` key wastes memory versus `LowCardinality`. +pub struct GroupByStringKey { + pub schema: Schema +} + +impl Rule for GroupByStringKey { + fn info(&self) -> RuleInfo { + RuleInfo { + id: "CH025", + name: "GROUP BY on plain String key", + severity: Severity::Info, + category: RuleCategory::Performance + } + } + + fn check(&self, query: &Query, query_index: usize) -> Vec { + if query.kind != QueryType::Select || query.group_cols.is_empty() { + return vec![]; + } + let mut violations = Vec::new(); + for table_name in &query.tables { + let Some(table) = find_table(&self.schema, table_name) else { + continue; + }; + for group in &query.group_cols { + let Some(col) = table + .columns + .iter() + .find(|c| c.name.eq_ignore_ascii_case(group.as_str())) + else { + continue; + }; + if col.data_type.eq_ignore_ascii_case("String") { + let info = self.info(); + violations.push(Violation { + rule_id: info.id, + rule_name: info.name, + message: format!( + "GROUP BY key '{}' is a plain String on '{}'", + col.name, table.name + ), + severity: info.severity, + category: info.category, + suggestion: Some( + "Use LowCardinality(String) for low-cardinality grouping keys to shrink hash tables" + .to_string() + ), + query_index + }); + } + } + } + violations + } +} diff --git a/src/rules/performance.rs b/src/rules/performance.rs index 96030ff..f0f73e3 100644 --- a/src/rules/performance.rs +++ b/src/rules/performance.rs @@ -15,7 +15,7 @@ impl Rule for ScalarSubquery { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } let upper = query.raw.to_uppercase(); @@ -169,7 +169,7 @@ impl Rule for SelectWithoutWhere { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } if query.where_cols.is_empty() && query.limit.is_none() && !query.tables.is_empty() { @@ -202,7 +202,7 @@ impl Rule for SelectStarWithoutLimit { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } let has_star = query.raw.to_uppercase().contains("SELECT *") @@ -275,10 +275,7 @@ impl Rule for OrInsteadOfIn { return vec![Violation { rule_id: info.id, rule_name: info.name, - message: format!( - "Query has {} OR conditions, consider using IN clause", - or_count - ), + message: format!("Query has {or_count} OR conditions, consider using IN clause"), severity: info.severity, category: info.category, suggestion: Some( @@ -312,10 +309,7 @@ impl Rule for LargeOffset { return vec![Violation { rule_id: info.id, rule_name: info.name, - message: format!( - "OFFSET {} is large, causing performance degradation", - offset - ), + message: format!("OFFSET {offset} is large, causing performance degradation"), severity: info.severity, category: info.category, suggestion: Some("Use keyset pagination (WHERE id > last_id) instead".to_string()), @@ -340,7 +334,7 @@ impl Rule for MissingJoinCondition { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } let table_count = query.tables.len(); @@ -351,8 +345,7 @@ impl Rule for MissingJoinCondition { rule_id: info.id, rule_name: info.name, message: format!( - "Query references {} tables without apparent JOIN conditions", - table_count + "Query references {table_count} tables without apparent JOIN conditions" ), severity: info.severity, category: info.category, @@ -366,7 +359,7 @@ impl Rule for MissingJoinCondition { } } -/// ORDER BY RAND() forces a full scan and sort of every candidate row +/// ORDER BY `RAND()` forces a full scan and sort of every candidate row /// /// The database must generate a random value per row and sort the whole /// result set before applying LIMIT, so cost stays O(n log n) regardless @@ -385,7 +378,7 @@ impl Rule for OrderByRandom { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } let upper = query.raw.to_uppercase(); @@ -432,7 +425,7 @@ impl Rule for CountWithoutWhere { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } if !query.where_cols.is_empty() || query.tables.is_empty() { @@ -530,7 +523,7 @@ impl Rule for LargeInClause { vec![Violation { rule_id: info.id, rule_name: info.name, - message: format!("IN clause contains {} values", items), + message: format!("IN clause contains {items} values"), severity, category: info.category, suggestion: Some( @@ -573,7 +566,7 @@ impl Rule for HavingWithoutAggregate { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select || query.having_cols.is_empty() { + if query.kind != QueryType::Select || query.having_cols.is_empty() { return vec![]; } let upper = query.raw.to_uppercase(); @@ -625,7 +618,7 @@ impl Rule for UnnecessaryDistinct { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select || !query.has_distinct { + if query.kind != QueryType::Select || !query.has_distinct { return vec![]; } let upper = query.raw.to_uppercase(); @@ -707,7 +700,7 @@ impl Rule for DeeplyNestedSubqueries { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } let upper = query.raw.to_uppercase(); @@ -726,7 +719,7 @@ impl Rule for DeeplyNestedSubqueries { vec![Violation { rule_id: info.id, rule_name: info.name, - message: format!("Query nests SELECTs {} levels deep", levels), + message: format!("Query nests SELECTs {levels} levels deep"), severity, category: info.category, suggestion: Some( @@ -776,7 +769,7 @@ impl Rule for RepeatedTableScan { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } let upper = query.raw.to_uppercase(); @@ -787,7 +780,7 @@ impl Rule for RepeatedTableScan { return vec![Violation { rule_id: info.id, rule_name: info.name, - message: format!("Table '{}' is scanned {} times", table, scans), + message: format!("Table '{table}' is scanned {scans} times"), severity: info.severity, category: info.category, suggestion: Some( @@ -925,7 +918,7 @@ impl Rule for CorrelatedSubquery { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select || !query.has_subquery { + if query.kind != QueryType::Select || !query.has_subquery { return vec![]; } let upper = query.raw.to_uppercase(); diff --git a/src/rules/schema_aware.rs b/src/rules/schema_aware.rs index 7898e35..ca0b7e3 100644 --- a/src/rules/schema_aware.rs +++ b/src/rules/schema_aware.rs @@ -10,7 +10,8 @@ pub struct MissingIndexOnFilterColumn { } impl MissingIndexOnFilterColumn { - pub fn new(schema: Schema) -> Self { + #[must_use] + pub const fn new(schema: Schema) -> Self { Self { schema } @@ -36,7 +37,7 @@ impl Rule for MissingIndexOnFilterColumn { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } let indexed_cols = self.get_indexed_columns(); @@ -48,10 +49,10 @@ impl Rule for MissingIndexOnFilterColumn { violations.push(Violation { rule_id: info.id, rule_name: info.name, - message: format!("Column '{}' in WHERE clause has no index", col), + message: format!("Column '{col}' in WHERE clause has no index"), severity: info.severity, category: info.category, - suggestion: Some(format!("Consider adding index on '{}'", col)), + suggestion: Some(format!("Consider adding index on '{col}'")), query_index }); } @@ -63,10 +64,10 @@ impl Rule for MissingIndexOnFilterColumn { violations.push(Violation { rule_id: info.id, rule_name: info.name, - message: format!("Column '{}' in JOIN clause has no index", col), + message: format!("Column '{col}' in JOIN clause has no index"), severity: info.severity, category: info.category, - suggestion: Some(format!("Consider adding index on '{}'", col)), + suggestion: Some(format!("Consider adding index on '{col}'")), query_index }); } @@ -81,7 +82,8 @@ pub struct ColumnNotInSchema { } impl ColumnNotInSchema { - pub fn new(schema: Schema) -> Self { + #[must_use] + pub const fn new(schema: Schema) -> Self { Self { schema } @@ -115,7 +117,7 @@ impl Rule for ColumnNotInSchema { .chain(query.join_cols.iter()) .chain(query.order_cols.iter()) .chain(query.group_cols.iter()) - .map(|s| s.as_str()) + .map(compact_str::CompactString::as_str) .collect(); for col in query_cols { let col_lower = col.to_lowercase(); @@ -127,7 +129,7 @@ impl Rule for ColumnNotInSchema { violations.push(Violation { rule_id: info.id, rule_name: info.name, - message: format!("Column '{}' not found in schema", col), + message: format!("Column '{col}' not found in schema"), severity: info.severity, category: info.category, suggestion: Some("Check column name spelling or table reference".to_string()), @@ -151,7 +153,8 @@ pub struct JoinOnNonIndexedColumn { } impl JoinOnNonIndexedColumn { - pub fn new(schema: Schema) -> Self { + #[must_use] + pub const fn new(schema: Schema) -> Self { Self { schema } @@ -169,7 +172,7 @@ impl Rule for JoinOnNonIndexedColumn { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select || query.join_cols.is_empty() { + if query.kind != QueryType::Select || query.join_cols.is_empty() { return vec![]; } let mut violations = Vec::new(); @@ -233,7 +236,8 @@ pub struct ImplicitTypeConversion { } impl ImplicitTypeConversion { - pub fn new(schema: Schema) -> Self { + #[must_use] + pub const fn new(schema: Schema) -> Self { Self { schema } @@ -302,8 +306,7 @@ impl Rule for ImplicitTypeConversion { rule_id: info.id, rule_name: info.name, message: format!( - "Text column '{}' is compared with a numeric literal", - col + "Text column '{col}' is compared with a numeric literal" ), severity: info.severity, category: info.category, @@ -325,7 +328,8 @@ pub struct SuggestIndex { } impl SuggestIndex { - pub fn new(schema: Schema) -> Self { + #[must_use] + pub const fn new(schema: Schema) -> Self { Self { schema } @@ -343,7 +347,7 @@ impl Rule for SuggestIndex { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } let indexed_cols: Vec = self @@ -359,7 +363,7 @@ impl Rule for SuggestIndex { return vec![Violation { rule_id: info.id, rule_name: info.name, - message: format!("ORDER BY column '{}' could benefit from index", col), + message: format!("ORDER BY column '{col}' could benefit from index"), severity: info.severity, category: info.category, suggestion: Some(format!( diff --git a/src/rules/security.rs b/src/rules/security.rs index 7a3fd28..5330e46 100644 --- a/src/rules/security.rs +++ b/src/rules/security.rs @@ -21,7 +21,7 @@ impl Rule for TruncateDetected { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Truncate { + if query.kind != QueryType::Truncate { return vec![]; } let info = self.info(); @@ -30,8 +30,7 @@ impl Rule for TruncateDetected { rule_id: info.id, rule_name: info.name, message: format!( - "TRUNCATE removes all rows from table(s) '{}' without logging individual deletions", - table_names + "TRUNCATE removes all rows from table(s) '{table_names}' without logging individual deletions" ), severity: info.severity, category: info.category, @@ -58,7 +57,7 @@ impl Rule for MissingWhereInUpdate { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Update { + if query.kind != QueryType::Update { return vec![]; } if query.where_cols.is_empty() { @@ -96,23 +95,19 @@ impl Rule for DropDetected { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Drop { + if query.kind != QueryType::Drop { return vec![]; } let info = self.info(); let object_type = query .cte_names .first() - .map(|s| s.as_str()) - .unwrap_or("object"); + .map_or("object", compact_str::CompactString::as_str); let names = query.tables.join(", "); vec![Violation { rule_id: info.id, rule_name: info.name, - message: format!( - "DROP {} '{}' permanently destroys data and schema", - object_type, names - ), + message: format!("DROP {object_type} '{names}' permanently destroys data and schema"), severity: info.severity, category: info.category, suggestion: Some( @@ -234,7 +229,7 @@ impl Rule for PrivilegeChange { /// query logs, and error logs, and violate PCI-DSS/SOC2/HIPAA plaintext /// storage rules. Flags `IDENTIFIED BY`/`WITH PASSWORD`/`SET PASSWORD` /// clauses and string literals assigned or inserted into sensitive columns -/// (password, secret, api_key, token, and similar). +/// (password, secret, `api_key`, token, and similar). pub struct HardcodedCredential; const SENSITIVE_COLUMNS: [&str; 9] = [ @@ -291,7 +286,7 @@ fn has_sensitive_assignment(upper: &str) -> bool { /// Returns true when an INSERT names a sensitive column before VALUES and /// supplies at least one string literal. fn has_sensitive_insert(query: &Query, upper: &str) -> bool { - if query.query_type != QueryType::Insert { + if query.kind != QueryType::Insert { return false; } let Some(values_pos) = upper.find(" VALUES") else { @@ -425,7 +420,7 @@ impl Rule for MissingWhereInDelete { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Delete { + if query.kind != QueryType::Delete { return vec![]; } if query.where_cols.is_empty() { diff --git a/src/rules/style.rs b/src/rules/style.rs index ba8099d..4fb1f5c 100644 --- a/src/rules/style.rs +++ b/src/rules/style.rs @@ -15,7 +15,7 @@ impl Rule for SelectStar { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } let has_star = query.raw.to_uppercase().contains("SELECT *") @@ -102,7 +102,7 @@ impl Rule for OrdinalInOrderOrGroupBy { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } let upper = query.raw.to_uppercase(); @@ -146,7 +146,7 @@ impl Rule for MissingTableAlias { } fn check(&self, query: &Query, query_index: usize) -> Vec { - if query.query_type != QueryType::Select { + if query.kind != QueryType::Select { return vec![]; } if query.tables.len() <= 1 { diff --git a/src/rules/types.rs b/src/rules/types.rs index 8f7e623..5f8e211 100644 --- a/src/rules/types.rs +++ b/src/rules/types.rs @@ -104,7 +104,8 @@ pub struct AnalysisReport { } impl AnalysisReport { - pub fn new(queries_count: usize, rules_count: usize) -> Self { + #[must_use] + pub const fn new(queries_count: usize, rules_count: usize) -> Self { Self { violations: Vec::new(), queries_count, @@ -116,6 +117,7 @@ impl AnalysisReport { self.violations.push(violation); } + #[must_use] pub fn error_count(&self) -> usize { self.violations .iter() @@ -123,6 +125,7 @@ impl AnalysisReport { .count() } + #[must_use] pub fn warning_count(&self) -> usize { self.violations .iter() @@ -130,6 +133,7 @@ impl AnalysisReport { .count() } + #[must_use] pub fn info_count(&self) -> usize { self.violations .iter() diff --git a/src/schema.rs b/src/schema.rs index 8dd005d..74f4bdc 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -33,7 +33,7 @@ //! assert!(summary.contains("users")); //! ``` -use std::collections::BTreeMap; +use std::{collections::BTreeMap, fmt::Write}; use sqlparser::parser::Parser; @@ -52,15 +52,25 @@ pub struct TableInfo { pub columns: Vec, /// Indexes defined on this table pub indexes: Vec, - /// Storage engine (ClickHouse: MergeTree, ReplicatedMergeTree, etc.) + /// Storage engine (`ClickHouse`: `MergeTree`, `ReplicatedMergeTree`, etc.) pub engine: Option, - /// Physical sort order columns (ClickHouse ORDER BY) + /// Physical sort order columns (`ClickHouse` ORDER BY) pub order_by: Option>, - /// Sparse index columns (ClickHouse PRIMARY KEY) + /// Sparse index columns (`ClickHouse` PRIMARY KEY) pub primary_key: Option>, - /// Partitioning expression (ClickHouse PARTITION BY) + /// Partitioning expression (`ClickHouse` PARTITION BY) pub partition_by: Option, - /// Cluster name (ClickHouse ON CLUSTER) + /// Sample by expression (`ClickHouse` SAMPLE BY) + pub sample_by: Option, + /// Data skipping indexes (`ClickHouse` INDEX ... TYPE ... GRANULARITY) + pub skip_indexes: Vec, + /// Projections (`ClickHouse` PROJECTION ... AS SELECT) + pub projections: Vec, + /// TTL expression (`ClickHouse` TTL) + pub ttl: Option, + /// Table-level settings (`ClickHouse` SETTINGS) + pub settings: std::collections::HashMap, + /// Cluster name (`ClickHouse` ON CLUSTER) pub cluster: Option } @@ -75,7 +85,7 @@ pub struct ColumnInfo { pub is_nullable: bool, /// Whether this is a primary key column pub is_primary: bool, - /// Compression codec (ClickHouse: ZSTD, LZ4, Delta, etc.) + /// Compression codec (`ClickHouse`: ZSTD, LZ4, Delta, etc.) pub codec: Option } @@ -96,7 +106,11 @@ pub struct IndexInfo { #[derive(Debug, Default, Clone)] pub struct Schema { /// Map of table name to table information - pub tables: BTreeMap + pub tables: BTreeMap, + /// `ClickHouse` dictionary names defined in the schema + pub dictionaries: Vec, + /// `ClickHouse` materialized views defined in the schema + pub materialized_views: Vec } impl Schema { @@ -122,16 +136,23 @@ impl Schema { .map_err(|e| schema_parse_error(e.to_string()))?; let mut schema = Self::default(); for stmt in statements { - schema.process_statement(stmt, &preprocessed.metadata)?; + schema.process_statement(stmt, &preprocessed.metadata, dialect); } + schema + .dictionaries + .clone_from(&preprocessed.metadata.dictionaries); + schema + .materialized_views + .clone_from(&preprocessed.metadata.materialized_views); Ok(schema) } fn process_statement( &mut self, stmt: sqlparser::ast::Statement, - metadata: &PreprocessorMetadata - ) -> AppResult<()> { + metadata: &PreprocessorMetadata, + dialect: SqlDialect + ) { use sqlparser::ast::Statement; match stmt { Statement::CreateTable(create) => { @@ -144,12 +165,22 @@ impl Schema { matches!(opt.option, sqlparser::ast::ColumnOption::PrimaryKey(_)) }); let codec = metadata.codecs.get(&col_name).cloned(); + let data_type = column.data_type.to_string(); + let is_nullable = if dialect == SqlDialect::ClickHouse { + data_type + .trim_start() + .to_uppercase() + .starts_with("NULLABLE") + } else { + !column + .options + .iter() + .any(|opt| matches!(opt.option, sqlparser::ast::ColumnOption::NotNull)) + }; columns.push(ColumnInfo { name: col_name, - data_type: column.data_type.to_string(), - is_nullable: !column.options.iter().any(|opt| { - matches!(opt.option, sqlparser::ast::ColumnOption::NotNull) - }), + data_type, + is_nullable, is_primary, codec }); @@ -157,8 +188,12 @@ impl Schema { for constraint in create.constraints { if let sqlparser::ast::TableConstraint::Index(idx) = constraint { indexes.push(IndexInfo { - name: idx.name.map(|n| n.to_string()).unwrap_or_default(), - columns: idx.columns.iter().map(|c| c.to_string()).collect(), + name: idx.name.map_or_default(|n| n.to_string()), + columns: idx + .columns + .iter() + .map(std::string::ToString::to_string) + .collect(), is_unique: false }); } @@ -167,6 +202,12 @@ impl Schema { let order_by = create.order_by.as_ref().map(Self::extract_exprs); let primary_key = create.primary_key.as_ref().map(|pk| vec![pk.to_string()]); let cluster = create.on_cluster.map(|c| c.value); + let partition_by = metadata.partition_by.first().cloned(); + let ttl = metadata.ttl_expressions.first().cloned(); + let settings = metadata.settings.clone(); + let sample_by = metadata.sample_by.first().cloned(); + let skip_indexes = metadata.skip_indexes.clone(); + let projections = metadata.projections.clone(); self.tables.insert( table_name.clone(), TableInfo { @@ -176,7 +217,12 @@ impl Schema { engine, order_by, primary_key, - partition_by: None, + partition_by, + ttl, + settings, + sample_by, + skip_indexes, + projections, cluster } ); @@ -185,15 +231,18 @@ impl Schema { let table_name = create_index.table_name.to_string(); if let Some(table) = self.tables.get_mut(&table_name) { table.indexes.push(IndexInfo { - name: create_index.name.map(|n| n.to_string()).unwrap_or_default(), - columns: create_index.columns.iter().map(|c| c.to_string()).collect(), + name: create_index.name.map_or_default(|n| n.to_string()), + columns: create_index + .columns + .iter() + .map(std::string::ToString::to_string) + .collect(), is_unique: create_index.unique }); } } _ => {} } - Ok(()) } fn extract_engine(options: &sqlparser::ast::CreateTableOptions) -> Option { @@ -221,62 +270,122 @@ impl Schema { use sqlparser::ast::OneOrManyWithParens; match exprs { OneOrManyWithParens::One(expr) => vec![expr.to_string()], - OneOrManyWithParens::Many(list) => list.iter().map(|e| e.to_string()).collect() + OneOrManyWithParens::Many(list) => { + list.iter().map(std::string::ToString::to_string).collect() + } } } /// Get summary of schema for LLM analysis + #[must_use] pub fn to_summary(&self) -> String { let mut summary = String::from("Database Schema:\n\n"); for table in self.tables.values() { - summary.push_str(&format!("Table: {}\n", table.name)); - if let Some(engine) = &table.engine { - summary.push_str(&format!("Engine: {}\n", engine)); - } - if let Some(cluster) = &table.cluster { - summary.push_str(&format!("Cluster: {}\n", cluster)); - } - if let Some(partition_by) = &table.partition_by { - summary.push_str(&format!("Partition By: {}\n", partition_by)); - } - if let Some(order_by) = &table.order_by { - summary.push_str(&format!("Order By: ({})\n", order_by.join(", "))); + Self::write_table_summary(table, &mut summary); + } + if !self.dictionaries.is_empty() { + let _ = writeln!(summary, "Dictionaries: {}", self.dictionaries.join(", ")); + } + if !self.materialized_views.is_empty() { + summary.push_str("Materialized Views:\n"); + for mv in &self.materialized_views { + let target = mv.target.as_ref().map_or_default(|t| format!(" TO {t}")); + let _ = writeln!( + summary, + " - {name}{target} AS {query}", + name = mv.name, + query = mv.query + ); } - if let Some(primary_key) = &table.primary_key { - summary.push_str(&format!("Primary Key: ({})\n", primary_key.join(", "))); + } + summary + } + + /// Append one table's full description (metadata, columns, indexes, skip + /// indexes, projections) to `summary`. + fn write_table_summary(table: &TableInfo, summary: &mut String) { + let _ = writeln!(summary, "Table: {}", table.name); + if let Some(engine) = &table.engine { + let _ = writeln!(summary, "Engine: {engine}"); + } + if let Some(cluster) = &table.cluster { + let _ = writeln!(summary, "Cluster: {cluster}"); + } + if let Some(partition_by) = &table.partition_by { + let _ = writeln!(summary, "Partition By: {partition_by}"); + } + if let Some(sample_by) = &table.sample_by { + let _ = writeln!(summary, "Sample By: {sample_by}"); + } + if let Some(ttl) = &table.ttl { + let _ = writeln!(summary, "TTL: {ttl}"); + } + if !table.settings.is_empty() { + let settings: Vec = table + .settings + .iter() + .map(|(k, v)| format!("{k} = {v}")) + .collect(); + let _ = writeln!(summary, "Settings: {}", settings.join(", ")); + } + if let Some(order_by) = &table.order_by { + let _ = writeln!(summary, "Order By: ({})", order_by.join(", ")); + } + if let Some(primary_key) = &table.primary_key { + let _ = writeln!(summary, "Primary Key: ({})", primary_key.join(", ")); + } + summary.push_str("Columns:\n"); + for col in &table.columns { + let nullable = if col.is_nullable { "NULL" } else { "NOT NULL" }; + let primary = if col.is_primary { " PRIMARY KEY" } else { "" }; + let codec = col + .codec + .as_ref() + .map_or_default(|c| format!(" CODEC({c})")); + let _ = writeln!( + summary, + " - {name} {data_type} {nullable}{primary}{codec}", + name = col.name, + data_type = col.data_type, + nullable = nullable, + primary = primary, + codec = codec + ); + } + if !table.indexes.is_empty() { + summary.push_str("Indexes:\n"); + for idx in &table.indexes { + let unique = if idx.is_unique { "UNIQUE " } else { "" }; + let _ = writeln!( + summary, + " - {unique}INDEX {name} ON ({columns})", + unique = unique, + name = idx.name, + columns = idx.columns.join(", ") + ); } - summary.push_str("Columns:\n"); - for col in &table.columns { - let nullable = if col.is_nullable { "NULL" } else { "NOT NULL" }; - let primary = if col.is_primary { " PRIMARY KEY" } else { "" }; - let codec = col - .codec - .as_ref() - .map(|c| format!(" CODEC({})", c)) - .unwrap_or_default(); - summary.push_str(&format!( - " - {name} {data_type} {nullable}{primary}{codec}\n", - name = col.name, - data_type = col.data_type, - nullable = nullable, - primary = primary, - codec = codec - )); + } + if !table.skip_indexes.is_empty() { + summary.push_str("Skip Indexes:\n"); + for si in &table.skip_indexes { + let args = si.type_args.as_ref().map_or_default(|a| format!("({a})")); + let _ = writeln!( + summary, + " - INDEX {name} ON {expr} TYPE {ty}{args} GRANULARITY {g}", + name = si.name, + expr = si.expr, + ty = si.type_name, + args = args, + g = si.granularity + ); } - if !table.indexes.is_empty() { - summary.push_str("Indexes:\n"); - for idx in &table.indexes { - let unique = if idx.is_unique { "UNIQUE " } else { "" }; - summary.push_str(&format!( - " - {unique}INDEX {name} ON ({columns})\n", - unique = unique, - name = idx.name, - columns = idx.columns.join(", ") - )); - } + } + if !table.projections.is_empty() { + summary.push_str("Projections:\n"); + for proj in &table.projections { + let _ = writeln!(summary, " - {} AS {}", proj.name, proj.query); } - summary.push('\n'); } - summary + summary.push('\n'); } } diff --git a/tests/app_analyze_tests.rs b/tests/app_analyze_tests.rs new file mode 100644 index 0000000..7325051 --- /dev/null +++ b/tests/app_analyze_tests.rs @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2025 RAprogramm +// SPDX-License-Identifier: MIT + +use std::io::{Read, Write}; + +use sql_query_analyzer::{ + app::{AnalyzeParams, run_analyze}, + cli::{Dialect, Format, Provider}, + config::Config +}; + +fn mock_ollama_server(body: &'static str) -> String { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + std::thread::spawn(move || { + if let Ok((mut sock, _)) = listener.accept() { + let mut buf = [0u8; 8192]; + let _ = sock.read(&mut buf); + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = sock.write_all(resp.as_bytes()); + } + }); + format!("http://{addr}") +} + +#[tokio::test] +async fn run_analyze_with_llm_appends_analysis() { + let server = mock_ollama_server(r#"{"response":"llm analysis text"}"#); + let dir = tempfile::tempdir().unwrap(); + let schema = dir.path().join("schema.sql"); + let queries = dir.path().join("queries.sql"); + std::fs::write(&schema, "CREATE TABLE users (id INT PRIMARY KEY);").unwrap(); + std::fs::write(&queries, "SELECT * FROM users WHERE id = 1;").unwrap(); + let params = AnalyzeParams { + schema_path: schema.to_string_lossy().into_owned(), + queries_path: queries.to_string_lossy().into_owned(), + provider: Provider::Ollama, + api_key: None, + model: None, + ollama_url: server, + dialect: Dialect::Generic, + output_format: Format::Text, + verbose: false, + dry_run: false, + no_color: true + }; + let result = run_analyze(params, Config::default()).await.unwrap(); + let llm_output = result.llm_output.expect("llm output present"); + assert!(llm_output.contains("llm analysis text"), "{llm_output}"); +} + +#[tokio::test] +async fn run_analyze_llm_failure_propagates_error() { + let dir = tempfile::tempdir().unwrap(); + let schema = dir.path().join("schema.sql"); + let queries = dir.path().join("queries.sql"); + std::fs::write(&schema, "CREATE TABLE users (id INT PRIMARY KEY);").unwrap(); + std::fs::write(&queries, "SELECT * FROM users;").unwrap(); + let params = AnalyzeParams { + schema_path: schema.to_string_lossy().into_owned(), + queries_path: queries.to_string_lossy().into_owned(), + provider: Provider::Ollama, + api_key: None, + model: None, + ollama_url: "http://127.0.0.1:1".into(), + dialect: Dialect::Generic, + output_format: Format::Text, + verbose: false, + dry_run: false, + no_color: true + }; + assert!(run_analyze(params, Config::default()).await.is_err()); +} diff --git a/tests/cache_tests.rs b/tests/cache_tests.rs index 74c4cba..8c28b99 100644 --- a/tests/cache_tests.rs +++ b/tests/cache_tests.rs @@ -63,8 +63,8 @@ fn test_cache_different_queries() { let mut cache = QueryCache::new(100); let q1 = parse_queries("SELECT a FROM t1", SqlDialect::Generic).unwrap(); let q2 = parse_queries("SELECT b FROM t2", SqlDialect::Generic).unwrap(); - cache.insert("SELECT a FROM t1", q1.clone()); - cache.insert("SELECT b FROM t2", q2.clone()); + cache.insert("SELECT a FROM t1", q1); + cache.insert("SELECT b FROM t2", q2); let cached1 = cache.get("SELECT a FROM t1"); let cached2 = cache.get("SELECT b FROM t2"); assert!(cached1.is_some()); diff --git a/tests/cli_tests.rs b/tests/cli_tests.rs index 42c4956..5c0cd24 100644 --- a/tests/cli_tests.rs +++ b/tests/cli_tests.rs @@ -23,56 +23,59 @@ fn test_provider_default_model_ollama() { #[test] fn test_dialect_variants() { - let _generic = Dialect::Generic; - let _mysql = Dialect::Mysql; - let _postgresql = Dialect::Postgresql; - let _sqlite = Dialect::Sqlite; + let dialects = [ + Dialect::Generic, + Dialect::Mysql, + Dialect::Postgresql, + Dialect::Sqlite + ]; + assert_eq!(dialects.len(), 4); } #[test] fn test_format_variants() { - let _text = Format::Text; - let _json = Format::Json; - let _yaml = Format::Yaml; - let _sarif = Format::Sarif; + let formats = [Format::Text, Format::Json, Format::Yaml, Format::Sarif]; + assert_eq!(formats.len(), 4); } #[test] fn test_provider_clone() { let provider = Provider::OpenAI; - let cloned = provider.clone(); + let cloned = provider; assert_eq!(cloned.default_model(), "gpt-4"); } #[test] fn test_dialect_clone() { let dialect = Dialect::Mysql; - let _cloned = dialect.clone(); + let cloned = dialect; + assert!(matches!(cloned, Dialect::Mysql)); } #[test] fn test_format_clone() { let format = Format::Json; - let _cloned = format.clone(); + let copied = format; + assert!(matches!(copied, Format::Json)); } #[test] fn test_provider_debug() { let provider = Provider::Ollama; - let debug = format!("{:?}", provider); + let debug = format!("{provider:?}"); assert!(debug.contains("Ollama")); } #[test] fn test_dialect_debug() { let dialect = Dialect::Postgresql; - let debug = format!("{:?}", dialect); + let debug = format!("{dialect:?}"); assert!(debug.contains("Postgresql")); } #[test] fn test_format_debug() { let format = Format::Sarif; - let debug = format!("{:?}", format); + let debug = format!("{format:?}"); assert!(debug.contains("Sarif")); } diff --git a/tests/clickhouse_tests.rs b/tests/clickhouse_tests.rs new file mode 100644 index 0000000..56e92ed --- /dev/null +++ b/tests/clickhouse_tests.rs @@ -0,0 +1,334 @@ +// SPDX-FileCopyrightText: 2025 RAprogramm +// SPDX-License-Identifier: MIT + +use sql_query_analyzer::{ + config::RulesConfig, + query::{SqlDialect, parse_queries}, + rules::RuleRunner, + schema::Schema +}; + +fn ch_ids(sql: &str, schema_sql: &str) -> Vec { + let schema = Schema::parse(schema_sql, SqlDialect::ClickHouse).unwrap(); + let queries = parse_queries(sql, SqlDialect::ClickHouse).unwrap(); + let runner = RuleRunner::with_schema_and_config_and_dialect( + SqlDialect::ClickHouse, + schema, + &RulesConfig::default() + ); + runner + .analyze(&queries) + .violations + .iter() + .map(|v| v.rule_id.to_string()) + .collect() +} + +const MERGE_TREE: &str = "CREATE TABLE t (d Date, x UInt64) ENGINE = MergeTree ORDER BY d"; + +#[test] +fn ch001_flags_select_star() { + let v = ch_ids("SELECT * FROM t", MERGE_TREE); + assert!(v.contains(&"CH001".to_string())); +} + +#[test] +fn ch001_ignores_explicit_columns() { + let v = ch_ids("SELECT d, x FROM t", MERGE_TREE); + assert!(!v.contains(&"CH001".to_string())); +} + +#[test] +fn ch002_flags_filter_off_sort_key() { + let v = ch_ids("SELECT d FROM t WHERE x = 1", MERGE_TREE); + assert!(v.contains(&"CH002".to_string())); +} + +#[test] +fn ch002_ok_when_filter_uses_sort_key() { + let v = ch_ids("SELECT x FROM t WHERE d = today()", MERGE_TREE); + assert!(!v.contains(&"CH002".to_string())); +} + +#[test] +fn ch003_flags_missing_partition_pruning() { + let schema = + "CREATE TABLE t (d Date, x UInt64) ENGINE = MergeTree ORDER BY d PARTITION BY toYYYYMM(d)"; + let v = ch_ids("SELECT x FROM t WHERE x = 1", schema); + assert!(v.contains(&"CH003".to_string())); +} + +#[test] +fn ch003_ok_when_partition_pruned() { + let schema = + "CREATE TABLE t (d Date, x UInt64) ENGINE = MergeTree ORDER BY d PARTITION BY toYYYYMM(d)"; + let v = ch_ids("SELECT x FROM t WHERE d = today()", schema); + assert!(!v.contains(&"CH003".to_string())); +} + +#[test] +fn ch004_flags_function_on_date_column() { + let v = ch_ids("SELECT x FROM t WHERE toDate(d) = today()", MERGE_TREE); + assert!(v.contains(&"CH004".to_string())); +} + +#[test] +fn ch004_ok_for_range_predicate() { + let v = ch_ids( + "SELECT x FROM t WHERE d >= today() AND d < today() + 1", + MERGE_TREE + ); + assert!(!v.contains(&"CH004".to_string())); +} + +#[test] +fn ch005_flags_uncovered_filter_column() { + let v = ch_ids("SELECT d FROM t WHERE x = 1", MERGE_TREE); + assert!(v.contains(&"CH005".to_string())); +} + +#[test] +fn ch005_ok_when_skip_index_present() { + let schema = "CREATE TABLE t (d Date, x UInt64, INDEX idx_x x TYPE minmax GRANULARITY 4) ENGINE = MergeTree ORDER BY d"; + let v = ch_ids("SELECT d FROM t WHERE x = 1", schema); + assert!(!v.contains(&"CH005".to_string())); +} + +#[test] +fn ch006_flags_lowcardinality_high_cardinality() { + let schema = "CREATE TABLE t (id LowCardinality(String)) ENGINE = MergeTree ORDER BY id"; + let v = ch_ids("SELECT id FROM t", schema); + assert!(v.contains(&"CH006".to_string())); +} + +#[test] +fn ch007_flags_nullable_in_filter() { + let schema = "CREATE TABLE t (d Date, s Nullable(String)) ENGINE = MergeTree ORDER BY d"; + let v = ch_ids("SELECT d FROM t WHERE s = 'x'", schema); + assert!(v.contains(&"CH007".to_string())); +} + +#[test] +fn ch009_flags_uniqexact() { + let v = ch_ids("SELECT uniqExact(x) FROM t", MERGE_TREE); + assert!(v.contains(&"CH009".to_string())); +} + +#[test] +fn ch009_ok_for_approximate_uniq() { + let v = ch_ids("SELECT uniq(x) FROM t", MERGE_TREE); + assert!(!v.contains(&"CH009".to_string())); +} + +#[test] +fn ch010_flags_multiple_count_subqueries() { + let sql = "SELECT (SELECT count() FROM t WHERE x = 1), (SELECT count() FROM t WHERE x = 2)"; + let v = ch_ids(sql, MERGE_TREE); + assert!(v.contains(&"CH010".to_string())); +} + +#[test] +fn ch011_flags_order_by_in_subquery_without_limit() { + let sql = "SELECT * FROM (SELECT d FROM t ORDER BY d)"; + let v = ch_ids(sql, MERGE_TREE); + assert!(v.contains(&"CH011".to_string())); +} + +#[test] +fn ch012_flags_group_by_mismatch() { + let v = ch_ids("SELECT x, count() FROM t GROUP BY x", MERGE_TREE); + assert!(v.contains(&"CH012".to_string())); +} + +#[test] +fn ch012_ok_when_group_by_matches_key() { + let v = ch_ids("SELECT d, count() FROM t GROUP BY d", MERGE_TREE); + assert!(!v.contains(&"CH012".to_string())); +} + +#[test] +fn ch016_flags_multi_table_join() { + let schema = "CREATE TABLE a (id UInt64) ENGINE = MergeTree ORDER BY id; \ + CREATE TABLE b (id UInt64) ENGINE = MergeTree ORDER BY id"; + let v = ch_ids("SELECT a.id FROM a JOIN b ON a.id = b.id", schema); + assert!(v.contains(&"CH016".to_string())); +} + +#[test] +fn ch019_flags_final() { + let v = ch_ids("SELECT d FROM t FINAL", MERGE_TREE); + assert!(v.contains(&"CH019".to_string())); +} + +#[test] +fn ch019_ok_without_final() { + let v = ch_ids("SELECT d FROM t", MERGE_TREE); + assert!(!v.contains(&"CH019".to_string())); +} + +#[test] +fn generic_dialect_does_not_run_clickhouse_rules() { + let schema = Schema::parse(MERGE_TREE, SqlDialect::Generic).unwrap(); + let queries = parse_queries("SELECT * FROM t", SqlDialect::Generic).unwrap(); + let runner = RuleRunner::with_schema_and_config_and_dialect( + SqlDialect::Generic, + schema, + &RulesConfig::default() + ); + let ids: Vec = runner + .analyze(&queries) + .violations + .iter() + .map(|v| v.rule_id.to_string()) + .collect(); + assert!(!ids.iter().any(|id| id.starts_with("CH"))); +} + +#[test] +fn ch021_flags_where_without_prewhere() { + let v = ch_ids("SELECT x FROM t WHERE x = 1", MERGE_TREE); + assert!(v.contains(&"CH021".to_string())); +} + +#[test] +fn ch021_ok_when_prewhere_present() { + let v = ch_ids("SELECT x FROM t PREWHERE x = 1", MERGE_TREE); + assert!(!v.contains(&"CH021".to_string())); +} + +#[test] +fn ch022_flags_alter_update() { + let v = ch_ids("ALTER TABLE t UPDATE x = 0 WHERE d = today()", MERGE_TREE); + assert!(v.contains(&"CH022".to_string())); +} + +#[test] +fn ch022_ignores_alter_add_column() { + let v = ch_ids("ALTER TABLE t ADD COLUMN y UInt64", MERGE_TREE); + assert!(!v.contains(&"CH022".to_string())); +} + +#[test] +fn ch023_flags_optimize_final() { + let v = ch_ids("OPTIMIZE TABLE t FINAL", MERGE_TREE); + assert!(v.contains(&"CH023".to_string())); +} + +#[test] +fn ch024_flags_join_with_dictionary() { + let schema = "CREATE DICTIONARY dict (id UInt64) PRIMARY KEY id SOURCE(NULL()) LAYOUT(FLAT()); \ + CREATE TABLE t (id UInt64) ENGINE = MergeTree ORDER BY id; \ + CREATE TABLE dict (id UInt64) ENGINE = MergeTree ORDER BY id"; + let v = ch_ids("SELECT t.id FROM t JOIN dict ON t.id = dict.id", schema); + assert!(v.contains(&"CH024".to_string())); +} + +#[test] +fn ch025_flags_group_by_plain_string() { + let schema = "CREATE TABLE t (d Date, s String) ENGINE = MergeTree ORDER BY d"; + let v = ch_ids("SELECT s, count() FROM t GROUP BY s", schema); + assert!(v.contains(&"CH025".to_string())); +} + +#[test] +fn ch025_ok_for_low_cardinality() { + let schema = "CREATE TABLE t (d Date, s LowCardinality(String)) ENGINE = MergeTree ORDER BY d"; + let v = ch_ids("SELECT s, count() FROM t GROUP BY s", schema); + assert!(!v.contains(&"CH025".to_string())); +} + +fn ch_preprocess(sql: &str) -> sql_query_analyzer::preprocessor::PreprocessorResult { + sql_query_analyzer::preprocessor::Preprocessor::new(SqlDialect::ClickHouse).process(sql) +} + +#[test] +fn test_projection_without_name_is_ignored() { + let result = ch_preprocess("CREATE TABLE t (a UInt64, PROJECTION (SELECT a))"); + assert!(result.metadata.projections.is_empty()); +} + +#[test] +fn test_projection_at_end_of_input_is_ignored() { + let result = ch_preprocess("CREATE TABLE t (a UInt64) PROJECTION p"); + assert!(result.metadata.projections.is_empty()); +} + +#[test] +fn test_projection_unclosed_paren_is_ignored() { + let result = ch_preprocess("CREATE TABLE t (a UInt64, PROJECTION p (SELECT a"); + assert!(result.metadata.projections.is_empty()); +} + +#[test] +fn test_projection_as_unclosed_is_ignored() { + let result = ch_preprocess("CREATE TABLE t (a UInt64) PROJECTION p AS SELECT a"); + assert!(result.metadata.projections.is_empty()); +} + +#[test] +fn test_projection_paren_with_string_containing_paren() { + let result = ch_preprocess("CREATE TABLE t (a UInt64, PROJECTION p (SELECT '(' ))"); + assert_eq!(result.metadata.projections.len(), 1); + assert_eq!(result.metadata.projections[0].name, "p"); + assert!(result.metadata.projections[0].query.contains('(')); +} + +#[test] +fn test_projection_as_with_string_containing_comma() { + let result = + ch_preprocess("CREATE TABLE t (a UInt64, PROJECTION p AS SELECT 'x,y', b UInt64)"); + assert_eq!(result.metadata.projections.len(), 1); + assert!(result.metadata.projections[0].query.contains("'x,y'")); +} + +#[test] +fn test_projection_removal_drops_leading_comma() { + let result = ch_preprocess("CREATE TABLE t (a UInt64, PROJECTION p AS SELECT a)"); + assert!(!result.sql.contains("PROJECTION")); + assert!(!result.sql.contains(", )")); +} + +#[test] +fn test_skip_index_granularity_overflow_falls_back_to_one() { + let result = ch_preprocess( + "CREATE TABLE t (a UInt64, INDEX i a TYPE minmax GRANULARITY 99999999999999999999999)" + ); + assert_eq!(result.metadata.skip_indexes.len(), 1); + assert_eq!(result.metadata.skip_indexes[0].granularity, 1); +} + +#[test] +fn test_schema_aware_rules_ignore_unknown_tables() { + let schema_sql = "CREATE TABLE known (a UInt64) ENGINE = MergeTree ORDER BY a"; + let ids = ch_ids( + "SELECT * FROM missing JOIN known USING (a) WHERE a = 1 GROUP BY a HAVING count() > 1", + schema_sql + ); + assert!( + !ids.contains(&"CH002".to_string()), + "unknown table must not produce violations: {ids:?}" + ); +} + +#[test] +fn test_primary_key_rules_skip_tables_without_sort_key() { + let schema_sql = "CREATE TABLE nokey (a UInt64) ENGINE = MergeTree"; + let ids = ch_ids( + "SELECT a FROM nokey WHERE a = 1 GROUP BY a ORDER BY a", + schema_sql + ); + assert!( + !ids.contains(&"CH002".to_string()) && !ids.contains(&"CH011".to_string()), + "table without ORDER BY must be skipped: {ids:?}" + ); +} + +#[test] +fn test_group_by_string_key_ignores_unknown_columns() { + let schema_sql = "CREATE TABLE t (a UInt64) ENGINE = MergeTree ORDER BY a"; + let ids = ch_ids("SELECT b FROM t GROUP BY b", schema_sql); + assert!( + !ids.contains(&"CH019".to_string()), + "group column absent from table must be skipped: {ids:?}" + ); +} diff --git a/tests/config_tests.rs b/tests/config_tests.rs index 94236b2..854cd01 100644 --- a/tests/config_tests.rs +++ b/tests/config_tests.rs @@ -10,7 +10,7 @@ fn test_default_config() { let config = Config::default(); assert!(config.llm.api_key.is_none()); assert!(config.llm.provider.is_none()); - assert!(config.rules.disabled.is_empty()); + assert_eq!(config.rules.disabled, [] as [std::string::String; 0]); } #[test] @@ -18,13 +18,13 @@ fn test_default_retry_config() { let config = Config::default(); assert_eq!(config.retry.max_retries, 3); assert_eq!(config.retry.initial_delay_ms, 1000); - assert_eq!(config.retry.backoff_factor, 2.0); + assert_eq!(config.retry.backoff_factor, 2); } #[test] fn test_default_rules_config() { let config = RulesConfig::default(); - assert!(config.disabled.is_empty()); + assert_eq!(config.disabled, [] as [std::string::String; 0]); assert!(config.severity.is_empty()); } @@ -69,7 +69,7 @@ fn test_retry_config_default() { assert_eq!(config.max_retries, 3); assert_eq!(config.initial_delay_ms, 1000); assert_eq!(config.max_delay_ms, 30000); - assert_eq!(config.backoff_factor, 2.0); + assert_eq!(config.backoff_factor, 2); } #[test] @@ -81,7 +81,7 @@ fn test_config_load() { #[test] fn test_config_debug() { let config = Config::default(); - let debug = format!("{:?}", config); + let debug = format!("{config:?}"); assert!(debug.contains("Config")); } @@ -89,7 +89,7 @@ fn test_config_debug() { fn test_llm_config_debug() { use sql_query_analyzer::config::LlmConfig; let config = LlmConfig::default(); - let debug = format!("{:?}", config); + let debug = format!("{config:?}"); assert!(debug.contains("LlmConfig")); } @@ -97,14 +97,14 @@ fn test_llm_config_debug() { fn test_retry_config_debug() { use sql_query_analyzer::config::RetryConfig; let config = RetryConfig::default(); - let debug = format!("{:?}", config); + let debug = format!("{config:?}"); assert!(debug.contains("RetryConfig")); } #[test] fn test_rules_config_debug() { let config = RulesConfig::default(); - let debug = format!("{:?}", config); + let debug = format!("{config:?}"); assert!(debug.contains("RulesConfig")); } @@ -161,3 +161,61 @@ fn test_config_load_with_env_vars() { remove_var("OLLAMA_URL"); } } + +fn with_home(home: &std::path::Path, f: impl FnOnce() -> T) -> T { + let saved = std::env::var_os("HOME"); + unsafe { set_var("HOME", home) }; + let result = f(); + unsafe { + match saved { + Some(v) => set_var("HOME", v), + None => remove_var("HOME") + } + } + result +} + +#[test] +fn test_load_home_config_file() { + let home = tempfile::tempdir().unwrap(); + let dir = home.path().join(".config").join("sql-analyzer"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("config.toml"), + "[llm]\nprovider = \"home-provider\"\nmodel = \"home-model\"\n" + ) + .unwrap(); + let config = with_home(home.path(), Config::load).unwrap(); + assert_eq!(config.llm.provider, Some("home-provider".to_string())); + assert_eq!(config.llm.model, Some("home-model".to_string())); +} + +#[test] +fn test_load_invalid_home_config_errors() { + let home = tempfile::tempdir().unwrap(); + let dir = home.path().join(".config").join("sql-analyzer"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("config.toml"), "not = [valid toml").unwrap(); + let err = with_home(home.path(), Config::load).unwrap_err(); + assert!(err.to_string().contains("Invalid config file")); +} + +#[test] +fn test_load_local_config_file_valid_and_invalid() { + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join(".sql-analyzer.toml"); + std::fs::write(&local, "[rules]\ndisabled = [\"STYLE001\"]\n").unwrap(); + let saved = std::env::current_dir().unwrap(); + std::env::set_current_dir(dir.path()).unwrap(); + let valid = Config::load(); + std::fs::write(&local, "broken [").unwrap(); + let invalid = Config::load(); + let _ = std::env::set_current_dir(saved); + assert_eq!(valid.unwrap().rules.disabled, vec!["STYLE001".to_string()]); + assert!( + invalid + .unwrap_err() + .to_string() + .contains("Invalid config file") + ); +} diff --git a/tests/error_tests.rs b/tests/error_tests.rs index 1b6b177..deab2e5 100644 --- a/tests/error_tests.rs +++ b/tests/error_tests.rs @@ -8,7 +8,7 @@ use sql_query_analyzer::error::{ #[test] fn test_file_read_error() { let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found"); - let error = file_read_error("/path/to/file.sql", io_error); + let error = file_read_error("/path/to/file.sql", &io_error); let _msg = error.to_string(); } @@ -66,8 +66,8 @@ fn test_error_types_are_different() { let query_err = query_parse_error("test"); let llm_err = llm_api_error("test"); let config_err = config_error("test"); - assert!(!schema_err.to_string().is_empty()); - assert!(!query_err.to_string().is_empty()); - assert!(!llm_err.to_string().is_empty()); - assert!(!config_err.to_string().is_empty()); + assert_ne!(schema_err.to_string(), ""); + assert_ne!(query_err.to_string(), ""); + assert_ne!(llm_err.to_string(), ""); + assert_ne!(config_err.to_string(), ""); } diff --git a/tests/output_tests.rs b/tests/output_tests.rs index 637f2ab..23dd31e 100644 --- a/tests/output_tests.rs +++ b/tests/output_tests.rs @@ -32,7 +32,7 @@ fn make_violation( severity, category: RuleCategory::Performance, query_index, - suggestion: suggestion.map(|s| s.to_string()) + suggestion: suggestion.map(std::string::ToString::to_string) } } @@ -437,7 +437,7 @@ fn test_format_static_analysis_multiple_queries() { #[test] fn test_output_format_debug() { let format = OutputFormat::Text; - let debug = format!("{:?}", format); + let debug = format!("{format:?}"); assert!(debug.contains("Text")); } @@ -451,7 +451,7 @@ fn test_output_format_copy() { #[test] fn test_output_options_debug() { let opts = OutputOptions::default(); - let debug = format!("{:?}", opts); + let debug = format!("{opts:?}"); assert!(debug.contains("OutputOptions")); } @@ -462,7 +462,7 @@ fn test_output_options_clone() { colored: false, verbose: true }; - let cloned = opts.clone(); + let cloned = opts; assert!(matches!(cloned.format, OutputFormat::Yaml)); assert!(!cloned.colored); assert!(cloned.verbose); @@ -474,7 +474,7 @@ fn test_analysis_result_debug() { queries: vec![], analysis: "test".to_string() }; - let debug = format!("{:?}", result); + let debug = format!("{result:?}"); assert!(debug.contains("AnalysisResult")); } @@ -737,3 +737,47 @@ fn test_analysis_report_counts() { assert_eq!(report.warning_count(), 1); assert_eq!(report.info_count(), 3); } + +#[test] +fn test_yaml_top_level_scalars_and_empty_containers() { + use sql_query_analyzer::output::yaml::to_string; + assert_eq!(to_string(&serde_json::json!("plain")).unwrap(), "plain\n"); + assert_eq!(to_string(&serde_json::json!([])).unwrap(), "[]\n"); + assert_eq!(to_string(&serde_json::json!({})).unwrap(), "{}\n"); + assert_eq!(to_string(&serde_json::json!(null)).unwrap(), "null\n"); +} + +#[test] +fn test_yaml_nested_empty_containers() { + use sql_query_analyzer::output::yaml::to_string; + let out = to_string(&serde_json::json!({"list": [], "map": {}})).unwrap(); + assert!(out.contains("list: []"), "{out}"); + assert!(out.contains("map: {}"), "{out}"); + let nested = to_string(&serde_json::json!([[], {"a": 1}])).unwrap(); + assert!(nested.contains("- []"), "{nested}"); +} + +#[test] +fn test_yaml_quotes_ambiguous_keys() { + use sql_query_analyzer::output::yaml::to_string; + let out = to_string(&serde_json::json!({"true": 1, "42": 2, "a: b": 3})).unwrap(); + assert!(out.contains("\"true\": 1"), "{out}"); + assert!(out.contains("\"42\": 2"), "{out}"); + assert!(out.contains("\"a: b\": 3"), "{out}"); +} + +#[test] +fn test_yaml_escapes_special_string_values() { + use sql_query_analyzer::output::yaml::to_string; + let out = to_string(&serde_json::json!({ + "quote": "say \"hi\"", + "back": "a\\b", + "line": "a\nb", + "ctrl": "a\u{7}b" + })) + .unwrap(); + assert!(out.contains("\"say \\\"hi\\\"\""), "{out}"); + assert!(out.contains("back: a\\b"), "{out}"); + assert!(out.contains("\"a\\nb\""), "{out}"); + assert!(out.contains("\"a\\u0007b\""), "{out}"); +} diff --git a/tests/query_tests.rs b/tests/query_tests.rs index d7a8893..223ba99 100644 --- a/tests/query_tests.rs +++ b/tests/query_tests.rs @@ -8,7 +8,7 @@ fn test_parse_simple_select() { let sql = "SELECT id, name FROM users WHERE id = 1"; let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); assert_eq!(queries.len(), 1); - assert_eq!(queries[0].query_type, QueryType::Select); + assert_eq!(queries[0].kind, QueryType::Select); assert_eq!(queries[0].tables.len(), 1); assert_eq!(queries[0].tables[0].as_str(), "users"); assert!(queries[0].where_cols.iter().any(|c| c.as_str() == "id")); @@ -19,7 +19,7 @@ fn test_parse_select_star() { let sql = "SELECT * FROM orders"; let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); assert_eq!(queries.len(), 1); - assert_eq!(queries[0].query_type, QueryType::Select); + assert_eq!(queries[0].kind, QueryType::Select); assert_eq!(queries[0].tables[0].as_str(), "orders"); } @@ -43,7 +43,7 @@ fn test_parse_insert() { let sql = "INSERT INTO users (id, name) VALUES (1, 'test')"; let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); assert_eq!(queries.len(), 1); - assert_eq!(queries[0].query_type, QueryType::Insert); + assert_eq!(queries[0].kind, QueryType::Insert); assert_eq!(queries[0].tables[0].as_str(), "users"); } @@ -52,7 +52,7 @@ fn test_parse_update() { let sql = "UPDATE users SET name = 'new' WHERE id = 1"; let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); assert_eq!(queries.len(), 1); - assert_eq!(queries[0].query_type, QueryType::Update); + assert_eq!(queries[0].kind, QueryType::Update); assert_eq!(queries[0].tables[0].as_str(), "users"); assert!(queries[0].where_cols.iter().any(|c| c.as_str() == "id")); } @@ -62,7 +62,7 @@ fn test_parse_update_without_where() { let sql = "UPDATE users SET status = 'inactive'"; let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); assert_eq!(queries.len(), 1); - assert_eq!(queries[0].query_type, QueryType::Update); + assert_eq!(queries[0].kind, QueryType::Update); assert!(queries[0].where_cols.is_empty()); } @@ -71,7 +71,7 @@ fn test_parse_delete() { let sql = "DELETE FROM users WHERE id = 1"; let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); assert_eq!(queries.len(), 1); - assert_eq!(queries[0].query_type, QueryType::Delete); + assert_eq!(queries[0].kind, QueryType::Delete); assert!(queries[0].where_cols.iter().any(|c| c.as_str() == "id")); } @@ -80,7 +80,7 @@ fn test_parse_delete_without_where() { let sql = "DELETE FROM users"; let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); assert_eq!(queries.len(), 1); - assert_eq!(queries[0].query_type, QueryType::Delete); + assert_eq!(queries[0].kind, QueryType::Delete); assert!(queries[0].where_cols.is_empty()); } @@ -399,7 +399,7 @@ fn test_recursive_cte() { let sql = "WITH RECURSIVE nums AS (SELECT 1 AS n UNION ALL SELECT n + 1 FROM nums WHERE n < 10) SELECT * FROM nums"; let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); assert_eq!(queries.len(), 1); - assert!(!queries[0].cte_names.is_empty()); + assert_ne!(queries[0].cte_names, [] as [compact_str::CompactString; 0]); } #[test] @@ -443,7 +443,7 @@ fn test_clickhouse_simple_select() { let sql = "SELECT id, name FROM users WHERE id = 1"; let queries = parse_queries(sql, SqlDialect::ClickHouse).unwrap(); assert_eq!(queries.len(), 1); - assert_eq!(queries[0].query_type, QueryType::Select); + assert_eq!(queries[0].kind, QueryType::Select); } #[test] @@ -516,3 +516,42 @@ fn test_left_join_extracts_join_cols() { let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); assert!(!queries[0].join_cols.is_empty()); } + +#[test] +fn test_case_expressions_and_compound_identifiers() { + let sql = "SELECT x FROM t WHERE t.a = 1 \ + AND CASE t.a WHEN 1 THEN t.b ELSE t.c END > 0 \ + AND CASE WHEN t.d > 0 THEN 1 ELSE 0 END = 1"; + let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); + let cols = &queries[0].where_cols; + for expected in ["a", "b", "c", "d"] { + assert!( + cols.iter().any(|c| c.as_str() == expected), + "column {expected} missing: {cols:?}" + ); + } +} + +#[test] +fn test_window_function_with_compound_partition_and_order() { + let sql = "SELECT sum(t.a) OVER (PARTITION BY t.b ORDER BY t.c) FROM t"; + let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); + let wf = &queries[0].window_funcs[0]; + assert!( + wf.partition_cols.iter().any(|c| c.as_str() == "b"), + "{wf:?}" + ); + assert!(wf.order_cols.iter().any(|c| c.as_str() == "c"), "{wf:?}"); +} + +#[test] +fn test_window_functions_in_nested_binary_and_case() { + let sql = "SELECT (count(*) OVER ()) + 1, \ + CASE WHEN sum(a) OVER () > 0 THEN 1 ELSE min(b) OVER () END FROM t"; + let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); + assert!( + queries[0].window_funcs.len() >= 3, + "expected windows in binary, nested and case branches: {:?}", + queries[0].window_funcs + ); +} diff --git a/tests/rules_tests.rs b/tests/rules_tests.rs index 845d2c0..19637c5 100644 --- a/tests/rules_tests.rs +++ b/tests/rules_tests.rs @@ -22,7 +22,11 @@ fn analyze_query(sql: &str) -> Vec { fn analyze_with_schema(sql: &str, schema_sql: &str) -> Vec { let queries = parse_queries(sql, SqlDialect::Generic).unwrap(); let schema = Schema::parse(schema_sql, SqlDialect::Generic).unwrap(); - let runner = RuleRunner::with_schema_and_config(schema, RulesConfig::default()); + let runner = RuleRunner::with_schema_and_config_and_dialect( + SqlDialect::Generic, + schema, + &RulesConfig::default() + ); let report = runner.analyze(&queries); report .violations @@ -525,10 +529,10 @@ fn test_distinct_with_order_by() { #[test] fn test_join_on_non_indexed_column_flagged() { - let schema = r#" + let schema = r" CREATE TABLE users (id INT PRIMARY KEY); CREATE TABLE orders (id INT PRIMARY KEY, user_id INT); - "#; + "; let violations = analyze_with_schema( "SELECT u.id FROM users u JOIN orders o ON o.user_id = u.id WHERE u.id > 0 LIMIT 10", schema @@ -538,11 +542,11 @@ fn test_join_on_non_indexed_column_flagged() { #[test] fn test_join_on_indexed_column_ok() { - let schema = r#" + let schema = r" CREATE TABLE users (id INT PRIMARY KEY); CREATE TABLE orders (id INT PRIMARY KEY, user_id INT); CREATE INDEX idx_orders_user_id ON orders(user_id); - "#; + "; let violations = analyze_with_schema( "SELECT u.id FROM users u JOIN orders o ON o.user_id = u.id WHERE u.id > 0 LIMIT 10", schema @@ -589,10 +593,10 @@ fn test_schema_missing_index() { #[test] fn test_schema_with_index() { - let schema = r#" + let schema = r" CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255)); CREATE INDEX idx_email ON users(email); - "#; + "; let violations = analyze_with_schema( "SELECT * FROM users WHERE email = 'test@test.com' LIMIT 10", schema @@ -611,7 +615,7 @@ fn test_rule_disabled() { ], ..Default::default() }; - let runner = RuleRunner::with_config(config); + let runner = RuleRunner::with_config(&config); let report = runner.analyze(&queries); let rule_ids: Vec<_> = report.violations.iter().map(|v| v.rule_id).collect(); assert!(!rule_ids.contains(&"PERF001")); @@ -628,7 +632,7 @@ fn test_severity_override() { disabled: vec![], severity }; - let runner = RuleRunner::with_config(config); + let runner = RuleRunner::with_config(&config); let report = runner.analyze(&queries); let style_violation = report.violations.iter().find(|v| v.rule_id == "STYLE001"); assert!(style_violation.is_some()); @@ -780,10 +784,10 @@ fn test_join_missing_alias() { #[test] fn test_schema_join_column_missing_index() { - let schema = r#" + let schema = r" CREATE TABLE users (id INT PRIMARY KEY); CREATE TABLE orders (id INT PRIMARY KEY, user_id INT); - "#; + "; let violations = analyze_with_schema( "SELECT * FROM users u INNER JOIN orders o ON u.id = o.user_id LIMIT 10", schema @@ -810,12 +814,12 @@ fn test_schema_column_not_in_schema() { #[test] fn test_schema_large_table_no_index() { - let schema = r#" + let schema = r" CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255)); INSERT INTO users VALUES (1, 'a'); INSERT INTO users VALUES (2, 'b'); INSERT INTO users VALUES (3, 'c'); - "#; + "; let violations = analyze_with_schema("SELECT * FROM users WHERE email = 'test' LIMIT 10", schema); assert!(violations.contains(&"SCHEMA001".to_string())); diff --git a/tests/schema_tests.rs b/tests/schema_tests.rs index 92f2199..a498736 100644 --- a/tests/schema_tests.rs +++ b/tests/schema_tests.rs @@ -17,10 +17,10 @@ fn test_parse_simple_table() { #[test] fn test_parse_multiple_tables() { - let sql = r#" + let sql = r" CREATE TABLE users (id INT PRIMARY KEY); CREATE TABLE orders (id INT PRIMARY KEY, user_id INT); - "#; + "; let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); assert_eq!(schema.tables.len(), 2); assert!(schema.tables.contains_key("users")); @@ -38,10 +38,10 @@ fn test_parse_not_null() { #[test] fn test_parse_index() { - let sql = r#" + let sql = r" CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255)); CREATE INDEX idx_email ON users(email); - "#; + "; let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); let users = &schema.tables["users"]; assert_eq!(users.indexes.len(), 1); @@ -50,10 +50,10 @@ fn test_parse_index() { #[test] fn test_parse_unique_index() { - let sql = r#" + let sql = r" CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255)); CREATE UNIQUE INDEX idx_email ON users(email); - "#; + "; let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); let users = &schema.tables["users"]; assert!(users.indexes[0].is_unique); @@ -61,10 +61,10 @@ fn test_parse_unique_index() { #[test] fn test_parse_composite_index() { - let sql = r#" + let sql = r" CREATE TABLE orders (id INT, user_id INT, created_at TIMESTAMP); CREATE INDEX idx_user_created ON orders(user_id, created_at); - "#; + "; let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); let orders = &schema.tables["orders"]; assert_eq!(orders.indexes[0].columns.len(), 2); @@ -84,7 +84,7 @@ fn test_to_summary() { #[test] fn test_parse_various_types() { - let sql = r#" + let sql = r" CREATE TABLE test ( id BIGINT, price DECIMAL(10,2), @@ -92,7 +92,7 @@ fn test_parse_various_types() { data TEXT, created_at TIMESTAMP ) - "#; + "; let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); let test = &schema.tables["test"]; assert_eq!(test.columns.len(), 5); @@ -116,7 +116,7 @@ fn test_empty_schema() { fn test_schema_debug() { let sql = "CREATE TABLE users (id INT PRIMARY KEY)"; let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); - let debug = format!("{:?}", schema); + let debug = format!("{schema:?}"); assert!(debug.contains("Schema")); } @@ -136,10 +136,10 @@ fn test_schema_default() { #[test] fn test_parse_insert_statement() { - let sql = r#" + let sql = r" CREATE TABLE users (id INT PRIMARY KEY); INSERT INTO users VALUES (1); - "#; + "; let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); assert_eq!(schema.tables.len(), 1); } @@ -154,10 +154,10 @@ fn test_parse_with_default_value() { #[test] fn test_schema_to_summary_with_index() { - let sql = r#" + let sql = r" CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255)); CREATE INDEX idx_email ON users(email); - "#; + "; let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); let summary = schema.to_summary(); assert!(summary.contains("idx_email")); @@ -166,10 +166,10 @@ fn test_schema_to_summary_with_index() { #[test] fn test_schema_to_summary_with_unique_index() { - let sql = r#" + let sql = r" CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255)); CREATE UNIQUE INDEX idx_email ON users(email); - "#; + "; let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); let summary = schema.to_summary(); assert!(summary.contains("UNIQUE")); @@ -196,7 +196,7 @@ fn test_table_info_debug() { let sql = "CREATE TABLE users (id INT PRIMARY KEY)"; let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); let users = &schema.tables["users"]; - let debug = format!("{:?}", users); + let debug = format!("{users:?}"); assert!(debug.contains("TableInfo")); } @@ -210,7 +210,7 @@ fn test_column_info_debug() { is_primary: false, codec: None }; - let debug = format!("{:?}", col); + let debug = format!("{col:?}"); assert!(debug.contains("test")); } @@ -230,7 +230,7 @@ fn test_index_info_debug() { columns: vec!["col1".to_string()], is_unique: false }; - let debug = format!("{:?}", idx); + let debug = format!("{idx:?}"); assert!(debug.contains("idx_test")); } @@ -251,9 +251,43 @@ fn test_table_info_clickhouse_fields_default_none() { assert!(users.order_by.is_none()); assert!(users.primary_key.is_none()); assert!(users.partition_by.is_none()); + assert!(users.sample_by.is_none()); + assert!(users.ttl.is_none()); + assert!(users.settings.is_empty()); + assert!(users.skip_indexes.is_empty()); assert!(users.cluster.is_none()); } +#[test] +fn test_clickhouse_projection_no_phantom_column() { + let sql = "CREATE TABLE t (a UInt64, b String, PROJECTION p (SELECT a ORDER BY a)) ENGINE = MergeTree ORDER BY a"; + let schema = Schema::parse(sql, SqlDialect::ClickHouse).unwrap(); + let t = &schema.tables["t"]; + assert_eq!(t.columns.len(), 2); + assert_eq!(t.projections.len(), 1); + assert_eq!(t.projections[0].name, "p"); +} + +#[test] +fn test_clickhouse_dictionary_and_view() { + let sql = "CREATE DICTIONARY d (id UInt64) PRIMARY KEY id SOURCE(NULL()) LAYOUT(FLAT()); \ + CREATE MATERIALIZED VIEW mv TO dest ENGINE = MergeTree ORDER BY a AS SELECT a FROM src; \ + CREATE TABLE dest (a UInt64) ENGINE = MergeTree ORDER BY a"; + let schema = Schema::parse(sql, SqlDialect::ClickHouse).unwrap(); + assert_eq!(schema.dictionaries, vec!["d".to_string()]); + assert_eq!(schema.materialized_views.len(), 1); + assert!(schema.tables.contains_key("dest")); +} + +#[test] +fn test_clickhouse_nullable_only_for_nullable_type() { + let sql = "CREATE TABLE t (a UInt64, b Nullable(String)) ENGINE = MergeTree ORDER BY a"; + let schema = Schema::parse(sql, SqlDialect::ClickHouse).unwrap(); + let t = &schema.tables["t"]; + assert!(!t.columns[0].is_nullable); + assert!(t.columns[1].is_nullable); +} + #[test] fn test_clickhouse_engine_extraction() { let sql = "CREATE TABLE logs (id UInt64) ENGINE = MergeTree ORDER BY id"; @@ -348,13 +382,13 @@ fn test_table_options_with() { #[test] fn test_mysql_inline_index_constraint() { - let sql = r#" + let sql = r" CREATE TABLE users ( id INT PRIMARY KEY, email VARCHAR(255), INDEX idx_email (email) ) - "#; + "; let schema = Schema::parse(sql, SqlDialect::MySQL).unwrap(); let users = &schema.tables["users"]; assert_eq!(users.indexes.len(), 1); @@ -365,15 +399,98 @@ fn test_mysql_inline_index_constraint() { #[test] fn test_mysql_inline_key_constraint() { - let sql = r#" + let sql = r" CREATE TABLE orders ( id INT PRIMARY KEY, user_id INT, KEY idx_user (user_id) ) - "#; + "; let schema = Schema::parse(sql, SqlDialect::MySQL).unwrap(); let orders = &schema.tables["orders"]; assert_eq!(orders.indexes.len(), 1); assert_eq!(orders.indexes[0].name, "idx_user"); } + +#[test] +fn test_to_summary_includes_all_clickhouse_metadata() { + let sql = "CREATE TABLE t (\ + a UInt64 CODEC(ZSTD), \ + b Nullable(String), \ + INDEX idx_b b TYPE minmax GRANULARITY 1, \ + INDEX idx_a a TYPE bloom_filter(0.01) GRANULARITY 2, \ + PROJECTION p (SELECT b ORDER BY b)\ + ) ENGINE = MergeTree \ + PARTITION BY toYYYYMM(a) \ + PRIMARY KEY a \ + SAMPLE BY a \ + TTL a + INTERVAL 1 DAY \ + SETTINGS index_granularity = 8192"; + let schema = Schema::parse(sql, SqlDialect::ClickHouse).unwrap(); + let summary = schema.to_summary(); + assert!(summary.contains("Partition By: toYYYYMM(a)")); + assert!(summary.contains("Sample By: a")); + assert!(summary.contains("TTL:")); + assert!(summary.contains("Settings: index_granularity = 8192")); + assert!(summary.contains("Skip Indexes:")); + assert!(summary.contains("INDEX idx_b ON b TYPE minmax GRANULARITY 1")); + assert!(summary.contains("INDEX idx_a ON a TYPE bloom_filter(0.01) GRANULARITY 2")); + assert!(summary.contains("Projections:")); + assert!(summary.contains("p AS SELECT b ORDER BY b")); + assert!(summary.contains("CODEC(ZSTD)")); +} + +#[test] +fn test_to_summary_includes_dictionaries_and_views() { + let sql = "CREATE DICTIONARY d (id UInt64) PRIMARY KEY id SOURCE(NULL()) LAYOUT(FLAT()); \ + CREATE MATERIALIZED VIEW mv TO dest ENGINE = MergeTree ORDER BY a AS SELECT a FROM src; \ + CREATE TABLE dest (a UInt64) ENGINE = MergeTree ORDER BY a"; + let schema = Schema::parse(sql, SqlDialect::ClickHouse).unwrap(); + let summary = schema.to_summary(); + assert!(summary.contains("Dictionaries: d")); + assert!(summary.contains("Materialized Views:")); + assert!(summary.contains("mv TO dest")); +} + +#[test] +fn test_create_index_statement_marks_unique() { + let sql = "CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255)); \ + CREATE UNIQUE INDEX idx_email ON users (email); \ + CREATE INDEX idx_id ON users (id)"; + let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); + let users = &schema.tables["users"]; + assert_eq!(users.indexes.len(), 2); + let unique = users + .indexes + .iter() + .find(|i| i.name == "idx_email") + .expect("unique index present"); + assert!(unique.is_unique); + assert_eq!(unique.columns, vec!["email".to_string()]); + let plain = users + .indexes + .iter() + .find(|i| i.name == "idx_id") + .expect("plain index present"); + assert!(!plain.is_unique); +} + +#[test] +fn test_create_index_on_unknown_table_is_ignored() { + let sql = "CREATE INDEX idx_x ON missing (a)"; + let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); + assert!(schema.tables.is_empty()); +} + +#[test] +fn test_inline_index_constraint_parsed() { + let sql = + "CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255), INDEX idx_email (email))"; + let schema = Schema::parse(sql, SqlDialect::Generic).unwrap(); + let users = &schema.tables["users"]; + assert!( + users.indexes.iter().any(|i| i.name == "idx_email"), + "inline INDEX constraint should be recorded: {:?}", + users.indexes + ); +} diff --git a/tests/types_tests.rs b/tests/types_tests.rs index ef6ce18..e60402a 100644 --- a/tests/types_tests.rs +++ b/tests/types_tests.rs @@ -6,19 +6,19 @@ use sql_query_analyzer::rules::{AnalysisReport, RuleCategory, RuleInfo, Severity #[test] fn test_severity_display_info() { let s = Severity::Info; - assert_eq!(format!("{}", s), "INFO"); + assert_eq!(format!("{s}"), "INFO"); } #[test] fn test_severity_display_warning() { let s = Severity::Warning; - assert_eq!(format!("{}", s), "WARN"); + assert_eq!(format!("{s}"), "WARN"); } #[test] fn test_severity_display_error() { let s = Severity::Error; - assert_eq!(format!("{}", s), "ERROR"); + assert_eq!(format!("{s}"), "ERROR"); } #[test] @@ -44,26 +44,26 @@ fn test_severity_copy() { #[test] fn test_severity_debug() { let s = Severity::Warning; - let debug = format!("{:?}", s); + let debug = format!("{s:?}"); assert!(debug.contains("Warning")); } #[test] fn test_rule_category_display_performance() { let c = RuleCategory::Performance; - assert_eq!(format!("{}", c), "Performance"); + assert_eq!(format!("{c}"), "Performance"); } #[test] fn test_rule_category_display_style() { let c = RuleCategory::Style; - assert_eq!(format!("{}", c), "Style"); + assert_eq!(format!("{c}"), "Style"); } #[test] fn test_rule_category_display_security() { let c = RuleCategory::Security; - assert_eq!(format!("{}", c), "Security"); + assert_eq!(format!("{c}"), "Security"); } #[test] @@ -82,7 +82,7 @@ fn test_rule_category_copy() { #[test] fn test_rule_category_debug() { let c = RuleCategory::Style; - let debug = format!("{:?}", c); + let debug = format!("{c:?}"); assert!(debug.contains("Style")); } @@ -143,7 +143,7 @@ fn test_violation_debug() { suggestion: None, query_index: 0 }; - let debug = format!("{:?}", v); + let debug = format!("{v:?}"); assert!(debug.contains("TEST004")); } @@ -180,7 +180,7 @@ fn test_rule_info_debug() { severity: Severity::Info, category: RuleCategory::Style }; - let debug = format!("{:?}", info); + let debug = format!("{info:?}"); assert!(debug.contains("STYLE001")); } @@ -261,7 +261,7 @@ fn test_analysis_report_clone() { #[test] fn test_analysis_report_debug() { let report = AnalysisReport::new(1, 1); - let debug = format!("{:?}", report); + let debug = format!("{report:?}"); assert!(debug.contains("AnalysisReport")); }