diff --git a/.env.example b/.env.example index f9cf99a..b047609 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,5 @@ # Copy to .env.test (ignored by git) and fill in. -# Used only by the integration tests: cd src-tauri && cargo test -- --ignored --test-threads=1 +# Used only by the integration tests: set -a && . ./.env.test && set +a && go test ./internal/... # Prefer a test user; the tests only create a TEMP table in PostgreSQL # and only run SELECT / anonymous PL/SQL in Oracle. MySQL and SQL Server # tests use temporary tables plus a few lq_* tables they drop at the end. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d632ede --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Shell scripts run in Git Bash and on Linux/macOS runners: keep LF. +*.sh text eol=lf diff --git a/.github/ISSUE_TEMPLATE/database_support.yml b/.github/ISSUE_TEMPLATE/database_support.yml index 27349db..71af338 100644 --- a/.github/ISSUE_TEMPLATE/database_support.yml +++ b/.github/ISSUE_TEMPLATE/database_support.yml @@ -23,5 +23,5 @@ body: - type: textarea id: driver attributes: - label: Known Rust drivers or protocol notes + label: Known Go drivers or protocol notes description: Optional. Links to drivers, protocol documentation or tools that handle this engine well. diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 5f97bd4..a9ea22c 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,20 +1,15 @@ version: 2 updates: - - package-ecosystem: cargo - directory: /src-tauri + - package-ecosystem: gomod + directory: / schedule: interval: weekly day: monday open-pull-requests-limit: 5 - # The Oracle driver is a pinned beta; upgrade it deliberately. - ignore: - - dependency-name: oracledb groups: - tauri: - patterns: ["tauri", "tauri-*"] - postgres: - patterns: ["tokio-postgres", "tokio-postgres-*", "postgres-*"] - rust-minor-and-patch: + wails: + patterns: ["github.com/wailsapp/*"] + go-minor-and-patch: update-types: [minor, patch] - package-ecosystem: npm @@ -24,8 +19,6 @@ updates: day: monday open-pull-requests-limit: 5 groups: - tauri: - patterns: ["@tauri-apps/*"] svelte: patterns: ["svelte", "svelte-check", "@sveltejs/*"] codemirror: diff --git a/.github/scripts/render_pkgbuild.py b/.github/scripts/render_pkgbuild.py index 039ba5b..fecea47 100644 --- a/.github/scripts/render_pkgbuild.py +++ b/.github/scripts/render_pkgbuild.py @@ -38,7 +38,7 @@ def render_release(version, assets, root=ROOT): "__VERSION__": version, "__SHA256_PORTABLE__": sha256(assets / f"LowQuery-{version}-linux-x64-portable.tar.gz"), "__SHA256_DESKTOP__": sha256(root / "packaging/arch/lowquery.desktop"), - "__SHA256_ICON__": sha256(root / "src-tauri/icons/128x128.png"), + "__SHA256_ICON__": sha256(root / "packaging/icons/128x128.png"), }, ) diff --git a/.github/scripts/test_update_manifest.py b/.github/scripts/test_update_manifest.py index f6d5a48..28cd573 100644 --- a/.github/scripts/test_update_manifest.py +++ b/.github/scripts/test_update_manifest.py @@ -11,7 +11,6 @@ def test_signed_assets_become_platforms_with_one_key_per_linux_format(self): assets = Path(tmp) for name in [ "LowQuery-1.2.3-windows-x64-setup.exe", - "LowQuery-1.2.3-windows-x64.msi", "LowQuery-1.2.3-macos-universal.app.tar.gz", "LowQuery-1.2.3-linux-x64.AppImage", "LowQuery-1.2.3-linux-x64.deb", @@ -25,12 +24,13 @@ def test_signed_assets_become_platforms_with_one_key_per_linux_format(self): self.assertEqual( sorted(doc["platforms"]), ["darwin-aarch64", "darwin-x86_64", "linux-x86_64-appimage", "linux-x86_64-deb", - "linux-x86_64-rpm", "windows-x86_64", "windows-x86_64-msi", "windows-x86_64-nsis"], + "linux-x86_64-rpm", "windows-x86_64", "windows-x86_64-nsis"], ) self.assertNotIn("linux-x86_64", doc["platforms"]) self.assertTrue(doc["platforms"]["linux-x86_64-deb"]["url"].endswith("/LowQuery-1.2.3-linux-x64.deb")) self.assertTrue(doc["platforms"]["linux-x86_64-rpm"]["url"].endswith("/LowQuery-1.2.3-linux-x64.rpm")) - self.assertEqual(doc["platforms"]["windows-x86_64-msi"]["signature"], "sig-LowQuery-1.2.3-windows-x64.msi") + self.assertNotIn("windows-x86_64-msi", doc["platforms"]) + self.assertEqual(doc["platforms"]["windows-x86_64-nsis"]["signature"], "sig-LowQuery-1.2.3-windows-x64-setup.exe") self.assertTrue(doc["platforms"]["windows-x86_64"]["url"].endswith("/v1.2.3/LowQuery-1.2.3-windows-x64-setup.exe")) def test_unsigned_assets_are_skipped(self): diff --git a/.github/scripts/update_manifest.py b/.github/scripts/update_manifest.py index f6a7166..5226a2b 100644 --- a/.github/scripts/update_manifest.py +++ b/.github/scripts/update_manifest.py @@ -17,9 +17,10 @@ def signed(keys, asset): for key in keys: platforms[key] = {"signature": signature.read_text().strip(), "url": f"{base}/{asset}"} - # Installed Windows copies update with the installer they came from. + # Every Windows install updates with the NSIS setup. Copies installed from + # the MSI of 0.5.x find no "-msi" key and fall back to "windows-x86_64"; + # the setup then replaces the MSI install with a per-user one. signed(["windows-x86_64", "windows-x86_64-nsis"], f"LowQuery-{version}-windows-x64-setup.exe") - signed(["windows-x86_64-msi"], f"LowQuery-{version}-windows-x64.msi") signed(["darwin-aarch64", "darwin-x86_64"], f"LowQuery-{version}-macos-universal.app.tar.gz") # One key per Linux format, never a generic one: a .deb install must get a # .deb, an .rpm install an .rpm, and the Arch package nothing (pacman owns it). diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c24afef..cf0dc15 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,11 +19,6 @@ on: permissions: contents: read -env: - # Debug-build driver futures (SQL Server TLS above all) need more than the - # 2 MiB default stack of test and tokio worker threads. - RUST_MIN_STACK: "16777216" - concurrency: group: verify-${{ github.workflow }}-${{ github.ref }} # Cancel superseded pull request runs, but let every push to main finish. @@ -78,11 +73,18 @@ jobs: LQ_PG_USER: postgres LQ_PG_PASSWORD: lowquery LQ_PG_DB: postgres + # internal/menubar imports Wails, which on Linux links GTK and WebKitGTK + # through cgo; gtk3 picks the WebKitGTK 4.1 backend the packages use. + GOFLAGS: -tags=gtk3 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod + - name: GTK and WebKitGTK headers + run: | + sudo apt-get update + sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev - name: Formatting run: test -z "$(gofmt -l internal main.go)" - run: go vet ./internal/... @@ -115,91 +117,172 @@ jobs: grep -q '"serverInfo"' mcp-out.txt grep -q '"list_connections"' mcp-out.txt - lint: - name: Rust format and lint - runs-on: ubuntu-22.04 + # The release files, built with the release scripts, and upgrades from the + # last Tauri release the way its updater installs them. The packages get a + # version above every Tauri release, so the setup, dpkg and rpm do a real + # upgrade; the app inside still reports package.json's version. + windows-setup: + name: Windows setup (upgrade from Tauri) + runs-on: windows-2022 timeout-minutes: 30 + env: + VERSION: "99.0.0" + TAURI_RELEASE: v0.5.7 steps: + # The packaging scripts are bash: keep their LF line endings. + - run: git config --global core.autocrlf false - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - with: - components: rustfmt, clippy - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: - workspaces: src-tauri - key: lint - - name: Install Linux desktop dependencies + go-version-file: go.mod + - run: bun install --frozen-lockfile + - run: bun run build + - name: Build the setup and the portable zip + shell: bash + run: bash packaging/windows/build.sh + - name: Download the Tauri setup + shell: bash + env: + GH_TOKEN: ${{ github.token }} run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libssl-dev libdbus-1-dev - # The Tauri context macro needs the frontend output folder to exist. - - run: mkdir -p dist - - name: rustfmt - run: cargo fmt --check --manifest-path src-tauri/Cargo.toml - - name: clippy - run: cargo clippy --locked --manifest-path src-tauri/Cargo.toml --lib --tests -- -D warnings + gh release download "$TAURI_RELEASE" --repo "$GITHUB_REPOSITORY" --dir tauri \ + --pattern "LowQuery-${TAURI_RELEASE#v}-windows-x64-setup.exe" + - name: Upgrade a Tauri install, uninstall, install fresh + shell: pwsh + run: | + ./packaging/test/windows-upgrade.ps1 ` + -TauriSetup (Resolve-Path "tauri/LowQuery-$($env:TAURI_RELEASE.TrimStart('v'))-windows-x64-setup.exe") ` + -Setup (Resolve-Path "build/release/LowQuery-$env:VERSION-windows-x64-setup.exe") ` + -BuiltExe (Resolve-Path build/windows/lowquery.exe) ` + -Version $env:VERSION + - name: Portable copy answers MCP + shell: bash + run: | + mkdir -p portable + powershell.exe -NoProfile -Command "Expand-Archive -Path 'build/release/LowQuery-${VERSION}-windows-x64-portable.zip' -DestinationPath portable" + ls portable + bash packaging/test/mcp-smoke.sh portable/LowQuery.exe - rust: - name: Rust (${{ matrix.os }}) - strategy: - fail-fast: false - matrix: - os: [windows-2022, ubuntu-22.04, macos-latest] - runs-on: ${{ matrix.os }} - timeout-minutes: 45 + linux-packages: + name: Linux packages (upgrade from Tauri) + runs-on: ubuntu-22.04 + timeout-minutes: 40 + env: + VERSION: "99.0.0" + TAURI_RELEASE: v0.5.7 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - with: - workspaces: src-tauri - - name: Install Linux desktop dependencies - if: runner.os == 'Linux' + - name: Install system libraries (GTK 3, WebKitGTK 4.1) run: | sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libssl-dev libdbus-1-dev - - name: Create frontend output folder - shell: bash - run: mkdir -p dist - - name: Rust tests - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml + sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev librsvg2-dev + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + - run: bun install --frozen-lockfile + - run: bun run build + - name: Build the .deb, .rpm, AppImage and portable tarball + run: bash packaging/linux/build.sh + - name: Download the Tauri packages + env: + GH_TOKEN: ${{ github.token }} + run: | + v="${TAURI_RELEASE#v}" + gh release download "$TAURI_RELEASE" --repo "$GITHUB_REPOSITORY" --dir tauri \ + --pattern "LowQuery-$v-linux-x64.deb" --pattern "LowQuery-$v-linux-x64.rpm" + - name: Package name and files match the Tauri package + run: | + set -euo pipefail + old="tauri/LowQuery-${TAURI_RELEASE#v}-linux-x64.deb" + new="build/release/LowQuery-${VERSION}-linux-x64.deb" + test "$(dpkg-deb -f "$old" Package)" = "$(dpkg-deb -f "$new" Package)" + # Regular files and links only: the Tauri .deb also lists every + # directory, without the trailing slash dpkg-deb usually prints. + files() { dpkg-deb -c "$1" | awk '$1 !~ /^d/ {print $6}' | sed -E 's|^\.?/?|/|' | sort; } + diff <(files "$old") <(files "$new") + dpkg-deb -I "$new" + - name: dpkg -i upgrades the Tauri .deb + run: | + set -euo pipefail + sudo apt-get install -y "./tauri/LowQuery-${TAURI_RELEASE#v}-linux-x64.deb" + test "$(dpkg-query -W -f='${Version}' low-query)" = "${TAURI_RELEASE#v}" + # What the Tauri updater runs (through pkexec). + sudo dpkg -i "build/release/LowQuery-${VERSION}-linux-x64.deb" + test "$(dpkg-query -W -f='${Version}' low-query)" = "$VERSION" + cmp /usr/bin/lowquery build/linux/lowquery + dpkg-query -S "$(readlink -f /usr/bin/lowquery)" + test -f /usr/share/applications/LowQuery.desktop + # No display: `lowquery mcp` must not need one. + env -u DISPLAY -u WAYLAND_DISPLAY bash packaging/test/mcp-smoke.sh /usr/bin/lowquery + - name: rpm -U upgrades the Tauri .rpm (Fedora) + run: | + docker run --rm -v "$PWD:/src:ro" -w /src -e VERSION -e TAURI_RELEASE fedora:44 bash -euo pipefail -c ' + dnf install -y --setopt=install_weak_deps=False "./tauri/LowQuery-${TAURI_RELEASE#v}-linux-x64.rpm" + test "$(rpm -q --qf "%{VERSION}" low-query)" = "${TAURI_RELEASE#v}" + rpm -U "build/release/LowQuery-${VERSION}-linux-x64.rpm" + test "$(rpm -q --qf "%{VERSION}" low-query)" = "$VERSION" + test "$(sha256sum < /usr/bin/lowquery)" = "$(sha256sum < build/linux/lowquery)" + rpm -qf "$(readlink -f /usr/bin/lowquery)" + bash packaging/test/mcp-smoke.sh /usr/bin/lowquery + ' + - name: AppImage answers MCP + run: | + file "build/release/LowQuery-${VERSION}-linux-x64.AppImage" + # No FUSE on the runner: the AppImage runtime extracts itself instead. + APPIMAGE_EXTRACT_AND_RUN=1 env -u DISPLAY -u WAYLAND_DISPLAY \ + bash packaging/test/mcp-smoke.sh "build/release/LowQuery-${VERSION}-linux-x64.AppImage" + - name: Portable tarball answers MCP + run: | + mkdir portable + tar -xzf "build/release/LowQuery-${VERSION}-linux-x64-portable.tar.gz" -C portable + ls -l portable + env -u DISPLAY -u WAYLAND_DISPLAY bash packaging/test/mcp-smoke.sh portable/LowQuery - postgres: - name: PostgreSQL integration (${{ matrix.postgres }}) - runs-on: ubuntu-22.04 + macos-app: + name: macOS universal app + runs-on: macos-15 + # macOS runners can queue for long: build and check the bundle, no DMG. timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - postgres: ["13", "17"] - services: - postgres: - image: postgres:${{ matrix.postgres }} - env: - POSTGRES_PASSWORD: lowquery - ports: ["5432:5432"] - options: >- - --health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10 env: - LQ_PG_HOST: localhost - LQ_PG_PORT: "5432" - LQ_PG_USER: postgres - LQ_PG_PASSWORD: lowquery - LQ_PG_DB: postgres + VERSION: "99.0.0" + MACOS_DMG: "0" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: - workspaces: src-tauri - key: postgres - - name: Install Linux desktop dependencies + go-version-file: go.mod + - run: bun install --frozen-lockfile + - run: bun run build + - name: Build LowQuery.app and the updater bundle + run: bash packaging/macos/build.sh + - name: Bundle matches the Tauri one run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libssl-dev libdbus-1-dev - - run: mkdir -p dist - - name: Integration tests against a real server - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml postgres -- --ignored --test-threads=1 + set -euo pipefail + app=build/macos/LowQuery.app + plist="$app/Contents/Info.plist" + test "$(plutil -extract CFBundleIdentifier raw "$plist")" = dev.lowbloat.lowquery + test "$(plutil -extract CFBundleExecutable raw "$plist")" = lowquery + test "$(plutil -extract CFBundleIconFile raw "$plist")" = icon.icns + test "$(plutil -extract CFBundleShortVersionString raw "$plist")" = "$VERSION" + # macOS 12 is the oldest Go and Wails support; Finder refuses older + # systems with a clear message instead of a crash. + test "$(plutil -extract LSMinimumSystemVersion raw "$plist")" = 12.0 + for arch in arm64 x86_64; do + vtool -arch "$arch" -show-build "$app/Contents/MacOS/lowquery" | grep -E 'minos 12\.0$' + done + test -f "$app/Contents/Resources/icon.icns" + lipo "$app/Contents/MacOS/lowquery" -verify_arch arm64 x86_64 + codesign --verify --deep --strict "$app" + codesign -dv "$app" 2>&1 | grep 'Signature=adhoc' + # The Tauri updater drops the first path component of every entry. + tar -tzf "build/release/LowQuery-${VERSION}-macos-universal.app.tar.gz" > entries.txt + head -n 5 entries.txt + if grep -v '^LowQuery\.app/' entries.txt; then exit 1; fi + - name: lowquery mcp answers + run: bash packaging/test/mcp-smoke.sh build/macos/LowQuery.app/Contents/MacOS/lowquery oracle: name: Oracle integration (${{ matrix.name }}) @@ -240,18 +323,6 @@ jobs: go-version-file: go.mod - name: Go driver, transfer and MCP tests against a real server run: go test -count=1 -v ./internal/drivers/oracle/... ./internal/transfer/... ./internal/mcp/... - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - with: - workspaces: src-tauri - key: oracle-${{ matrix.service }} - - name: Install Linux desktop dependencies - run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libssl-dev libdbus-1-dev - - run: mkdir -p dist - - name: Integration tests against a real server - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml oracle -- --ignored --test-threads=1 mysql: name: ${{ matrix.name }} integration @@ -294,20 +365,6 @@ jobs: go-version-file: go.mod - name: Go driver, transfer and MCP tests against a real server run: go test -count=1 -v ./internal/drivers/mysql/... ./internal/transfer/... ./internal/mcp/... - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - with: - workspaces: src-tauri - key: mysql - - name: Install Linux desktop dependencies - run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libssl-dev libdbus-1-dev - - run: mkdir -p dist - - name: Integration tests against a real server - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml drivers::mysql -- --ignored --test-threads=1 - - name: MCP tests against a real server - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml mcp_mysql -- --ignored --test-threads=1 sqlserver: name: SQL Server 2022 integration @@ -336,20 +393,6 @@ jobs: go-version-file: go.mod - name: Go driver, transfer and MCP tests against a real server run: go test -count=1 -v ./internal/drivers/sqlserver/... ./internal/transfer/... ./internal/mcp/... - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - with: - workspaces: src-tauri - key: sqlserver - - name: Install Linux desktop dependencies - run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libssl-dev libdbus-1-dev - - run: mkdir -p dist - - name: Integration tests against a real server - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml drivers::sqlserver -- --ignored --test-threads=1 - - name: MCP tests against a real server - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml mcp_sqlserver -- --ignored --test-threads=1 redis: name: ${{ matrix.name }} integration @@ -377,20 +420,6 @@ jobs: go-version-file: go.mod - name: Go driver, transfer and MCP tests against a real server run: go test -count=1 -v ./internal/drivers/redis/... ./internal/transfer/... ./internal/mcp/... - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - with: - workspaces: src-tauri - key: redis - - name: Install Linux desktop dependencies - run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libssl-dev libdbus-1-dev - - run: mkdir -p dist - - name: Integration tests against a real server - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml drivers::redis_db -- --ignored --test-threads=1 - - name: MCP tests against a real server - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml mcp_redis -- --ignored --test-threads=1 cassandra: name: Cassandra ${{ matrix.version }} integration @@ -421,58 +450,24 @@ jobs: go-version-file: go.mod - name: Go driver, transfer and MCP tests against a real server run: go test -count=1 -v ./internal/drivers/cassandra/... ./internal/transfer/... ./internal/mcp/... - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - with: - workspaces: src-tauri - key: cassandra - - name: Install Linux desktop dependencies - run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev libssl-dev libdbus-1-dev - - run: mkdir -p dist - - name: Integration tests against a real server - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml drivers::cassandra -- --ignored --test-threads=1 - - name: MCP tests against a real server - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml mcp_cassandra -- --ignored --test-threads=1 - - name: Export and import round trip - run: cargo test --locked --lib --manifest-path src-tauri/Cargo.toml cassandra_export_import -- --ignored --test-threads=1 - # Builds the native Arch package the release publishes. Manual runs only: - # it compiles the whole app, which pull requests do not need. arch-package: name: Arch Linux package if: github.event_name == 'workflow_dispatch' runs-on: ubuntu-22.04 - timeout-minutes: 60 + timeout-minutes: 40 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - name: Install system libraries (WebKitGTK) + - name: Install system libraries (GTK 3, WebKitGTK 4.1) run: | sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libdbus-1-dev libappindicator3-dev \ - librsvg2-dev patchelf libjavascriptcoregtk-4.1-dev libsoup-3.0-dev + sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev librsvg2-dev - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: - workspaces: src-tauri - key: arch + go-version-file: go.mod - run: bun install --frozen-lockfile - - run: bun run tauri build --no-bundle + - run: bun run build + - run: bash packaging/linux/build.sh - name: makepkg in an Arch container - shell: bash - run: | - set -euo pipefail - version=$(node -p "require('./package.json').version") - arch_build="$PWD/arch-build" - mkdir -p "$arch_build" - cp src-tauri/target/release/lowquery "$arch_build/lowquery" - cp src-tauri/icons/128x128.png "$arch_build/lowquery.png" - cp packaging/arch/lowquery.desktop "$arch_build/lowquery.desktop" - python3 .github/scripts/render_pkgbuild.py local "$version" "$arch_build" - docker run --rm -v "$arch_build":/workspace -w /workspace archlinux:base-devel bash -c " - useradd -m builder && chown -R builder:builder /workspace && - su builder -c 'makepkg -f --nodeps' && - pacman -Qip *.pkg.tar.zst && pacman -Qlp *.pkg.tar.zst - " + run: bash packaging/arch/build.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 16cbe7d..263d43f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -19,9 +19,12 @@ concurrency: cancel-in-progress: false env: - CARGO_TERM_COLOR: always RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }} +# Every platform builds the Go app with the scripts in packaging/, which CI +# also runs (and tests upgrades of the Tauri builds with). The updater files +# (setup, .app.tar.gz, AppImage, .deb, .rpm) get a .sig made with the Tauri +# updater key, so Tauri installs (0.5.x) and Go installs both accept them. jobs: verify: name: Check version @@ -49,118 +52,74 @@ jobs: runs-on: windows-2022 env: VERSION: ${{ needs.verify.outputs.version }} - TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} - TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} steps: + # The packaging scripts are bash: keep their LF line endings. + - run: git config --global core.autocrlf false - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ env.RELEASE_TAG }} - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod - run: bun install --frozen-lockfile - - name: Build with Tauri - run: bun run tauri build - - name: Collect installers and portable build - shell: pwsh - run: | - New-Item -ItemType Directory -Force -Path "out" | Out-Null - - $nsis = Get-ChildItem "src-tauri/target/release/bundle/nsis/*.exe" | Select-Object -First 1 - if (-not $nsis) { throw "NSIS installer not found." } - Copy-Item $nsis.FullName "out/LowQuery-$env:VERSION-windows-x64-setup.exe" - Copy-Item "$($nsis.FullName).sig" "out/LowQuery-$env:VERSION-windows-x64-setup.exe.sig" - - $msi = Get-ChildItem "src-tauri/target/release/bundle/msi/*.msi" | Select-Object -First 1 - if ($msi) { - Copy-Item $msi.FullName "out/LowQuery-$env:VERSION-windows-x64.msi" - Copy-Item "$($msi.FullName).sig" "out/LowQuery-$env:VERSION-windows-x64.msi.sig" - } - - $portable = "out/LowQuery-$env:VERSION-windows-x64-portable" - New-Item -ItemType Directory -Force -Path $portable | Out-Null - Copy-Item "src-tauri/target/release/lowquery.exe" "$portable/LowQuery.exe" - Copy-Item README.md, LICENSE $portable - Compress-Archive -Path "$portable/*" -DestinationPath "$portable.zip" -Force - Remove-Item -Recurse -Force $portable - - Get-ChildItem out -File -Exclude *.sig | ForEach-Object { - $hash = (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant() - "$hash $($_.Name)" | Set-Content "$($_.FullName).sha256" -Encoding ascii -NoNewline - } + - run: bun run build + - name: Build the setup and the portable zip + shell: bash + run: bash packaging/windows/build.sh + - name: Sign the setup for the updater + shell: bash + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + run: go run ./tools/updatesign -app-version "$VERSION" "build/release/LowQuery-${VERSION}-windows-x64-setup.exe" + - name: Checksums + shell: bash + run: source packaging/common.sh && write_checksums build/release && ls -l build/release - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: lowquery-windows - path: out/* + path: build/release/* if-no-files-found: error linux: name: Linux x64 needs: [verify, checks] + # The oldest supported base, as for the Tauri builds: the AppImage needs + # its glibc or newer. runs-on: ubuntu-22.04 env: VERSION: ${{ needs.verify.outputs.version }} - TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} - TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ env.RELEASE_TAG }} - - name: Install system libraries (WebKitGTK) + - name: Install system libraries (GTK 3, WebKitGTK 4.1) run: | sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libdbus-1-dev libappindicator3-dev \ - librsvg2-dev patchelf libjavascriptcoregtk-4.1-dev libsoup-3.0-dev + sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev librsvg2-dev - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod - run: bun install --frozen-lockfile - - name: Build with Tauri - run: bun run tauri build - - name: Collect packages and portable build - shell: bash + - run: bun run build + - name: Build the .deb, .rpm, AppImage and portable tarball + run: bash packaging/linux/build.sh + - name: Build the Arch package (makepkg in an Arch container) + run: bash packaging/arch/build.sh + - name: Sign the packages for the updater + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} run: | - set -euo pipefail - mkdir -p out - bundle=src-tauri/target/release/bundle - # Each package keeps its updater signature: .deb and .rpm installs - # update themselves through dpkg/rpm. - deb="$(find $bundle/deb -name '*.deb' | head -n 1)" - cp "$deb" "out/LowQuery-${VERSION}-linux-x64.deb" - cp "$deb.sig" "out/LowQuery-${VERSION}-linux-x64.deb.sig" - rpm="$(find $bundle/rpm -name '*.rpm' | head -n 1)" - cp "$rpm" "out/LowQuery-${VERSION}-linux-x64.rpm" - cp "$rpm.sig" "out/LowQuery-${VERSION}-linux-x64.rpm.sig" - appimage="$(find $bundle/appimage -name '*.AppImage' | head -n 1)" - cp "$appimage" "out/LowQuery-${VERSION}-linux-x64.AppImage" - cp "$appimage.sig" "out/LowQuery-${VERSION}-linux-x64.AppImage.sig" - - portable="out/LowQuery-${VERSION}-linux-x64-portable" - mkdir -p "$portable" - cp src-tauri/target/release/lowquery "$portable/LowQuery" - chmod +x "$portable/LowQuery" - cp README.md LICENSE "$portable/" - tar -czf "$portable.tar.gz" -C "$portable" . - rm -rf "$portable" - - # Native Arch Linux package (pacman -U), built with makepkg in an - # Arch container from the binary compiled above. - arch_build="$PWD/arch-build" - mkdir -p "$arch_build" - cp src-tauri/target/release/lowquery "$arch_build/lowquery" - cp src-tauri/icons/128x128.png "$arch_build/lowquery.png" - cp packaging/arch/lowquery.desktop "$arch_build/lowquery.desktop" - python3 .github/scripts/render_pkgbuild.py local "$VERSION" "$arch_build" - docker run --rm -v "$arch_build":/workspace -w /workspace archlinux:base-devel bash -c " - useradd -m builder && chown -R builder:builder /workspace && - su builder -c 'makepkg -f --nodeps' - " - cp "$(find "$arch_build" -name '*.pkg.tar.zst' | head -n 1)" "out/LowQuery-${VERSION}-linux-x86_64.pkg.tar.zst" - sudo rm -rf "$arch_build" - - (cd out && for f in *; do [[ "$f" == *.sig ]] || sha256sum "$f" > "$f.sha256"; done) + go run ./tools/updatesign -app-version "$VERSION" "build/release/LowQuery-${VERSION}-linux-x64.deb" "build/release/LowQuery-${VERSION}-linux-x64.rpm" "build/release/LowQuery-${VERSION}-linux-x64.AppImage" + - name: Checksums + run: source packaging/common.sh && write_checksums build/release && ls -l build/release - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: lowquery-linux - path: out/* + path: build/release/* if-no-files-found: error macos: @@ -169,34 +128,29 @@ jobs: runs-on: macos-15 env: VERSION: ${{ needs.verify.outputs.version }} - TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} - TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ env.RELEASE_TAG }} - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: - targets: aarch64-apple-darwin,x86_64-apple-darwin + go-version-file: go.mod - run: bun install --frozen-lockfile - - name: Build with Tauri (universal) - run: bun run tauri build --target universal-apple-darwin - - name: Collect DMG and updater bundle - shell: bash - run: | - set -euo pipefail - mkdir -p out - dmg=$(find src-tauri/target/universal-apple-darwin/release/bundle/dmg -name '*.dmg' | head -n 1) - cp "$dmg" "out/LowQuery-${VERSION}-macos-universal.dmg" - tarball=$(find src-tauri/target/universal-apple-darwin/release/bundle/macos -name '*.app.tar.gz' | head -n 1) - cp "$tarball" "out/LowQuery-${VERSION}-macos-universal.app.tar.gz" - cp "$tarball.sig" "out/LowQuery-${VERSION}-macos-universal.app.tar.gz.sig" - (cd out && for f in *; do [[ "$f" == *.sig ]] || shasum -a 256 "$f" > "$f.sha256"; done) + - run: bun run build + - name: Build LowQuery.app, the DMG and the updater bundle + run: bash packaging/macos/build.sh + - name: Sign the updater bundle + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + run: go run ./tools/updatesign -app-version "$VERSION" "build/release/LowQuery-${VERSION}-macos-universal.app.tar.gz" + - name: Checksums + run: source packaging/common.sh && write_checksums build/release && ls -l build/release - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: lowquery-macos - path: out/* + path: build/release/* if-no-files-found: error publish: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 18e61cd..7c06ef0 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -6,11 +6,10 @@ on: workflow_dispatch: pull_request: paths: - - "src-tauri/Cargo.toml" - - "src-tauri/Cargo.lock" + - "go.mod" + - "go.sum" - "package.json" - "bun.lock" - - "src-tauri/deny.toml" - ".github/workflows/security.yml" permissions: @@ -21,17 +20,23 @@ concurrency: cancel-in-progress: true jobs: - rust: - name: Rust advisories and bans + go: + name: Go vulnerabilities runs-on: ubuntu-22.04 timeout-minutes: 20 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: - tool: cargo-deny - - name: cargo deny - run: cargo deny --manifest-path src-tauri/Cargo.toml check advisories bans sources + go-version-file: go.mod + # internal/menubar imports Wails, which on Linux needs these through cgo. + - name: GTK and WebKitGTK headers + run: | + sudo apt-get update + sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev + # Reports only vulnerabilities in code the app actually calls. + - name: govulncheck + run: go run golang.org/x/vuln/cmd/govulncheck@v1.1.4 -tags gtk3 ./internal/... ./tools/... javascript: name: npm advisories diff --git a/.gitignore b/.gitignore index 07ba6d2..840d29e 100644 --- a/.gitignore +++ b/.gitignore @@ -32,11 +32,7 @@ vite.config.js.timestamp-* vite.config.ts.timestamp-* .vite/ -# --- Tauri / Rust --- -src-tauri/target/ -src-tauri/gen/ -target/ -**/*.rs.bk +# --- Build output --- *.pdb # --- Tests --- @@ -52,6 +48,8 @@ blob-report/ !.env.example *.pem *.key +# Throwaway minisign key that signs the updater test fixtures; not a release key. +!internal/updater/testdata/throwaway.key *.p12 *.pfx *.jks @@ -80,3 +78,6 @@ logs/ # --- Release artifacts --- /release-assets + +# Windows resources generated by packaging/windows/build.sh +*.syso diff --git a/CHANGELOG.md b/CHANGELOG.md index ad6965b..af62d0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to LowQuery are documented here. The format follows [Keep a ## [Unreleased] +### Changed +- **LowQuery now runs on Go and Wails instead of Rust and Tauri.** It has the same window, connections, drivers, export and import, AI agents (MCP) and connection importers. Every driver passes the same tests against real servers in CI: PostgreSQL 13 and 17, Oracle 21c and 23ai, MySQL 8.4, MariaDB 11.4, SQL Server 2022, Redis 7.4, Valkey 8, and Cassandra 4.1 and 5.0. + - **Installed copies update as usual.** + - The Windows setup installs over the previous version in the same folder and keeps its shortcuts. + - `.deb`, `.rpm`, AppImage and the macOS app replace the previous version in place. + - **Kept from the previous version:** + - saved connections and passwords; + - open query tabs and their SQL, export preferences and the sidebar width. + - **Oracle:** Cancel now interrupts a running statement. + - **SQL Server:** `PRINT` and `RAISERROR` messages show in the messages panel. + +### Removed +- **The Windows MSI.** MSI installs update to the setup: it removes the MSI copy, which needs administrator rights once, and installs per user. +- **macOS 10.13 to 11.** The app now needs macOS 12 or later, the oldest version Go and Wails support. The update is still offered on older Macs, and once installed the app no longer opens there. On macOS 10.13 to 11, skip **Restart to update** and keep using 0.5.7; if the update is already installed, download [0.5.7](https://github.com/LowBloat/LowQuery/releases/tag/v0.5.7) again. + ## [0.5.7] - 2026-11-27 ### Changed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fafcc3c..9a6aaac 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing to LowQuery -LowQuery is an open-source SQL client built with Svelte, TypeScript, Tauri and Rust. Contributions can include bug fixes, database support, documentation, accessibility improvements and tests. +LowQuery is an open-source SQL client built with Svelte, TypeScript, Go and Wails. Contributions can include bug fixes, database support, documentation, accessibility improvements and tests. Keep repository documentation, issues and pull requests in English so contributors around the world can participate. @@ -19,7 +19,7 @@ Never include passwords, connection strings with credentials or real business da ## Set up development -Install [Bun](https://bun.sh/), the stable [Rust toolchain](https://rustup.rs/) and the [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/) for your operating system. No Oracle Client or Instant Client is needed. +Install [Bun](https://bun.sh/) and [Go](https://go.dev/dl/) (the version in `go.mod`). On Linux, also install the GTK 3 and WebKitGTK 4.1 development packages (`libgtk-3-dev libwebkit2gtk-4.1-dev` on Debian and Ubuntu). No Oracle Client or Instant Client is needed. Fork the repository, then clone your fork and create a branch: @@ -28,7 +28,7 @@ git clone https://github.com/YOUR-USERNAME/LowQuery.git cd LowQuery git switch -c fix/short-description bun install --frozen-lockfile -bun run tauri dev +bun run app ``` To work on the interface without a database, run `bun run dev` and open http://localhost:1420. A development-only mock backend answers every command; add `?demo` to the URL to start with a sample query and result. @@ -41,20 +41,19 @@ Run the checks relevant to your change: bun run check bun test bun run build -cargo fmt --check --manifest-path src-tauri/Cargo.toml -cargo clippy --manifest-path src-tauri/Cargo.toml --lib --tests -- -D warnings -cargo test --locked --lib --manifest-path src-tauri/Cargo.toml +gofmt -l internal main.go tools +go vet ./... +go test ./... ``` Driver changes need integration tests against a real server. Copy `.env.example` to `.env.test` (it is ignored by git), fill in a test database and run: ```bash -cd src-tauri -set -a; source ../.env.test; set +a -cargo test --lib -- --ignored --test-threads=1 +set -a; source .env.test; set +a +go test -count=1 ./internal/... ``` -SQLite tests need no server and always run. CI runs the server tests against PostgreSQL 13 and 17, Oracle Database Free, MySQL 8.4, MariaDB 11.4, SQL Server 2022, Redis 7.4, Valkey 8 and Apache Cassandra 4.1 and 5.0 in containers, so a pull request shows whether a change works on every engine. For a bug fix, add a regression test that fails without the fix. +Each engine's tests run only when its `LQ_*` variables are set; SQLite tests need no server and always run. CI runs the server tests against PostgreSQL 13 and 17, Oracle Database Free, MySQL 8.4, MariaDB 11.4, SQL Server 2022, Redis 7.4, Valkey 8 and Apache Cassandra 4.1 and 5.0 in containers, so a pull request shows whether a change works on every engine. For a bug fix, add a regression test that fails without the fix. ## Open a pull request diff --git a/README.md b/README.md index 1f5dc03..71e8988 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- LowQuery logo + LowQuery logo

LowQuery

@@ -25,17 +25,17 @@ --- -LowQuery is an **open-source desktop SQL client** for Windows, Linux and macOS. It connects to **PostgreSQL, Oracle, MySQL, MariaDB, SQL Server, SQLite, Redis and Apache Cassandra**, and treats each one as itself: every engine goes through its own native driver and protocol, with server-side row limits, exact values and the script rules of that engine. Oracle needs **no Oracle Client or Instant Client**. The app is built with Tauri and Rust, so it starts fast and stays small. +LowQuery is an **open-source desktop SQL client** for Windows, Linux and macOS. It connects to **PostgreSQL, Oracle, MySQL, MariaDB, SQL Server, SQLite, Redis and Apache Cassandra**, and treats each one as itself: every engine goes through its own native driver and protocol, with server-side row limits, exact values and the script rules of that engine. Oracle needs **no Oracle Client or Instant Client**. The app is built with Go and Wails on the system webview, so it starts fast and stays small. | Database | How LowQuery connects | | --- | --- | -| PostgreSQL | Extended protocol with [`tokio-postgres`](https://crates.io/crates/tokio-postgres) | -| Oracle | [`oracledb`](https://github.com/oracle/rust-oracledb), Oracle's official thin driver in pure Rust | -| MySQL and MariaDB | Native protocol with [`mysql_async`](https://crates.io/crates/mysql_async) | -| SQL Server and Azure SQL | TDS protocol with [`tiberius`](https://crates.io/crates/tiberius), SQL logins or Windows accounts | -| SQLite | Embedded engine ([`rusqlite`](https://crates.io/crates/rusqlite)), opens local database files | -| Redis and Valkey | RESP3 with [`redis-rs`](https://crates.io/crates/redis): redis-cli commands, results as tables, keys browsed by type | -| Apache Cassandra | CQL native protocol with [`scylla`](https://crates.io/crates/scylla) (Cassandra 3.x to 5.x): keyspaces, tables, views, types and functions from `system_schema`, exact CQL values | +| PostgreSQL | Extended protocol with [`pgx`](https://github.com/jackc/pgx)'s `pgconn` | +| Oracle | [`go-ora`](https://github.com/sijms/go-ora), a thin driver in pure Go | +| MySQL and MariaDB | Native protocol; the handshake from [`go-sql-driver/mysql`](https://github.com/go-sql-driver/mysql) | +| SQL Server and Azure SQL | TDS protocol with [`go-mssqldb`](https://github.com/microsoft/go-mssqldb), SQL logins or Windows accounts | +| SQLite | Embedded engine ([`ncruces/go-sqlite3`](https://github.com/ncruces/go-sqlite3), no C compiler needed), opens local database files | +| Redis and Valkey | RESP3 with [`go-redis`](https://github.com/redis/go-redis): redis-cli commands, results as tables, keys browsed by type | +| Apache Cassandra | CQL native protocol with [`gocql`](https://github.com/apache/cassandra-gocql-driver) (Cassandra 3.x to 5.x): keyspaces, tables, views, types and functions from `system_schema`, exact CQL values | ![LowQuery on Windows with the schema browser, SQL editor and result grid](assets/screenshots/lowquery-desktop.png) @@ -72,9 +72,9 @@ The [latest release](https://github.com/LowBloat/LowQuery/releases/latest) inclu | Platform | Available formats | | --- | --- | -| Windows x64 | Setup `.exe`, `.msi`, portable `.zip` | +| Windows x64 | Setup `.exe`, portable `.zip` | | Linux x64 | `.AppImage`, `.deb`, `.rpm`, Arch `.pkg.tar.zst`, portable `.tar.gz` | -| macOS (Apple Silicon and Intel) | Universal `.dmg` | +| macOS 12 or later (Apple Silicon and Intel) | Universal `.dmg` | **Arch Linux, Omarchy and other Arch-based systems.** Install the native package with `sudo pacman -U LowQuery--linux-x86_64.pkg.tar.zst`. Each release also publishes a `PKGBUILD` with real checksums that builds the same package from the portable archive with `makepkg -si`. @@ -117,9 +117,9 @@ gh attestation verify LowQuery--linux-x64.AppImage --repo LowBloat/LowQ | Database | Row limit | Values | Server messages | Cancel | Scripts | | --- | --- | --- | --- | --- | --- | | PostgreSQL | Portal executed with `max_rows` | Binary format decoded per type into server-style text: exact NUMERIC, infinite dates, intervals, arrays, ranges | `NOTICE`, `WARNING` | Server cancel protocol | `;`, `$$` bodies, nested comments, `E''` strings | -| Oracle | `prefetch_rows` and fetch size sized from the limit | NUMBER, DATE, TIMESTAMP with time zone, RAW/BLOB, CLOB, JSON, VECTOR, intervals | `DBMS_OUTPUT` | Not in the driver yet; scripts stop before the next statement | `;` for SQL, `/` for PL/SQL, `q'[...]'` strings | +| Oracle | Prefetch and fetch size sized from the limit | NUMBER, DATE, TIMESTAMP with time zone, RAW/BLOB, CLOB, JSON, VECTOR, intervals | `DBMS_OUTPUT` | Interrupts the running statement | `;` for SQL, `/` for PL/SQL, `q'[...]'` strings | | MySQL, MariaDB | `sql_select_limit` on the server | Text protocol: exact DECIMAL, unsigned BIGINT, zero dates, binary as hex | `SHOW WARNINGS` | `KILL QUERY` from a second connection | `DELIMITER`, `#` comments, backticks, backslash escapes | -| SQL Server, Azure SQL | `SET ROWCOUNT` for plain SELECT batches | Exact decimal, datetime2 and datetimeoffset precision, uniqueidentifier, binary as hex | Not exposed by the driver yet | TDS attention | `GO` batches, `BEGIN...END` blocks, `[brackets]` | +| SQL Server, Azure SQL | `SET ROWCOUNT` for plain SELECT batches | Exact decimal, datetime2 and datetimeoffset precision, uniqueidentifier, binary as hex | `PRINT`, `RAISERROR` below severity 11 | TDS attention | `GO` batches, `BEGIN...END` blocks, `[brackets]` | | SQLite | Stops stepping at the limit | Storage class and declared type; blobs as hex | — | `sqlite3_interrupt` | Trigger bodies, `[brackets]`, backticks | | Redis, Valkey | Long replies cut at the limit; the tree uses `SCAN` | RESP3 types: maps as field/value, `WITHSCORES` as member/score, `INFO` as rows | — | `CLIENT UNBLOCK` for blocking commands | One redis-cli command per line, `#` comments | | Apache Cassandra | Paging: the page size comes from the limit and reading stops there | Exact `varint` and `decimal`, `timestamp`, `date`, `time`, `duration`, `uuid`, blobs as hex; collections, tuples, UDTs and vectors as CQL literals | Server warnings (tombstones, aggregations without a partition key) | Stops waiting; CQL cannot cancel on the server | `;`, `BEGIN BATCH ... APPLY BATCH` as one statement, `$$` bodies, `--`, `//` and `/* */` comments | @@ -132,20 +132,19 @@ Read [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for the code layout and how a ## Build from source -Install [Bun](https://bun.sh), the stable [Rust toolchain](https://rustup.rs/) and the [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/). +Install [Bun](https://bun.sh) and [Go](https://go.dev/dl/) (the version in `go.mod`). On Linux, also install the GTK 3 and WebKitGTK 4.1 development packages (`libgtk-3-dev libwebkit2gtk-4.1-dev` on Debian and Ubuntu). Windows uses the WebView2 runtime that ships with Windows 10 and 11. ```bash git clone https://github.com/LowBloat/LowQuery.git cd LowQuery bun install -bun run tauri dev +bun run app ``` -`bun run tauri build --no-bundle` builds the app for your system. Installers are also signed for the updater, so a full `bun run tauri build` needs the signing key; without it, disable that step with `bun run tauri build -c '{"bundle":{"createUpdaterArtifacts":false}}'`. To work only on the interface, `bun run dev` serves it at http://localhost:1420 with a development mock backend. +`bun run app` starts the interface with hot reload inside the desktop window. `bun run build:app` builds `bin/LowQuery.exe` on Windows; `bun run package:windows`, `package:linux` and `package:macos` build the installers and packages of a release (see `packaging/`). Release files are signed for the updater in CI only. To work only on the interface, `bun run dev` serves it at http://localhost:1420 with a development mock backend. ## Roadmap -- Interrupt a running Oracle call when the driver exposes it. - Bind variables (`:name`, `$1`) with a value dialog. - Fetch more rows on demand without running the query again. - Execution plans (`EXPLAIN`, `DBMS_XPLAN`). diff --git a/bun.lock b/bun.lock index e8939bf..8692923 100644 --- a/bun.lock +++ b/bun.lock @@ -17,17 +17,11 @@ "@lezer/highlight": "^1.2.5", "@lucide/svelte": "^1.59.0", "@tanstack/svelte-table": "^9.3.1", - "@tauri-apps/api": "^2.12.4", - "@tauri-apps/plugin-dialog": "^2.8.3", - "@tauri-apps/plugin-opener": "^2.7.2", - "@tauri-apps/plugin-process": "^2.4.0", - "@tauri-apps/plugin-updater": "^2.14.0", "@wailsio/runtime": "3.1.0", "codemirror": "^6.0.2", }, "devDependencies": { "@sveltejs/vite-plugin-svelte": "^7.3.1", - "@tauri-apps/cli": "^2.12.3", "@tsconfig/svelte": "^5.0.8", "@types/bun": "^1.4.3", "svelte": "^5.57.2", @@ -138,40 +132,6 @@ "@tanstack/table-core": ["@tanstack/table-core@9.3.1", "", { "dependencies": { "@tanstack/store": "^0.11.2" } }, "sha512-zQvlxSNi2qGM3L4jh85Z6hqMfdIR5qOfD9KHOU32nuKFJGN0RlJ7UvV1lsPb1fPVhpFYI0VP3jJGxLdLDpTKjQ=="], - "@tauri-apps/api": ["@tauri-apps/api@2.12.4", "", {}, "sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg=="], - - "@tauri-apps/cli": ["@tauri-apps/cli@2.12.3", "", { "optionalDependencies": { "@tauri-apps/cli-darwin-arm64": "2.12.3", "@tauri-apps/cli-darwin-x64": "2.12.3", "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.3", "@tauri-apps/cli-linux-arm64-gnu": "2.12.3", "@tauri-apps/cli-linux-arm64-musl": "2.12.3", "@tauri-apps/cli-linux-riscv64-gnu": "2.12.3", "@tauri-apps/cli-linux-x64-gnu": "2.12.3", "@tauri-apps/cli-linux-x64-musl": "2.12.3", "@tauri-apps/cli-win32-arm64-msvc": "2.12.3", "@tauri-apps/cli-win32-ia32-msvc": "2.12.3", "@tauri-apps/cli-win32-x64-msvc": "2.12.3" }, "bin": { "tauri": "tauri.js" } }, "sha512-f7/LsY74SVb1ChmOPw1ajOpxii0GSzDAgmWHRci8JUYuuai04rXsSbFobpmB0sP2DdlvMD/B5ZotEn8GOGMRUg=="], - - "@tauri-apps/cli-darwin-arm64": ["@tauri-apps/cli-darwin-arm64@2.12.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-xmVNoJOOKzKLj7GLHXmXLimRby9M42aBIJa0sB80N7o24eKV5JiVmToKTRLVH9yhL05GZ/B6rSSOmbzNFJwBAA=="], - - "@tauri-apps/cli-darwin-x64": ["@tauri-apps/cli-darwin-x64@2.12.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-URd+0usfmUQQyb5kNPiKt2OT8gp7oGU7QR+qOppB6e35mpVBFFVNhWc9oWb3p0u71fDJ09DpF4T6m9xYxoIB8g=="], - - "@tauri-apps/cli-linux-arm-gnueabihf": ["@tauri-apps/cli-linux-arm-gnueabihf@2.12.3", "", { "os": "linux", "cpu": "arm" }, "sha512-0kwUVx2LbmOoTRlwF1oDww7th4/NSluv4ZBQ6KRZsFKg4g0TlTcIiJ0VehqkQYUeC9xIT1Mk6XtF52mI155VSQ=="], - - "@tauri-apps/cli-linux-arm64-gnu": ["@tauri-apps/cli-linux-arm64-gnu@2.12.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-gKSGDx6fx+HBLQmG6guChFdisbrCSdx9Yli+j5teOa64gm1CeM+C6NLru5Pj3ZkkEep05BmCFjxvX+cjqAycZQ=="], - - "@tauri-apps/cli-linux-arm64-musl": ["@tauri-apps/cli-linux-arm64-musl@2.12.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-Yr59qMy/gcvAfBuFdCGlAmGiLsYWMFDbsP4bAI6iNBzcJTGrYWZGeiQhGDo29MQwfF/NUBqyM2qljXu5tZ6wjQ=="], - - "@tauri-apps/cli-linux-riscv64-gnu": ["@tauri-apps/cli-linux-riscv64-gnu@2.12.3", "", { "os": "linux", "cpu": "none" }, "sha512-jKr0/REBMnLKC0OwPQZkyge0mKDaNZ0b/AbfGwVyCgFfwS730EVLfVDo3nt7MUu6jJaytRq08+xSj5qfy+U1+Q=="], - - "@tauri-apps/cli-linux-x64-gnu": ["@tauri-apps/cli-linux-x64-gnu@2.12.3", "", { "os": "linux", "cpu": "x64" }, "sha512-gTkEqJAGCMROGanxHnzaJzQ+/rXl39HWVg0/hDODS1wDWBGqoceqGC6Qm1+mQbyT11xnsB8mKu/gyVID/YpFIw=="], - - "@tauri-apps/cli-linux-x64-musl": ["@tauri-apps/cli-linux-x64-musl@2.12.3", "", { "os": "linux", "cpu": "x64" }, "sha512-T2dTxL1svRym71fZtaW4pZYXbthbfFsEJr1NeOUg/p7laWXZbUt/8DMSZf8recu9f7+1F/Lv00HtzsEu6vDO9w=="], - - "@tauri-apps/cli-win32-arm64-msvc": ["@tauri-apps/cli-win32-arm64-msvc@2.12.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-eoiQwpEZWbpsVHcM9BAzqqe4TCHszvr3rsM7pUQ4ofLK0lF1i1d/jX0Qo5DYMqcrUtwQuDdDuOCbcT0Izf1VwQ=="], - - "@tauri-apps/cli-win32-ia32-msvc": ["@tauri-apps/cli-win32-ia32-msvc@2.12.3", "", { "os": "win32", "cpu": "ia32" }, "sha512-kE+KUg6Dbbkgvcw0m99wJVIToFQzJqpMBAXah74WqxaLzssNwSTUccrHp6+QVzMhjQP330tvekFmnQF+0NbE6Q=="], - - "@tauri-apps/cli-win32-x64-msvc": ["@tauri-apps/cli-win32-x64-msvc@2.12.3", "", { "os": "win32", "cpu": "x64" }, "sha512-L7wndWAgX2mLW7alswpL3d1R0P9FN2WYBgHaQkAYEBxHHGkY4vFX9CjcRQ1LAxDAMIJxrY7/aDziFJeChS84NQ=="], - - "@tauri-apps/plugin-dialog": ["@tauri-apps/plugin-dialog@2.8.3", "", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-Hd/yBfk2R5v2MFrz/0VArSXeh8xKLLXGunqSiTtcHKn1zNZwaKujuA0VSwUvNfwC4hDoF1PveS+gBDNe3nHspw=="], - - "@tauri-apps/plugin-opener": ["@tauri-apps/plugin-opener@2.7.2", "", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-LyybP1VSzTMQiaFYcsbAse47KpivlyXdLZMQzGLEnkgQacGESnpjAfFoQ6h5sqWgAdZDH9szYjPzHMpv0Sz+TQ=="], - - "@tauri-apps/plugin-process": ["@tauri-apps/plugin-process@2.4.0", "", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-GddrmsSLAYrLa/yTXlXK/YRDzUgYeeOnUXTbiyvJWkmI424RmDPD3FVLeqcon7rv6O6ZfhBilcrHWnSo7o6hIQ=="], - - "@tauri-apps/plugin-updater": ["@tauri-apps/plugin-updater@2.14.0", "", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-gdylJ9tger4hkyOn24QZd6MNOKVo2Eh53iw5th2Qj1vKTR/+u4PIwJWuiis5hohYvobn6iOvlnALfrqIPSzh7Q=="], - "@tsconfig/svelte": ["@tsconfig/svelte@5.0.8", "", {}, "sha512-UkNnw1/oFEfecR8ypyHIQuWYdkPvHiwcQ78sh+ymIiYoF+uc5H1UBetbjyqT+vgGJ3qQN6nhucJviX6HesWtKQ=="], "@types/bun": ["@types/bun@1.4.3", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="], diff --git a/docs/AI.md b/docs/AI.md index ab892cb..a3b6b99 100644 --- a/docs/AI.md +++ b/docs/AI.md @@ -46,15 +46,15 @@ Read-only access does not rely on the agent's good behaviour. Every call goes th | --- | --- | --- | | PostgreSQL | `SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY` | read-only transaction, rolled back | | MySQL, MariaDB | `SET SESSION TRANSACTION READ ONLY` | `START TRANSACTION READ ONLY`, rolled back | - | Oracle | manual commit | `SET TRANSACTION READ ONLY`, rolled back | + | Oracle | manual commit | `SET TRANSACTION READ ONLY` (not for `explain`, which writes `PLAN_TABLE`), rolled back | | SQL Server | implicit transactions | always rolled back | - | SQLite | file opened read-only (`mode=ro`) and `PRAGMA query_only` | rolled back | + | SQLite | file opened read-only (`mode=ro`) when it can be, and `PRAGMA query_only` | rolled back | | Redis | | allowlist of read commands; `KEYS` refused in favour of `SCAN` | | Cassandra | | CQL has no read-only transaction: only `SELECT` and `LIST` pass the classifier, and `USE` is refused so no call changes the session keyspace (names are written `keyspace.table`) | On **Read and write** connections, `execute` runs with autocommit. Transaction control (`BEGIN`, `COMMIT`, `SET autocommit`...) is refused (on Cassandra: `BEGIN TRANSACTION`, `COMMIT`, `ROLLBACK`; `BEGIN BATCH` is allowed), and a statement that leaves a transaction open is rolled back. -Every call has a time limit (30 seconds, or `LOWQUERY_MCP_TIMEOUT` in seconds), after which the statement is cancelled on the server. +Every call has a time limit (30 seconds, or `LOWQUERY_MCP_TIMEOUT` in seconds). When it runs out, or the client cancels the call, LowQuery cancels the statement through the driver; on Cassandra, which has no server-side cancel, it only stops waiting. A session that does not stop in time is dropped and a new one is opened for the next call. The database still decides what its user may do. For production databases, give agents a connection whose database user has only the rights they need: a read-only role is stronger than any client-side check. Side effects the database runs outside the transaction (an Oracle autonomous transaction inside a function, for example) cannot be rolled back by LowQuery. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2077610..ee88d57 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,103 +1,116 @@ # Architecture -LowQuery is a Tauri 2 desktop app. The interface is Svelte 5 with the [CodeAtlas UI](https://ui.codeatlas.com.br/) components; everything that touches a database runs in the Rust process. +LowQuery is a Go desktop app built on Wails v3. The interface is Svelte 5 with the [CodeAtlas UI](https://ui.codeatlas.com.br/) components; everything that touches a database runs in the Go process. ``` -┌──────────────── WebView (Svelte) ────────────────┐ ┌──────────── Rust (Tauri) ────────────┐ -│ SqlEditor (CodeMirror) split.ts (per dialect) │ │ lib.rs Tauri commands │ -│ QueryView → workspace.svelte.ts (tabs, sessions) │ IPC │ profiles.rs JSON + OS keychain │ -│ ResultGrid (virtualized) explorer.svelte.ts │ ───► │ drivers/mod.rs Session enum │ -│ api.ts (typed invoke wrappers) │ │ postgres.rs + pg_value.rs │ -└──────────────────────────────────────────────────┘ │ oracle.rs │ - └──────────────────────────────────────┘ +┌──────────────── WebView (Svelte) ────────────────┐ ┌───────────────── Go (Wails v3) ─────────────────┐ +│ SqlEditor (CodeMirror) split.ts (per dialect) │ │ main.go window, `lowquery mcp` │ +│ QueryView → workspace.svelte.ts (tabs, sessions) │ Call │ app/ Service.Invoke(cmd, args) │ +│ ResultGrid (virtualized) explorer.svelte.ts │ ────► │ profiles/ JSON + OS credential store │ +│ api.ts (typed wrappers) → host.ts (Wails calls) │ ◄──── │ engines/ opens the driver of an engine │ +└──────────────────────────────────────────────────┘ events│ drivers/ Session interface │ + │ postgres/ oracle/ mysql/ sqlserver/ ... │ + └─────────────────────────────────────────────────┘ ``` ## Principles -1. **Each database is used the way it is meant to be used.** There is no generic ODBC/JDBC layer. Every engine gets its own driver module that speaks its native protocol, formats its own types and follows its own transaction and script conventions. -2. **Values cross the IPC boundary as text.** Drivers format each value exactly (NUMERIC and NUMBER keep every digit, dates keep their precision) and send `string | null` plus a column kind (`number`, `text`, `temporal`, ...) the grid uses for alignment. JavaScript numbers never touch database values. +1. **Each database is used the way it is meant to be used.** There is no generic ODBC/JDBC layer. Every engine gets its own driver package that speaks its native protocol, formats its own types and follows its own transaction and script conventions. +2. **Values cross into the interface as text.** Drivers format each value exactly (NUMERIC and NUMBER keep every digit, dates keep their precision) and send `string | null` plus a column kind (`number`, `text`, `temporal`, ...) the grid uses for alignment. JavaScript numbers never touch database values. 3. **Row limits are applied by the server.** A `SELECT` on a large table never streams everything just to show 500 rows. -4. **Secrets stay in the native process.** Passwords go from the connection dialog to the OS credential store and are read back only by Rust. +4. **Secrets stay in the native process.** Passwords go from the connection dialog to the OS credential store and are read back only by Go. 5. **One session per tab.** Transactions never leak between tabs. The schema browser opens its own session per connection so it does not wait behind a long query. -## Rust side (`src-tauri/src`) +## Go side (`main.go`, `internal/`) -| File | Responsibility | +| Path | Responsibility | | --- | --- | -| `lib.rs` | Tauri commands, session registry, password resolution | -| `window.rs` | The main window starts hidden and is shown once the page has painted (`window_painted`), with a five-second fallback; `tauri.macos.conf.json` keeps the native traffic lights | -| `profiles.rs` | `connections.json` in the user config folder; passwords in the keychain (`keyring`) | -| `model.rs` | Serializable types shared with the interface | -| `error.rs` | `AppError` with kind, native code, position, detail and hint | -| `drivers/mod.rs` | `Session` enum that dispatches to each engine | -| `drivers/postgres.rs` | PostgreSQL session on `tokio-postgres` | -| `drivers/pg_value.rs` | Binary decoding of PostgreSQL types into server-style text | -| `drivers/oracle.rs` | Oracle session on the official `oracledb` thin driver | -| `drivers/mysql.rs` | MySQL and MariaDB session on `mysql_async` | -| `drivers/sqlserver.rs` | SQL Server and Azure SQL session on `tiberius` (TDS) | -| `drivers/redis_db.rs` | Redis and Valkey session on `redis-rs` (RESP3) | -| `drivers/sqlite.rs` | SQLite session on `rusqlite` (bundled engine) | -| `drivers/cassandra.rs` | Apache Cassandra session on `scylla` (CQL native protocol); `cassandra_tests.rs` holds its tests against a real server | -| `mcp/` | `lowquery mcp`: MCP server over stdio for AI agents (`server.rs` protocol and sessions, `tools.rs`, `guard.rs` statement checks, `catalog.rs` search/foreign keys/plans per engine, `audit.rs` activity log); see [AI.md](AI.md) | -| `transfer/` | Export to SQL, CSV and JSON and import from CSV and JSON (`export.rs`, `import.rs`, `sql.rs` literals, `catalog.rs` generated and identity columns, foreign key order) | -| `ai_setup.rs` | The MCP command and the configuration of each AI client | -| `import/` | Reads connection files of DBeaver, DataGrip, pgAdmin 4 and SQL Developer (`jdbc.rs` parses JDBC URLs); passwords go from the file to the keychain without reaching the interface | -| `drivers/tns.rs` | Finds and parses `tnsnames.ora` (TNS_ADMIN, ORACLE_HOME, Windows registry, clients on PATH) | -| `drivers/integration_tests.rs` | Tests against real servers (`#[ignore]`, see CONTRIBUTING) | -| `drivers/view_fixtures.rs`, `drivers/ddl_fixtures.rs` | Run the SQL the interface writes (grid sort and filter, tree actions) against each real database | +| `main.go` | Starts Wails with the embedded `dist/` and one bound service; `lowquery mcp` serves MCP before Wails starts. The frameless main window starts hidden and is shown once the page has painted (`window_painted`), with a five-second fallback; on macOS the hidden-inset title bar keeps the traffic lights | +| `app/` | The backend the interface calls: one bound method, `Service.Invoke(cmd, args)`, dispatches to a handler per command (the names `api.ts` uses); the session registry; password resolution (typed now, credential store, or none); events to the interface (`transfer-progress`, `update-progress`, `app-menu`) | +| `model/` | Types shared with the interface; their JSON shape is the contract with `src/lib/api.ts` | +| `apperr/` | The error every command returns: kind, native code, position, detail and hint | +| `profiles/` | `connections.json` in the user config folder; passwords in Windows Credential Manager, the macOS Keychain or the Secret Service, under the same names the earlier releases used | +| `engines/` | Opens a session with the driver of a profile's engine | +| `drivers/drivers.go` | The `Session` interface every engine implements, `StreamEvent`/`StreamBatch` (500 rows) and `WithFullValues` | +| `drivers/postgres/` | PostgreSQL session on `pgconn` (pgx); `value.go` decodes the binary format into server-style text | +| `drivers/oracle/` | Oracle session on `go-ora`, a pure Go driver, so no Oracle Client is installed; `goora.go` reaches a few unexported driver fields (column descriptions, the network session, the fetch size) by reflection; `tns.go` finds and parses `tnsnames.ora` | +| `drivers/mysql/` | MySQL and MariaDB session: `go-sql-driver/mysql` does the handshake, then `wire.go` speaks the command phase of the protocol | +| `drivers/sqlserver/` | SQL Server and Azure SQL session on `go-mssqldb` (TDS) | +| `drivers/sqlite/` | SQLite session on `ncruces/go-sqlite3` (SQLite compiled to Wasm and translated to Go, no cgo) | +| `drivers/redis/` | Redis and Valkey session on `go-redis` | +| `drivers/cassandra/` | Apache Cassandra session on `gocql` (`apache/cassandra-gocql-driver/v2`) | +| `drivers/fixtures/` | Runs the SQL the interface writes (grid sort and filter, tree actions) against each real database | +| `mcp/` | `lowquery mcp`: MCP server over stdio for AI agents (`server.go` protocol and sessions, `tools.go`, `guard.go` statement checks, `catalog.go` search/foreign keys/plans per engine, `audit.go` activity log); see [AI.md](AI.md) | +| `transfer/` | Export to SQL, CSV and JSON and import from CSV and JSON (`export.go`, `import.go`, `sql.go` literals, `catalog.go` generated and identity columns, foreign key order) | +| `aisetup/` | The MCP command and the configuration of each AI client | +| `importers/` | Reads connection files of DBeaver, DataGrip, pgAdmin 4 and SQL Developer (`jdbc.go` parses JDBC URLs); passwords go from the file to the credential store without reaching the interface | +| `ojson/` | JSON objects that keep their key order (connection order, other programs' configuration files) | +| `textcodec/` | Reads text files as UTF-8, UTF-16 with a BOM, or Windows-1252 | +| `updater/` | Self-update from GitHub Releases (see [Updates](#updates)) | +| `legacystore/` | Reads the localStorage the Tauri builds kept (editor drafts, export preferences, sidebar width) from the WebView2 LevelDB or the WebKit SQLite files, from a temporary copy; the interface imports the missing entries once (`legacy_storage`, `src/lib/legacy-storage.ts`) | +| `menubar/` | Turns the menus the page describes (`set_app_menu`) into the native macOS menu bar; clicks come back as `app-menu` events. Windows and Linux keep the menus in the title bar | +| `tools/updatesign/` | Signs release files for the updater, writing the same `.sig` as `tauri signer sign` | + +Driver tests against real servers live next to each driver (`integration_test.go`) and skip unless the engine's `LQ__*` variables are set (see CONTRIBUTING). ### PostgreSQL -- Each statement is prepared first, which gives column types without executing it. -- Statements that return rows run inside a short transaction through a portal with `max_rows`, then the transaction commits. In manual-commit mode the portal runs inside the user's transaction. +- `pgconn` speaks the extended query protocol. Each statement is prepared first, which gives column types without executing it. +- Statements that return rows run through a portal executed with a row limit (`max_rows` = limit + 1), so the server stops at the limit. In autocommit mode the portal runs in the implicit transaction of its own Sync; in manual-commit mode it runs inside the user's transaction. +- Results arrive in binary format and are formatted the way the server prints them. - An error inside a manual transaction rolls it back explicitly, since PostgreSQL rejects every later statement in that transaction anyway. - Utility commands that cannot run in a transaction block (`VACUUM`, `CREATE DATABASE`, `... CONCURRENTLY`) always run outside one. -- The connection task collects NOTICE/WARNING messages; cancel uses the server's cancel protocol over a separate connection. +- NOTICE/WARNING messages are collected and returned with the result. Cancel uses the server's cancel protocol over a separate connection; if the server does not stop within 15 seconds, the connection is cut. ### Oracle -- The `oracledb` crate is Oracle's pure-Rust thin driver, so no Oracle Client is installed. It is synchronous; every call runs in `spawn_blocking`. -- `prefetch_rows` and `fetch_array_size` are sized from the row limit, and reading stops at the limit. +- `go-ora` is a pure Go implementation of the Oracle network protocol, so no Oracle Client is installed. +- The fetch size is set from the row limit (limit + 1, at most 1000 rows per round trip), and the cursor is closed at the limit without fetching the rest. - SQL statements lose their trailing `;`, PL/SQL keeps it, and a `/` on its own line ends a block, as in SQL*Plus. -- `DBMS_OUTPUT` is enabled when the session opens and read after each non-query statement. -- The driver cannot interrupt a running call yet; a script stops before the next statement instead. -- TNS aliases are resolved by `tns.rs`, not by the driver: it searches the same places an Oracle client does plus clients on `PATH` and the Windows registry, reads Latin-1 files, follows `IFILE` and applies `NAMES.DEFAULT_DOMAIN`. The driver receives the full descriptor and the folder, which it still uses for `sqlnet.ora`. +- `go-ora` never commits on its own: with autocommit on, the session commits after DML and PL/SQL. +- `DBMS_OUTPUT` is enabled when the session opens. After each non-query statement an anonymous block calls `DBMS_OUTPUT.GET_LINE` in a loop and returns the lines through out binds (up to 5000 lines). +- Cancel cancels the call's context: the server receives a break and stops the running statement or fetch with ORA-01013, and the session stays usable. If the driver loses track of the server's reply, the session reconnects; an open transaction is lost and the error says so. +- TNS aliases are resolved by `tns.go`, not by the driver: it searches the same places an Oracle client does plus clients on `PATH` and the Windows registry, reads Latin-1 files, follows `IFILE` and applies `NAMES.DEFAULT_DOMAIN`. The driver receives the full descriptor. ### MySQL and MariaDB -- Statements use the text protocol, so the server formats every value; binary-charset columns are shown as hex. -- Row-returning statements run with `sql_select_limit` set to the limit and restored afterwards. +- `go-sql-driver/mysql` only opens the connection (dial, TLS, authentication). The session then takes over the network connection and speaks the command phase itself (`wire.go`), because the driver does not expose column origins, status flags or warning counts. +- Statements use the text protocol, so the server formats every value; binary-charset columns are shown as `0x...`. +- Row-returning statements run with `sql_select_limit` set to the limit + 1 and restored afterwards. - Transaction state comes from the server status flags of the last OK packet. -- Warnings are read with `SHOW WARNINGS`; cancel sends `KILL QUERY` from a short-lived second connection. +- Warnings are read with `SHOW WARNINGS` when a statement reports any; cancel sends `KILL QUERY` from a short-lived second connection. ### SQL Server - Each call is one batch (`GO` splits them in the interface), so `#temp` tables, `USE` and `SET` persist. -- Plain `SELECT`/`WITH` batches run with `SET ROWCOUNT`; others stop reading at the limit. +- `go-mssqldb` runs in message mode: result sets come one at a time, and `PRINT` and `RAISERROR` below severity 11 arrive as messages, shown as notices. A statement error does not stop the batch; the first error is reported once the whole response is read. +- Plain `SELECT`/`WITH` batches run with `SET ROWCOUNT` (limit + 1). Other batches keep the first result set up to the limit and read the rest of the response so the connection stays in sync. - Manual commit mode uses `SET IMPLICIT_TRANSACTIONS ON`, and `@@TRANCOUNT`/`XACT_STATE()` after each call drive the transaction indicator. -- Cancel sends a TDS attention. The driver does not expose `PRINT` messages yet. +- Windows authentication (SSPI, the signed-in account) is available when LowQuery runs on Windows; otherwise the driver signs in with user and password. +- Cancel sends a TDS attention through the call's context. If the server does not acknowledge it, the connection is reopened. ### SQLite -- The connection lives behind a mutex and every call runs in `spawn_blocking`; cancel uses `sqlite3_interrupt`. +- `ncruces/go-sqlite3` runs SQLite without cgo. The connection is used by one call at a time; the row limit stops stepping at limit + 1. +- Cancel cancels the connection's interrupt context, which SQLite checks from its progress handler while a statement runs. - Manual commit mode opens `BEGIN` before the first statement; the indicator follows `sqlite3_get_autocommit`. ### Redis -- Redis is not SQL: each editor line is one redis-cli command, split into arguments with redis-cli quoting rules and sent as is. -- Replies keep their RESP3 types and are laid out as tables: scalars as one value, maps as field/value, arrays of pairs as columns, `INFO` as section/key/value rows. +- Redis is not SQL: each editor line is one redis-cli command, split into arguments with redis-cli quoting rules and sent as is through `go-redis`. +- The connection speaks RESP3 (RESP2 on servers before Redis 6). Replies are parsed from raw RESP, so they keep their types, map order and binary strings, and are laid out as tables: scalars as one value, maps as field/value, arrays of pairs as columns, `INFO` as section/key/value rows. - The tree lists databases (`db0`...) and up to 1000 keys per database with `SCAN` and `TYPE`; ▶ runs the read command that fits the key type. - There is no autocommit: `MULTI` opens a queue that the toolbar's EXEC and DISCARD close. Cancel only works for blocking commands, through `CLIENT UNBLOCK` from a second connection. ### Apache Cassandra -- The `scylla` driver speaks the CQL native protocol to Apache Cassandra 3.x, 4.x and 5.x. Statements are sent as text, unprepared, at consistency `LOCAL_ONE`; contact points are comma separated, and a local datacenter limits requests to its nodes. TLS uses rustls (`prefer` and `require` encrypt without validating the certificate; `verify-full` checks the chain against the system and bundled roots, but not the host name, because the driver connects to the addresses the cluster reports). -- Rows are read with paging: the page size is derived from the row limit and reading stops at `max_rows + 1`. Values keep their exact CQL text; collections, tuples, UDTs and vectors are valid CQL literals, so a cell can be pasted into an `INSERT`. `cql_literal` turns cell text back into a literal per column type (used by grid edits, export and import). +- `gocql` speaks the CQL native protocol to Apache Cassandra 3.x, 4.x and 5.x. Statements are sent as text, unprepared (a `/**/` prefix stops gocql from preparing them), at consistency `LOCAL_ONE`; contact points are comma separated, and a local datacenter limits requests to its nodes. `USE` cannot run on a connection pool, so the session reconnects with the new keyspace. +- TLS: `prefer` tries TLS and falls back to plain TCP; `prefer` and `require` encrypt without validating the certificate; `verify-full` checks the chain against the system roots, but not the host name, because the driver connects to the addresses the cluster reports. +- Rows are read with paging: the page size is derived from the row limit and reading stops at `max_rows + 1`. Values keep their exact CQL text; collections, tuples, UDTs and vectors are valid CQL literals, so a cell can be pasted into an `INSERT`. `CQLLiteral` turns cell text back into a literal per column type (used by grid edits, export and import). - There are no transactions: the session is always in autocommit mode (the interface hides the controls), `BEGIN BATCH ... APPLY BATCH` is one statement, and saving grid edits sends one logged batch. CQL writes are upserts, so an UPDATE or DELETE never reports a missing row. -- CQL has no server-side cancel. Cancel stops waiting (the request future is dropped); the coordinator finishes or times out on its own. +- CQL has no server-side cancel. Cancel stops waiting; the coordinator finishes or times out on its own. - Server warnings arrive as messages, like PostgreSQL notices. - The schema browser reads `system_schema` (and `system_virtual_schema` for the virtual keyspaces of 4.0+): keyspaces are the schemas; tables, materialized views, types, functions and aggregates (named `name(argument types)`, since CQL allows overloads) and indexes are the objects. `DESCRIBE` is a cqlsh command, not part of the protocol, so `object_ddl` builds the `CREATE` statements from the catalog. -- Result editing: a `SELECT` on one table whose columns include the whole primary key (partition and clustering columns); expressions, aliases, counters, materialized views and system tables are read-only. - Imports run one `INSERT` per row without a transaction (multi-partition batches are an anti-pattern in Cassandra), so a failed import leaves the rows already written. ## Interface side (`src`) @@ -106,6 +119,7 @@ LowQuery is a Tauri 2 desktop app. The interface is Svelte 5 with the [CodeAtlas | --- | --- | | `lib/engines/` | Engine registry (name, logo, default port, dialect) used by the picker and the sidebar | | `theme.ts` | LowBloat theme for CodeAtlas: palette, zero radius, no shadows | +| `lib/host.ts` | The desktop host: backend calls (`Call.ByName` on `Service.Invoke`), events, native dialogs and the window, through the Wails runtime | | `lib/api.ts` | Types and `invoke` wrappers for every command | | `lib/sql/split.ts` | Script splitting per dialect: strings, quoted identifiers, nested comments, dollar quotes, `q'[...]'`, PL/SQL blocks | | `lib/sql/ident.ts` | Identifier quoting and preview queries per engine | @@ -118,6 +132,8 @@ LowQuery is a Tauri 2 desktop app. The interface is Svelte 5 with the [CodeAtlas | `lib/state/ai.svelte.ts` | AI agents dialog: client setup and activity | | `lib/state/importer.svelte.ts` | Import dialog: detected tool files, preview, duplicate check | | `lib/state/tns.svelte.ts` | Detected `tnsnames.ora` sources and aliases for the connection and import dialogs | +| `lib/state/updates.svelte.ts` | Update check, download progress and install | +| `lib/legacy-storage.ts` | One-time import of the Tauri builds' localStorage | | `lib/components/` | Editor, grid, results, sidebar, dialogs | | `lib/app-menu.ts`, `lib/components/TitleBar.svelte`, `lib/state/window-frame.svelte.ts` | Title bar and File/Query/View/Help menus (in the title bar on Windows and Linux, in the menu bar on macOS) | | `lib/dev-mock.ts` | Development-only backend for `bun run dev` in a browser | @@ -135,38 +151,59 @@ LowQuery is a Tauri 2 desktop app. The interface is Svelte 5 with the [CodeAtlas | SQLite | The statements kept in `sqlite_schema` for the table, its indexes and triggers | | Apache Cassandra | `system_schema`: `CREATE TABLE` with its primary key, clustering order and options followed by the table's `CREATE INDEX` statements; materialized views, types, functions, aggregates, indexes and keyspaces | -The statements the menus and the table designer run come from `lib/sql/ddl.ts`. They run one at a time on the tree's session (never a tab's, so an open transaction in a tab is not touched), and every one is shown before it runs. `ddl.fixtures.json` holds them for a fixed scenario per dialect; `drivers/ddl_fixtures.rs` runs that scenario on every database in CI, including a round trip of the DDL each driver reads back (drop the object, run its DDL, compare the columns). +The statements the menus and the table designer run come from `lib/sql/ddl.ts`. They run one at a time on the tree's session (never a tab's, so an open transaction in a tab is not touched), and every one is shown before it runs. `lib/sql/ddl.fixtures.json` holds them for a fixed scenario per dialect; `internal/drivers/fixtures` runs that scenario on every database in CI, including a round trip of the DDL each driver reads back (drop the object, run its DDL, compare the columns). ## Export and import -`transfer/` moves data in and out on a session opened for the job, so the tree and the tabs stay usable: +`internal/transfer` moves data in and out on a session opened for the job, so the tree and the tabs stay usable: -- **Reading rows.** `Session::stream` sends the columns and then batches of 500 rows through a channel, straight from each driver's cursor (a PostgreSQL portal in a read-only snapshot, `query_iter` in MySQL, the TDS stream, the Oracle cursor, SQLite steps). Values are formatted as in the grid but in full (`drivers::full_values`: binary values are not cut to the preview size). Dropping the receiver stops the reader; cancel also stops the query on the server. -- **SQL scripts** (`export.rs`, `sql.rs`): the structure comes from `object_ddl`, tables in foreign key order (`catalog.rs`), foreign keys PostgreSQL and SQL Server script as `ALTER TABLE` moved to the end, MySQL wrapped in `FOREIGN_KEY_CHECKS = 0`. Rows become INSERTs with literals each database reads back exactly (`decode(..., 'hex')`, `0x...`, `HEXTORAW`, `X'...'`, `TIMESTAMP '...'`, CLOB pieces in Oracle, backslashes in MySQL), generated columns left out, and identity columns kept: `OVERRIDING SYSTEM VALUE` and `setval` in PostgreSQL, `SET IDENTITY_INSERT` in SQL Server, `START WITH LIMIT VALUE` in Oracle. +- **Reading rows.** `Session.Stream` sends the columns and then batches of `StreamBatch` (500) rows, straight from each driver's cursor (a PostgreSQL portal in a read-only snapshot, the MySQL text protocol, the TDS stream, the Oracle cursor, SQLite steps, Cassandra pages). The export runs it under `drivers.WithFullValues`, so values are formatted as in the grid but in full (binary values are not cut to the preview size). Cancelling the job's context stops the reader; cancel also stops the query on the server through `Session.Cancel`. +- **SQL scripts** (`export.go`, `sql.go`): the structure comes from `object_ddl`, tables in foreign key order (`catalog.go`), foreign keys PostgreSQL and SQL Server script as `ALTER TABLE` moved to the end, MySQL wrapped in `FOREIGN_KEY_CHECKS = 0`. Rows become INSERTs with literals each database reads back exactly (`decode(..., 'hex')`, `0x...`, `HEXTORAW`, `X'...'`, `TIMESTAMP '...'`, CLOB pieces in Oracle, backslashes in MySQL), generated columns left out, and identity columns kept: `OVERRIDING SYSTEM VALUE` and `setval` in PostgreSQL, `SET IDENTITY_INSERT` in SQL Server, `START WITH LIMIT VALUE` in Oracle. - **CSV and JSON**: one file per table; *CSV for Excel* uses `;`, a BOM and CRLF. -- **Import** (`import.rs`): the file is decoded (UTF-8, UTF-16, Windows-1252), the delimiter and header detected, columns matched by name, and values converted for the column type (`1.234,56`, `31/12/2024`, `sim`/`não`). Rows go in batches of INSERTs (the same literal writer) in one transaction. -- `transfer/round_trip.rs` exports a table with awkward values on every database in CI and loads it back from the SQL script, CSV, CSV for Excel and JSON. +- **Import** (`import.go`): the file is decoded (UTF-8, UTF-16, Windows-1252), the delimiter and header detected, columns matched by name, and values converted for the column type (`1.234,56`, `31/12/2024`, `sim`/`não`). Rows go in batches of INSERTs (the same literal writer) in one transaction. +- `roundtrip_test.go` exports a table with awkward values on every database in CI and loads it back from the SQL script, CSV, CSV for Excel and JSON. Scripts are split in the interface so the editor knows where each statement starts. Each statement is a separate command call: results appear as they finish, and an error position maps back to the document. ## Editing results -A result is editable only when the driver can prove which table row each grid row is. Every driver answers that in `execute` by setting `ExecResult.editable` (table, the table column behind each result column or `null` for expressions, and the result columns that hold the key) or `readOnlyReason`. The key is the primary key, otherwise a unique key whose columns are all NOT NULL. Detection never fails a query and costs at most one extra round trip, usually cached per table on the session. +A result is editable only when the driver can prove which table row each grid row is. Every driver answers that in `Execute` by setting `ExecResult.editable` (table, the table column behind each result column or `null` for expressions, and the result columns that hold the key) or `readOnlyReason`. The key is the primary key, otherwise a unique key whose columns are all NOT NULL. Detection never fails a query and costs at most one extra round trip, usually cached per table on the session. | Database | Where the source table comes from | Why a result is read-only | | --- | --- | --- | -| PostgreSQL | `table_oid`/`column_id` of the prepared statement; key and types from `pg_index`/`format_type` | Several tables, any join (a self-join reports one OID), UNION, views | -| Oracle | The SQL is read by a small parser that accepts `SELECT columns FROM table [alias] [WHERE/ORDER BY/FETCH]` only; the names are checked against the result metadata and resolved in the dictionary like Oracle does (schema, then public synonym) | Joins, subqueries, WITH, GROUP BY, set operators, views, database links | -| MySQL, MariaDB | `org_table`/`org_name`/`schema` of each column plus the alias; key from `information_schema` | Several tables or aliases, set operators, views, temporary tables | -| SQL Server | `sys.dm_exec_describe_first_result_set` in browse mode, with the keys from `sys.indexes` in the same batch | Several tables or the same table twice, computed and rowversion columns, temp tables | +| PostgreSQL | Table OID and attribute number of each column in the row description; key and types from `pg_index`/`format_type` | Several tables, any join (a self-join reports one OID), UNION, views | +| Oracle | The SQL is read by a small parser that accepts `SELECT columns FROM [schema.]table [alias] [WHERE/ORDER BY/FETCH/OFFSET/FOR]` only; the names are checked against the result columns and resolved in the dictionary like Oracle does (schema, then public synonym) | Joins, subqueries in FROM, WITH, DISTINCT, GROUP BY, set operators, hierarchical queries, views, database links | +| MySQL, MariaDB | `org_table`/`org_name`/`schema` of each column plus the alias, read by `wire.go`; key from `information_schema` | Several tables or aliases, set operators, views, temporary tables | +| SQL Server | `sys.dm_exec_describe_first_result_set` in browse mode, with the keys from `sys.indexes` in the same batch | Several tables or the same table twice, a table in another database, set operators; computed and rowversion columns are not editable | | SQLite | Column metadata (`sqlite3_column_table_name`) checked against `EXPLAIN QUERY PLAN`; `rowid` works as the key of a table without one | Compound selects, more than one table scan, results without the key | -| Apache Cassandra | The table of each result column (the result metadata names it); keys from `system_schema.columns` | Several tables, aliases, counters, views, system tables, results without the whole primary key | +| Apache Cassandra | The table of each result column (the result metadata names it); keys from `system_schema.columns` | Several tables, aliases, counters, materialized views, system tables, results without the whole primary key | `apply_changes` receives the target and a list of updates (old key plus new values), deletes and inserts. Each driver builds one statement per change with quoted, schema-qualified names and binds every value, converting the text the grid shows back into the column type the engine's own way (typed binds or explicit conversions that do not depend on session date or number formats). Every UPDATE and DELETE must touch exactly one row. With autocommit on the whole save is one transaction; inside an open transaction it runs behind a savepoint, so a failed save is undone without losing earlier work. After saving, the interface runs the query again to show what the database now holds. +## Updates + +`internal/updater` reads the same `latest.json` manifest and trusts the same minisign public key as the Tauri builds, so Tauri installs and Go installs update from one release. + +- `updater.Detect` works out whether this copy can install updates: the Windows setup, a macOS `.app` in a writable folder, a writable AppImage, or a `.deb`/`.rpm` install. The Arch package and portable copies are only told that a new version exists. +- The package for this platform is downloaded and its signature checked: a Tauri signature (base64 of a minisign signature) whose trusted comment, when it names a version, must match the announced one. The signature is checked again just before install. +- Install: on Windows the NSIS setup runs with `/P /UPDATE /R` and the app quits; on macOS the new bundle replaces the old one; on Linux the AppImage is replaced, or the `.deb`/`.rpm` goes to `dpkg`/`rpm` through `pkexec`. The app then restarts. +- `tools/updatesign` signs the release files with the key in `TAURI_SIGNING_PRIVATE_KEY` and refuses a key that does not match `updater.PublicKey` unless `-any-key` is given. The release workflow runs it on every updater file. + +## Packaging (`packaging/`) + +| Path | Responsibility | +| --- | --- | +| `common.sh` | Shared by the build scripts: version, output folders (`build/release/`), the `wails3` tool matching `go.mod` | +| `windows/` | NSIS setup (`installer.nsi`) and portable zip; the setup installs over a Tauri install in place and keeps its layout and registry values | +| `macos/` | Universal, ad-hoc signed `LowQuery.app`, as `.app.tar.gz` for the updater and as a `.dmg` | +| `linux/` | `.deb` and `.rpm` (nfpm, same package name and files as the Tauri packages), AppImage and portable `.tar.gz` | +| `arch/` | pacman package built with `makepkg` in an Arch container, and the PKGBUILD template for releases | +| `test/` | `mcp-smoke.sh` checks that `lowquery mcp` answers over stdio; `windows-upgrade.ps1` installs the Tauri setup, upgrades it with the new one and uninstalls, in CI | +| `icons/` | App icons | + ## Adding a database engine 1. Open a [database support issue](https://github.com/LowBloat/LowQuery/issues/new?template=database_support.yml) describing the driver and the engine conventions to follow. -2. Add a module in `src-tauri/src/drivers/` that implements connect, execute (with a server-side row limit), transactions, cancel when the protocol allows it, the metadata queries, and result editing (or a read-only reason for every result); add a variant to `Session`. -3. Add the engine to `Engine` in `model.rs` and `api.ts`, its connection fields to the dialog, its dialect to `split.ts` and the editor, and its quoting rules to `ident.ts`. -4. Add integration tests and a CI job with the engine in a container. +2. Add a package under `internal/drivers/` that implements `drivers.Session`: connect, execute (with a server-side row limit), transactions, cancel when the protocol allows it, the metadata queries, `Stream`, and result editing (or a read-only reason for every result). Add a case to `engines.Open` in `internal/engines`. +3. Add the engine to `Engine` in `internal/model` and in the interface (`src/lib/engines/`, re-exported by `src/lib/api.ts`), its connection fields to the dialog, its dialect to `split.ts` and the editor, and its quoting rules to `ident.ts`. +4. Add integration tests that skip unless the engine's `LQ__*` variables are set, and a CI job that runs them with the engine in a container. diff --git a/go.mod b/go.mod index 6cb8533..c224a13 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/LowBloat/LowQuery -go 1.26.4 +go 1.26.11 require ( github.com/apache/cassandra-gocql-driver/v2 v2.2.0 @@ -19,6 +19,7 @@ require ( ) require ( + aead.dev/minisign v0.3.0 filippo.io/edwards25519 v1.2.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/coder/websocket v1.8.14 // indirect @@ -26,11 +27,13 @@ require ( github.com/go-ole/go-ole v1.3.0 // indirect github.com/godbus/dbus/v5 v5.2.2 // indirect github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect + github.com/golang/snappy v0.0.4 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/ncruces/go-sqlite3-wasm/v6 v6.7.35401 // indirect github.com/ncruces/julianday v1.0.0 // indirect github.com/shopspring/decimal v1.4.0 // indirect + github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d go.uber.org/atomic v1.12.0 // indirect golang.org/x/crypto v0.59.0 // indirect golang.org/x/term v0.48.0 // indirect diff --git a/go.sum b/go.sum index 4b9f54c..1a0bef5 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +aead.dev/minisign v0.3.0 h1:8Xafzy5PEVZqYDNP60yJHARlW1eOQtsKNp/Ph2c0vRA= +aead.dev/minisign v0.3.0/go.mod h1:NLvG3Uoq3skkRMDuc3YHpWUTMTrSExqm+Ij73W13F6Y= filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1 h1:zvXfGJCWvywnCA814d8ZiVyt+fm9nnTE8xSb99zRyfo= @@ -20,17 +22,27 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g= github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0= github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= github.com/go-sql-driver/mysql v1.11.0 h1:0dFnuu2mR7g+8Smo/rL18y1WnTLgVrHttzSahf20Gb4= github.com/go-sql-driver/mysql v1.11.0/go.mod h1:evJsoGjlO/9BFsnfXyjtluDYb3OSGzPNOnUaBl/2Dao= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ= github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= @@ -39,10 +51,26 @@ github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0kt github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A= github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= @@ -69,6 +97,20 @@ github.com/ncruces/go-sqlite3-wasm/v6 v6.7.35401 h1:BlrYMg6wi+S0oxZ8IeGMHXi2nfjK github.com/ncruces/go-sqlite3-wasm/v6 v6.7.35401/go.mod h1:K/Z0eKUURoWW9cJ9rHeMGDF0G4pr0A6WizdC+Ohzj54= github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M= github.com/ncruces/julianday v1.0.0/go.mod h1:Dusn2KvZrrovOMJuOt0TNXL6tB7U2E8kvza5fFc9G7g= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= +github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw= +github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= github.com/pierrec/lz4/v4 v4.1.27 h1:+PhzhWDrjRj89TH2sw43nE3+4+W8lSxIuQadEHZyjUk= github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= @@ -86,11 +128,16 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d h1:vfofYNRScrDdvS342BElfbETmL1Aiz3i2t0zfRj16Hs= +github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d/go.mod h1:RRCYJbIwD5jmqPI9XoAFR0OcDxqUctll6zUj/+B4S48= github.com/wailsapp/wails/v3 v3.1.0 h1:ld0AXSicXiTTsIvmTq3qNn9FzCP8vIHRSJdkRLgaAo8= github.com/wailsapp/wails/v3 v3.1.0/go.mod h1:tzDY3W1jzN3ksSqfGalTt7K3PwnGfIqtl+IgIXlXz0I= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs= github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0= github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= @@ -103,20 +150,82 @@ go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= +golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/app/app.go b/internal/app/app.go index 4611b74..33ff1f7 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -24,7 +24,13 @@ type App struct { profiles *profiles.Store window Window emit func(event string, data any) - jobs transfer.Jobs + quit func() + + menuMu sync.Mutex + menuBar func([]MenuNode) + + update updateState + jobs transfer.Jobs mu sync.RWMutex sessions map[string]drivers.Session @@ -52,6 +58,10 @@ func (a *App) SetWindow(w Window) { a.window = w } // (transfer progress, for example). func (a *App) SetEmitter(emit func(event string, data any)) { a.emit = emit } +// SetQuit connects the function that closes the app (to let an installer +// replace it, for example). +func (a *App) SetQuit(quit func()) { a.quit = quit } + // Emit sends an event to the interface; without an emitter it does nothing. func (a *App) Emit(event string, data any) { if a.emit != nil { diff --git a/internal/app/commands.go b/internal/app/commands.go index f55a80e..e0a0748 100644 --- a/internal/app/commands.go +++ b/internal/app/commands.go @@ -192,17 +192,11 @@ func (a *App) commands() map[string]handler { }) (any, error) { return nil, revealInFolder(p.Path) }), - // Self-update arrives with the installers; until then this build - // only learns about new versions. - "update_policy": command(func(ctx context.Context, _ none) (map[string]any, error) { - return map[string]any{"channel": "portable", "canInstall": false, "target": nil}, nil - }), - "update_check": command(func(ctx context.Context, _ none) (*availableUpdate, error) { - return a.checkUpdate(ctx) - }), } a.transferCommands(m) a.integrationCommands(m) + a.updateCommands(m) + a.desktopCommands(m) return m } diff --git a/internal/app/desktop_commands.go b/internal/app/desktop_commands.go new file mode 100644 index 0000000..2fc87f1 --- /dev/null +++ b/internal/app/desktop_commands.go @@ -0,0 +1,26 @@ +package app + +import ( + "context" + + "github.com/LowBloat/LowQuery/internal/legacystore" +) + +// desktopCommands adds commands for the desktop shell: the macOS menu bar +// and the editor drafts kept by the previous (Tauri) builds. +func (a *App) desktopCommands(m map[string]handler) { + // set_app_menu {about: {id, label}, menus: [{label, entries: [{id, label, + // accelerator?, disabled?, checked?} | {separator: true}]}]} replaces the + // macOS menu bar; clicks come back as the app-menu event, {id}. Does + // nothing on Windows and Linux. + m["set_app_menu"] = command(func(ctx context.Context, d MenuBarDescription) (any, error) { + a.applyMenuBar(d) + return nil, nil + }) + // legacy_storage returns {key: value} for the localStorage entries the + // Tauri builds kept (drafts, export preferences, sidebar width), {} when + // there are none. It never fails. + m["legacy_storage"] = command(func(ctx context.Context, _ none) (map[string]string, error) { + return legacystore.Read(), nil + }) +} diff --git a/internal/app/menu.go b/internal/app/menu.go new file mode 100644 index 0000000..c423d56 --- /dev/null +++ b/internal/app/menu.go @@ -0,0 +1,217 @@ +package app + +import ( + "log" + "strconv" + "strings" + "unicode" +) + +// The macOS menu bar. The interface describes its menus (set_app_menu) and +// sends the description again whenever their state changes; the shell +// replaces the native menu bar with the MenuNode tree BuildMenuBar makes and +// reports clicks as MenuEvent with the entry's id. Windows and Linux keep the +// menus the page draws in its title bar, and have no menu bar to set. + +// MenuEvent is emitted with a MenuClick when an entry of the menu bar is +// chosen. +const MenuEvent = "app-menu" + +// MenuClick is the payload of MenuEvent. +type MenuClick struct { + ID string `json:"id"` +} + +// MenuBarDescription is what set_app_menu receives: the About item and the +// app's own menus, which go between the standard Edit and Window menus. +type MenuBarDescription struct { + About MenuEntryDescription `json:"about"` + Menus []MenuDescription `json:"menus"` +} + +type MenuDescription struct { + Label string `json:"label"` + Entries []MenuEntryDescription `json:"entries"` +} + +// MenuEntryDescription is an item, a check box (Checked set) or a separator. +type MenuEntryDescription struct { + Separator bool `json:"separator,omitempty"` + ID string `json:"id,omitempty"` + Label string `json:"label,omitempty"` + // Accelerator in Wails notation: "CmdOrCtrl+Shift+Enter", "F5". + Accelerator string `json:"accelerator,omitempty"` + Disabled bool `json:"disabled,omitempty"` + Checked *bool `json:"checked,omitempty"` +} + +type MenuKind int + +const ( + MenuItemKind MenuKind = iota + MenuCheckboxKind + MenuSeparatorKind + MenuSubmenuKind + // MenuRoleKind is a standard item the system implements (Copy, Hide, + // Quit, ...). + MenuRoleKind +) + +// MenuRole names a standard item of the macOS menu bar. +type MenuRole string + +const ( + RoleServices MenuRole = "services" + RoleHide MenuRole = "hide" + RoleHideOthers MenuRole = "hideOthers" + RoleShowAll MenuRole = "showAll" + RoleQuit MenuRole = "quit" + RoleUndo MenuRole = "undo" + RoleRedo MenuRole = "redo" + RoleCut MenuRole = "cut" + RoleCopy MenuRole = "copy" + RolePaste MenuRole = "paste" + RoleSelectAll MenuRole = "selectAll" + RoleMinimise MenuRole = "minimise" + RoleZoom MenuRole = "zoom" + RoleFullscreen MenuRole = "fullscreen" + RoleBringAllToFront MenuRole = "bringAllToFront" +) + +// MenuNode is one entry of the native menu bar, independent of the toolkit. +type MenuNode struct { + Kind MenuKind + Role MenuRole + ID string + Label string + Accelerator string + Disabled bool + Checked bool + Children []MenuNode +} + +func roleNode(r MenuRole) MenuNode { return MenuNode{Kind: MenuRoleKind, Role: r} } + +var separatorNode = MenuNode{Kind: MenuSeparatorKind} + +// BuildMenuBar makes the macOS menu bar: the application menu (About, +// Services, Hide, Quit), the standard Edit menu, so Command+C and friends +// keep working in text fields, the described menus, and the standard Window +// menu. +func BuildMenuBar(appName string, d MenuBarDescription) []MenuNode { + var appMenu []MenuNode + if d.About.ID != "" { + label := d.About.Label + if label == "" { + label = "About " + appName + } + appMenu = append(appMenu, MenuNode{Kind: MenuItemKind, ID: d.About.ID, Label: label}, separatorNode) + } + appMenu = append(appMenu, + roleNode(RoleServices), separatorNode, + roleNode(RoleHide), roleNode(RoleHideOthers), roleNode(RoleShowAll), separatorNode, + roleNode(RoleQuit)) + + bar := []MenuNode{ + {Kind: MenuSubmenuKind, Label: appName, Children: appMenu}, + {Kind: MenuSubmenuKind, Label: "Edit", Children: []MenuNode{ + roleNode(RoleUndo), roleNode(RoleRedo), separatorNode, + roleNode(RoleCut), roleNode(RoleCopy), roleNode(RolePaste), roleNode(RoleSelectAll), + }}, + } + for _, m := range d.Menus { + if strings.TrimSpace(m.Label) == "" { + continue + } + bar = append(bar, MenuNode{Kind: MenuSubmenuKind, Label: m.Label, Children: menuEntries(m.Entries)}) + } + return append(bar, MenuNode{Kind: MenuSubmenuKind, Label: "Window", Children: []MenuNode{ + roleNode(RoleMinimise), roleNode(RoleZoom), roleNode(RoleFullscreen), separatorNode, + roleNode(RoleBringAllToFront), + }}) +} + +// menuEntries translates described entries, dropping those without an id +// or label and separators at the edges or next to each other. +func menuEntries(entries []MenuEntryDescription) []MenuNode { + out := []MenuNode{} + for _, e := range entries { + if e.Separator { + if len(out) > 0 && out[len(out)-1].Kind != MenuSeparatorKind { + out = append(out, separatorNode) + } + continue + } + if e.ID == "" || e.Label == "" { + continue + } + n := MenuNode{Kind: MenuItemKind, ID: e.ID, Label: e.Label, Disabled: e.Disabled} + if e.Checked != nil { + n.Kind = MenuCheckboxKind + n.Checked = *e.Checked + } + if e.Accelerator != "" { + if ValidAccelerator(e.Accelerator) { + n.Accelerator = e.Accelerator + } else { + log.Printf("menu %q: ignoring invalid accelerator %q", e.Label, e.Accelerator) + } + } + out = append(out, n) + } + for len(out) > 0 && out[len(out)-1].Kind == MenuSeparatorKind { + out = out[:len(out)-1] + } + return out +} + +// Modifiers and named keys Wails accepts in an accelerator +// (pkg/application/keys.go); it reports any other as an error. +var ( + acceleratorModifiers = map[string]bool{ + "cmdorctrl": true, "cmd": true, "command": true, "ctrl": true, + "optionoralt": true, "alt": true, "option": true, "shift": true, "super": true, + } + acceleratorKeys = map[string]bool{ + "plus": true, "backspace": true, "tab": true, "return": true, "enter": true, + "escape": true, "left": true, "right": true, "up": true, "down": true, + "space": true, "delete": true, "forward delete": true, "home": true, + "end": true, "page up": true, "page down": true, "numlock": true, + } +) + +// ValidAccelerator reports whether Wails can parse s: modifiers joined by +// "+", then a named key, a function key F1-F35 or one printable character. +func ValidAccelerator(s string) bool { + parts := strings.Split(s, "+") + for _, m := range parts[:len(parts)-1] { + if !acceleratorModifiers[strings.ToLower(m)] { + return false + } + } + key := strings.ToLower(parts[len(parts)-1]) + if acceleratorKeys[key] { + return true + } + if n, err := strconv.Atoi(strings.TrimPrefix(key, "f")); err == nil && strings.HasPrefix(key, "f") && n >= 1 && n <= 35 && !strings.HasPrefix(key, "f0") { + return true + } + return len(key) == 1 && unicode.IsPrint(rune(key[0])) +} + +// SetMenuBar connects the function that replaces the native menu bar. main.go +// sets it on macOS; elsewhere it stays nil and set_app_menu does nothing. +func (a *App) SetMenuBar(set func([]MenuNode)) { + a.menuMu.Lock() + a.menuBar = set + a.menuMu.Unlock() +} + +func (a *App) applyMenuBar(d MenuBarDescription) { + a.menuMu.Lock() + set := a.menuBar + a.menuMu.Unlock() + if set != nil { + set(BuildMenuBar("LowQuery", d)) + } +} diff --git a/internal/app/menu_test.go b/internal/app/menu_test.go new file mode 100644 index 0000000..d73e8bb --- /dev/null +++ b/internal/app/menu_test.go @@ -0,0 +1,165 @@ +package app + +import ( + "context" + "encoding/json" + "reflect" + "testing" +) + +func labels(nodes []MenuNode) []string { + out := make([]string, len(nodes)) + for i, n := range nodes { + switch n.Kind { + case MenuSeparatorKind: + out[i] = "-" + case MenuRoleKind: + out[i] = "role:" + string(n.Role) + default: + out[i] = n.Label + } + } + return out +} + +// The description the interface sends (src/lib/app-menu.ts). +const description = `{ + "about": {"id": "about", "label": "About LowQuery"}, + "menus": [ + {"label": "File", "entries": [ + {"separator": true}, + {"id": "file/New query", "label": "New query", "accelerator": "CmdOrCtrl+T"}, + {"separator": true}, + {"separator": true}, + {"id": "file/Close tab", "label": "Close tab", "accelerator": "CmdOrCtrl+W", "disabled": true}, + {"id": "file/Bad", "label": "Bad", "accelerator": "Hyper+K"}, + {"id": "", "label": "No id"}, + {"separator": true} + ]}, + {"label": "Query", "entries": [ + {"id": "query/Run script", "label": "Run script", "accelerator": "F5"}, + {"id": "query/Run statement", "label": "Run statement", "accelerator": "CmdOrCtrl+Enter"}, + {"id": "query/Auto-commit", "label": "Auto-commit", "checked": true, "disabled": true}, + {"id": "query/Off", "label": "Off", "checked": false} + ]}, + {"label": "", "entries": []} + ] +}` + +func TestBuildMenuBar(t *testing.T) { + var d MenuBarDescription + if err := json.Unmarshal([]byte(description), &d); err != nil { + t.Fatal(err) + } + bar := BuildMenuBar("LowQuery", d) + if got, want := labels(bar), []string{"LowQuery", "Edit", "File", "Query", "Window"}; !reflect.DeepEqual(got, want) { + t.Fatalf("menus %q, want %q", got, want) + } + for _, m := range bar { + if m.Kind != MenuSubmenuKind { + t.Errorf("%s is not a submenu", m.Label) + } + } + if got, want := labels(bar[0].Children), []string{"About LowQuery", "-", "role:services", "-", "role:hide", "role:hideOthers", "role:showAll", "-", "role:quit"}; !reflect.DeepEqual(got, want) { + t.Errorf("app menu %q, want %q", got, want) + } + if bar[0].Children[0].ID != "about" { + t.Errorf("about id %q", bar[0].Children[0].ID) + } + if got, want := labels(bar[1].Children), []string{"role:undo", "role:redo", "-", "role:cut", "role:copy", "role:paste", "role:selectAll"}; !reflect.DeepEqual(got, want) { + t.Errorf("edit menu %q, want %q", got, want) + } + if got, want := labels(bar[4].Children), []string{"role:minimise", "role:zoom", "role:fullscreen", "-", "role:bringAllToFront"}; !reflect.DeepEqual(got, want) { + t.Errorf("window menu %q, want %q", got, want) + } + + file := bar[2].Children + wantFile := []MenuNode{ + {Kind: MenuItemKind, ID: "file/New query", Label: "New query", Accelerator: "CmdOrCtrl+T"}, + separatorNode, + {Kind: MenuItemKind, ID: "file/Close tab", Label: "Close tab", Accelerator: "CmdOrCtrl+W", Disabled: true}, + // An accelerator Wails cannot parse is dropped, not the item. + {Kind: MenuItemKind, ID: "file/Bad", Label: "Bad"}, + } + if !reflect.DeepEqual(file, wantFile) { + t.Errorf("file menu\n%+v\nwant\n%+v", file, wantFile) + } + query := bar[3].Children + wantQuery := []MenuNode{ + {Kind: MenuItemKind, ID: "query/Run script", Label: "Run script", Accelerator: "F5"}, + {Kind: MenuItemKind, ID: "query/Run statement", Label: "Run statement", Accelerator: "CmdOrCtrl+Enter"}, + {Kind: MenuCheckboxKind, ID: "query/Auto-commit", Label: "Auto-commit", Checked: true, Disabled: true}, + {Kind: MenuCheckboxKind, ID: "query/Off", Label: "Off"}, + } + if !reflect.DeepEqual(query, wantQuery) { + t.Errorf("query menu\n%+v\nwant\n%+v", query, wantQuery) + } +} + +func TestBuildMenuBarWithoutAbout(t *testing.T) { + bar := BuildMenuBar("LowQuery", MenuBarDescription{}) + if got := labels(bar[0].Children)[0]; got != "role:services" { + t.Errorf("first app menu item %q", got) + } + if len(bar) != 3 { + t.Errorf("%d menus", len(bar)) + } +} + +func TestValidAccelerator(t *testing.T) { + for s, want := range map[string]bool{ + "CmdOrCtrl+T": true, + "CmdOrCtrl+Shift+Enter": true, + "F5": true, + "F35": true, + "F36": false, + "F0": false, + "f": true, + "Alt+Page Up": true, + "Ctrl+Plus": true, + "CmdOrCtrl+": false, + "Hyper+K": false, + "PageUp": false, + "": false, + } { + if got := ValidAccelerator(s); got != want { + t.Errorf("%q: %v, want %v", s, got, want) + } + } +} + +func TestSetAppMenuCommand(t *testing.T) { + a := New("test", nil) + var got []MenuNode + a.SetMenuBar(func(nodes []MenuNode) { got = nodes }) + defer a.SetMenuBar(nil) + h := a.commands()["set_app_menu"] + if _, err := h(context.Background(), json.RawMessage(description)); err != nil { + t.Fatal(err) + } + if len(got) != 5 || got[3].Label != "Query" { + t.Fatalf("menu bar %q", labels(got)) + } + // Without a menu bar (Windows, Linux) the command does nothing. + a.SetMenuBar(nil) + if _, err := h(context.Background(), json.RawMessage(description)); err != nil { + t.Fatal(err) + } +} + +func TestLegacyStorageCommand(t *testing.T) { + // Point every OS's lookup at an empty folder: no old install, {}. + empty := t.TempDir() + t.Setenv("LOCALAPPDATA", empty) + t.Setenv("HOME", empty) + t.Setenv("USERPROFILE", empty) + t.Setenv("XDG_DATA_HOME", empty) + out, err := New("test", nil).commands()["legacy_storage"](context.Background(), nil) + if err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(out) + if string(b) != "{}" { + t.Fatalf("got %s", b) + } +} diff --git a/internal/app/update_commands.go b/internal/app/update_commands.go new file mode 100644 index 0000000..155cc9e --- /dev/null +++ b/internal/app/update_commands.go @@ -0,0 +1,36 @@ +package app + +import ( + "context" + + "github.com/LowBloat/LowQuery/internal/updater" +) + +// updateCommands adds the self-update commands: +// +// update_policy -> {channel, canInstall, target} +// update_check -> {version, notes} | null +// update_download {version} -> {version, notes}, with `update-progress` +// events {version, received, total|null} +// update_install -> null; the app restarts +// update_cancel -> null; stops a running download +func (a *App) updateCommands(m map[string]handler) { + m["update_policy"] = command(func(ctx context.Context, _ none) (updater.Policy, error) { + return a.updatePolicy(), nil + }) + m["update_check"] = command(func(ctx context.Context, _ none) (*availableUpdate, error) { + return a.checkUpdate(ctx) + }) + m["update_download"] = command(func(ctx context.Context, p struct { + Version string `json:"version"` + }) (*availableUpdate, error) { + return a.downloadUpdate(ctx, p.Version) + }) + m["update_install"] = command(func(ctx context.Context, _ none) (any, error) { + return nil, a.installUpdate(ctx) + }) + m["update_cancel"] = command(func(ctx context.Context, _ none) (any, error) { + a.cancelUpdateDownload() + return nil, nil + }) +} diff --git a/internal/app/updates.go b/internal/app/updates.go index bcc1bf2..937137c 100644 --- a/internal/app/updates.go +++ b/internal/app/updates.go @@ -2,52 +2,271 @@ package app import ( "context" - "encoding/json" - "net/http" + "errors" + "os" + "path/filepath" "strconv" "strings" + "sync" "time" "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/updater" ) -// latestManifest is the update manifest every release publishes. -const latestManifest = "https://github.com/LowBloat/LowQuery/releases/latest/download/latest.json" +// Where updates come from and the key they are checked with; tests point +// them at a local server and a throwaway key. +var ( + manifestURL = updater.ManifestURL + updatePublicKey = updater.PublicKey + detectPolicy = updater.DetectCurrent + updateDir = func(version string) string { + return filepath.Join(os.TempDir(), "LowQuery-update", version) + } +) -// A check that hangs (a network that changed under it, a sleeping laptop) -// would otherwise keep every later check waiting. -const updateCheckTimeout = 30 * time.Second +const ( + // A check that hangs (a network that changed under it, a sleeping + // laptop) would otherwise keep every later check waiting. + updateCheckTimeout = 30 * time.Second + // A download stops when nothing arrives for this long, or when it has + // not finished after the second limit. + updateStallTimeout = 60 * time.Second + updateDownloadTimeout = 30 * time.Minute +) type availableUpdate struct { Version string `json:"version"` Notes string `json:"notes"` } +// updateProgress is the payload of the `update-progress` event. Total is +// null when the server does not send the size. +type updateProgress struct { + Version string `json:"version"` + Received int64 `json:"received"` + Total *int64 `json:"total"` +} + +// updateState is the self-update state of one App: the policy, the manifest +// of the last check, the running download and the verified package. +type updateState struct { + mu sync.Mutex + policy *updater.Policy + manifest *updater.Manifest + job *downloadJob + ready *updater.Package +} + +type downloadJob struct { + version string + cancel context.CancelFunc + done chan struct{} + pkg *updater.Package + err error +} + +func (a *App) updates() *updateState { return &a.update } + +// updatePolicy detects once whether this copy can install updates. +func (a *App) updatePolicy() updater.Policy { + u := a.updates() + u.mu.Lock() + defer u.mu.Unlock() + if u.policy == nil { + p := detectPolicy() + u.policy = &p + } + return *u.policy +} + // checkUpdate returns the latest release when it is newer than this build. func (a *App) checkUpdate(ctx context.Context) (*availableUpdate, error) { ctx, cancel := context.WithTimeout(ctx, updateCheckTimeout) defer cancel() - req, err := http.NewRequestWithContext(ctx, http.MethodGet, latestManifest, nil) + m, err := updater.FetchManifest(ctx, nil, manifestURL) if err != nil { - return nil, apperr.Internalf("%v", err) + return nil, apperr.Connectionf("Could not check for updates: %v", err) + } + u := a.updates() + u.mu.Lock() + u.manifest = m + u.mu.Unlock() + if !newerVersion(m.Version, a.version) { + return nil, nil + } + return &availableUpdate{Version: m.Version, Notes: m.Notes}, nil +} + +// downloadUpdate downloads and verifies the update to version (or a newer +// one, if a release came out since the check). A call for the version +// already downloading waits for that download; a call for another version +// cancels it. +func (a *App) downloadUpdate(ctx context.Context, version string) (*availableUpdate, error) { + policy := a.updatePolicy() + if !policy.CanInstall { + return nil, apperr.New(apperr.Invalid, updater.ErrCannotInstall.Error()) + } + version = strings.TrimPrefix(version, "v") + u := a.updates() + u.mu.Lock() + if r := u.ready; r != nil && r.Version == version && fileExists(r.Path) { + u.mu.Unlock() + return &availableUpdate{Version: r.Version, Notes: r.Notes}, nil + } + job := u.job + if job == nil || job.version != version { + if job != nil { + job.cancel() + } + job = a.startDownload(u, version, policy) + } + u.mu.Unlock() + + select { + case <-job.done: + case <-ctx.Done(): + return nil, apperr.CancelledErr() + } + if job.err != nil { + if errors.Is(job.err, context.Canceled) { + return nil, apperr.CancelledErr() + } + var e *apperr.Error + if errors.As(job.err, &e) { + return nil, e + } + return nil, apperr.Connectionf("Could not download the update: %v", job.err) } - resp, err := http.DefaultClient.Do(req) + return &availableUpdate{Version: job.pkg.Version, Notes: job.pkg.Notes}, nil +} + +// startDownload runs a download job in the background. Called with u.mu held. +func (a *App) startDownload(u *updateState, version string, policy updater.Policy) *downloadJob { + ctx, cancel := context.WithTimeout(context.Background(), updateDownloadTimeout) + job := &downloadJob{version: version, cancel: cancel, done: make(chan struct{})} + u.job = job + manifest := u.manifest + target := "" + if policy.Target != nil { + target = *policy.Target + } + go func() { + defer cancel() + job.pkg, job.err = a.runDownload(ctx, manifest, version, target) + u.mu.Lock() + if u.job == job { + u.job = nil + if job.err == nil { + u.ready = job.pkg + } + } + u.mu.Unlock() + close(job.done) + }() + return job +} + +func (a *App) runDownload(ctx context.Context, m *updater.Manifest, version, target string) (*updater.Package, error) { + if m == nil || m.Version != version { + var err error + m, err = updater.FetchManifest(ctx, nil, manifestURL) + if err != nil { + return nil, err + } + } + if !newerVersion(m.Version, a.version) { + return nil, apperr.New(apperr.NotFound, "LowQuery is up to date.") + } + dir := updateDir(m.Version) + removeOtherDownloads(dir) + return updater.Download(ctx, updater.DownloadOptions{ + Manifest: m, + Target: target, + Dir: dir, + PublicKey: updatePublicKey, + StallTimeout: updateStallTimeout, + OnProgress: func(p updater.Progress) { + ev := updateProgress{Version: m.Version, Received: p.Received} + if p.Total > 0 { + ev.Total = &p.Total + } + a.Emit(updater.ProgressEvent, ev) + }, + }) +} + +// removeOtherDownloads deletes packages of other versions next to dir. +func removeOtherDownloads(dir string) { + parent := filepath.Dir(dir) + entries, err := os.ReadDir(parent) if err != nil { - return nil, apperr.Connectionf("Could not check for updates: %v", err) + return } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return nil, apperr.Connectionf("Could not check for updates: %s", resp.Status) + for _, e := range entries { + if e.IsDir() && e.Name() != filepath.Base(dir) { + _ = os.RemoveAll(filepath.Join(parent, e.Name())) + } } - var latest availableUpdate - if err := json.NewDecoder(resp.Body).Decode(&latest); err != nil { - return nil, apperr.Connectionf("Could not read the update manifest: %v", err) +} + +// cancelUpdateDownload stops a running download. +func (a *App) cancelUpdateDownload() { + u := a.updates() + u.mu.Lock() + defer u.mu.Unlock() + if u.job != nil { + u.job.cancel() } - if !newerVersion(latest.Version, a.version) { - return nil, nil +} + +// installUpdate installs the downloaded update and restarts: the Windows +// setup restarts the app itself; elsewhere the new copy is started here. +// Either way this copy then quits. +func (a *App) installUpdate(ctx context.Context) error { + policy := a.updatePolicy() + if !policy.CanInstall { + return apperr.New(apperr.Invalid, updater.ErrCannotInstall.Error()) + } + u := a.updates() + u.mu.Lock() + job, pkg := u.job, u.ready + u.mu.Unlock() + // Still downloading, or the download was deleted since (temp cleanup): + // download first. + if job != nil || (pkg != nil && !fileExists(pkg.Path)) { + version := "" + if job != nil { + version = job.version + } else { + version = pkg.Version + } + if _, err := a.downloadUpdate(ctx, version); err != nil { + return err + } + u.mu.Lock() + pkg = u.ready + u.mu.Unlock() } - latest.Version = strings.TrimPrefix(latest.Version, "v") - return &latest, nil + if pkg == nil { + return apperr.New(apperr.Invalid, "Download the update first.") + } + if err := updater.Install(pkg, policy, updatePublicKey); err != nil { + return apperr.Internalf("Could not install the update: %v", err) + } + if err := updater.Relaunch(policy); err != nil { + return apperr.Internalf("LowQuery %s is installed. Restart LowQuery to use it (%v).", pkg.Version, err) + } + if a.quit != nil { + // After the reply, so the interface is not left waiting. + go a.quit() + } + return nil +} + +func fileExists(path string) bool { + info, err := os.Stat(path) + return err == nil && !info.IsDir() } // newerVersion reports whether semver a is newer than b. Pre-release and diff --git a/internal/app/updates_test.go b/internal/app/updates_test.go index 1ef5831..cdc94e9 100644 --- a/internal/app/updates_test.go +++ b/internal/app/updates_test.go @@ -1,6 +1,21 @@ package app -import "testing" +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/updater" +) func TestNewerVersion(t *testing.T) { cases := []struct { @@ -21,3 +36,211 @@ func TestNewerVersion(t *testing.T) { } } } + +// updateServer serves latest.json for version 2.0.0 and its package, +// signed with the throwaway key of the updater tests. +type updateServer struct { + *httptest.Server + requests atomic.Int32 + stall chan struct{} +} + +func newUpdateServer(t *testing.T, policy updater.Policy) *updateServer { + t.Helper() + testdata := filepath.Join("..", "updater", "testdata") + keyText, err := os.ReadFile(filepath.Join(testdata, "throwaway.key")) + if err != nil { + t.Fatal(err) + } + pub, _ := os.ReadFile(filepath.Join(testdata, "throwaway.key.pub")) + key, err := updater.LoadSecretKey(string(keyText), "throwaway-pass") + if err != nil { + t.Fatal(err) + } + asset := make([]byte, 200<<10) + copy(asset, "MZ") + file := filepath.Join(t.TempDir(), "LowQuery-2.0.0-windows-x64-setup.exe") + if err := os.WriteFile(file, asset, 0o644); err != nil { + t.Fatal(err) + } + sig, err := updater.SignFile(key, file, "2.0.0", time.Now()) + if err != nil { + t.Fatal(err) + } + + us := &updateServer{} + mux := http.NewServeMux() + mux.HandleFunc("/latest.json", func(w http.ResponseWriter, r *http.Request) { + p := updater.Platform{URL: "http://" + r.Host + "/asset/" + filepath.Base(file), Signature: sig} + _ = json.NewEncoder(w).Encode(updater.Manifest{Version: "v2.0.0", Notes: "What's new", Platforms: map[string]updater.Platform{ + "windows-x86_64": p, "windows-x86_64-nsis": p, "darwin-aarch64": p, "darwin-x86_64": p, "linux-x86_64-deb": p, + }}) + }) + mux.HandleFunc("/asset/", func(w http.ResponseWriter, r *http.Request) { + us.requests.Add(1) + w.Header().Set("Content-Length", strconv.Itoa(len(asset))) + if us.stall != nil { + _, _ = w.Write(asset[:1000]) + w.(http.Flusher).Flush() + select { + case <-us.stall: + case <-r.Context().Done(): + } + return + } + _, _ = w.Write(asset) + }) + us.Server = httptest.NewServer(mux) + t.Cleanup(us.Close) + + dir := t.TempDir() + saved := []any{manifestURL, updatePublicKey, detectPolicy, updateDir} + manifestURL = us.URL + "/latest.json" + updatePublicKey = string(pub) + detectPolicy = func() updater.Policy { return policy } + updateDir = func(version string) string { return filepath.Join(dir, version) } + t.Cleanup(func() { + manifestURL = saved[0].(string) + updatePublicKey = saved[1].(string) + detectPolicy = saved[2].(func() updater.Policy) + updateDir = saved[3].(func(string) string) + }) + return us +} + +var installable = updater.Policy{Channel: "deb", CanInstall: true, Target: func() *string { s := "linux-x86_64-deb"; return &s }()} + +type events struct { + mu sync.Mutex + list []updateProgress +} + +func (e *events) emit(name string, data any) { + if name != updater.ProgressEvent { + return + } + e.mu.Lock() + defer e.mu.Unlock() + e.list = append(e.list, data.(updateProgress)) +} + +func (e *events) count() int { + e.mu.Lock() + defer e.mu.Unlock() + return len(e.list) +} + +func TestUpdateCheckDownload(t *testing.T) { + us := newUpdateServer(t, installable) + a := New("1.0.0", nil) + ev := &events{} + a.SetEmitter(ev.emit) + ctx := context.Background() + + if p := a.updatePolicy(); p.Channel != "deb" || !p.CanInstall { + t.Fatalf("policy %+v", p) + } + found, err := a.checkUpdate(ctx) + if err != nil || found == nil || found.Version != "2.0.0" || found.Notes != "What's new" { + t.Fatalf("check: %+v %v", found, err) + } + + // Two requests at once (background prefetch and the dialog): one download. + var wg sync.WaitGroup + results := make([]*availableUpdate, 2) + errs := make([]error, 2) + for i := range 2 { + wg.Add(1) + go func() { + defer wg.Done() + results[i], errs[i] = a.downloadUpdate(ctx, "2.0.0") + }() + } + wg.Wait() + for i := range 2 { + if errs[i] != nil || results[i].Version != "2.0.0" { + t.Fatalf("download %d: %+v %v", i, results[i], errs[i]) + } + } + if n := us.requests.Load(); n != 1 { + t.Fatalf("%d downloads", n) + } + last := ev.list[len(ev.list)-1] + if last.Version != "2.0.0" || last.Total == nil || last.Received != *last.Total { + t.Fatalf("last progress %+v", last) + } + ready := a.updates().ready + if ready == nil || filepath.Base(ready.Path) != "LowQuery-2.0.0-windows-x64-setup.exe" || ready.Target != "linux-x86_64-deb" { + t.Fatalf("ready %+v", ready) + } + // Already downloaded. + if _, err := a.downloadUpdate(ctx, "2.0.0"); err != nil || us.requests.Load() != 1 { + t.Fatalf("again: %v, %d downloads", err, us.requests.Load()) + } +} + +func TestUpdateDownloadCancel(t *testing.T) { + us := newUpdateServer(t, installable) + us.stall = make(chan struct{}) + defer close(us.stall) + a := New("1.0.0", nil) + ev := &events{} + a.SetEmitter(ev.emit) + + done := make(chan error, 1) + go func() { + _, err := a.downloadUpdate(context.Background(), "2.0.0") + done <- err + }() + deadline := time.Now().Add(5 * time.Second) + for ev.count() < 1 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + a.cancelUpdateDownload() + select { + case err := <-done: + if e := apperr.From(err); e.Kind != apperr.Cancelled { + t.Fatalf("got %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("cancel did not stop the download") + } + if a.updates().ready != nil { + t.Fatal("cancelled download marked ready") + } +} + +func TestUpdateRefusals(t *testing.T) { + newUpdateServer(t, updater.Policy{Channel: "portable"}) + ctx := context.Background() + + // Up to date. + current := New("2.0.0", nil) + if found, err := current.checkUpdate(ctx); err != nil || found != nil { + t.Fatalf("check: %+v %v", found, err) + } + // A copy that cannot install neither downloads nor installs. + a := New("1.0.0", nil) + if _, err := a.downloadUpdate(ctx, "2.0.0"); apperr.From(err).Kind != apperr.Invalid { + t.Fatalf("download: %v", err) + } + if err := a.installUpdate(ctx); apperr.From(err).Kind != apperr.Invalid { + t.Fatalf("install: %v", err) + } +} + +func TestUpdateInstallNeedsDownload(t *testing.T) { + newUpdateServer(t, installable) + a := New("1.0.0", nil) + quit := false + a.SetQuit(func() { quit = true }) + err := a.installUpdate(context.Background()) + if err == nil || apperr.From(err).Message != "Download the update first." || quit { + t.Fatalf("got %v, quit %v", err, quit) + } + // Up to date: the download says so. + b := New("2.0.0", nil) + if _, err := b.downloadUpdate(context.Background(), "2.0.0"); apperr.From(err).Kind != apperr.NotFound { + t.Fatalf("got %v", err) + } +} diff --git a/internal/legacystore/legacystore.go b/internal/legacystore/legacystore.go new file mode 100644 index 0000000..aaa38a0 --- /dev/null +++ b/internal/legacystore/legacystore.go @@ -0,0 +1,173 @@ +// Package legacystore reads what the Tauri builds of LowQuery kept in their +// webview's localStorage (editor drafts, export preferences, sidebar width), +// so the Go build, which runs on another origin and data folder, can carry it +// over on its first start. +// +// Where the Tauri builds kept it: +// +// - Windows (WebView2, origin http://tauri.localhost): a Chromium LevelDB at +// %LOCALAPPDATA%\dev.lowbloat.lowquery\EBWebView\Default\Local Storage\leveldb. +// - macOS (WKWebView, origin tauri://localhost): SQLite files under +// ~/Library/WebKit/dev.lowbloat.lowquery/WebsiteData, either the legacy +// LocalStorage/tauri_localhost_0.localstorage or, with WebKit's unified +// origin storage, Default///LocalStorage/localstorage.sqlite3. +// - Linux (WebKitGTK, origin tauri://localhost): the same SQLite files under +// ~/.local/share/dev.lowbloat.lowquery (localstorage/ or storage/). +// +// Every source is read from a temporary copy, never in place: the old app +// may still be running and holding it. +package legacystore + +import ( + "bytes" + "errors" + "fmt" + "io" + "io/fs" + "log" + "os" + "path/filepath" + "runtime" + "strings" + "unicode/utf16" +) + +// Keys are the localStorage entries carried over, and the only ones read. +var Keys = []string{ + "lowquery.tabs.v1", // editor drafts (src/lib/state/workspace.svelte.ts) + "lowquery.export.v1", // export preferences (src/lib/state/transfer.svelte.ts) + "lowquery.sidebar.width", // sidebar width (src/App.svelte) +} + +// identifier is the Tauri bundle identifier, which named the data folders. +const identifier = "dev.lowbloat.lowquery" + +// Read returns the Keys found in the Tauri builds' storage on this machine, +// or an empty map. It never fails: problems are logged. +func Read() map[string]string { + found, err := read(runtime.GOOS, environment()) + if err != nil { + log.Printf("legacy storage: %v", err) + } + if found == nil { + found = map[string]string{} + } + return found +} + +// env holds the folders the sources are found from. +type env struct { + home, localAppData, xdgDataHome string +} + +func environment() env { + home, _ := os.UserHomeDir() + return env{home: home, localAppData: os.Getenv("LOCALAPPDATA"), xdgDataHome: os.Getenv("XDG_DATA_HOME")} +} + +func read(goos string, e env) (map[string]string, error) { + switch goos { + case "windows": + if e.localAppData == "" { + return nil, nil + } + dir := filepath.Join(e.localAppData, identifier, "EBWebView", "Default", "Local Storage", "leveldb") + return ReadLevelDB(dir, ChromiumOrigins) + case "darwin", "linux": + found := map[string]string{} + var errs []error + for _, db := range FindWebKitDatabases(webKitRoots(goos, e)) { + values, err := ReadWebKit(db) + if err != nil { + errs = append(errs, err) + continue + } + for k, v := range values { + if _, seen := found[k]; !seen { + found[k] = v + } + } + } + return found, errors.Join(errs...) + } + return nil, nil +} + +// webKitRoots are the folders that may hold the WebKit storage of the Tauri +// builds, most likely first. +func webKitRoots(goos string, e env) []string { + if e.home == "" { + return nil + } + if goos == "darwin" { + // WebKit names the folder after the bundle identifier; an unbundled + // binary gets its process name instead. + lib := filepath.Join(e.home, "Library", "WebKit") + return []string{filepath.Join(lib, identifier), filepath.Join(lib, "lowquery"), filepath.Join(lib, "LowQuery")} + } + data := e.xdgDataHome + if data == "" { + data = filepath.Join(e.home, ".local", "share") + } + return []string{filepath.Join(data, identifier), filepath.Join(data, "lowquery")} +} + +// wanted reports whether key is one of Keys. +func wanted(key string) bool { + for _, k := range Keys { + if k == key { + return true + } + } + return false +} + +// decodeUTF16LE decodes little-endian UTF-16, the encoding WebKit and +// Chromium store strings in. +func decodeUTF16LE(b []byte) (string, error) { + if len(b)%2 != 0 { + return "", fmt.Errorf("odd UTF-16 length %d", len(b)) + } + units := make([]uint16, len(b)/2) + for i := range units { + units[i] = uint16(b[2*i]) | uint16(b[2*i+1])<<8 + } + return string(utf16.Decode(units)), nil +} + +// decodeLatin1 decodes ISO-8859-1: each byte is the code point. +func decodeLatin1(b []byte) string { + var sb strings.Builder + sb.Grow(len(b)) + for _, c := range b { + sb.WriteRune(rune(c)) + } + return sb.String() +} + +// copyFile copies src to dst. A missing source is not an error when +// optional is set. +func copyFile(src, dst string, optional bool) error { + in, err := os.Open(src) + if err != nil { + if optional && errors.Is(err, fs.ErrNotExist) { + return nil + } + return err + } + defer in.Close() + out, err := os.Create(dst) + if err != nil { + return err + } + if _, err := io.Copy(out, in); err != nil { + out.Close() + return err + } + return out.Close() +} + +// containsFold reports whether b contains s, ignoring ASCII case. +func containsFold(b []byte, s string) bool { + return bytes.Contains(bytes.ToLower(b), []byte(strings.ToLower(s))) +} diff --git a/internal/legacystore/legacystore_test.go b/internal/legacystore/legacystore_test.go new file mode 100644 index 0000000..e0eb6ab --- /dev/null +++ b/internal/legacystore/legacystore_test.go @@ -0,0 +1,329 @@ +package legacystore + +import ( + "os" + "path/filepath" + "reflect" + "sort" + "strings" + "testing" + "unicode/utf16" + + "github.com/ncruces/go-sqlite3" + "github.com/syndtr/goleveldb/leveldb" +) + +const drafts = `{"drafts":[{"id":"a","title":"Query 1","sql":"select 'ação' -- ✓"}],"active":"a"}` + +func utf16le(s string) []byte { + units := utf16.Encode([]rune(s)) + b := make([]byte, 2*len(units)) + for i, u := range units { + b[2*i], b[2*i+1] = byte(u), byte(u>>8) + } + return b +} + +func latin1(s string) []byte { + b := make([]byte, 0, len(s)) + for _, r := range s { + b = append(b, byte(r)) + } + return b +} + +// chromium encodes s the way Chromium's localStorage does: Latin-1 when it +// fits, UTF-16LE otherwise. +func chromium(s string) []byte { + for _, r := range s { + if r > 0xff { + return append([]byte{chromiumUTF16}, utf16le(s)...) + } + } + return append([]byte{chromiumLatin1}, latin1(s)...) +} + +func chromiumKey(origin, key string) []byte { + return append([]byte("_"+origin+"\x00"), chromium(key)...) +} + +func writeLevelDB(t *testing.T, dir string, entries map[string][]byte) { + t.Helper() + db, err := leveldb.OpenFile(dir, nil) + if err != nil { + t.Fatal(err) + } + for k, v := range entries { + if err := db.Put([]byte(k), v, nil); err != nil { + t.Fatal(err) + } + } + if err := db.Close(); err != nil { + t.Fatal(err) + } +} + +func TestReadLevelDB(t *testing.T) { + dir := t.TempDir() + writeLevelDB(t, dir, map[string][]byte{ + "VERSION": []byte("1"), + "META:http://tauri.localhost": {0x08, 0x01}, + string(chromiumKey("http://tauri.localhost", "lowquery.tabs.v1")): chromium(drafts), + string(chromiumKey("http://tauri.localhost", "lowquery.sidebar.width")): chromium("312"), + string(chromiumKey("http://tauri.localhost", "lowquery.theme")): chromium("dark"), + // Another origin's value for a wanted key is not ours. + string(chromiumKey("http://localhost:1420", "lowquery.export.v1")): chromium(`{"format":"csv"}`), + // A UTF-16 key. + "_http://tauri.localhost\x00\x00" + string(utf16le("lowquery.export.v1")): chromium(`{"format":"sql","content":"all"}`), + }) + got, err := ReadLevelDB(dir, ChromiumOrigins) + if err != nil { + t.Fatal(err) + } + want := map[string]string{ + "lowquery.tabs.v1": drafts, + "lowquery.sidebar.width": "312", + "lowquery.export.v1": `{"format":"sql","content":"all"}`, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %q\nwant %q", got, want) + } + // The original is read through a copy: its lock stays as it was. + if _, err := os.Stat(filepath.Join(dir, "LOCK")); err != nil { + t.Fatal(err) + } +} + +// The old app may be running and hold the database: the copy leaves its +// LOCK out, and the latest writes are still in the unflushed log. +func TestReadLevelDBWhileOpen(t *testing.T) { + dir := t.TempDir() + db, err := leveldb.OpenFile(dir, nil) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if err := db.Put(chromiumKey("http://tauri.localhost", "lowquery.sidebar.width"), chromium("300"), nil); err != nil { + t.Fatal(err) + } + got, err := ReadLevelDB(dir, ChromiumOrigins) + if err != nil { + t.Fatal(err) + } + if got["lowquery.sidebar.width"] != "300" { + t.Fatalf("got %q", got) + } +} + +func TestReadLevelDBMissing(t *testing.T) { + got, err := ReadLevelDB(filepath.Join(t.TempDir(), "none"), ChromiumOrigins) + if err != nil || len(got) != 0 { + t.Fatalf("got %q, %v", got, err) + } +} + +func TestDecodeChromium(t *testing.T) { + for _, s := range []string{"", "plain", "ação", "✓ 漢字 😀"} { + got, err := decodeChromium(chromium(s)) + if err != nil || got != s { + t.Errorf("%q: got %q, %v", s, got, err) + } + } + if _, err := decodeChromium([]byte{0x07, 'x'}); err == nil { + t.Error("unknown format accepted") + } + if _, err := decodeChromium([]byte{chromiumUTF16, 'x'}); err == nil { + t.Error("odd UTF-16 accepted") + } +} + +// writeWebKit creates a WebKit localStorage database with values stored the +// way WebKit stores them: key as TEXT, value as a UTF-16LE BLOB. +func writeWebKit(t *testing.T, path string, items map[string]string, wal bool) (closeDB func()) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + conn, err := sqlite3.Open(path) + if err != nil { + t.Fatal(err) + } + if wal { + if err := conn.Exec(`PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0`); err != nil { + t.Fatal(err) + } + } + if err := conn.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`); err != nil { + t.Fatal(err) + } + stmt, _, err := conn.Prepare(`INSERT INTO ItemTable VALUES (?, ?)`) + if err != nil { + t.Fatal(err) + } + for k, v := range items { + if err := stmt.BindText(1, k); err != nil { + t.Fatal(err) + } + if err := stmt.BindBlob(2, utf16le(v)); err != nil { + t.Fatal(err) + } + if err := stmt.Exec(); err != nil { + t.Fatal(err) + } + } + if err := stmt.Close(); err != nil { + t.Fatal(err) + } + return func() { conn.Close() } +} + +func TestReadWebKit(t *testing.T) { + path := filepath.Join(t.TempDir(), legacyFileName) + writeWebKit(t, path, map[string]string{ + "lowquery.tabs.v1": drafts, + "lowquery.export.v1": `{"format":"csv","content":"data"}`, + "lowquery.sidebar.width": "250", + "other": "x", + }, false)() + got, err := ReadWebKit(path) + if err != nil { + t.Fatal(err) + } + want := map[string]string{ + "lowquery.tabs.v1": drafts, + "lowquery.export.v1": `{"format":"csv","content":"data"}`, + "lowquery.sidebar.width": "250", + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %q\nwant %q", got, want) + } +} + +// With the old app running, the latest writes may be only in the WAL. +func TestReadWebKitWAL(t *testing.T) { + path := filepath.Join(t.TempDir(), unifiedFileName) + closeDB := writeWebKit(t, path, map[string]string{"lowquery.sidebar.width": "222"}, true) + defer closeDB() + if _, err := os.Stat(path + "-wal"); err != nil { + t.Skipf("no WAL file: %v", err) + } + got, err := ReadWebKit(path) + if err != nil { + t.Fatal(err) + } + if got["lowquery.sidebar.width"] != "222" { + t.Fatalf("got %q", got) + } +} + +func TestFindWebKitDatabases(t *testing.T) { + home := t.TempDir() + mac := filepath.Join(home, "Library", "WebKit", identifier, "WebsiteData") + legacy := filepath.Join(mac, "LocalStorage", legacyFileName) + unified := filepath.Join(mac, "Default", "XXsalted", "YYsalted", "LocalStorage", unifiedFileName) + other := filepath.Join(mac, "Default", "AAother", "BBother", "LocalStorage", unifiedFileName) + unknown := filepath.Join(mac, "Default", "CC", "DD", "LocalStorage", unifiedFileName) + for _, p := range []string{legacy, unified, other, unknown} { + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, nil, 0o644); err != nil { + t.Fatal(err) + } + } + // WebKit's serialized origins: protocol, host and port of the top and + // frame origins. + origin := func(dir string, s string) { + if err := os.WriteFile(filepath.Join(dir, "origin"), []byte(s), 0o644); err != nil { + t.Fatal(err) + } + } + origin(filepath.Join(mac, "Default", "XXsalted", "YYsalted"), "\x05\x00\x00\x00tauri\x09\x00\x00\x00localhost\x00\x05\x00\x00\x00tauri\x09\x00\x00\x00localhost\x00") + origin(filepath.Join(mac, "Default", "AAother", "BBother"), "\x05\x00\x00\x00https\x0b\x00\x00\x00example.com\x00") + + got := FindWebKitDatabases(webKitRoots("darwin", env{home: home})) + want := []string{unified, legacy, unknown} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %q\nwant %q", got, want) + } +} + +func TestReadMacAndLinux(t *testing.T) { + for _, goos := range []string{"darwin", "linux"} { + t.Run(goos, func(t *testing.T) { + home := t.TempDir() + var legacyPath, unifiedDir string + if goos == "darwin" { + base := filepath.Join(home, "Library", "WebKit", identifier, "WebsiteData") + legacyPath = filepath.Join(base, "LocalStorage", legacyFileName) + unifiedDir = filepath.Join(base, "Default", "h1", "h2") + } else { + base := filepath.Join(home, ".local", "share", identifier) + legacyPath = filepath.Join(base, "localstorage", legacyFileName) + unifiedDir = filepath.Join(base, "storage", "h1", "h2") + } + // The unified database wins for a key both have; the legacy file + // fills in what it lacks. + writeWebKit(t, filepath.Join(unifiedDir, "LocalStorage", unifiedFileName), map[string]string{"lowquery.tabs.v1": drafts}, false)() + if err := os.WriteFile(filepath.Join(unifiedDir, "origin"), []byte("tauri localhost"), 0o644); err != nil { + t.Fatal(err) + } + writeWebKit(t, legacyPath, map[string]string{"lowquery.tabs.v1": "old", "lowquery.sidebar.width": "260"}, false)() + + got, err := read(goos, env{home: home}) + if err != nil { + t.Fatal(err) + } + want := map[string]string{"lowquery.tabs.v1": drafts, "lowquery.sidebar.width": "260"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %q\nwant %q", got, want) + } + }) + } +} + +func TestReadWindows(t *testing.T) { + local := t.TempDir() + dir := filepath.Join(local, identifier, "EBWebView", "Default", "Local Storage", "leveldb") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + writeLevelDB(t, dir, map[string][]byte{string(chromiumKey("http://tauri.localhost", "lowquery.tabs.v1")): chromium(drafts)}) + got, err := read("windows", env{localAppData: local}) + if err != nil || got["lowquery.tabs.v1"] != drafts { + t.Fatalf("got %q, %v", got, err) + } + // Nothing installed: empty, no error. + got, err = read("windows", env{localAppData: t.TempDir()}) + if err != nil || len(got) != 0 { + t.Fatalf("got %q, %v", got, err) + } +} + +// TestRealLevelDB checks a copy of a real Tauri WebView2 localStorage folder, +// named by LQ_LEGACY_LEVELDB. It prints key names and value sizes only: the +// drafts are the user's SQL. +func TestRealLevelDB(t *testing.T) { + dir := os.Getenv("LQ_LEGACY_LEVELDB") + if dir == "" { + t.Skip("LQ_LEGACY_LEVELDB not set") + } + got, err := ReadLevelDB(dir, ChromiumOrigins) + if err != nil { + t.Fatal(err) + } + keys := make([]string, 0, len(got)) + for k := range got { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + t.Logf("%s: %d characters", k, len([]rune(got[k]))) + } + if len(got) == 0 { + t.Error("no keys found") + } + if v, ok := got["lowquery.tabs.v1"]; ok && !strings.HasPrefix(v, "{") { + t.Error("drafts are not JSON") + } +} diff --git a/internal/legacystore/leveldb.go b/internal/legacystore/leveldb.go new file mode 100644 index 0000000..1554cb4 --- /dev/null +++ b/internal/legacystore/leveldb.go @@ -0,0 +1,115 @@ +package legacystore + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + + "github.com/syndtr/goleveldb/leveldb" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" +) + +// ChromiumOrigins are the origins the Tauri builds served the interface from +// in WebView2: http://tauri.localhost, or https:// with useHttpsScheme. +var ChromiumOrigins = []string{"http://tauri.localhost", "https://tauri.localhost"} + +// Chromium's localStorage LevelDB keeps each item under +// +// "_" + origin + "\x00" + encoded key +// +// and an encoded string (key or value) is one format byte followed by the +// characters: 0x01 for Latin-1, one byte each; 0x00 for UTF-16LE. +const ( + chromiumUTF16 = 0x00 + chromiumLatin1 = 0x01 +) + +// ReadLevelDB returns the Keys stored for any of origins in the Chromium +// localStorage LevelDB at dir. A missing folder yields an empty map. +func ReadLevelDB(dir string, origins []string) (map[string]string, error) { + if _, err := os.Stat(dir); err != nil { + if errors.Is(err, fs.ErrNotExist) { + return map[string]string{}, nil + } + return nil, err + } + tmp, err := os.MkdirTemp("", "lowquery-legacy-leveldb-") + if err != nil { + return nil, err + } + defer os.RemoveAll(tmp) + if err := copyLevelDB(dir, tmp); err != nil { + return nil, fmt.Errorf("copying %s: %w", dir, err) + } + db, err := leveldb.OpenFile(tmp, &opt.Options{ReadOnly: true, ErrorIfMissing: true}) + if err != nil { + // A copy taken while the old app was writing may need its manifest + // rebuilt; the copy is ours to repair. + db, err = leveldb.RecoverFile(tmp, nil) + if err != nil { + return nil, fmt.Errorf("opening %s: %w", dir, err) + } + } + defer db.Close() + + found := map[string]string{} + for _, origin := range origins { + prefix := []byte("_" + origin + "\x00") + it := db.NewIterator(util.BytesPrefix(prefix), nil) + for it.Next() { + key, err := decodeChromium(it.Key()[len(prefix):]) + if err != nil || !wanted(key) { + continue + } + if _, seen := found[key]; seen { + continue + } + value, err := decodeChromium(it.Value()) + if err != nil { + return nil, fmt.Errorf("value of %s: %w", key, err) + } + found[key] = value + } + it.Release() + if err := it.Error(); err != nil { + return nil, err + } + } + return found, nil +} + +// copyLevelDB copies the database files of src into dst, leaving out LOCK, +// which the old app may hold, and the text logs. +func copyLevelDB(src, dst string) error { + entries, err := os.ReadDir(src) + if err != nil { + return err + } + for _, e := range entries { + name := e.Name() + if !e.Type().IsRegular() || name == "LOCK" || name == "LOG" || strings.HasPrefix(name, "LOG.") { + continue + } + if err := copyFile(filepath.Join(src, name), filepath.Join(dst, name), true); err != nil { + return err + } + } + return nil +} + +func decodeChromium(b []byte) (string, error) { + if len(b) == 0 { + return "", errors.New("empty string encoding") + } + switch b[0] { + case chromiumLatin1: + return decodeLatin1(b[1:]), nil + case chromiumUTF16: + return decodeUTF16LE(b[1:]) + } + return "", fmt.Errorf("unknown string format 0x%02x", b[0]) +} diff --git a/internal/legacystore/webkit.go b/internal/legacystore/webkit.go new file mode 100644 index 0000000..e749c4e --- /dev/null +++ b/internal/legacystore/webkit.go @@ -0,0 +1,147 @@ +package legacystore + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + + "github.com/ncruces/go-sqlite3" +) + +// WebKit (macOS and WebKitGTK) keeps localStorage in SQLite: +// +// CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, +// value BLOB NOT NULL ON CONFLICT FAIL) +// +// with each value stored as UTF-16 (native order, little-endian on every Mac +// and PC WebKit runs on). Two layouts exist: +// +// - legacy: one file per origin in the localStorage folder, named after the +// origin's database identifier, tauri_localhost_0.localstorage; +// - unified origin storage (WebKit 2.38+/Safari 16.x+): one folder per +// origin, //, holding an +// "origin" file with the serialized origins and +// LocalStorage/localstorage.sqlite3. WebKit moves a legacy file there the +// first time the origin's storage is opened. +const ( + unifiedFileName = "localstorage.sqlite3" + legacyFileName = "tauri_localhost_0.localstorage" + // How deep under a root the files are looked for: unified storage sits at + // WebsiteData/Default///LocalStorage/localstorage.sqlite3. + maxSearchDepth = 7 +) + +// FindWebKitDatabases lists the WebKit localStorage databases of the Tauri +// origin (tauri://localhost) under roots, the most likely first: unified +// storage whose origin file names tauri, then legacy files, then unified +// storage without an origin file. +func FindWebKitDatabases(roots []string) []string { + var tauri, legacy, unknown []string + for _, root := range roots { + _ = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + if path == root { + return filepath.SkipDir + } + return nil + } + if d.IsDir() { + if depth(root, path) > maxSearchDepth { + return filepath.SkipDir + } + return nil + } + switch name := d.Name(); { + case name == legacyFileName: + legacy = append(legacy, path) + case name == unifiedFileName: + // /LocalStorage/localstorage.sqlite3 + origin, err := os.ReadFile(filepath.Join(filepath.Dir(filepath.Dir(path)), "origin")) + switch { + case err != nil: + unknown = append(unknown, path) + case containsFold(origin, "tauri"): + tauri = append(tauri, path) + } + } + return nil + }) + } + return append(append(tauri, legacy...), unknown...) +} + +func depth(root, path string) int { + rel, err := filepath.Rel(root, path) + if err != nil || rel == "." { + return 0 + } + return strings.Count(rel, string(filepath.Separator)) + 1 +} + +// ReadWebKit returns the Keys found in the WebKit localStorage database at +// path, read from a copy opened read-only. +func ReadWebKit(path string) (map[string]string, error) { + tmp, err := os.MkdirTemp("", "lowquery-legacy-webkit-") + if err != nil { + return nil, err + } + defer os.RemoveAll(tmp) + copyPath := filepath.Join(tmp, "localstorage.sqlite3") + if err := copyFile(path, copyPath, false); err != nil { + return nil, fmt.Errorf("copying %s: %w", path, err) + } + // The write-ahead log may hold the latest writes. + for _, suffix := range []string{"-wal", "-shm", "-journal"} { + if err := copyFile(path+suffix, copyPath+suffix, true); err != nil { + return nil, fmt.Errorf("copying %s%s: %w", path, suffix, err) + } + } + values, err := readItemTable(copyPath) + if err != nil { + return nil, fmt.Errorf("reading %s: %w", path, err) + } + return values, nil +} + +func readItemTable(path string) (found map[string]string, err error) { + conn, err := sqlite3.OpenFlags(path, sqlite3.OPEN_READONLY) + if err != nil { + return nil, err + } + defer func() { err = errors.Join(err, conn.Close()) }() + stmt, _, err := conn.Prepare(`SELECT key, value FROM ItemTable`) + if err != nil { + return nil, err + } + defer stmt.Close() + found = map[string]string{} + for stmt.Step() { + key, err := webKitString(stmt, 0) + if err != nil || !wanted(key) { + continue + } + value, err := webKitString(stmt, 1) + if err != nil { + return nil, fmt.Errorf("value of %s: %w", key, err) + } + found[key] = value + } + return found, stmt.Err() +} + +// webKitString reads a column WebKit wrote: TEXT as SQLite returns it, a BLOB +// as UTF-16LE. +func webKitString(stmt *sqlite3.Stmt, col int) (string, error) { + switch stmt.ColumnType(col) { + case sqlite3.BLOB: + return decodeUTF16LE(stmt.ColumnRawBlob(col)) + case sqlite3.TEXT: + return stmt.ColumnText(col), nil + case sqlite3.NULL: + return "", errors.New("null") + } + return stmt.ColumnText(col), nil +} diff --git a/internal/menubar/menubar.go b/internal/menubar/menubar.go new file mode 100644 index 0000000..345c8e5 --- /dev/null +++ b/internal/menubar/menubar.go @@ -0,0 +1,99 @@ +// Package menubar turns the toolkit-independent menu bar of package app +// (app.MenuNode) into a Wails application menu. Only macOS uses it; the code +// builds on every OS so it is compiled and tested everywhere. +package menubar + +import ( + "sync" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/LowBloat/LowQuery/internal/app" +) + +// roles maps the standard items to Wails roles, which macOS implements +// through the responder chain (copy:, hide:, terminate:, ...). +var roles = map[app.MenuRole]application.Role{ + app.RoleServices: application.ServicesMenu, + app.RoleHide: application.Hide, + app.RoleHideOthers: application.HideOthers, + app.RoleShowAll: application.ShowAll, + app.RoleQuit: application.Quit, + app.RoleUndo: application.Undo, + app.RoleRedo: application.Redo, + app.RoleCut: application.Cut, + app.RoleCopy: application.Copy, + app.RolePaste: application.Paste, + app.RoleSelectAll: application.SelectAll, + app.RoleMinimise: application.Minimise, + app.RoleZoom: application.Zoom, + app.RoleFullscreen: application.ToggleFullscreen, + app.RoleBringAllToFront: application.BringAllToFront, +} + +// Build makes the Wails menu for nodes; choosing an item calls onClick with +// its id. +func Build(nodes []app.MenuNode, onClick func(id string)) *application.Menu { + menu := application.NewMenu() + add(menu, nodes, onClick) + return menu +} + +func add(menu *application.Menu, nodes []app.MenuNode, onClick func(id string)) { + for _, n := range nodes { + switch n.Kind { + case app.MenuSeparatorKind: + menu.AddSeparator() + case app.MenuSubmenuKind: + add(menu.AddSubmenu(n.Label), n.Children, onClick) + case app.MenuRoleKind: + if role, ok := roles[n.Role]; ok { + menu.AddRole(role) + } + case app.MenuItemKind, app.MenuCheckboxKind: + var item *application.MenuItem + if n.Kind == app.MenuCheckboxKind { + item = menu.AddCheckbox(n.Label, n.Checked) + } else { + item = menu.Add(n.Label) + } + item.SetEnabled(!n.Disabled) + // BuildMenuBar keeps only accelerators Wails parses. + if n.Accelerator != "" { + item.SetAccelerator(n.Accelerator) + } + id := n.ID + item.OnClick(func(*application.Context) { onClick(id) }) + } + } +} + +// Bar replaces the application menu each time the interface describes it. +type Bar struct { + mu sync.Mutex + set func(*application.Menu) + onClick func(id string) + // The menu on screen and the one before it. The one before is released + // on the next change rather than at once, so a click already on its way + // from the replaced menu still finds its item. + current, previous *application.Menu +} + +// New returns a Bar that installs menus with set (the Wails +// Menu.SetApplicationMenu) and reports clicks to onClick. +func New(set func(*application.Menu), onClick func(id string)) *Bar { + return &Bar{set: set, onClick: onClick} +} + +// Set replaces the menu bar with nodes. +func (b *Bar) Set(nodes []app.MenuNode) { + b.mu.Lock() + defer b.mu.Unlock() + menu := Build(nodes, b.onClick) + b.set(menu) + if old := b.previous; old != nil { + // Releasing native items belongs on the main thread. + application.InvokeAsync(old.Destroy) + } + b.previous, b.current = b.current, menu +} diff --git a/internal/menubar/menubar_test.go b/internal/menubar/menubar_test.go new file mode 100644 index 0000000..ec51d05 --- /dev/null +++ b/internal/menubar/menubar_test.go @@ -0,0 +1,82 @@ +package menubar + +import ( + "testing" + + "github.com/wailsapp/wails/v3/pkg/application" + + "github.com/LowBloat/LowQuery/internal/app" +) + +// Every standard item BuildMenuBar uses has a Wails role. +func TestRolesCovered(t *testing.T) { + var walk func([]app.MenuNode) + walk = func(nodes []app.MenuNode) { + for _, n := range nodes { + if n.Kind == app.MenuRoleKind { + if _, ok := roles[n.Role]; !ok { + t.Errorf("no Wails role for %q", n.Role) + } + } + walk(n.Children) + } + } + walk(app.BuildMenuBar("LowQuery", app.MenuBarDescription{About: app.MenuEntryDescription{ID: "about"}})) +} + +// Role items need a running Wails app (their labels use its name), so the +// build is checked on the app's own menus. +func TestBuild(t *testing.T) { + checked := true + bar := app.BuildMenuBar("LowQuery", app.MenuBarDescription{Menus: []app.MenuDescription{ + {Label: "Query", Entries: []app.MenuEntryDescription{ + {ID: "q/run", Label: "Run statement", Accelerator: "CmdOrCtrl+Enter"}, + {ID: "q/stop", Label: "Stop", Disabled: true}, + {Separator: true}, + {ID: "q/auto", Label: "Auto-commit", Checked: &checked}, + }}, + }}) + var own []app.MenuNode + for _, n := range bar { + if n.Label == "Query" { + own = append(own, n) + } + } + menu := Build(own, func(string) {}) + + query := menu.ItemAt(0) + if query == nil || !query.IsSubmenu() || query.Label() != "Query" { + t.Fatalf("first item %+v", query) + } + sub := query.GetSubmenu() + run, stop, sep, auto := sub.ItemAt(0), sub.ItemAt(1), sub.ItemAt(2), sub.ItemAt(3) + if run.Label() != "Run statement" || !run.Enabled() || run.IsCheckbox() || run.GetAccelerator() == "" { + t.Errorf("run: %q enabled=%v accelerator=%q", run.Label(), run.Enabled(), run.GetAccelerator()) + } + if stop.Enabled() || stop.GetAccelerator() != "" { + t.Errorf("stop: enabled=%v", stop.Enabled()) + } + if !sep.IsSeparator() { + t.Error("third item is not a separator") + } + if !auto.IsCheckbox() || !auto.Checked() || !auto.Enabled() { + t.Errorf("auto-commit: checkbox=%v checked=%v", auto.IsCheckbox(), auto.Checked()) + } + if sub.ItemAt(4) != nil { + t.Error("extra items") + } +} + +func TestBarKeepsOnePreviousMenu(t *testing.T) { + var installed []*application.Menu + b := New(func(m *application.Menu) { installed = append(installed, m) }, func(string) {}) + nodes := []app.MenuNode{{Kind: app.MenuSubmenuKind, Label: "File", Children: []app.MenuNode{{Kind: app.MenuItemKind, ID: "x", Label: "X"}}}} + b.Set(nodes) + b.Set(nodes) + if len(installed) != 2 || installed[0] == installed[1] { + t.Fatalf("installed %d menus", len(installed)) + } + if b.current != installed[1] || b.previous != installed[0] { + t.Error("current and previous menus not kept") + } +} diff --git a/internal/updater/download.go b/internal/updater/download.go new file mode 100644 index 0000000..55b990f --- /dev/null +++ b/internal/updater/download.go @@ -0,0 +1,203 @@ +package updater + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path" + "path/filepath" + "strings" + "sync" + "time" +) + +// Package is a downloaded update whose signature has been verified. +type Package struct { + Version string + Notes string + // Target is the manifest key it was downloaded for. + Target string + // Path is the downloaded file, named like the release asset. + Path string + Signature string +} + +// Progress reports a running download. Total is 0 when the size is unknown. +type Progress struct { + Received int64 + Total int64 +} + +// DownloadOptions are the inputs of Download. +type DownloadOptions struct { + Client *http.Client + Manifest *Manifest + // Target is the manifest key; empty picks DefaultTargets. + Target string + // Dir receives the package; it is created when missing. + Dir string + // PublicKey verifies the package; empty means PublicKey. + PublicKey string + // StallTimeout aborts a download that receives nothing for this long. + StallTimeout time.Duration + OnProgress func(Progress) +} + +// ErrStalled reports a download that stopped receiving data. +var ErrStalled = errors.New("the download stalled") + +// Download fetches the package for opts.Target from the manifest into +// opts.Dir and verifies its signature. A package that fails verification is +// deleted. Cancel ctx to stop it. +func Download(ctx context.Context, opts DownloadOptions) (*Package, error) { + m := opts.Manifest + target, platform, err := m.Select(opts.Target) + if err != nil { + return nil, err + } + name, err := assetName(platform.URL) + if err != nil { + return nil, err + } + if err := os.MkdirAll(opts.Dir, 0o755); err != nil { + return nil, err + } + key := opts.PublicKey + if key == "" { + key = PublicKey + } + dest := filepath.Join(opts.Dir, name) + pkg := &Package{Version: m.Version, Notes: m.Notes, Target: target, Path: dest, Signature: platform.Signature} + + // Downloaded before (an earlier prefetch): keep it if it still verifies. + if _, err := os.Stat(dest); err == nil { + if VerifyFile(dest, platform.Signature, key, m.Version) == nil { + return pkg, nil + } + _ = os.Remove(dest) + } + + part := dest + ".part" + if err := fetch(ctx, opts, platform.URL, part); err != nil { + _ = os.Remove(part) + return nil, err + } + if err := VerifyFile(part, platform.Signature, key, m.Version); err != nil { + _ = os.Remove(part) + return nil, err + } + if err := os.Rename(part, dest); err != nil { + _ = os.Remove(part) + return nil, err + } + return pkg, nil +} + +// assetName is the file name of the release asset at rawURL. +func assetName(rawURL string) (string, error) { + u, err := url.Parse(rawURL) + if err != nil || (u.Scheme != "https" && u.Scheme != "http") { + return "", fmt.Errorf("invalid update URL %q", rawURL) + } + name := path.Base(u.Path) + if name == "" || name == "." || name == "/" || name == ".." || strings.ContainsAny(name, `\:*?"<>|`) { + return "", fmt.Errorf("invalid update URL %q", rawURL) + } + return name, nil +} + +func fetch(ctx context.Context, opts DownloadOptions, rawURL, dest string) error { + ctx, cancel := context.WithCancelCause(ctx) + defer cancel(nil) + client := opts.Client + if client == nil { + client = http.DefaultClient + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return err + } + req.Header.Set("Accept", "application/octet-stream") + + // The stall timer runs from the request on and restarts with every read. + var watchdog *time.Timer + if opts.StallTimeout > 0 { + watchdog = time.AfterFunc(opts.StallTimeout, func() { cancel(ErrStalled) }) + defer watchdog.Stop() + } + fail := func(err error) error { + if cause := context.Cause(ctx); cause != nil && ctx.Err() != nil { + return cause + } + return err + } + + resp, err := client.Do(req) + if err != nil { + return fail(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("download failed: %s", resp.Status) + } + total := resp.ContentLength + if total < 0 { + total = 0 + } + f, err := os.OpenFile(dest, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644) + if err != nil { + return err + } + defer f.Close() + + report := throttle(opts.OnProgress, 100*time.Millisecond) + report(Progress{Total: total}, true) + var received int64 + buf := make([]byte, 64<<10) + for { + n, rerr := resp.Body.Read(buf) + if n > 0 { + if watchdog != nil { + watchdog.Reset(opts.StallTimeout) + } + if _, err := f.Write(buf[:n]); err != nil { + return err + } + received += int64(n) + report(Progress{Received: received, Total: total}, false) + } + if rerr == io.EOF { + break + } + if rerr != nil { + return fail(rerr) + } + } + if total > 0 && received != total { + return fmt.Errorf("download incomplete: %d of %d bytes", received, total) + } + report(Progress{Received: received, Total: total}, true) + return f.Close() +} + +// throttle limits progress reports to one per interval, plus forced ones. +func throttle(f func(Progress), every time.Duration) func(Progress, bool) { + if f == nil { + return func(Progress, bool) {} + } + var mu sync.Mutex + var last time.Time + return func(p Progress, force bool) { + mu.Lock() + defer mu.Unlock() + if !force && time.Since(last) < every { + return + } + last = time.Now() + f(p) + } +} diff --git a/internal/updater/download_test.go b/internal/updater/download_test.go new file mode 100644 index 0000000..7972499 --- /dev/null +++ b/internal/updater/download_test.go @@ -0,0 +1,194 @@ +package updater + +import ( + "context" + "crypto/rand" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "sync" + "testing" + "time" +) + +// releaseServer serves latest.json and one package signed with the +// throwaway key, the way GitHub Releases does (the asset behind a redirect). +type releaseServer struct { + *httptest.Server + asset []byte + sig string + tamper bool + stall chan struct{} + requests int + mu sync.Mutex +} + +func newReleaseServer(t *testing.T, version string) *releaseServer { + t.Helper() + asset := make([]byte, 300<<10) + _, _ = rand.Read(asset) + asset[0], asset[1] = 'M', 'Z' + file := filepath.Join(t.TempDir(), "LowQuery-"+version+"-windows-x64-setup.exe") + if err := os.WriteFile(file, asset, 0o644); err != nil { + t.Fatal(err) + } + sig, err := SignFile(throwawayKey(t), file, version, time.Now()) + if err != nil { + t.Fatal(err) + } + rs := &releaseServer{asset: asset, sig: sig} + mux := http.NewServeMux() + mux.HandleFunc("/latest.json", func(w http.ResponseWriter, r *http.Request) { + base := "http://" + r.Host + p := Platform{URL: base + "/download/" + filepath.Base(file), Signature: rs.sig} + _ = json.NewEncoder(w).Encode(Manifest{Version: version, Notes: "notes", Platforms: map[string]Platform{ + "windows-x86_64": p, "windows-x86_64-nsis": p, "linux-x86_64-deb": p, + }}) + }) + mux.HandleFunc("/download/", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/assets/"+filepath.Base(r.URL.Path), http.StatusFound) + }) + mux.HandleFunc("/assets/", func(w http.ResponseWriter, r *http.Request) { + rs.mu.Lock() + rs.requests++ + rs.mu.Unlock() + body := append([]byte(nil), rs.asset...) + if rs.tamper { + body[len(body)/2] ^= 0xff + } + w.Header().Set("Content-Length", strconv.Itoa(len(body))) + if rs.stall != nil { + _, _ = w.Write(body[:1000]) + w.(http.Flusher).Flush() + select { + case <-rs.stall: + case <-r.Context().Done(): + } + return + } + _, _ = w.Write(body) + }) + rs.Server = httptest.NewServer(mux) + t.Cleanup(rs.Close) + return rs +} + +func (rs *releaseServer) manifest(t *testing.T) *Manifest { + t.Helper() + m, err := FetchManifest(context.Background(), rs.Client(), rs.URL+"/latest.json") + if err != nil { + t.Fatal(err) + } + return m +} + +func TestDownloadEndToEnd(t *testing.T) { + rs := newReleaseServer(t, "2.0.0") + dir := t.TempDir() + var progress []Progress + opts := DownloadOptions{ + Client: rs.Client(), + Manifest: rs.manifest(t), + Target: "linux-x86_64-deb", + Dir: dir, + PublicKey: readTestdata(t, "throwaway.key.pub"), + OnProgress: func(p Progress) { progress = append(progress, p) }, + } + pkg, err := Download(context.Background(), opts) + if err != nil { + t.Fatal(err) + } + if pkg.Version != "2.0.0" || pkg.Notes != "notes" || pkg.Target != "linux-x86_64-deb" || + pkg.Path != filepath.Join(dir, "LowQuery-2.0.0-windows-x64-setup.exe") { + t.Fatalf("%+v", pkg) + } + got, _ := os.ReadFile(pkg.Path) + if len(got) != len(rs.asset) { + t.Fatalf("size %d", len(got)) + } + last := progress[len(progress)-1] + if len(progress) < 2 || last.Received != int64(len(rs.asset)) || last.Total != int64(len(rs.asset)) { + t.Fatalf("progress %+v", progress) + } + if _, err := os.Stat(pkg.Path + ".part"); err == nil { + t.Fatal(".part left behind") + } + // What Install checks first. + if err := VerifyFile(pkg.Path, pkg.Signature, opts.PublicKey, pkg.Version); err != nil { + t.Fatal(err) + } + + // Downloaded already: kept without a request. + before := rs.requests + if _, err := Download(context.Background(), opts); err != nil || rs.requests != before { + t.Fatalf("second download: %v, %d requests", err, rs.requests-before) + } +} + +func TestDownloadRejectsTamperedPackage(t *testing.T) { + rs := newReleaseServer(t, "2.0.0") + rs.tamper = true + dir := t.TempDir() + _, err := Download(context.Background(), DownloadOptions{ + Client: rs.Client(), Manifest: rs.manifest(t), Target: "windows-x86_64", Dir: dir, + PublicKey: readTestdata(t, "throwaway.key.pub"), + }) + if !errors.Is(err, ErrBadSignature) { + t.Fatalf("got %v", err) + } + if entries, _ := os.ReadDir(dir); len(entries) != 0 { + t.Fatalf("left behind: %v", entries) + } +} + +func TestDownloadRejectsOtherKey(t *testing.T) { + rs := newReleaseServer(t, "2.0.0") + _, err := Download(context.Background(), DownloadOptions{ + Client: rs.Client(), Manifest: rs.manifest(t), Target: "windows-x86_64", Dir: t.TempDir(), + // The key every release is checked with by default. + PublicKey: PublicKey, + }) + if !errors.Is(err, ErrBadSignature) { + t.Fatalf("got %v", err) + } +} + +func TestDownloadRejectsOtherVersion(t *testing.T) { + rs := newReleaseServer(t, "2.0.0") + m := rs.manifest(t) + m.Version = "3.0.0" // a manifest pairing a new number with an old package + _, err := Download(context.Background(), DownloadOptions{ + Client: rs.Client(), Manifest: m, Target: "windows-x86_64", Dir: t.TempDir(), + PublicKey: readTestdata(t, "throwaway.key.pub"), + }) + if err == nil { + t.Fatal("accepted") + } +} + +func TestDownloadStallAndCancel(t *testing.T) { + rs := newReleaseServer(t, "2.0.0") + rs.stall = make(chan struct{}) + defer close(rs.stall) + opts := DownloadOptions{ + Client: rs.Client(), Manifest: rs.manifest(t), Target: "windows-x86_64", Dir: t.TempDir(), + PublicKey: readTestdata(t, "throwaway.key.pub"), StallTimeout: 300 * time.Millisecond, + } + if _, err := Download(context.Background(), opts); !errors.Is(err, ErrStalled) { + t.Fatalf("stall: %v", err) + } + + opts.StallTimeout = 0 + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(300*time.Millisecond, cancel) + if _, err := Download(ctx, opts); !errors.Is(err, context.Canceled) { + t.Fatalf("cancel: %v", err) + } + if entries, _ := os.ReadDir(opts.Dir); len(entries) != 0 { + t.Fatalf("left behind: %v", entries) + } +} diff --git a/internal/updater/install.go b/internal/updater/install.go new file mode 100644 index 0000000..1833921 --- /dev/null +++ b/internal/updater/install.go @@ -0,0 +1,212 @@ +package updater + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "errors" + "fmt" + "io" + "os" + "path" + "path/filepath" + "strings" +) + +// ErrCannotInstall reports a copy that has no way to install updates. +var ErrCannotInstall = errors.New("this copy of LowQuery cannot install updates: download the new version instead") + +// Install installs pkg over the copy policy describes. The signature is +// checked again first, so a file changed since the download is never run. +// On Windows it starts the setup, which waits for the app to close: quit +// right after. Elsewhere the new version is in place on return: call +// Relaunch, then quit. +func Install(pkg *Package, policy Policy, publicKey string) error { + if pkg == nil { + return errors.New("no update has been downloaded") + } + if !policy.CanInstall { + return ErrCannotInstall + } + if publicKey == "" { + publicKey = PublicKey + } + if err := VerifyFile(pkg.Path, pkg.Signature, publicKey, pkg.Version); err != nil { + return err + } + if err := checkFormat(policy.Channel, pkg.Path); err != nil { + return err + } + return install(pkg, policy) +} + +// Relaunch starts the updated copy. The Windows setup restarts the app +// itself, so there it does nothing. +func Relaunch(policy Policy) error { return relaunch(policy) } + +// Magic numbers of the packages each channel installs. +var formats = map[string]struct { + magic []byte + name string +}{ + "windows": {[]byte("MZ"), "a Windows setup program"}, + "darwin": {[]byte{0x1f, 0x8b}, "a .app.tar.gz archive"}, + "appimage": {[]byte("\x7fELF"), "an AppImage"}, + "deb": {[]byte("!\n"), "a .deb package"}, + "rpm": {[]byte{0xed, 0xab, 0xee, 0xdb}, "an .rpm package"}, +} + +// checkFormat makes sure the package is what the channel installs. +func checkFormat(channel, file string) error { + key := channel + if channel == "installer" { + key = installerFormat + } + f, ok := formats[key] + if !ok { + return ErrCannotInstall + } + head := make([]byte, len(f.magic)) + fh, err := os.Open(file) + if err != nil { + return err + } + defer fh.Close() + if _, err := io.ReadFull(fh, head); err != nil || !bytes.Equal(head, f.magic) { + return fmt.Errorf("the update is not %s", f.name) + } + return nil +} + +// replaceFile puts the content of src at target, keeping target's mode. The +// new file is written next to target and renamed over it, so target is +// never half written (a running AppImage keeps its open inode). +func replaceFile(target, src string) error { + info, err := os.Stat(target) + if err != nil { + return err + } + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + tmp, err := os.CreateTemp(filepath.Dir(target), ".lowquery-update-*") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + if _, err := io.Copy(tmp, in); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + if err := os.Chmod(tmp.Name(), info.Mode().Perm()); err != nil { + return err + } + return os.Rename(tmp.Name(), target) +} + +// extractAppBundle unpacks a .app.tar.gz (LowQuery.app/...) into dest, +// dropping the first path component as the Tauri updater does, so dest +// becomes the bundle. +func extractAppBundle(archive, dest string) error { + f, err := os.Open(archive) + if err != nil { + return err + } + defer f.Close() + gz, err := gzip.NewReader(f) + if err != nil { + return err + } + defer gz.Close() + if err := os.MkdirAll(dest, 0o755); err != nil { + return err + } + tr := tar.NewReader(gz) + files := 0 + for { + h, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return err + } + rel, ok := bundlePath(h.Name) + if !ok { + return fmt.Errorf("unsafe path in update archive: %q", h.Name) + } + if rel == "" { + continue + } + out := filepath.Join(dest, filepath.FromSlash(rel)) + mode := os.FileMode(h.Mode).Perm() + switch h.Typeflag { + case tar.TypeDir: + if err := os.MkdirAll(out, mode|0o700); err != nil { + return err + } + case tar.TypeReg: + if err := os.MkdirAll(filepath.Dir(out), 0o755); err != nil { + return err + } + w, err := os.OpenFile(out, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode|0o600) + if err != nil { + return err + } + _, err = io.Copy(w, tr) + if cerr := w.Close(); err == nil { + err = cerr + } + if err != nil { + return err + } + files++ + case tar.TypeSymlink: + // Frameworks link Versions/Current and the like; the link must + // stay inside the bundle. + if path.IsAbs(h.Linkname) { + return fmt.Errorf("unsafe link in update archive: %q", h.Name) + } + if _, ok := bundlePath("x/" + path.Join(path.Dir(rel), h.Linkname)); !ok { + return fmt.Errorf("unsafe link in update archive: %q", h.Name) + } + if err := os.MkdirAll(filepath.Dir(out), 0o755); err != nil { + return err + } + if err := os.Symlink(h.Linkname, out); err != nil { + return err + } + default: + return fmt.Errorf("unsupported entry in update archive: %q", h.Name) + } + } + if files == 0 { + return errors.New("the update archive is empty") + } + return nil +} + +// bundlePath is name without its first component; false when it would +// leave the bundle. +func bundlePath(name string) (string, bool) { + name = strings.TrimPrefix(name, "./") + if path.IsAbs(name) || strings.Contains(name, `\`) { + return "", false + } + _, rest, _ := strings.Cut(name, "/") + clean := path.Clean("/" + rest) + if clean == "/" { + return "", true + } + for _, part := range strings.Split(rest, "/") { + if part == ".." { + return "", false + } + } + return strings.TrimPrefix(clean, "/"), true +} diff --git a/internal/updater/install_darwin.go b/internal/updater/install_darwin.go new file mode 100644 index 0000000..4b58593 --- /dev/null +++ b/internal/updater/install_darwin.go @@ -0,0 +1,58 @@ +package updater + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "time" + + "golang.org/x/sys/unix" +) + +const installerFormat = "darwin" + +// install unpacks the .app.tar.gz next to the bundle (same volume, so the +// renames work) and swaps it with the bundle in one step where the file +// system can (APFS), or moves the old one aside and restores it on failure. +func install(pkg *Package, policy Policy) error { + if policy.Channel != "installer" || policy.Path == "" { + return ErrCannotInstall + } + bundle := policy.Path + staging, err := os.MkdirTemp(filepath.Dir(bundle), ".lowquery-update-") + if err != nil { + return err + } + defer os.RemoveAll(staging) + staged := filepath.Join(staging, "new.app") + if err := extractAppBundle(pkg.Path, staged); err != nil { + return err + } + if err := os.Chmod(staged, 0o755); err != nil { + return err + } + // After a swap, staged holds the old bundle and goes with staging. + if err := unix.RenamexNp(staged, bundle, unix.RENAME_SWAP); err != nil { + if errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM) { + return err + } + old := filepath.Join(staging, "old.app") + if err := os.Rename(bundle, old); err != nil { + return err + } + if err := os.Rename(staged, bundle); err != nil { + _ = os.Rename(old, bundle) + return err + } + } + // Tells Launch Services and the Dock the bundle changed. + now := time.Now() + _ = os.Chtimes(bundle, now, now) + return nil +} + +// relaunch opens a new instance of the bundle; the caller then quits. +func relaunch(policy Policy) error { + return exec.Command("/usr/bin/open", "-n", policy.Path).Start() +} diff --git a/internal/updater/install_linux.go b/internal/updater/install_linux.go new file mode 100644 index 0000000..d2ac3e7 --- /dev/null +++ b/internal/updater/install_linux.go @@ -0,0 +1,48 @@ +package updater + +import ( + "fmt" + "os" + "os/exec" + "syscall" +) + +const installerFormat = "" + +// install replaces a writable AppImage, or hands a .deb/.rpm to dpkg/rpm +// through pkexec, which asks for the administrator password. +func install(pkg *Package, policy Policy) error { + switch policy.Channel { + case "appimage": + return replaceFile(policy.Path, pkg.Path) + case "deb": + return pkexec("dpkg", "-i", pkg.Path) + case "rpm": + return pkexec("rpm", "-U", pkg.Path) + } + return ErrCannotInstall +} + +func pkexec(program, flag, file string) error { + cmd := exec.Command("pkexec", program, flag, file) + out, err := cmd.CombinedOutput() + if err != nil { + if exit, ok := err.(*exec.ExitError); ok && (exit.ExitCode() == 126 || exit.ExitCode() == 127) { + return fmt.Errorf("the update needs the administrator password, which was not given") + } + return fmt.Errorf("%s could not install the update: %v\n%s", program, err, out) + } + return nil +} + +// relaunch starts the updated AppImage or executable in its own session; +// the caller then quits. +func relaunch(policy Policy) error { + cmd := exec.Command(policy.Path) + cmd.Env = os.Environ() + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} + if err := cmd.Start(); err != nil { + return err + } + return cmd.Process.Release() +} diff --git a/internal/updater/install_other.go b/internal/updater/install_other.go new file mode 100644 index 0000000..0487a2a --- /dev/null +++ b/internal/updater/install_other.go @@ -0,0 +1,9 @@ +//go:build !windows && !darwin && !linux + +package updater + +const installerFormat = "" + +func install(*Package, Policy) error { return ErrCannotInstall } + +func relaunch(Policy) error { return ErrCannotInstall } diff --git a/internal/updater/install_test.go b/internal/updater/install_test.go new file mode 100644 index 0000000..6b1c631 --- /dev/null +++ b/internal/updater/install_test.go @@ -0,0 +1,185 @@ +package updater + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "errors" + "os" + "path/filepath" + "runtime" + "testing" +) + +type tarEntry struct { + name, body, link string + dir bool +} + +func writeTarGz(t *testing.T, path string, entries []tarEntry) { + t.Helper() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + for _, e := range entries { + h := &tar.Header{Name: e.name, Mode: 0o755} + switch { + case e.dir: + h.Typeflag = tar.TypeDir + case e.link != "": + h.Typeflag, h.Linkname = tar.TypeSymlink, e.link + default: + h.Typeflag, h.Size, h.Mode = tar.TypeReg, int64(len(e.body)), 0o644 + } + if err := tw.WriteHeader(h); err != nil { + t.Fatal(err) + } + if h.Typeflag == tar.TypeReg { + _, _ = tw.Write([]byte(e.body)) + } + } + tw.Close() + gz.Close() + if err := os.WriteFile(path, buf.Bytes(), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestExtractAppBundle(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "LowQuery.app.tar.gz") + entries := []tarEntry{ + {name: "LowQuery.app/", dir: true}, + {name: "LowQuery.app/Contents/", dir: true}, + {name: "LowQuery.app/Contents/Info.plist", body: ""}, + {name: "LowQuery.app/Contents/MacOS/LowQuery", body: "binary"}, + } + if runtime.GOOS != "windows" { + entries = append(entries, + tarEntry{name: "LowQuery.app/Contents/Frameworks/X.framework/Versions/A/X", body: "lib"}, + tarEntry{name: "LowQuery.app/Contents/Frameworks/X.framework/Versions/Current", link: "A"}) + } + writeTarGz(t, archive, entries) + dest := filepath.Join(dir, "new.app") + if err := extractAppBundle(archive, dest); err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(filepath.Join(dest, "Contents", "MacOS", "LowQuery")) + if err != nil || string(b) != "binary" { + t.Fatalf("%q %v", b, err) + } + if runtime.GOOS != "windows" { + b, err := os.ReadFile(filepath.Join(dest, "Contents", "Frameworks", "X.framework", "Versions", "Current", "X")) + if err != nil || string(b) != "lib" { + t.Fatalf("symlink: %q %v", b, err) + } + } +} + +func TestExtractAppBundleRejectsEscapes(t *testing.T) { + cases := [][]tarEntry{ + {{name: "LowQuery.app/../../evil", body: "x"}}, + {{name: "/etc/evil", body: "x"}}, + {{name: "LowQuery.app/Contents/link", link: "../../../etc"}}, + {{name: "LowQuery.app/Contents/link", link: "/etc"}}, + {{name: "LowQuery.app/", dir: true}}, + } + for i, entries := range cases { + dir := t.TempDir() + archive := filepath.Join(dir, "a.tar.gz") + writeTarGz(t, archive, entries) + if err := extractAppBundle(archive, filepath.Join(dir, "out")); err == nil { + t.Errorf("case %d extracted", i) + } + if _, err := os.Stat(filepath.Join(dir, "evil")); err == nil { + t.Errorf("case %d escaped", i) + } + } +} + +func TestReplaceFile(t *testing.T) { + dir := t.TempDir() + current := filepath.Join(dir, "LowQuery.AppImage") + next := filepath.Join(t.TempDir(), "new.AppImage") + if err := os.WriteFile(current, []byte("old"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(next, []byte("\x7fELFnew"), 0o600); err != nil { + t.Fatal(err) + } + if err := replaceFile(current, next); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(current) + if string(b) != "\x7fELFnew" { + t.Fatalf("content %q", b) + } + if runtime.GOOS != "windows" { + if info, _ := os.Stat(current); info.Mode().Perm() != 0o755 { + t.Fatalf("mode %v", info.Mode()) + } + } + if entries, _ := os.ReadDir(dir); len(entries) != 1 { + t.Fatalf("left behind: %v", entries) + } +} + +func TestCheckFormat(t *testing.T) { + dir := t.TempDir() + write := func(name, content string) string { + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + return p + } + ok := map[string]string{ + "appimage": write("a.AppImage", "\x7fELF\x02\x01"), + "deb": write("a.deb", "!\ndebian-binary"), + "rpm": write("a.rpm", "\xed\xab\xee\xdb\x03\x00"), + } + for channel, file := range ok { + if err := checkFormat(channel, file); err != nil { + t.Errorf("%s: %v", channel, err) + } + } + bad := write("bad", "") + for _, channel := range []string{"appimage", "deb", "rpm"} { + if err := checkFormat(channel, bad); err == nil { + t.Errorf("%s accepted html", channel) + } + } + if !errors.Is(checkFormat("portable", bad), ErrCannotInstall) { + t.Error("portable channel accepted") + } + switch runtime.GOOS { + case "windows": + if checkFormat("installer", write("s.exe", "MZ\x90")) != nil || checkFormat("installer", bad) == nil { + t.Error("windows setup check") + } + case "darwin": + if checkFormat("installer", write("a.tar.gz", "\x1f\x8b\x08")) != nil || checkFormat("installer", bad) == nil { + t.Error("mac archive check") + } + } +} + +// Install checks the signature before anything else, so a package changed +// after its download is never run. (A valid package is never installed +// here: that would run the setup.) +func TestInstallRejectsTamperedPackage(t *testing.T) { + data := []byte(readTestdata(t, "payload.bin")) + data[0] ^= 1 + path := filepath.Join(t.TempDir(), "payload.bin") + if err := os.WriteFile(path, data, 0o644); err != nil { + t.Fatal(err) + } + pkg := &Package{Version: "1.2.3", Path: path, Signature: readTestdata(t, "payload.bin.sig")} + policy := Policy{Channel: "installer", CanInstall: true, Path: t.TempDir()} + if err := Install(pkg, policy, readTestdata(t, "throwaway.key.pub")); !errors.Is(err, ErrBadSignature) { + t.Fatalf("got %v", err) + } + if err := Install(pkg, Policy{Channel: "portable"}, readTestdata(t, "throwaway.key.pub")); !errors.Is(err, ErrCannotInstall) { + t.Fatalf("portable: %v", err) + } +} diff --git a/internal/updater/install_windows.go b/internal/updater/install_windows.go new file mode 100644 index 0000000..ede3e25 --- /dev/null +++ b/internal/updater/install_windows.go @@ -0,0 +1,36 @@ +package updater + +import ( + "fmt" + "path/filepath" + + "golang.org/x/sys/windows" +) + +const installerFormat = "windows" + +// SetupArgs are what the Tauri updater passes the NSIS setup in passive +// mode: progress only (/P), an update of the existing install (/UPDATE) and +// a restart of the app when done (/R). +const SetupArgs = "/P /UPDATE /R" + +// install starts the setup through the shell, so a setup that needs +// elevation gets the UAC prompt. The caller quits so it can replace files. +func install(pkg *Package, policy Policy) error { + if policy.Channel != "installer" { + return ErrCannotInstall + } + verb, _ := windows.UTF16PtrFromString("open") + file, err := windows.UTF16PtrFromString(pkg.Path) + if err != nil { + return err + } + args, _ := windows.UTF16PtrFromString(SetupArgs) + dir, _ := windows.UTF16PtrFromString(filepath.Dir(pkg.Path)) + if err := windows.ShellExecute(0, verb, file, args, dir, windows.SW_SHOWNORMAL); err != nil { + return fmt.Errorf("could not start the setup: %w", err) + } + return nil +} + +func relaunch(Policy) error { return nil } diff --git a/internal/updater/manifest.go b/internal/updater/manifest.go new file mode 100644 index 0000000..cf21bf1 --- /dev/null +++ b/internal/updater/manifest.go @@ -0,0 +1,98 @@ +package updater + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "runtime" + "strings" +) + +// Manifest is latest.json, as .github/scripts/update_manifest.py writes it. +type Manifest struct { + Version string `json:"version"` + Notes string `json:"notes"` + PubDate string `json:"pub_date"` + Platforms map[string]Platform `json:"platforms"` +} + +// Platform is one downloadable package and its signature (base64 of the +// minisign signature text). +type Platform struct { + URL string `json:"url"` + Signature string `json:"signature"` +} + +// manifestLimit bounds the manifest read: it is a few kilobytes. +const manifestLimit = 4 << 20 + +// FetchManifest downloads and parses the manifest at url. +func FetchManifest(ctx context.Context, client *http.Client, url string) (*Manifest, error) { + if client == nil { + client = http.DefaultClient + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("manifest request failed: %s", resp.Status) + } + var m Manifest + if err := json.NewDecoder(io.LimitReader(resp.Body, manifestLimit)).Decode(&m); err != nil { + return nil, fmt.Errorf("invalid update manifest: %w", err) + } + m.Version = strings.TrimPrefix(strings.TrimSpace(m.Version), "v") + if m.Version == "" { + return nil, fmt.Errorf("invalid update manifest: no version") + } + return &m, nil +} + +// Select returns the manifest key and package for this copy: the policy's +// target when it has one, otherwise `{os}-{arch}`, as the Tauri updater does +// for installs without a bundle-specific key. +func (m *Manifest) Select(target string) (string, Platform, error) { + keys := []string{target} + if target == "" { + keys = DefaultTargets(runtime.GOOS, runtime.GOARCH) + } + for _, key := range keys { + if p, ok := m.Platforms[key]; ok && p.URL != "" && p.Signature != "" { + return key, p, nil + } + } + return "", Platform{}, fmt.Errorf("this release has no update for %s", strings.Join(keys, " or ")) +} + +// DefaultTargets are the manifest keys tried when the policy names none. +func DefaultTargets(goos, goarch string) []string { + base := goos + "-" + targetArch(goarch) + if goos == "windows" { + return []string{base + "-nsis", base} + } + return []string{base} +} + +// targetArch names goarch the way Rust (and so the manifest) does. +func targetArch(goarch string) string { + switch goarch { + case "amd64": + return "x86_64" + case "arm64": + return "aarch64" + case "386": + return "i686" + case "arm": + return "armv7" + } + return goarch +} diff --git a/internal/updater/manifest_test.go b/internal/updater/manifest_test.go new file mode 100644 index 0000000..c3789c0 --- /dev/null +++ b/internal/updater/manifest_test.go @@ -0,0 +1,105 @@ +package updater + +import ( + "context" + "net/http" + "net/http/httptest" + "reflect" + "runtime" + "testing" +) + +// The keys .github/scripts/update_manifest.py writes. +func releaseManifest() *Manifest { + p := func(name string) Platform { + return Platform{URL: "https://example.test/" + name, Signature: "sig-" + name} + } + return &Manifest{Version: "1.0.0", Platforms: map[string]Platform{ + "windows-x86_64": p("setup.exe"), + "windows-x86_64-nsis": p("setup.exe"), + "windows-x86_64-msi": p("x64.msi"), + "darwin-aarch64": p("macos-universal.app.tar.gz"), + "darwin-x86_64": p("macos-universal.app.tar.gz"), + "linux-x86_64-appimage": p("linux-x64.AppImage"), + "linux-x86_64-deb": p("linux-x64.deb"), + "linux-x86_64-rpm": p("linux-x64.rpm"), + }} +} + +func TestDefaultTargets(t *testing.T) { + cases := []struct { + goos, goarch string + want []string + }{ + {"windows", "amd64", []string{"windows-x86_64-nsis", "windows-x86_64"}}, + {"darwin", "arm64", []string{"darwin-aarch64"}}, + {"darwin", "amd64", []string{"darwin-x86_64"}}, + {"linux", "amd64", []string{"linux-x86_64"}}, + } + for _, c := range cases { + if got := DefaultTargets(c.goos, c.goarch); !reflect.DeepEqual(got, c.want) { + t.Errorf("%s/%s: %v, want %v", c.goos, c.goarch, got, c.want) + } + } +} + +func TestSelect(t *testing.T) { + m := releaseManifest() + for target, want := range map[string]string{ + "linux-x86_64-appimage": "linux-x64.AppImage", + "linux-x86_64-deb": "linux-x64.deb", + "linux-x86_64-rpm": "linux-x64.rpm", + "darwin-aarch64": "macos-universal.app.tar.gz", + } { + key, p, err := m.Select(target) + if err != nil || key != target || p.URL != "https://example.test/"+want { + t.Errorf("%s: %s %v %v", target, key, p, err) + } + } + if _, _, err := m.Select("linux-aarch64-deb"); err == nil { + t.Error("missing target selected") + } + // No target: the defaults of this machine (none for Linux, whose + // installable copies always name a target). + key, _, err := m.Select("") + switch runtime.GOOS + "/" + runtime.GOARCH { + case "windows/amd64": + if key != "windows-x86_64-nsis" { + t.Errorf("default key %s %v", key, err) + } + case "darwin/arm64", "darwin/amd64": + if err != nil { + t.Errorf("default key: %v", err) + } + case "linux/amd64": + if err == nil { + t.Errorf("linux default selected %s", key) + } + } + // An entry without a signature is never picked. + m.Platforms["linux-x86_64-deb"] = Platform{URL: "https://example.test/x.deb"} + if _, _, err := m.Select("linux-x86_64-deb"); err == nil { + t.Error("unsigned entry selected") + } +} + +func TestFetchManifest(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/missing" { + http.NotFound(w, r) + return + } + _, _ = w.Write([]byte(`{"version":"v2.0.1","notes":"n","pub_date":"2026-01-01T00:00:00Z","platforms":{"windows-x86_64":{"url":"https://x/a.exe","signature":"s"}}}`)) + })) + defer srv.Close() + m, err := FetchManifest(context.Background(), srv.Client(), srv.URL+"/latest.json") + if err != nil { + t.Fatal(err) + } + if m.Version != "2.0.1" || m.Notes != "n" || m.Platforms["windows-x86_64"].URL != "https://x/a.exe" { + t.Fatalf("%+v", m) + } + if _, err := FetchManifest(context.Background(), srv.Client(), srv.URL+"/missing"); err == nil { + t.Fatal("404 accepted") + } +} diff --git a/internal/updater/policy.go b/internal/updater/policy.go new file mode 100644 index 0000000..b30e4b8 --- /dev/null +++ b/internal/updater/policy.go @@ -0,0 +1,175 @@ +package updater + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" +) + +// Policy says whether this copy can update itself, as the Tauri builds +// decided it. Installs from the Windows setup, macOS app bundles in a writable +// folder, writable AppImages and .deb/.rpm installs download the signed +// update, install it and restart; others (the Arch package, portable copies) +// are only told a new version exists. +type Policy struct { + // installer, appimage, deb, rpm, package or portable. + Channel string `json:"channel"` + CanInstall bool `json:"canInstall"` + // Target is the manifest key when the default one does not apply. + Target *string `json:"target"` + + // Path is what an install replaces or restarts: the install folder + // (Windows), the .app bundle (macOS), the AppImage, or the executable. + Path string `json:"-"` +} + +// Env is what Detect looks at; tests replace its functions. +type Env struct { + GOOS string + GOARCH string + // Exe is the running executable. + Exe string + Getenv func(string) string + // Writable reports whether files can be created in dir. + Writable func(dir string) bool + // InstallLocations are the folders the Windows setup registered + // (HKCU, then HKLM, Uninstall\LowQuery\InstallLocation). + InstallLocations func() []string + // Owns reports whether the package manager behind program (dpkg-query + // -S, rpm -qf) installed path. + Owns func(program, flag, path string) bool +} + +// CurrentEnv is the Env of this process. +func CurrentEnv() Env { + exe, err := os.Executable() + if err == nil { + if resolved, err := filepath.EvalSymlinks(exe); err == nil { + exe = resolved + } + } + return Env{ + GOOS: runtime.GOOS, + GOARCH: runtime.GOARCH, + Exe: exe, + Getenv: os.Getenv, + Writable: dirWritable, + InstallLocations: registeredInstallLocations, + Owns: ownedBy, + } +} + +// DetectCurrent is Detect for this process. +func DetectCurrent() Policy { return Detect(CurrentEnv()) } + +// Detect works out the update policy of the copy env describes. +func Detect(env Env) Policy { + portable := Policy{Channel: "portable", Path: env.Exe} + if env.Exe == "" { + return portable + } + switch env.GOOS { + case "windows": + return detectWindows(env) + case "darwin": + return detectMac(env) + case "linux": + return detectLinux(env) + } + return portable +} + +// detectWindows: an install by the setup is the folder it registered under +// Uninstall\LowQuery, holding the executable and uninstall.exe. That is the +// Tauri NSIS layout (%LOCALAPPDATA%\LowQuery by default), which the Go setup +// keeps. +func detectWindows(env Env) Policy { + dir := filepath.Dir(env.Exe) + portable := Policy{Channel: "portable", Path: env.Exe} + if !fileExists(filepath.Join(dir, "uninstall.exe")) || env.InstallLocations == nil { + return portable + } + for _, loc := range env.InstallLocations() { + loc = strings.Trim(strings.TrimSpace(loc), `"`) + if loc != "" && strings.EqualFold(filepath.Clean(loc), filepath.Clean(dir)) { + return Policy{Channel: "installer", CanInstall: true, Path: dir} + } + } + return portable +} + +// detectMac: the executable must sit in Foo.app/Contents/MacOS, and the +// folder holding the bundle must be writable to swap it for the new one. +func detectMac(env Env) Policy { + bundle := appBundle(env.Exe) + if bundle == "" { + return Policy{Channel: "portable", Path: env.Exe} + } + writable := env.Writable != nil && env.Writable(filepath.Dir(bundle)) + return Policy{Channel: "installer", CanInstall: writable, Path: bundle} +} + +// appBundle is the .app bundle holding exe, or "". +func appBundle(exe string) string { + macos := filepath.Dir(exe) + contents := filepath.Dir(macos) + bundle := filepath.Dir(contents) + if filepath.Base(macos) != "MacOS" || filepath.Base(contents) != "Contents" || + !strings.HasSuffix(strings.ToLower(bundle), ".app") { + return "" + } + return bundle +} + +func detectLinux(env Env) Policy { + arch := targetArch(env.GOARCH) + if appimage := env.Getenv("APPIMAGE"); appimage != "" { + writable := env.Writable != nil && env.Writable(filepath.Dir(appimage)) + return Policy{Channel: "appimage", CanInstall: writable, Target: ptr(fmt.Sprintf("linux-%s-appimage", arch)), Path: appimage} + } + if env.Owns != nil { + for _, pm := range []struct{ channel, program, flag string }{ + {"deb", "dpkg-query", "-S"}, + {"rpm", "rpm", "-qf"}, + } { + if env.Owns(pm.program, pm.flag, env.Exe) { + return Policy{Channel: pm.channel, CanInstall: true, Target: ptr(fmt.Sprintf("linux-%s-%s", arch, pm.channel)), Path: env.Exe} + } + } + } + if strings.HasPrefix(env.Exe, "/usr/") || strings.HasPrefix(env.Exe, "/opt/") { + return Policy{Channel: "package", Path: env.Exe} + } + return Policy{Channel: "portable", Path: env.Exe} +} + +func ptr(s string) *string { return &s } + +func fileExists(path string) bool { + info, err := os.Stat(path) + return err == nil && !info.IsDir() +} + +// dirWritable creates and removes a probe file in dir. +func dirWritable(dir string) bool { + probe := filepath.Join(dir, fmt.Sprintf(".lowquery-update-check-%d", os.Getpid())) + f, err := os.OpenFile(probe, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err != nil { + return false + } + f.Close() + _ = os.Remove(probe) + return true +} + +// ownedBy runs `program flag path` (dpkg-query -S, rpm -qf), which succeeds +// when a package installed path. +func ownedBy(program, flag, path string) bool { + if _, err := exec.LookPath(program); err != nil { + return false + } + return exec.Command(program, flag, path).Run() == nil +} diff --git a/internal/updater/policy_test.go b/internal/updater/policy_test.go new file mode 100644 index 0000000..2a350cd --- /dev/null +++ b/internal/updater/policy_test.go @@ -0,0 +1,135 @@ +package updater + +import ( + "os" + "path/filepath" + "testing" +) + +func touch(t *testing.T, path string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, nil, 0o755); err != nil { + t.Fatal(err) + } +} + +func target(p Policy) string { + if p.Target == nil { + return "" + } + return *p.Target +} + +func TestDetectWindows(t *testing.T) { + dir := filepath.Join(t.TempDir(), "LowQuery") + exe := filepath.Join(dir, "lowquery.exe") + touch(t, exe) + env := func(locations ...string) Env { + return Env{GOOS: "windows", GOARCH: "amd64", Exe: exe, InstallLocations: func() []string { return locations }} + } + + // No uninstall.exe: a copied folder, even if registered. + if p := Detect(env(dir)); p.Channel != "portable" || p.CanInstall { + t.Fatalf("without uninstall.exe: %+v", p) + } + touch(t, filepath.Join(dir, "uninstall.exe")) + // The setup writes InstallLocation in quotes. + for _, loc := range []string{dir, `"` + dir + `"`, dir + string(filepath.Separator)} { + p := Detect(env(loc)) + if p.Channel != "installer" || !p.CanInstall || p.Target != nil || p.Path != dir { + t.Fatalf("registered at %s: %+v", loc, p) + } + } + // Registered somewhere else, or not at all. + if p := Detect(env(filepath.Join(t.TempDir(), "Other"))); p.Channel != "portable" { + t.Fatalf("other location: %+v", p) + } + if p := Detect(env()); p.Channel != "portable" { + t.Fatalf("unregistered: %+v", p) + } +} + +func TestDetectMac(t *testing.T) { + apps := t.TempDir() + exe := filepath.Join(apps, "LowQuery.app", "Contents", "MacOS", "LowQuery") + writable := true + env := Env{GOOS: "darwin", GOARCH: "arm64", Exe: exe, Writable: func(dir string) bool { + if dir != apps { + t.Errorf("probed %s, want %s", dir, apps) + } + return writable + }} + if p := Detect(env); p.Channel != "installer" || !p.CanInstall || p.Path != filepath.Join(apps, "LowQuery.app") || p.Target != nil { + t.Fatalf("writable: %+v", p) + } + writable = false + if p := Detect(env); p.Channel != "installer" || p.CanInstall { + t.Fatalf("read-only folder: %+v", p) + } + env.Exe = filepath.Join(apps, "lowquery") + if p := Detect(env); p.Channel != "portable" || p.CanInstall { + t.Fatalf("outside a bundle: %+v", p) + } +} + +func TestDetectLinux(t *testing.T) { + vars := map[string]string{} + owner := "" + writable := true + env := Env{ + GOOS: "linux", GOARCH: "amd64", Exe: "/usr/bin/lowquery", + Getenv: func(k string) string { return vars[k] }, + Writable: func(string) bool { return writable }, + Owns: func(program, flag, path string) bool { + return program+" "+flag == owner && path == "/usr/bin/lowquery" + }, + } + + vars["APPIMAGE"] = "/home/u/Apps/LowQuery.AppImage" + if p := Detect(env); p.Channel != "appimage" || !p.CanInstall || target(p) != "linux-x86_64-appimage" || p.Path != vars["APPIMAGE"] { + t.Fatalf("appimage: %+v", p) + } + writable = false + if p := Detect(env); p.Channel != "appimage" || p.CanInstall { + t.Fatalf("read-only appimage: %+v", p) + } + delete(vars, "APPIMAGE") + + owner = "dpkg-query -S" + if p := Detect(env); p.Channel != "deb" || !p.CanInstall || target(p) != "linux-x86_64-deb" { + t.Fatalf("deb: %+v", p) + } + owner = "rpm -qf" + if p := Detect(env); p.Channel != "rpm" || !p.CanInstall || target(p) != "linux-x86_64-rpm" { + t.Fatalf("rpm: %+v", p) + } + env.GOARCH = "arm64" + if p := Detect(env); target(p) != "linux-aarch64-rpm" { + t.Fatalf("arm64 rpm: %+v", p) + } + // Installed by another package manager (pacman). + owner = "" + if p := Detect(env); p.Channel != "package" || p.CanInstall || p.Target != nil { + t.Fatalf("package: %+v", p) + } + env.Exe = "/home/u/bin/lowquery" + if p := Detect(env); p.Channel != "portable" || p.CanInstall { + t.Fatalf("portable: %+v", p) + } +} + +func TestDirWritable(t *testing.T) { + dir := t.TempDir() + if !dirWritable(dir) { + t.Fatal("temp dir not writable") + } + if entries, _ := os.ReadDir(dir); len(entries) != 0 { + t.Fatal("probe file left behind") + } + if dirWritable(filepath.Join(dir, "missing")) { + t.Fatal("missing dir writable") + } +} diff --git a/internal/updater/registry_other.go b/internal/updater/registry_other.go new file mode 100644 index 0000000..5f17b6e --- /dev/null +++ b/internal/updater/registry_other.go @@ -0,0 +1,5 @@ +//go:build !windows + +package updater + +func registeredInstallLocations() []string { return nil } diff --git a/internal/updater/registry_windows.go b/internal/updater/registry_windows.go new file mode 100644 index 0000000..a7dcff2 --- /dev/null +++ b/internal/updater/registry_windows.go @@ -0,0 +1,22 @@ +package updater + +import "golang.org/x/sys/windows/registry" + +const uninstallKey = `Software\Microsoft\Windows\CurrentVersion\Uninstall\LowQuery` + +// registeredInstallLocations reads InstallLocation of the setup's uninstall +// entry, per user first, then per machine. Read only. +func registeredInstallLocations() []string { + var out []string + for _, root := range []registry.Key{registry.CURRENT_USER, registry.LOCAL_MACHINE} { + k, err := registry.OpenKey(root, uninstallKey, registry.QUERY_VALUE) + if err != nil { + continue + } + if v, _, err := k.GetStringValue("InstallLocation"); err == nil && v != "" { + out = append(out, v) + } + k.Close() + } + return out +} diff --git a/internal/updater/signature.go b/internal/updater/signature.go new file mode 100644 index 0000000..8016f07 --- /dev/null +++ b/internal/updater/signature.go @@ -0,0 +1,177 @@ +package updater + +import ( + "bytes" + "encoding/base64" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "aead.dev/minisign" +) + +// Signatures are Tauri updater signatures: base64 of a minisign signature +// file. tauri signer sign writes them with the untrusted comment below and a +// trusted comment of tab-separated fields, `timestamp:\tfile:` +// and, when signed for a version, `\tversion:`. +const untrustedComment = "signature from tauri secret key" + +// ErrBadSignature reports a package that does not match its signature. +var ErrBadSignature = errors.New("the update's signature does not match: it was not installed") + +// ParsePublicKey decodes a Tauri public key (base64 of a minisign public key +// file). +func ParsePublicKey(encoded string) (minisign.PublicKey, error) { + var key minisign.PublicKey + text, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded)) + if err != nil { + return key, fmt.Errorf("invalid public key: %w", err) + } + if err := key.UnmarshalText(bytes.TrimSpace(text)); err != nil { + return key, fmt.Errorf("invalid public key: %w", err) + } + return key, nil +} + +// ParseSignature decodes a Tauri signature (base64 of a minisign signature). +func ParseSignature(encoded string) (minisign.Signature, error) { + var sig minisign.Signature + text, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded)) + if err != nil { + return sig, fmt.Errorf("invalid signature: %w", err) + } + if err := sig.UnmarshalText(text); err != nil { + return sig, fmt.Errorf("invalid signature: %w", err) + } + return sig, nil +} + +// VerifyFile checks the file at path against signature with publicKey, as +// the Tauri updater does: minisign signature (prehashed or legacy) and, when +// the trusted comment names a version, that it is the announced one. +func VerifyFile(path, signature, publicKey, announcedVersion string) error { + key, err := ParsePublicKey(publicKey) + if err != nil { + return err + } + sig, err := ParseSignature(signature) + if err != nil { + return err + } + if sig.KeyID != key.ID() { + return fmt.Errorf("%w (signed with key %X, expected %X)", ErrBadSignature, sig.KeyID, key.ID()) + } + raw, _ := base64.StdEncoding.DecodeString(strings.TrimSpace(signature)) + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + var ok bool + if sig.Algorithm == minisign.HashEdDSA { + r := minisign.NewReader(f) + if _, err := io.Copy(io.Discard, r); err != nil { + return err + } + ok = r.Verify(key, raw) + } else { + data, err := io.ReadAll(f) + if err != nil { + return err + } + ok = minisign.Verify(key, data, raw) + } + if !ok { + return ErrBadSignature + } + // The trusted comment is covered by the signature, so it is only read + // once the signature holds. + return checkSignedVersion(sig.TrustedComment, announcedVersion) +} + +// checkSignedVersion rejects a manifest that pairs a version number with the +// package of another release. +func checkSignedVersion(trustedComment, announced string) error { + signed, ok := signedVersion(trustedComment) + if !ok { + return nil + } + if strings.TrimPrefix(signed, "v") == strings.TrimPrefix(announced, "v") { + return nil + } + return fmt.Errorf("the update was signed for version %s, not %s: it was not installed", signed, announced) +} + +func signedVersion(trustedComment string) (string, bool) { + for _, field := range strings.Split(trustedComment, "\t") { + if v, ok := strings.CutPrefix(field, "version:"); ok { + return v, true + } + } + return "", false +} + +// LoadSecretKey decodes a Tauri private key (base64 of a minisign secret key +// file, usually scrypt-encrypted) with its password, which may be empty. +func LoadSecretKey(encoded, password string) (minisign.PrivateKey, error) { + text := []byte(strings.TrimSpace(encoded)) + if !bytes.HasPrefix(text, []byte("untrusted comment:")) { + decoded, err := base64.StdEncoding.DecodeString(string(text)) + if err != nil { + return minisign.PrivateKey{}, errors.New("the private key is not valid base64") + } + text = bytes.TrimSpace(decoded) + } + text = bytes.ReplaceAll(text, []byte("\r\n"), []byte("\n")) + if minisign.IsEncrypted(text) { + key, err := minisign.DecryptKey(password, text) + if err != nil { + return minisign.PrivateKey{}, errors.New("could not decrypt the private key: wrong password?") + } + return key, nil + } + var key minisign.PrivateKey + if err := key.UnmarshalText(text); err != nil { + return minisign.PrivateKey{}, errors.New("the private key is not a minisign secret key") + } + return key, nil +} + +// SignFile signs the file at path as tauri signer sign does and returns the +// content of its .sig file. version, when not empty, is bound into the +// trusted comment. +func SignFile(key minisign.PrivateKey, path, version string, now time.Time) (string, error) { + name := filepath.Base(path) + if strings.ContainsAny(name, "\t\r\n") { + return "", fmt.Errorf("%q cannot be signed: its name contains a tab or newline", name) + } + if strings.ContainsAny(version, "\t\r\n") { + return "", fmt.Errorf("version %q contains a tab or newline", version) + } + comment := "timestamp:" + strconv.FormatInt(now.Unix(), 10) + "\tfile:" + name + if version != "" { + comment += "\tversion:" + version + } + return signFileWithComment(key, path, comment) +} + +func signFileWithComment(key minisign.PrivateKey, path, trustedComment string) (string, error) { + f, err := os.Open(path) + if err != nil { + return "", err + } + defer f.Close() + r := minisign.NewReader(f) + if _, err := io.Copy(io.Discard, r); err != nil { + return "", err + } + // Prehashed (BLAKE2b-512) like rust-minisign; the text ends with a newline + // like its SignatureBox, so the bytes match what Tauri writes. + text := r.SignWithComments(key, trustedComment, untrustedComment) + return base64.StdEncoding.EncodeToString(text), nil +} diff --git a/internal/updater/signature_test.go b/internal/updater/signature_test.go new file mode 100644 index 0000000..d284e9c --- /dev/null +++ b/internal/updater/signature_test.go @@ -0,0 +1,180 @@ +package updater + +import ( + "encoding/base64" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "aead.dev/minisign" +) + +// testdata holds a throwaway key made with `tauri signer generate -p +// throwaway-pass` (tauri-cli 2.12.3) and payload.bin signed by `tauri signer +// sign`, without and with --app-version 1.2.3. other.key.pub is an unrelated +// key. +const throwawayPassword = "throwaway-pass" + +func readTestdata(t *testing.T, name string) string { + t.Helper() + b, err := os.ReadFile(filepath.Join("testdata", name)) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func throwawayKey(t *testing.T) minisign.PrivateKey { + t.Helper() + key, err := LoadSecretKey(readTestdata(t, "throwaway.key"), throwawayPassword) + if err != nil { + t.Fatal(err) + } + return key +} + +// The key every release since 0.1 is signed with; existing installs only +// accept updates signed by it. +func TestPublicKeyID(t *testing.T) { + key, err := ParsePublicKey(PublicKey) + if err != nil { + t.Fatal(err) + } + if key.ID() != 0xC3B42EFDD4E426AB { + t.Fatalf("key id %X", key.ID()) + } +} + +func TestVerifyTauriSignatures(t *testing.T) { + pub := readTestdata(t, "throwaway.key.pub") + payload := filepath.Join("testdata", "payload.bin") + plain := readTestdata(t, "payload.bin.sig") + versioned := readTestdata(t, "payload.bin.v1.2.3.sig") + + if err := VerifyFile(payload, plain, pub, "4.5.6"); err != nil { + t.Fatalf("unversioned signature: %v", err) + } + for _, v := range []string{"1.2.3", "v1.2.3"} { + if err := VerifyFile(payload, versioned, pub, v); err != nil { + t.Fatalf("versioned signature, %s: %v", v, err) + } + } + if err := VerifyFile(payload, versioned, pub, "1.2.4"); err == nil || !strings.Contains(err.Error(), "signed for version 1.2.3") { + t.Fatalf("version mismatch accepted: %v", err) + } +} + +func TestVerifyRejectsTamperedFile(t *testing.T) { + data := []byte(readTestdata(t, "payload.bin")) + data[100] ^= 1 + path := filepath.Join(t.TempDir(), "payload.bin") + if err := os.WriteFile(path, data, 0o644); err != nil { + t.Fatal(err) + } + err := VerifyFile(path, readTestdata(t, "payload.bin.sig"), readTestdata(t, "throwaway.key.pub"), "") + if !errors.Is(err, ErrBadSignature) { + t.Fatalf("got %v", err) + } +} + +func TestVerifyRejectsWrongKey(t *testing.T) { + err := VerifyFile(filepath.Join("testdata", "payload.bin"), readTestdata(t, "payload.bin.sig"), readTestdata(t, "other.key.pub"), "") + if !errors.Is(err, ErrBadSignature) { + t.Fatalf("got %v", err) + } + // Nor the key LowQuery ships with. + err = VerifyFile(filepath.Join("testdata", "payload.bin"), readTestdata(t, "payload.bin.sig"), PublicKey, "") + if !errors.Is(err, ErrBadSignature) { + t.Fatalf("got %v", err) + } +} + +func TestVerifyRejectsTamperedTrustedComment(t *testing.T) { + text, _ := base64.StdEncoding.DecodeString(readTestdata(t, "payload.bin.v1.2.3.sig")) + forged := strings.Replace(string(text), "version:1.2.3", "version:9.9.9", 1) + sig := base64.StdEncoding.EncodeToString([]byte(forged)) + err := VerifyFile(filepath.Join("testdata", "payload.bin"), sig, readTestdata(t, "throwaway.key.pub"), "9.9.9") + if !errors.Is(err, ErrBadSignature) { + t.Fatalf("got %v", err) + } +} + +// The .sig SignFile writes has the layout tauri signer sign writes; Ed25519 +// signatures from rust-minisign are randomized, so the bytes differ only in +// the signatures and the timestamp. +func TestSignMatchesTauriFormat(t *testing.T) { + key := throwawayKey(t) + payload := filepath.Join("testdata", "payload.bin") + now := time.Unix(1796409937, 0) + for _, version := range []string{"", "1.2.3"} { + got, err := SignFile(key, payload, version, now) + if err != nil { + t.Fatal(err) + } + if strings.ContainsAny(got, "\r\n") { + t.Fatal(".sig content must be one base64 line without a newline") + } + want := readTestdata(t, "payload.bin.sig") + comment := "timestamp:1796409937\tfile:payload.bin" + if version != "" { + want = readTestdata(t, "payload.bin.v1.2.3.sig") + comment += "\tversion:1.2.3" + } + gotText, _ := base64.StdEncoding.DecodeString(got) + wantText, _ := base64.StdEncoding.DecodeString(want) + gl, wl := strings.Split(string(gotText), "\n"), strings.Split(string(wantText), "\n") + if len(gl) != 5 || len(wl) != 5 || gl[4] != "" || wl[4] != "" { + t.Fatalf("line layout: got %q want %q", gl, wl) + } + if gl[0] != wl[0] { + t.Fatalf("untrusted comment %q, want %q", gl[0], wl[0]) + } + // Algorithm (ED, prehashed) and key id lead the signature line. + if gl[1][:12] != wl[1][:12] || len(gl[1]) != len(wl[1]) || len(gl[3]) != len(wl[3]) { + t.Fatalf("signature line %q, want like %q", gl[1], wl[1]) + } + if gl[2] != "trusted comment: "+comment { + t.Fatalf("trusted comment %q", gl[2]) + } + if err := VerifyFile(payload, got, readTestdata(t, "throwaway.key.pub"), "1.2.3"); err != nil { + t.Fatal(err) + } + } +} + +func TestLoadSecretKey(t *testing.T) { + encoded := readTestdata(t, "throwaway.key") + if _, err := LoadSecretKey(encoded, "wrong"); err == nil { + t.Fatal("wrong password accepted") + } + if _, err := LoadSecretKey("not base64!", ""); err == nil { + t.Fatal("garbage accepted") + } + // The decoded key file (minisign's own format) works too. + text, _ := base64.StdEncoding.DecodeString(encoded) + key, err := LoadSecretKey(string(text), throwawayPassword) + if err != nil { + t.Fatal(err) + } + pub, _ := ParsePublicKey(readTestdata(t, "throwaway.key.pub")) + if key.ID() != pub.ID() { + t.Fatalf("key id %X, public key id %X", key.ID(), pub.ID()) + } + // An unencrypted key. + raw, _ := key.MarshalText() + if _, err := LoadSecretKey(base64.StdEncoding.EncodeToString(raw), ""); err != nil { + t.Fatal(err) + } +} + +func TestSignRejectsTabInName(t *testing.T) { + if _, err := SignFile(throwawayKey(t), "a\tb", "", time.Now()); err == nil { + t.Fatal("tab accepted") + } + if _, err := SignFile(throwawayKey(t), filepath.Join("testdata", "payload.bin"), "1\n2", time.Now()); err == nil { + t.Fatal("newline in version accepted") + } +} diff --git a/internal/updater/testdata/other.key.pub b/internal/updater/testdata/other.key.pub new file mode 100644 index 0000000..10b6519 --- /dev/null +++ b/internal/updater/testdata/other.key.pub @@ -0,0 +1 @@ +dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDg5NUJGRDBERkY2RDg1MDkKUldRSmhXMy9EZjFiaVVKYkFLZzNtc3VHcU9DbHRtYWtGb3NtdllFZVhJOFZLdGFVaFd0VWVvWUEK \ No newline at end of file diff --git a/internal/updater/testdata/payload.bin b/internal/updater/testdata/payload.bin new file mode 100644 index 0000000..334d115 Binary files /dev/null and b/internal/updater/testdata/payload.bin differ diff --git a/internal/updater/testdata/payload.bin.sig b/internal/updater/testdata/payload.bin.sig new file mode 100644 index 0000000..52f3b30 --- /dev/null +++ b/internal/updater/testdata/payload.bin.sig @@ -0,0 +1 @@ +dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUeEV4UGJ0MzVocDd5aUhodHZHQnk3Zlo3MFdCYXNqU04reWFaZk9OTTNyTmEwV3hwc1RsOFZBb2FJL0NzSkxROHpyeDY5VFR5YTJoUzRycXQrU29xZytQSU5RMGxGUHdVPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzk2NDA5OTM3CWZpbGU6cGF5bG9hZC5iaW4KSmJlckdBTnVIQ1JtMjdUZVZFQXhBeUo3M1NkWlJhbFl3Q1RFUVNING55SlNwV2VtYUw5ZDd3akQ1SjRnVzBqNnBGRGRsSHhOcVNrRDV3YmNHQVkvQ1E9PQo= \ No newline at end of file diff --git a/internal/updater/testdata/payload.bin.v1.2.3.sig b/internal/updater/testdata/payload.bin.v1.2.3.sig new file mode 100644 index 0000000..eacbe93 --- /dev/null +++ b/internal/updater/testdata/payload.bin.v1.2.3.sig @@ -0,0 +1 @@ +dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUeEV4UGJ0MzVocDVZbm1MUWMzdlp6NHN0T0VhTHZ3OVN3ZHdJejlHQklXMHA1c2hranBobTFrR21TU01uWG8ydkRjUjMzd1AyNFFwakpXSU5WU01kYWY0MkJNQjVFb2dzPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzk2NDA5OTM3CWZpbGU6cGF5bG9hZC5iaW4JdmVyc2lvbjoxLjIuMwpsTUtEbTA3REp5OWVTNTRBWVZwMndyMjJnRlNjNEVEQzNIczV4K011Vm1xelFwR2dSWVhZTS92MVlnS1lWV3l1dk1xRmxNa08rTkJCakNiZ25KYU1DZz09Cg== \ No newline at end of file diff --git a/internal/updater/testdata/throwaway.key b/internal/updater/testdata/throwaway.key new file mode 100644 index 0000000..9153060 --- /dev/null +++ b/internal/updater/testdata/throwaway.key @@ -0,0 +1 @@ +dW50cnVzdGVkIGNvbW1lbnQ6IHJzaWduIGVuY3J5cHRlZCBzZWNyZXQga2V5ClJXUlRZMEl5NnR4OGc2Ump0N1FkaWJEWkNqKzZRSWFtSDR2NytYbktCeVlvNk9ha0dKMEFBQkFBQUFBQUFBQUFBQUlBQUFBQXVZZFNUcjRSOTRpaXY3Vm5uSHNncXFiV1FscEpaVDRaQlpFS3lpVzFEc0lUbnlvVjIzanZSNFBMa01qR2NkQ3kvaUtFakFid0poR0RTMTBtNSs4ckFacEZsT2J0MElJbEhVbHhldEhTbTNBVE9LNGdrREFDWTBJRUF3SzREMTVYT3d3NVppS1JweGM9Cg== \ No newline at end of file diff --git a/internal/updater/testdata/throwaway.key.pub b/internal/updater/testdata/throwaway.key.pub new file mode 100644 index 0000000..62d1471 --- /dev/null +++ b/internal/updater/testdata/throwaway.key.pub @@ -0,0 +1 @@ +dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEE3NjE3RUI3REIxMzEzRjEKUldUeEV4UGJ0MzVocHh1djE5eXN3M0NDeVpJMjJqT05vYW5lUkQ3aEYybFJuUWpEVGJoUXBsSGYK \ No newline at end of file diff --git a/internal/updater/updater.go b/internal/updater/updater.go new file mode 100644 index 0000000..46a770e --- /dev/null +++ b/internal/updater/updater.go @@ -0,0 +1,19 @@ +// Package updater updates LowQuery from GitHub Releases with the same +// manifest (latest.json) and signatures as the Tauri updater, so Tauri +// installs and Go installs read one manifest and trust one key. +// +// The flow: FetchManifest, Manifest.Select for this platform, Download +// (which verifies the minisign signature against PublicKey), then Install +// and Relaunch. Detect tells whether this copy can install updates at all. +package updater + +// PublicKey verifies every update: base64 of a minisign public key file, the +// same key the Tauri builds trusted (plugins.updater.pubkey). Changing it +// strands every install that trusts the old key. +const PublicKey = "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEMzQjQyRUZERDRFNDI2QUIKUldTckp1VFUvUzYwdzYwaVpFS1dtRjhzeFZxbkt4VEpjMUorbEN2emk1MjdHektJczlTcXl4SkYK" + +// ManifestURL is the manifest every release publishes. +const ManifestURL = "https://github.com/LowBloat/LowQuery/releases/latest/download/latest.json" + +// ProgressEvent is the event download progress is sent as. +const ProgressEvent = "update-progress" diff --git a/main.go b/main.go index 47be1f1..ea9738c 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,7 @@ import ( "log" "os" "path/filepath" + "runtime" "strconv" "strings" "sync" @@ -16,6 +17,7 @@ import ( "github.com/LowBloat/LowQuery/internal/app" "github.com/LowBloat/LowQuery/internal/mcp" + "github.com/LowBloat/LowQuery/internal/menubar" "github.com/LowBloat/LowQuery/internal/profiles" ) @@ -98,7 +100,19 @@ func main() { }) frame := &mainWindow{win: win} backend.SetWindow(frame) + backend.SetQuit(wails.Quit) backend.SetEmitter(func(event string, data any) { wails.Event.Emit(event, data) }) + // macOS has a global menu bar: the page describes its menus and Go + // builds them. Until it does, the bar holds only the standard menus, not + // Wails' default one with Reload and developer tools. Windows and Linux + // keep the menus the page draws in its title bar. + if runtime.GOOS == "darwin" { + bar := menubar.New(wails.Menu.SetApplicationMenu, func(id string) { + backend.Emit(app.MenuEvent, app.MenuClick{ID: id}) + }) + bar.Set(app.BuildMenuBar("LowQuery", app.MenuBarDescription{})) + backend.SetMenuBar(bar.Set) + } time.AfterFunc(firstShowFallback, frame.showFirstTime) if err := wails.Run(); err != nil { diff --git a/main_windows.go b/main_windows.go new file mode 100644 index 0000000..6ff4908 --- /dev/null +++ b/main_windows.go @@ -0,0 +1,23 @@ +package main + +import ( + "unsafe" + + "golang.org/x/sys/windows" +) + +// The Start Menu shortcut the setup creates carries this ID, as the Tauri +// builds' did, so a window started by the setup or at login groups with a +// pinned shortcut. +const appUserModelID = "dev.lowbloat.lowquery" + +func init() { + id, err := windows.UTF16PtrFromString(appUserModelID) + if err != nil { + return + } + proc := windows.NewLazySystemDLL("shell32.dll").NewProc("SetCurrentProcessExplicitAppUserModelID") + if proc.Find() == nil { + _, _, _ = proc.Call(uintptr(unsafe.Pointer(id))) + } +} diff --git a/package.json b/package.json index f006821..7e93657 100644 --- a/package.json +++ b/package.json @@ -20,8 +20,10 @@ "preview": "vite preview", "check": "svelte-check --tsconfig ./tsconfig.json", "test": "bun test", - "tauri": "tauri", - "version:check": "bun scripts/check-version.mjs" + "version:check": "bun scripts/check-version.mjs", + "package:windows": "bash packaging/windows/build.sh", + "package:linux": "bash packaging/linux/build.sh", + "package:macos": "bash packaging/macos/build.sh" }, "dependencies": { "@codeatlasdev/ui": "^4.5.0", @@ -36,17 +38,11 @@ "@lezer/highlight": "^1.2.5", "@lucide/svelte": "^1.59.0", "@tanstack/svelte-table": "^9.3.1", - "@tauri-apps/api": "^2.12.4", - "@tauri-apps/plugin-dialog": "^2.8.3", - "@tauri-apps/plugin-opener": "^2.7.2", - "@tauri-apps/plugin-process": "^2.4.0", - "@tauri-apps/plugin-updater": "^2.14.0", "@wailsio/runtime": "3.1.0", "codemirror": "^6.0.2" }, "devDependencies": { "@sveltejs/vite-plugin-svelte": "^7.3.1", - "@tauri-apps/cli": "^2.12.3", "@tsconfig/svelte": "^5.0.8", "@types/bun": "^1.4.3", "svelte": "^5.57.2", diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD index 44f6bf4..dd7e40b 100644 --- a/packaging/arch/PKGBUILD +++ b/packaging/arch/PKGBUILD @@ -16,7 +16,7 @@ options=('!strip') source=( "lowquery-${pkgver}.tar.gz::https://github.com/LowBloat/LowQuery/releases/download/v${pkgver}/LowQuery-${pkgver}-linux-x64-portable.tar.gz" "lowquery.desktop::https://raw.githubusercontent.com/LowBloat/LowQuery/v${pkgver}/packaging/arch/lowquery.desktop" - "lowquery.png::https://raw.githubusercontent.com/LowBloat/LowQuery/v${pkgver}/src-tauri/icons/128x128.png" + "lowquery.png::https://raw.githubusercontent.com/LowBloat/LowQuery/v${pkgver}/packaging/icons/128x128.png" ) sha256sums=('__SHA256_PORTABLE__' '__SHA256_DESKTOP__' '__SHA256_ICON__') diff --git a/packaging/arch/build.sh b/packaging/arch/build.sh new file mode 100644 index 0000000..761cd96 --- /dev/null +++ b/packaging/arch/build.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Builds the native Arch Linux package (pacman -U) with makepkg in an Arch +# container, from build/linux/lowquery (run packaging/linux/build.sh first): +# build/release/LowQuery--linux-x86_64.pkg.tar.zst +# Needs Docker and python3. +set -euo pipefail +cd "$(dirname "$0")/../.." +source packaging/common.sh + +version="$(app_version)" +if [ ! -x build/linux/lowquery ]; then + echo "build/linux/lowquery is missing: run packaging/linux/build.sh first." >&2 + exit 1 +fi +arch_build="$PWD/build/arch" +# The container leaves files owned by its build user. +rm -rf "$arch_build" 2>/dev/null || sudo rm -rf "$arch_build" +mkdir -p "$arch_build" "$RELEASE_DIR" +cp build/linux/lowquery "$arch_build/lowquery" +cp packaging/icons/128x128.png "$arch_build/lowquery.png" +cp packaging/arch/lowquery.desktop "$arch_build/lowquery.desktop" +python3 .github/scripts/render_pkgbuild.py local "$version" "$arch_build" +docker run --rm -v "$arch_build":/workspace -w /workspace archlinux:base-devel bash -c " + useradd -m builder && chown -R builder:builder /workspace && + su builder -c 'makepkg -f --nodeps' && + pacman -Qip *.pkg.tar.zst && pacman -Qlp *.pkg.tar.zst +" +package="$(find "$arch_build" -maxdepth 1 -name 'lowquery-bin-*.pkg.tar.zst' ! -name '*-debug-*' | head -n 1)" +cp "$package" "$RELEASE_DIR/LowQuery-$version-linux-x86_64.pkg.tar.zst" diff --git a/packaging/arch/lowquery.desktop b/packaging/arch/lowquery.desktop index 3fec228..5b03da5 100644 --- a/packaging/arch/lowquery.desktop +++ b/packaging/arch/lowquery.desktop @@ -7,4 +7,4 @@ Terminal=false Type=Application Categories=Development;Database; Keywords=sql;database;postgresql;oracle;mysql;mariadb;sqlserver;sqlite;redis;cassandra; -StartupWMClass=LowQuery +StartupWMClass=lowquery diff --git a/packaging/common.sh b/packaging/common.sh new file mode 100644 index 0000000..1c2eeeb --- /dev/null +++ b/packaging/common.sh @@ -0,0 +1,62 @@ +# Shared by the packaging scripts. Source it from the repository root. +# +# Release files go to build/release/ (git-ignored) under the names the +# releases have always used; intermediate files stay in build//. + +RELEASE_DIR=build/release + +# The Wails version in go.mod, so the wails3 tool matches the library. +wails_version() { + go list -m -f '{{.Version}}' github.com/wailsapp/wails/v3 +} + +wails3() { + local tags="" + # On Linux the CLI links WebKitGTK through cgo; gtk3 picks WebKitGTK 4.1. + if [ "$(uname -s)" = Linux ]; then + tags=gtk3 + fi + go run -tags "$tags" "github.com/wailsapp/wails/v3/cmd/wails3@$(wails_version)" "$@" +} + +# VERSION from the environment (the release passes the checked tag version, +# CI a test version), otherwise package.json, which main.go embeds. +app_version() { + local version="${VERSION:-}" + if [ -z "$version" ]; then + version="$(sed -nE 's/^[[:space:]]*"version":[[:space:]]*"([^"]+)".*/\1/p' package.json | head -n 1)" + fi + if ! [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Version '$version' is not X.Y.Z." >&2 + return 1 + fi + printf '%s\n' "$version" +} + +# main.go embeds dist/, so the interface has to be built first. +require_dist() { + if [ ! -f dist/index.html ]; then + echo "dist/index.html is missing: run 'bun run build' first." >&2 + return 1 + fi +} + +# Replaces @VERSION@ in a template. +render() { + sed "s/@VERSION@/$2/g" "$1" > "$3" +} + +# .sha256 next to every release file, in sha256sum's format. +write_checksums() { + local dir="$1" file hash + for file in "$dir"/*; do + case "$file" in *.sig | *.sha256) continue ;; esac + [ -f "$file" ] || continue + if command -v sha256sum >/dev/null 2>&1; then + hash="$(sha256sum "$file" | cut -d ' ' -f 1)" + else + hash="$(shasum -a 256 "$file" | cut -d ' ' -f 1)" + fi + printf '%s %s\n' "$hash" "$(basename "$file")" > "$file.sha256" + done +} diff --git a/src-tauri/icons/128x128.png b/packaging/icons/128x128.png similarity index 100% rename from src-tauri/icons/128x128.png rename to packaging/icons/128x128.png diff --git a/src-tauri/icons/128x128@2x.png b/packaging/icons/128x128@2x.png similarity index 100% rename from src-tauri/icons/128x128@2x.png rename to packaging/icons/128x128@2x.png diff --git a/src-tauri/icons/32x32.png b/packaging/icons/32x32.png similarity index 100% rename from src-tauri/icons/32x32.png rename to packaging/icons/32x32.png diff --git a/src-tauri/icons/icon.icns b/packaging/icons/icon.icns similarity index 100% rename from src-tauri/icons/icon.icns rename to packaging/icons/icon.icns diff --git a/src-tauri/icons/icon.ico b/packaging/icons/icon.ico similarity index 100% rename from src-tauri/icons/icon.ico rename to packaging/icons/icon.ico diff --git a/packaging/linux/LowQuery.desktop b/packaging/linux/LowQuery.desktop new file mode 100644 index 0000000..5b03da5 --- /dev/null +++ b/packaging/linux/LowQuery.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Name=LowQuery +Comment=Light SQL client for PostgreSQL, Oracle, MySQL, MariaDB, SQL Server, SQLite, Redis and Apache Cassandra +Exec=lowquery +Icon=lowquery +Terminal=false +Type=Application +Categories=Development;Database; +Keywords=sql;database;postgresql;oracle;mysql;mariadb;sqlserver;sqlite;redis;cassandra; +StartupWMClass=lowquery diff --git a/packaging/linux/build.sh b/packaging/linux/build.sh new file mode 100644 index 0000000..a4cb067 --- /dev/null +++ b/packaging/linux/build.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Builds the Linux release files from the Go app (x86_64): +# build/release/LowQuery--linux-x64.deb (updater file) +# build/release/LowQuery--linux-x64.rpm (updater file) +# build/release/LowQuery--linux-x64.AppImage (updater file) +# build/release/LowQuery--linux-x64-portable.tar.gz LowQuery, README, LICENSE +# and build/linux/lowquery, which packaging/arch/build.sh packages for pacman. +# Needs dist/ (bun run build), Go, a C compiler, libgtk-3-dev and +# libwebkit2gtk-4.1-dev. Build on the oldest distro the AppImage should run on +# (the release uses Ubuntu 22.04, as the Tauri builds did). +set -euo pipefail +cd "$(dirname "$0")/../.." +source packaging/common.sh + +NFPM_VERSION=v2.48.0 +LINUXDEPLOY_TAG=1-alpha-20251107-1 +LINUXDEPLOY_SHA256=c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d + +version="$(app_version)" +require_dist +work=build/linux +rm -rf "$work" +mkdir -p "$work" "$RELEASE_DIR" + +# gtk3: WebKitGTK 4.1 and GTK 3, which the Tauri builds used; Wails' default +# Linux backend is GTK 4 with WebKitGTK 6.0. +CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -tags production,gtk3 -trimpath \ + -ldflags "-s -w" -o "$work/lowquery" . + +# .deb and .rpm (package low-query, /usr/bin/lowquery, as Tauri's). +export VERSION="$version" +for format in deb rpm; do + go run "github.com/goreleaser/nfpm/v2/cmd/nfpm@$NFPM_VERSION" package \ + --config packaging/linux/nfpm.yaml --packager "$format" \ + --target "$RELEASE_DIR/LowQuery-$version-linux-x64.$format" +done + +# AppImage: wails3 copies the WebKit helper processes in and runs linuxdeploy +# with its GTK plugin. linuxdeploy is pinned here; wails3 would otherwise +# download the "continuous" build. +appimage="$work/appimage" +mkdir -p "$appimage" +curl -fsSL -o "$appimage/linuxdeploy-x86_64.AppImage" \ + "https://github.com/linuxdeploy/linuxdeploy/releases/download/$LINUXDEPLOY_TAG/linuxdeploy-x86_64.AppImage" +echo "$LINUXDEPLOY_SHA256 $appimage/linuxdeploy-x86_64.AppImage" | sha256sum -c - +cp packaging/icons/128x128@2x.png "$work/lowquery.png" +wails3 generate appimage -binary "$work/lowquery" -icon "$work/lowquery.png" \ + -desktopfile packaging/linux/LowQuery.desktop -outputdir "$work" -builddir "$appimage" +mv "$work/lowquery-x86_64.AppImage" "$RELEASE_DIR/LowQuery-$version-linux-x64.AppImage" +chmod 755 "$RELEASE_DIR/LowQuery-$version-linux-x64.AppImage" + +portable="$work/portable" +mkdir -p "$portable" +cp "$work/lowquery" "$portable/LowQuery" +chmod 755 "$portable/LowQuery" +cp README.md LICENSE "$portable/" +tar -czf "$RELEASE_DIR/LowQuery-$version-linux-x64-portable.tar.gz" -C "$portable" . + +ls -l "$RELEASE_DIR" diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml new file mode 100644 index 0000000..752a8cb --- /dev/null +++ b/packaging/linux/nfpm.yaml @@ -0,0 +1,57 @@ +# .deb and .rpm of LowQuery, built by packaging/linux/build.sh with nfpm from +# the repository root. VERSION comes from the environment. +# +# Same package name and files as the Tauri packages (0.5.x), so `dpkg -i` and +# `rpm -U` (what their updater runs) upgrade a Tauri install in place. +name: low-query +arch: amd64 +platform: linux +version: ${VERSION} +version_schema: none +maintainer: LowBloat +vendor: LowBloat +homepage: https://github.com/LowBloat/LowQuery +license: AGPL-3.0-only +section: devel +priority: optional +description: |- + Light SQL client for PostgreSQL, Oracle, MySQL, MariaDB, SQL Server, SQLite, Redis and Apache Cassandra + LowQuery is a lightweight SQL client for people who work with multiple databases, with a native driver for each one. + +contents: + - src: build/linux/lowquery + dst: /usr/bin/lowquery + file_info: + mode: 0755 + - src: packaging/linux/LowQuery.desktop + dst: /usr/share/applications/LowQuery.desktop + file_info: + mode: 0644 + - src: packaging/icons/32x32.png + dst: /usr/share/icons/hicolor/32x32/apps/lowquery.png + file_info: + mode: 0644 + - src: packaging/icons/128x128.png + dst: /usr/share/icons/hicolor/128x128/apps/lowquery.png + file_info: + mode: 0644 + # The Tauri packages put the 256 px icon here. + - src: packaging/icons/128x128@2x.png + dst: /usr/share/icons/hicolor/256x256@2/apps/lowquery.png + file_info: + mode: 0644 + +overrides: + deb: + depends: + - libwebkit2gtk-4.1-0 + - libgtk-3-0 + rpm: + depends: + - libwebkit2gtk-4.1.so.0()(64bit) + - libgtk-3.so.0()(64bit) + +rpm: + summary: Light SQL client for PostgreSQL, Oracle, MySQL, MariaDB, SQL Server, SQLite, Redis and Apache Cassandra + group: Development/Tools + compression: gzip diff --git a/packaging/macos/Info.plist b/packaging/macos/Info.plist new file mode 100644 index 0000000..5abf2e7 --- /dev/null +++ b/packaging/macos/Info.plist @@ -0,0 +1,39 @@ + + + + + + CFBundleDevelopmentRegion + English + CFBundleDisplayName + LowQuery + CFBundleExecutable + lowquery + CFBundleIdentifier + dev.lowbloat.lowquery + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + LowQuery + CFBundlePackageType + APPL + CFBundleShortVersionString + @VERSION@ + CFBundleVersion + @VERSION@ + CSResourcesFileMapped + + LSApplicationCategoryType + public.app-category.developer-tools + LSMinimumSystemVersion + 12.0 + CFBundleIconFile + icon.icns + NSHighResolutionCapable + + NSHumanReadableCopyright + Copyright © 2026 LowBloat. Licensed under AGPL-3.0-only. + + diff --git a/packaging/macos/build.sh b/packaging/macos/build.sh new file mode 100644 index 0000000..2e501db --- /dev/null +++ b/packaging/macos/build.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Builds the macOS release files from the Go app, on macOS: +# build/release/LowQuery--macos-universal.app.tar.gz (updater file) +# build/release/LowQuery--macos-universal.dmg (skipped with MACOS_DMG=0) +# LowQuery.app is universal (arm64 + x86_64) and ad-hoc signed; the Tauri +# updater swaps it in for the installed bundle. +# Needs dist/ (bun run build), Go and the Xcode command line tools. +set -euo pipefail +cd "$(dirname "$0")/../.." +source packaging/common.sh + +version="$(app_version)" +require_dist +work=build/macos +rm -rf "$work" +mkdir -p "$work" "$RELEASE_DIR" + +# Wails needs cgo; Go 1.25+ and Wails 3 support macOS 12 and later. +export CGO_ENABLED=1 MACOSX_DEPLOYMENT_TARGET=12.0 +export CGO_CFLAGS="-mmacosx-version-min=12.0" CGO_LDFLAGS="-mmacosx-version-min=12.0" +for arch in arm64 amd64; do + GOOS=darwin GOARCH="$arch" go build -tags production -trimpath \ + -ldflags "-s -w" -o "$work/lowquery-$arch" . +done + +app="$work/LowQuery.app" +mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" +lipo -create -output "$app/Contents/MacOS/lowquery" "$work/lowquery-arm64" "$work/lowquery-amd64" +chmod 755 "$app/Contents/MacOS/lowquery" +cp packaging/icons/icon.icns "$app/Contents/Resources/icon.icns" +render packaging/macos/Info.plist "$version" "$app/Contents/Info.plist" +plutil -lint "$app/Contents/Info.plist" + +codesign --force --deep --sign - "$app" +codesign --verify --deep --strict --verbose=2 "$app" + +# Entries rooted at LowQuery.app/ (no ./): the updater drops the first path +# component. COPYFILE_DISABLE keeps AppleDouble (._*) files out. +COPYFILE_DISABLE=1 tar -czf "$RELEASE_DIR/LowQuery-$version-macos-universal.app.tar.gz" -C "$work" LowQuery.app + +if [ "${MACOS_DMG:-1}" != "0" ]; then + staging="$work/dmg" + mkdir -p "$staging" + cp -R "$app" "$staging/" + ln -s /Applications "$staging/Applications" + dmg="$RELEASE_DIR/LowQuery-$version-macos-universal.dmg" + # hdiutil fails now and then on CI machines with "Resource busy". + for attempt in 1 2 3; do + if hdiutil create -volname LowQuery -srcfolder "$staging" -fs HFS+ -format UDZO -ov "$dmg"; then + break + fi + [ "$attempt" = 3 ] && exit 1 + sleep 10 + done +fi + +ls -l "$RELEASE_DIR" diff --git a/packaging/test/mcp-smoke.sh b/packaging/test/mcp-smoke.sh new file mode 100644 index 0000000..66fac42 --- /dev/null +++ b/packaging/test/mcp-smoke.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Usage: packaging/test/mcp-smoke.sh [args...] +# Runs ` [args...] mcp`, the way AI clients start LowQuery, and checks +# that it answers MCP initialize and tools/list over stdio. It needs no window +# or display: main.go serves MCP before Wails starts. +set -euo pipefail + +out="$(mktemp)" +trap 'rm -f "$out"' EXIT +requests='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"ci","version":"0"}}} +{"jsonrpc":"2.0","method":"notifications/initialized"} +{"jsonrpc":"2.0","id":2,"method":"tools/list"}' + +if command -v timeout >/dev/null 2>&1; then + limit=(timeout 60) +else + limit=(perl -e 'alarm shift; exec @ARGV' 60) +fi +printf '%s\n' "$requests" | "${limit[@]}" "$@" mcp > "$out" +cat "$out" +grep -q '"serverInfo"' "$out" +grep -q '"list_connections"' "$out" +echo "MCP answered: $*" diff --git a/packaging/test/windows-upgrade.ps1 b/packaging/test/windows-upgrade.ps1 new file mode 100644 index 0000000..941a6bb --- /dev/null +++ b/packaging/test/windows-upgrade.ps1 @@ -0,0 +1,158 @@ +# CI test of the Windows setup (never run it on a machine with a real install): +# 1. installs the Tauri setup silently and starts that app; +# 2. runs the new setup the way the Tauri updater does (/P /UPDATE /R /ARGS) +# and checks that it closed the old app, replaced lowquery.exe with the Go +# build, kept the Tauri registry values and shortcuts, and restarted the app; +# 3. uninstalls silently and checks that files, shortcuts and registry entries +# are gone while user data stays; +# 4. does a fresh silent install and uninstall. +param( + [Parameter(Mandatory)] [string] $TauriSetup, + [Parameter(Mandatory)] [string] $Setup, + [Parameter(Mandatory)] [string] $BuiltExe, + [Parameter(Mandatory)] [string] $Version +) +$ErrorActionPreference = 'Stop' + +$dir = Join-Path $env:LOCALAPPDATA 'LowQuery' +$exe = Join-Path $dir 'lowquery.exe' +$uninstaller = Join-Path $dir 'uninstall.exe' +$uninstKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\LowQuery' +$dirKey = 'HKCU:\Software\LowBloat\LowQuery' +$startMenuLnk = Join-Path ([Environment]::GetFolderPath('Programs')) 'LowQuery.lnk' +$desktopLnk = Join-Path ([Environment]::GetFolderPath('Desktop')) 'LowQuery.lnk' +$valueNames = 'DisplayName', 'DisplayIcon', 'DisplayVersion', 'Publisher', 'InstallLocation', + 'UninstallString', 'MainBinaryName', 'NoModify', 'NoRepair', 'EstimatedSize' + +function Assert([bool] $condition, [string] $message) { + if (-not $condition) { throw "FAILED: $message" } + Write-Host "ok: $message" +} + +function Invoke-Setup([string] $path, [string] $arguments) { + Write-Host "> $path $arguments" + $process = Start-Process -FilePath $path -ArgumentList $arguments -PassThru + $null = $process.Handle # keeps the exit code readable + # Only this process: the app it starts keeps running. + if (-not $process.WaitForExit(300000)) { throw "$path did not finish" } + Assert ($process.ExitCode -eq 0) "$([IO.Path]::GetFileName($path)) $arguments exits with 0 (got $($process.ExitCode))" +} + +function Get-AppProcess { + @(Get-Process -Name lowquery -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $exe }) +} + +function Get-ShortcutTarget([string] $lnk) { + (New-Object -ComObject WScript.Shell).CreateShortcut($lnk).TargetPath +} + +function Get-Values { + $key = Get-ItemProperty $uninstKey + $values = @{} + foreach ($name in $valueNames) { $values[$name] = $key.$name } + $values +} + +# What AI clients do: `lowquery.exe mcp` over stdin and stdout. +function Test-Mcp { + $info = New-Object System.Diagnostics.ProcessStartInfo $exe, 'mcp' + $info.UseShellExecute = $false + $info.RedirectStandardInput = $true + $info.RedirectStandardOutput = $true + $process = [System.Diagnostics.Process]::Start($info) + $process.StandardInput.WriteLine('{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"ci","version":"0"}}}') + $process.StandardInput.WriteLine('{"jsonrpc":"2.0","method":"notifications/initialized"}') + $process.StandardInput.WriteLine('{"jsonrpc":"2.0","id":2,"method":"tools/list"}') + $process.StandardInput.Close() + $output = $process.StandardOutput.ReadToEndAsync() + if (-not $process.WaitForExit(60000)) { $process.Kill(); throw 'lowquery.exe mcp did not exit' } + $text = $output.Result + Assert ($text -match '"serverInfo"' -and $text -match '"list_connections"') 'installed lowquery.exe mcp answers initialize and tools/list' +} + +function Wait-Uninstalled { + Write-Host "> $uninstaller /S" + # The NSIS uninstaller copies itself to %TEMP% and returns at once. + Start-Process -FilePath $uninstaller -ArgumentList '/S' + $deadline = (Get-Date).AddSeconds(120) + while ((Test-Path $exe) -or (Test-Path $uninstKey) -or (Test-Path $uninstaller)) { + if ((Get-Date) -gt $deadline) { throw 'the uninstaller did not finish' } + Start-Sleep -Milliseconds 500 + } + Start-Sleep -Seconds 2 + Assert (-not (Test-Path $dir)) 'install folder removed' + Assert (-not (Test-Path $uninstKey)) 'uninstall entry removed' + Assert (-not (Test-Path $dirKey)) 'HKCU\Software\LowBloat\LowQuery removed' + Assert (-not (Test-Path $startMenuLnk)) 'Start Menu shortcut removed' + Assert (-not (Test-Path $desktopLnk)) 'desktop shortcut removed' + Assert ((Get-AppProcess).Count -eq 0) 'no LowQuery process left' +} + +Write-Host '== Tauri 0.5.x install' +Invoke-Setup $TauriSetup '/S' +Assert (Test-Path $exe) 'Tauri lowquery.exe installed' +$tauriValues = Get-Values +Write-Host ($tauriValues | Out-String) +Assert (Test-Path $startMenuLnk) 'Tauri Start Menu shortcut exists' +$hadDesktopLnk = Test-Path $desktopLnk + +# The updater leaves the app closing while the setup starts. +Start-Process -FilePath $exe +Start-Sleep -Seconds 5 +$oldProcesses = Get-AppProcess +if ($oldProcesses.Count -eq 0) { + Write-Host '::warning::The Tauri app did not stay running; closing a running app is not tested.' +} + +Write-Host '== Update with the new setup, as the Tauri updater runs it' +$updateStart = Get-Date +Invoke-Setup $Setup '/P /UPDATE /R /ARGS' +foreach ($old in $oldProcesses) { + Assert ($null -eq (Get-Process -Id $old.Id -ErrorAction SilentlyContinue)) "Tauri app (pid $($old.Id)) closed by the setup" +} +Assert ((Get-FileHash $exe).Hash -eq (Get-FileHash $BuiltExe).Hash) 'lowquery.exe is the Go build' +Assert (Test-Path $uninstaller) 'uninstall.exe present' +Assert (@(Get-ChildItem $dir).Count -eq 2) 'install folder holds lowquery.exe and uninstall.exe only' +$values = Get-Values +Write-Host ($values | Out-String) +Assert ($values.DisplayVersion -eq $Version) "DisplayVersion is $Version" +Assert ($values.EstimatedSize -gt 0) 'EstimatedSize set' +foreach ($name in $valueNames | Where-Object { $_ -notin 'DisplayVersion', 'EstimatedSize' }) { + Assert ("$($values[$name])" -eq "$($tauriValues[$name])") "$name unchanged ($($values[$name]))" +} +Assert ((Get-ItemProperty $dirKey).'(default)' -eq $dir) 'HKCU\Software\LowBloat\LowQuery points at the install folder' +Assert ((Get-ShortcutTarget $startMenuLnk) -eq $exe) 'Start Menu shortcut kept, opens lowquery.exe' +Assert ((Test-Path $desktopLnk) -eq $hadDesktopLnk) 'desktop shortcut left as it was' + +$deadline = (Get-Date).AddSeconds(20) +$started = @() +while ($started.Count -eq 0 -and (Get-Date) -lt $deadline) { + $started = @(Get-AppProcess | Where-Object { $_.StartTime -ge $updateStart }) + Start-Sleep -Milliseconds 500 +} +Assert ($started.Count -gt 0) '/R started the updated app' + +Test-Mcp + +# User data lives outside the install folder and survives the uninstall. +$marker = Join-Path $env:APPDATA 'LowBloat\LowQuery\config\ci-marker.txt' +New-Item -ItemType Directory -Force (Split-Path $marker) | Out-Null +Set-Content $marker 'keep' + +Write-Host '== Uninstall (closes the running app)' +Wait-Uninstalled +Assert (Test-Path $marker) 'user data kept' + +Write-Host '== Fresh silent install' +Invoke-Setup $Setup '/S' +Assert ((Get-FileHash $exe).Hash -eq (Get-FileHash $BuiltExe).Hash) 'lowquery.exe installed' +$values = Get-Values +Assert ($values.DisplayVersion -eq $Version) "DisplayVersion is $Version" +Assert ($values.InstallLocation -eq "`"$dir`"") 'InstallLocation is the quoted install folder' +Assert ($values.UninstallString -eq "`"$uninstaller`"") 'UninstallString is the quoted uninstaller' +Assert ($values.MainBinaryName -eq 'lowquery.exe') 'MainBinaryName is lowquery.exe' +Assert ((Get-ShortcutTarget $startMenuLnk) -eq $exe) 'Start Menu shortcut created' +Assert ((Get-ShortcutTarget $desktopLnk) -eq $exe) 'desktop shortcut created' +Assert ((Get-AppProcess).Count -eq 0) 'no restart without /R' +Test-Mcp +Wait-Uninstalled diff --git a/packaging/windows/build.sh b/packaging/windows/build.sh new file mode 100644 index 0000000..284bb97 --- /dev/null +++ b/packaging/windows/build.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Builds the Windows release files from the Go app, in Git Bash: +# build/release/LowQuery--windows-x64-setup.exe NSIS setup (updater file) +# build/release/LowQuery--windows-x64-portable.zip LowQuery.exe, README, LICENSE +# Needs dist/ (bun run build), Go and makensis (MAKENSIS overrides the path). +set -euo pipefail +cd "$(dirname "$0")/../.." +source packaging/common.sh + +version="$(app_version)" +require_dist +work=build/windows +rm -rf "$work" +mkdir -p "$work" "$RELEASE_DIR" + +# Icon, version information and manifest (DPI awareness, Common Controls 6), +# compiled into a .syso that go build links into package main. Wails' own +# build generates it the same way and deletes it afterwards. +render packaging/windows/info.json "$version" "$work/info.json" +render packaging/windows/lowquery.exe.manifest "$version" "$work/lowquery.exe.manifest" +syso="$PWD/wails_windows_amd64.syso" +trap 'rm -f "$syso"' EXIT +wails3 generate syso -arch amd64 -icon packaging/icons/icon.ico \ + -manifest "$work/lowquery.exe.manifest" -info "$work/info.json" -out "$syso" + +GOOS=windows GOARCH=amd64 go build -tags production -trimpath \ + -ldflags "-s -w -H windowsgui" -o "$work/lowquery.exe" . +rm -f "$syso" + +makensis="${MAKENSIS:-}" +if [ -z "$makensis" ]; then + for candidate in makensis "/c/Program Files (x86)/NSIS/makensis.exe" "/c/Program Files/NSIS/makensis.exe"; do + if command -v "$candidate" >/dev/null 2>&1; then + makensis="$candidate" + break + fi + done +fi +if [ -z "$makensis" ]; then + echo "makensis not found: install NSIS 3 or set MAKENSIS." >&2 + exit 1 +fi +setup="$RELEASE_DIR/LowQuery-$version-windows-x64-setup.exe" +MSYS_NO_PATHCONV=1 "$makensis" -V3 -WX -INPUTCHARSET UTF8 \ + "-DVERSION=$version" \ + "-DAPPEXE=$(cygpath -w "$PWD/$work/lowquery.exe")" \ + "-DOUTFILE=$(cygpath -w "$PWD/$setup")" \ + "$(cygpath -w "$PWD/packaging/windows/installer.nsi")" + +portable="$work/portable" +mkdir -p "$portable" +cp "$work/lowquery.exe" "$portable/LowQuery.exe" +cp README.md LICENSE "$portable/" +zip="$RELEASE_DIR/LowQuery-$version-windows-x64-portable.zip" +rm -f "$zip" +powershell.exe -NoProfile -NonInteractive -Command \ + "Compress-Archive -Path '$(cygpath -w "$PWD/$portable")\\*' -DestinationPath '$(cygpath -w "$PWD/$zip")'" + +ls -l "$RELEASE_DIR" diff --git a/packaging/windows/info.json b/packaging/windows/info.json new file mode 100644 index 0000000..d279159 --- /dev/null +++ b/packaging/windows/info.json @@ -0,0 +1,18 @@ +{ + "fixed": { + "file_version": "@VERSION@", + "product_version": "@VERSION@" + }, + "info": { + "0409": { + "CompanyName": "LowBloat", + "FileDescription": "LowQuery", + "FileVersion": "@VERSION@", + "InternalName": "lowquery", + "LegalCopyright": "Copyright © 2026 LowBloat. Licensed under AGPL-3.0-only.", + "OriginalFilename": "lowquery.exe", + "ProductName": "LowQuery", + "ProductVersion": "@VERSION@" + } + } +} diff --git a/packaging/windows/installer.nsi b/packaging/windows/installer.nsi new file mode 100644 index 0000000..1d594c3 --- /dev/null +++ b/packaging/windows/installer.nsi @@ -0,0 +1,507 @@ +; LowQuery setup for Windows (packaging/windows/build.sh builds it). +; +; Installs over a Tauri build of LowQuery (0.5.x) in place, so those copies +; update to this one through their own updater. It keeps the Tauri layout: +; - per-user install in %LOCALAPPDATA%\LowQuery, no administrator rights; +; - lowquery.exe and uninstall.exe; +; - HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\LowQuery with the +; same values, and HKCU\Software\LowBloat\LowQuery = install folder; +; - Start Menu shortcut LowQuery.lnk (AppUserModelID dev.lowbloat.lowquery). +; Modelled on Tauri's NSIS template (tauri-cli 2.12.3), without its plugin. +; +; Command line: +; /S silent +; /P passive: progress only, no questions, closes itself +; /UPDATE an update: leaves the user's shortcuts as they are +; /NS no shortcuts +; /R start LowQuery when done (with /S or /P), with what follows /ARGS +; /D= install folder (last argument) +; The Tauri updater runs the setup with "/P /UPDATE /R /ARGS ". +; +; Defined by the build: VERSION (X.Y.Z), APPEXE (the built lowquery.exe) and +; OUTFILE (the setup to write). + +Unicode true +ManifestDPIAware true +ManifestDPIAwareness PerMonitorV2 +SetCompressor /SOLID lzma + +!ifndef VERSION + !error "Build with -DVERSION=X.Y.Z -DAPPEXE= -DOUTFILE=" +!endif +!ifndef APPEXE + !error "Build with -DAPPEXE=" +!endif +!ifndef OUTFILE + !error "Build with -DOUTFILE=" +!endif + +!include MUI2.nsh +!include FileFunc.nsh +!include LogicLib.nsh +!include WordFunc.nsh +!include x64.nsh +!include "Win\COM.nsh" +!include "Win\Propkey.nsh" +!include "Win\RestartManager.nsh" + +!define PRODUCTNAME "LowQuery" +!define MANUFACTURER "LowBloat" +!define MAINBINARYNAME "lowquery" +!define BUNDLEID "dev.lowbloat.lowquery" +!define COPYRIGHT "Copyright © 2026 LowBloat. Licensed under AGPL-3.0-only." +!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCTNAME}" +!define MANUKEY "Software\${MANUFACTURER}" +!define MANUPRODUCTKEY "${MANUKEY}\${PRODUCTNAME}" +!define WEBVIEW2APPGUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" +!define WEBVIEW2BOOTSTRAPPERURL "https://go.microsoft.com/fwlink/p/?LinkId=2124703" +!define /ifndef ERROR_MORE_DATA 234 +!define /ifndef MAX_PATH 260 +!define /ifndef SLGP_RAWPATH 0x4 + +Var PassiveMode +Var UpdateMode +Var NoShortcutMode +Var MsiMode +Var MsiProductCode + +Name "${PRODUCTNAME}" +BrandingText "${COPYRIGHT}" +OutFile "${OUTFILE}" +RequestExecutionLevel user + +; Only a marker: .onInit sets the real folder, keeping the previous one. +!define PLACEHOLDER_INSTALL_DIR "placeholder\${PRODUCTNAME}" +InstallDir "${PLACEHOLDER_INSTALL_DIR}" + +VIProductVersion "${VERSION}.0" +VIAddVersionKey "ProductName" "${PRODUCTNAME}" +VIAddVersionKey "CompanyName" "${MANUFACTURER}" +VIAddVersionKey "FileDescription" "${PRODUCTNAME}" +VIAddVersionKey "LegalCopyright" "${COPYRIGHT}" +VIAddVersionKey "FileVersion" "${VERSION}" +VIAddVersionKey "ProductVersion" "${VERSION}" + +!define MUI_ICON "${__FILEDIR__}\..\icons\icon.ico" +!define MUI_UNICON "${__FILEDIR__}\..\icons\icon.ico" + +; Installer pages. Passive mode shows only the progress page. +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_WELCOME +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_DIRECTORY +!insertmacro MUI_PAGE_INSTFILES +!define MUI_FINISHPAGE_NOAUTOCLOSE +; The "show readme" checkbox creates the desktop shortcut, as in Tauri's setup. +!define MUI_FINISHPAGE_SHOWREADME +!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(createDesktop)" +!define MUI_FINISHPAGE_SHOWREADME_FUNCTION CreateDesktopShortcut +!define MUI_FINISHPAGE_RUN +!define MUI_FINISHPAGE_RUN_FUNCTION RunMainBinary +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_FINISH + +; Uninstaller pages. +!define MUI_PAGE_CUSTOMFUNCTION_PRE un.SkipIfPassive +!insertmacro MUI_UNPAGE_CONFIRM +!insertmacro MUI_UNPAGE_INSTFILES + +!insertmacro MUI_LANGUAGE "English" + +LangString createDesktop ${LANG_ENGLISH} "Create desktop shortcut" +LangString appRunning ${LANG_ENGLISH} "${PRODUCTNAME} is running. Close it first, then try again." +LangString appRunningOkKill ${LANG_ENGLISH} "${PRODUCTNAME} is running.$\nClick OK to close it." +LangString failedToKillApp ${LANG_ENGLISH} "Could not close ${PRODUCTNAME}. Close it and try again." +LangString webview2Downloading ${LANG_ENGLISH} "Downloading the WebView2 runtime..." +LangString webview2Installing ${LANG_ENGLISH} "Installing the WebView2 runtime..." +LangString webview2Installed ${LANG_ENGLISH} "WebView2 runtime installed." +LangString webview2Failed ${LANG_ENGLISH} "Could not install the WebView2 runtime, which ${PRODUCTNAME} needs. Check the internet connection and try again." +LangString msiRemoving ${LANG_ENGLISH} "Removing the copy of ${PRODUCTNAME} installed for all users..." +LangString msiFailed ${LANG_ENGLISH} "Could not remove the copy of ${PRODUCTNAME} installed for all users (MSI). Remove it in Settings > Apps, then run this setup again." + +; Ends the installation with an error. A silent install writes the message +; to the console it was started from, if any. +!macro FailInstall message + ${If} ${Silent} + System::Call 'kernel32::AttachConsole(i -1)i.r0' + ${If} $0 <> 0 + System::Call 'kernel32::GetStdHandle(i -11)i.r0' + FileWrite $0 "${message}$\r$\n" + ${EndIf} + ${EndIf} + Abort "${message}" +!macroend + +; Waits a few seconds for running copies of $INSTDIR\lowquery.exe to exit (the +; Tauri updater quits right after starting the setup), then closes them with +; the Restart Manager. Interactive installs ask first. From Tauri's +; CheckIfAppIsRunning, with the wait added. +!macro CloseRunningApp + !define UniqueID ${__LINE__} + !insertmacro RestartManager_StartSession $R0 + ${If} $R0 != "" + !insertmacro RestartManager_RegisterFile $R0 "$INSTDIR\${MAINBINARYNAME}.exe" + ${If} $0 = 0 + StrCpy $R5 0 + wait_${UniqueID}: + ; ERROR_MORE_DATA: some process still has the file open. + System::Call 'RSTRTMGR::RmGetList(p R0, *i .r1, *i .r2, p 0, *i .r3) i .r0' + ${If} $0 = ${ERROR_MORE_DATA} + ${AndIf} $R5 < 20 + Sleep 250 + IntOp $R5 $R5 + 1 + Goto wait_${UniqueID} + ${EndIf} + ${If} $0 = ${ERROR_MORE_DATA} + IfSilent kill_${UniqueID} + ${If} $PassiveMode <> 1 + MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "$(appRunningOkKill)" IDOK kill_${UniqueID} + !insertmacro RestartManager_EndSession $R0 + Abort "$(appRunning)" + ${EndIf} + kill_${UniqueID}: + DetailPrint "Closing ${PRODUCTNAME}..." + System::Call 'RSTRTMGR::RmShutdown(p R0, i ${RmForceShutdown}, p 0) i .r0' + ${If} $0 <> 0 + !insertmacro RestartManager_EndSession $R0 + !insertmacro FailInstall "$(failedToKillApp)" + ${EndIf} + Sleep 500 + ${EndIf} + ${EndIf} + !insertmacro RestartManager_EndSession $R0 + ${EndIf} + !undef UniqueID +!macroend + +; Shortcut helpers, from Tauri's utils.nsh. + +; Sets the AppUserModelID on a shortcut, so pinned and running copies group. +!macro SetLnkAppUserModelId shortcut + !insertmacro ComHlpr_CreateInProcInstance ${CLSID_ShellLink} ${IID_IShellLink} r0 "" + ${If} $0 P<> 0 + ${IUnknown::QueryInterface} $0 '("${IID_IPersistFile}",.r1)' + ${If} $1 P<> 0 + ${IPersistFile::Load} $1 '("${shortcut}", ${STGM_READWRITE})' + ${IUnknown::QueryInterface} $0 '("${IID_IPropertyStore}",.r2)' + ${If} $2 P<> 0 + System::Call 'Oleaut32::SysAllocString(w "${BUNDLEID}") i.r3' + System::Call '*${SYSSTRUCT_PROPERTYKEY}(${PKEY_AppUserModel_ID})p.r4' + System::Call '*${SYSSTRUCT_PROPVARIANT}(${VT_BSTR},,&i4 $3)p.r5' + ${IPropertyStore::SetValue} $2 '($4,$5)' + System::Call 'Oleaut32::SysFreeString($3)' + System::Free $4 + System::Free $5 + ${IPropertyStore::Commit} $2 "" + ${IUnknown::Release} $2 "" + ${IPersistFile::Save} $1 '("${shortcut}",1)' + ${EndIf} + ${IUnknown::Release} $1 "" + ${EndIf} + ${IUnknown::Release} $0 "" + ${EndIf} +!macroend + +; Removes the app's jump list entries and recent destinations. +!macro DeleteAppUserModelId + !insertmacro ComHlpr_CreateInProcInstance ${CLSID_DestinationList} ${IID_ICustomDestinationList} r1 "" + ${If} $1 P<> 0 + ${ICustomDestinationList::DeleteList} $1 '("${BUNDLEID}")' + ${IUnknown::Release} $1 "" + ${EndIf} + !insertmacro ComHlpr_CreateInProcInstance ${CLSID_ApplicationDestinations} ${IID_IApplicationDestinations} r1 "" + ${If} $1 P<> 0 + ${IApplicationDestinations::SetAppID} $1 '("${BUNDLEID}")i.r0' + ${If} $0 >= 0 + ${IApplicationDestinations::RemoveAllDestinations} $1 '' + ${EndIf} + ${IUnknown::Release} $1 "" + ${EndIf} +!macroend + +; Unpins a shortcut from Start and the taskbar. +!macro UnpinShortcut shortcut + !insertmacro ComHlpr_CreateInProcInstance ${CLSID_StartMenuPin} ${IID_IStartMenuPinnedList} r0 "" + ${If} $0 P<> 0 + System::Call 'SHELL32::SHCreateItemFromParsingName(ws, p0, g "${IID_IShellItem}", *p0r1)' "${shortcut}" + ${If} $1 P<> 0 + ${IStartMenuPinnedList::RemoveFromList} $0 '(r1)' + ${IUnknown::Release} $1 "" + ${EndIf} + ${IUnknown::Release} $0 "" + ${EndIf} +!macroend + +; Pushes 1 when the shortcut opens target, 0 otherwise. Changes $0 to $3. +!macro IsShortcutTarget shortcut target + StrCpy $3 0 + !insertmacro ComHlpr_CreateInProcInstance ${CLSID_ShellLink} ${IID_IShellLink} r0 "" + ${If} $0 P<> 0 + ${IUnknown::QueryInterface} $0 '("${IID_IPersistFile}", .r1)' + ${If} $1 P<> 0 + ${IPersistFile::Load} $1 '("${shortcut}", ${STGM_READ})' + System::Alloc MAX_PATH + Pop $2 + ${IShellLink::GetPath} $0 '(.r2, ${MAX_PATH}, 0, ${SLGP_RAWPATH})' + ${If} $2 == "${target}" + StrCpy $3 1 + ${EndIf} + System::Free $2 + ${IUnknown::Release} $1 "" + ${EndIf} + ${IUnknown::Release} $0 "" + ${EndIf} + Push $3 +!macroend + +; Deletes a shortcut, and its pins, when it opens this install. +!macro DeleteShortcutIfOurs shortcut + !insertmacro IsShortcutTarget "${shortcut}" "$INSTDIR\${MAINBINARYNAME}.exe" + Pop $0 + ${If} $0 = 1 + !insertmacro UnpinShortcut "${shortcut}" + Delete "${shortcut}" + ${EndIf} +!macroend + +!macro ParseOptions + ${GetOptions} $CMDLINE "/P" $PassiveMode + ${IfNot} ${Errors} + StrCpy $PassiveMode 1 + ${EndIf} + ${GetOptions} $CMDLINE "/UPDATE" $UpdateMode + ${IfNot} ${Errors} + StrCpy $UpdateMode 1 + ${EndIf} + ${GetOptions} $CMDLINE "/NS" $NoShortcutMode + ${IfNot} ${Errors} + StrCpy $NoShortcutMode 1 + ${EndIf} +!macroend + +!macro SetContext + SetShellVarContext current + ${If} ${RunningX64} + SetRegView 64 + ${EndIf} +!macroend + +Function .onInit + !insertmacro ParseOptions + !insertmacro SetContext + ${If} $INSTDIR == "${PLACEHOLDER_INSTALL_DIR}" + StrCpy $INSTDIR "$LOCALAPPDATA\${PRODUCTNAME}" + ; Where the previous setup (Tauri's or this one) installed. + ReadRegStr $4 HKCU "${MANUPRODUCTKEY}" "" + ${If} $4 != "" + StrCpy $INSTDIR $4 + ${EndIf} + ${EndIf} +FunctionEnd + +Section "-WebView2" + ; Installed if the registry lists any version, per machine or per user. + ReadRegStr $4 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${If} $4 == "" + ${OrIf} $4 == "0.0.0.0" + ReadRegStr $4 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${EndIf} + ${If} $4 == "" + ${OrIf} $4 == "0.0.0.0" + ReadRegStr $4 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${EndIf} + ; An update comes from a running copy, which had the runtime. + ${If} $4 == "" + ${OrIf} $4 == "0.0.0.0" + ${If} $UpdateMode <> 1 + ; Microsoft's bootstrapper, downloaded as in Tauri's default + ; (downloadBootstrapper), with curl.exe (Windows 10 1803+) or PowerShell. + StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe" + Delete $6 + DetailPrint "$(webview2Downloading)" + nsExec::ExecToLog '"$SYSDIR\curl.exe" --fail --silent --show-error --location --output "$6" "${WEBVIEW2BOOTSTRAPPERURL}"' + Pop $0 + ${IfNot} ${FileExists} $6 + ${WordReplace} $6 "'" "''" "+" $7 + nsExec::ExecToLog `"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -UseBasicParsing -Uri '${WEBVIEW2BOOTSTRAPPERURL}' -OutFile '$7'"` + Pop $0 + ${EndIf} + ${IfNot} ${FileExists} $6 + !insertmacro FailInstall "$(webview2Failed)" + ${EndIf} + DetailPrint "$(webview2Installing)" + ExecWait '"$6" /silent /install' $1 + Delete $6 + ${If} $1 = 0 + DetailPrint "$(webview2Installed)" + ${Else} + !insertmacro FailInstall "$(webview2Failed)" + ${EndIf} + ${EndIf} + ${EndIf} +SectionEnd + +Section "-RemoveMsiInstall" + ; LowQuery 0.5.x also shipped an MSI that installs for all users. Its + ; updater falls back to this setup, which removes that copy (Windows asks + ; for administrator rights) and installs per user instead, as Tauri's + ; setup did. + StrCpy $0 0 + ${Do} + EnumRegKey $1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $0 + ${If} $1 == "" + ${Break} + ${EndIf} + IntOp $0 $0 + 1 + ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "DisplayName" + ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "Publisher" + ReadRegDWORD $R2 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "WindowsInstaller" + ${If} "$R0|$R1" == "${PRODUCTNAME}|${MANUFACTURER}" + ${AndIf} $R2 = 1 + StrCpy $MsiMode 1 + StrCpy $MsiProductCode $1 + ${Break} + ${EndIf} + ${Loop} + + ${If} $MsiMode = 1 + DetailPrint "$(msiRemoving)" + StrCpy $R1 '"$SYSDIR\msiexec.exe" /x $MsiProductCode /norestart' + ${If} $PassiveMode = 1 + ${OrIf} ${Silent} + StrCpy $R1 "$R1 /passive" + ${EndIf} + ClearErrors + ExecWait $R1 $0 + ${IfThen} ${Errors} ${|} StrCpy $0 1 ${|} + ; 3010: removed, a restart finishes the job. + ${If} $0 <> 0 + ${AndIf} $0 <> 3010 + !insertmacro FailInstall "$(msiFailed)" + ${EndIf} + ${EndIf} +SectionEnd + +Section "-Install" + SetOutPath $INSTDIR + !insertmacro CloseRunningApp + + File "/oname=${MAINBINARYNAME}.exe" "${APPEXE}" + WriteUninstaller "$INSTDIR\uninstall.exe" + + ; Where to install next time. + WriteRegStr HKCU "${MANUPRODUCTKEY}" "" $INSTDIR + + ; A previous main binary with another name goes away. + ReadRegStr $R0 HKCU "${UNINSTKEY}" "MainBinaryName" + ${If} $R0 != "" + ${AndIf} $R0 != "${MAINBINARYNAME}.exe" + Delete "$INSTDIR\$R0" + ${EndIf} + + ; Apps & features entry, value for value as Tauri's setup writes it. + WriteRegStr HKCU "${UNINSTKEY}" "MainBinaryName" "${MAINBINARYNAME}.exe" + WriteRegStr HKCU "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}" + WriteRegStr HKCU "${UNINSTKEY}" "DisplayIcon" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\"" + WriteRegStr HKCU "${UNINSTKEY}" "DisplayVersion" "${VERSION}" + WriteRegStr HKCU "${UNINSTKEY}" "Publisher" "${MANUFACTURER}" + WriteRegStr HKCU "${UNINSTKEY}" "InstallLocation" "$\"$INSTDIR$\"" + WriteRegStr HKCU "${UNINSTKEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\"" + WriteRegDWORD HKCU "${UNINSTKEY}" "NoModify" "1" + WriteRegDWORD HKCU "${UNINSTKEY}" "NoRepair" "1" + ${GetSize} "$INSTDIR" "/S=0K /G=0" $0 $1 $2 + IntFmt $0 "0x%08X" $0 + WriteRegDWORD HKCU "${UNINSTKEY}" "EstimatedSize" "$0" + + Call CreateStartMenuShortcut + ; The finish page, which offers the desktop shortcut, is skipped. + ${If} $PassiveMode = 1 + ${OrIf} ${Silent} + Call CreateDesktopShortcut + ${EndIf} + + ${If} $PassiveMode = 1 + SetAutoClose true + ${EndIf} +SectionEnd + +Function .onInstSuccess + ; /R only applies without the finish page, which has its own checkbox. + ${If} $PassiveMode = 1 + ${OrIf} ${Silent} + ${GetOptions} $CMDLINE "/R" $R0 + ${IfNot} ${Errors} + ${GetOptions} $CMDLINE "/ARGS" $R0 + Exec '"$INSTDIR\${MAINBINARYNAME}.exe" $R0' + ${EndIf} + ${EndIf} +FunctionEnd + +Function RunMainBinary + Exec '"$INSTDIR\${MAINBINARYNAME}.exe"' +FunctionEnd + +; Updates keep the user's shortcuts, deleted ones included; they open the +; same path. Replacing the MSI copy, whose uninstaller removed its shortcuts, +; creates them. +Function CreateStartMenuShortcut + ${If} $MsiMode <> 1 + ${If} $UpdateMode = 1 + ${OrIf} $NoShortcutMode = 1 + Return + ${EndIf} + ${EndIf} + CreateShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\${PRODUCTNAME}.lnk" +FunctionEnd + +Function CreateDesktopShortcut + ${If} $MsiMode <> 1 + ${If} $UpdateMode = 1 + ${OrIf} $NoShortcutMode = 1 + Return + ${EndIf} + ${EndIf} + CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetLnkAppUserModelId "$DESKTOP\${PRODUCTNAME}.lnk" +FunctionEnd + +Function SkipIfPassive + ${IfThen} $PassiveMode = 1 ${|} Abort ${|} +FunctionEnd + +Function un.SkipIfPassive + ${IfThen} $PassiveMode = 1 ${|} Abort ${|} +FunctionEnd + +Function un.onInit + !insertmacro ParseOptions + !insertmacro SetContext +FunctionEnd + +; Removes the program, its shortcuts and its registry entries. Connections, +; settings and the webview profile stay: they live outside the install folder +; (%APPDATA%\LowBloat, %LOCALAPPDATA%\LowBloat and Tauri's dev.lowbloat.lowquery). +Section Uninstall + !insertmacro CloseRunningApp + + Delete "$INSTDIR\${MAINBINARYNAME}.exe" + Delete "$INSTDIR\uninstall.exe" + RMDir "$INSTDIR" + + ${If} $UpdateMode <> 1 + !insertmacro DeleteAppUserModelId + !insertmacro DeleteShortcutIfOurs "$SMPROGRAMS\${PRODUCTNAME}.lnk" + !insertmacro DeleteShortcutIfOurs "$DESKTOP\${PRODUCTNAME}.lnk" + ; Start at login, if the app was set to. + DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}" + DeleteRegKey HKCU "${MANUPRODUCTKEY}" + DeleteRegKey /ifempty HKCU "${MANUKEY}" + ${EndIf} + DeleteRegKey HKCU "${UNINSTKEY}" + + ${If} $PassiveMode = 1 + ${OrIf} $UpdateMode = 1 + SetAutoClose true + ${EndIf} +SectionEnd diff --git a/packaging/windows/lowquery.exe.manifest b/packaging/windows/lowquery.exe.manifest new file mode 100644 index 0000000..7edc63e --- /dev/null +++ b/packaging/windows/lowquery.exe.manifest @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + true/pm + permonitorv2,permonitor + + + + + + + + + + diff --git a/scripts/check-version.mjs b/scripts/check-version.mjs index ac65fd1..46e20e4 100644 --- a/scripts/check-version.mjs +++ b/scripts/check-version.mjs @@ -1,30 +1,26 @@ // Usage: bun scripts/check-version.mjs [vX.Y.Z] -// Fails when the version-bearing files disagree, or differ from the given tag. +// The app version lives in package.json (main.go embeds it; the packaging +// scripts read it). Fails when it is not X.Y.Z or when it differs from the +// given tag. import { appendFileSync, readFileSync } from "node:fs"; -const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), "utf8"); +const path = (file) => new URL(`../${file}`, import.meta.url); +const read = (file) => readFileSync(path(file), "utf8"); -const versions = [ - { path: "package.json", version: JSON.parse(read("package.json")).version }, - { path: "src-tauri/tauri.conf.json", version: JSON.parse(read("src-tauri/tauri.conf.json")).version }, - { - path: "src-tauri/Cargo.toml", - version: /^\[package\][\s\S]*?^version\s*=\s*"([^"]+)"/m.exec(read("src-tauri/Cargo.toml"))?.[1], - }, -]; +const versions = [{ file: "package.json", version: JSON.parse(read("package.json")).version }]; +for (const { file, version } of versions) console.log(`${String(version).padEnd(10)} ${file}`); -for (const { path, version } of versions) console.log(`${String(version).padEnd(10)} ${path}`); - -const distinct = [...new Set(versions.map((v) => v.version))]; -if (distinct.length !== 1 || !distinct[0]) { - console.error("Version files disagree. Update package.json, src-tauri/tauri.conf.json and src-tauri/Cargo.toml together."); +const version = versions[0].version; +// The Windows setup and the release tags need a plain X.Y.Z. +if (!/^\d+\.\d+\.\d+$/.test(String(version))) { + console.error(`package.json version ${version} is not X.Y.Z.`); process.exit(1); } const tag = process.argv[2]; -if (tag && tag !== `v${distinct[0]}`) { - console.error(`Tag ${tag} does not match version ${distinct[0]}.`); +if (tag && tag !== `v${version}`) { + console.error(`Tag ${tag} does not match version ${version}.`); process.exit(1); } -if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `version=${distinct[0]}\n`); +if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\n`); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock deleted file mode 100644 index 0b99236..0000000 --- a/src-tauri/Cargo.lock +++ /dev/null @@ -1,7050 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "aead" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" -dependencies = [ - "crypto-common 0.2.2", - "inout", -] - -[[package]] -name = "aes" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32" -dependencies = [ - "cipher", - "cpubits", - "cpufeatures 0.3.1", -] - -[[package]] -name = "aes-gcm" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f" -dependencies = [ - "aead", - "aes", - "cipher", - "ctr", - "ctutils", - "ghash", -] - -[[package]] -name = "aho-corasick" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" -dependencies = [ - "memchr", -] - -[[package]] -name = "alloc-no-stdlib" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" - -[[package]] -name = "alloc-stdlib" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" -dependencies = [ - "alloc-no-stdlib", -] - -[[package]] -name = "allocator-api2" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "anyhow" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" - -[[package]] -name = "arc-swap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" -dependencies = [ - "rustversion", -] - -[[package]] -name = "arcstr" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03918c3dbd7701a85c6b9887732e2921175f26c350b4563841d0958c21d57e6d" - -[[package]] -name = "async-broadcast" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" -dependencies = [ - "event-listener", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-channel" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" -dependencies = [ - "concurrent-queue", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-executor" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" -dependencies = [ - "async-task", - "concurrent-queue", - "fastrand", - "futures-lite", - "pin-project-lite", - "slab", -] - -[[package]] -name = "async-io" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" -dependencies = [ - "autocfg", - "cfg-if", - "concurrent-queue", - "futures-io", - "futures-lite", - "parking", - "polling", - "rustix", - "slab", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-lock" -version = "3.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" -dependencies = [ - "event-listener", - "event-listener-strategy", - "pin-project-lite", -] - -[[package]] -name = "async-process" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" -dependencies = [ - "async-channel", - "async-io", - "async-lock", - "async-signal", - "async-task", - "blocking", - "cfg-if", - "event-listener", - "futures-lite", - "rustix", -] - -[[package]] -name = "async-recursion" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "async-signal" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" -dependencies = [ - "async-io", - "async-lock", - "atomic-waker", - "cfg-if", - "futures-core", - "futures-io", - "rustix", - "signal-hook-registry", - "slab", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-task" -version = "4.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" - -[[package]] -name = "async-trait" -version = "0.1.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "asynchronous-codec" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a860072022177f903e59730004fb5dc13db9275b79bb2aef7ba8ce831956c233" -dependencies = [ - "bytes", - "futures-sink", - "futures-util", - "memchr", - "pin-project-lite", -] - -[[package]] -name = "atk" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" -dependencies = [ - "atk-sys", - "glib", - "libc", -] - -[[package]] -name = "atk-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "aws-lc-rs" -version = "1.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" -dependencies = [ - "aws-lc-sys", - "zeroize", -] - -[[package]] -name = "aws-lc-sys" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" -dependencies = [ - "cc", - "cmake", - "dunce", - "fs_extra", - "pkg-config", -] - -[[package]] -name = "base16ct" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" - -[[package]] -name = "base64" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e" -dependencies = [ - "byteorder", -] - -[[package]] -name = "base64" -version = "0.21.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" - -[[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" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" - -[[package]] -name = "base64ct" -version = "1.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" - -[[package]] -name = "bit-set" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" -dependencies = [ - "serde_core", -] - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[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 = "block-padding" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" -dependencies = [ - "hybrid-array", -] - -[[package]] -name = "block2" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" -dependencies = [ - "objc2", -] - -[[package]] -name = "blocking" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" -dependencies = [ - "async-channel", - "async-task", - "futures-io", - "futures-lite", - "piper", -] - -[[package]] -name = "brotli" -version = "9.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", - "brotli-decompressor", -] - -[[package]] -name = "brotli-decompressor" -version = "6.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", -] - -[[package]] -name = "bs58" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "btoi" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b5ab9db53bcda568284df0fd39f6eac24ad6f7ba7ff1168b9e76eba6576b976" -dependencies = [ - "num-traits", -] - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "bytemuck" -version = "1.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "bytes" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" -dependencies = [ - "serde", -] - -[[package]] -name = "cairo-rs" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" -dependencies = [ - "bitflags 2.13.2", - "cairo-sys-rs", - "glib", - "libc", - "once_cell", - "thiserror 1.0.69", -] - -[[package]] -name = "cairo-sys-rs" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" -dependencies = [ - "glib-sys", - "libc", - "system-deps", -] - -[[package]] -name = "camino" -version = "1.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" -dependencies = [ - "serde_core", -] - -[[package]] -name = "cargo-platform" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" -dependencies = [ - "serde", -] - -[[package]] -name = "cargo_metadata" -version = "0.19.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" -dependencies = [ - "camino", - "cargo-platform", - "semver", - "serde", - "serde_json", - "thiserror 2.0.21", -] - -[[package]] -name = "cargo_toml" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9" -dependencies = [ - "semver", - "serde", - "toml 1.1.8+spec-1.1.0", -] - -[[package]] -name = "cbc" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" -dependencies = [ - "cipher", -] - -[[package]] -name = "cc" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" -dependencies = [ - "find-msvc-tools", - "jobserver", - "libc", - "shlex", -] - -[[package]] -name = "cesu8" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" - -[[package]] -name = "cfb" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3" -dependencies = [ - "fnv", - "uuid", - "web-time", -] - -[[package]] -name = "cfg-expr" -version = "0.15.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" -dependencies = [ - "smallvec", - "target-lexicon", -] - -[[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 0.3.1", - "rand_core 0.10.1", -] - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "cipher" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" -dependencies = [ - "block-buffer 0.12.1", - "crypto-common 0.2.2", - "inout", -] - -[[package]] -name = "cmake" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" -dependencies = [ - "cc", -] - -[[package]] -name = "cmov" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" - -[[package]] -name = "combine" -version = "4.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" -dependencies = [ - "bytes", - "futures-core", - "memchr", - "pin-project-lite", - "tokio", - "tokio-util", -] - -[[package]] -name = "concurrent-queue" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "connection-string" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "510ca239cf13b7f8d16a2b48f263de7b4f8c566f0af58d901031473c76afb1e3" - -[[package]] -name = "const-oid" -version = "0.9.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" - -[[package]] -name = "const-oid" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" - -[[package]] -name = "constant_time_eq" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" -dependencies = [ - "rustversion", -] - -[[package]] -name = "cookie" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" -dependencies = [ - "time", - "version_check", -] - -[[package]] -name = "core-foundation" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[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 = "core-graphics" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.10.1", - "core-graphics-types", - "foreign-types", - "libc", -] - -[[package]] -name = "core-graphics-types" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.10.1", - "libc", -] - -[[package]] -name = "core_detect" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" - -[[package]] -name = "cpubits" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "cpufeatures" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" -dependencies = [ - "libc", -] - -[[package]] -name = "crc32fast" -version = "1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crossbeam-channel" -version = "0.5.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-queue" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" -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.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[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 = "cssparser" -version = "0.37.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" -dependencies = [ - "cssparser-macros", - "dtoa-short", - "itoa", - "phf", - "smallvec", -] - -[[package]] -name = "cssparser-macros" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" -dependencies = [ - "quote", - "syn 3.0.9", -] - -[[package]] -name = "ctor" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" - -[[package]] -name = "ctr" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" -dependencies = [ - "cipher", -] - -[[package]] -name = "ctutils" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0" -dependencies = [ - "cmov", -] - -[[package]] -name = "darling" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" -dependencies = [ - "darling_core 0.23.0", - "darling_macro 0.23.0", -] - -[[package]] -name = "darling" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" -dependencies = [ - "darling_core 0.24.1", - "darling_macro 0.24.1", -] - -[[package]] -name = "darling_core" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" -dependencies = [ - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 2.0.119", -] - -[[package]] -name = "darling_core" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" -dependencies = [ - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 3.0.9", -] - -[[package]] -name = "darling_macro" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" -dependencies = [ - "darling_core 0.23.0", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "darling_macro" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" -dependencies = [ - "darling_core 0.24.1", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "dashmap" -version = "6.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" -dependencies = [ - "cfg-if", - "crossbeam-utils", - "hashbrown 0.14.5", - "lock_api", - "once_cell", - "parking_lot_core", -] - -[[package]] -name = "dbus" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" -dependencies = [ - "libc", - "libdbus-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "dbus-secret-service" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6" -dependencies = [ - "dbus", - "zeroize", -] - -[[package]] -name = "defmt" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" -dependencies = [ - "bitflags 1.3.2", - "defmt-macros", -] - -[[package]] -name = "defmt-macros" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" -dependencies = [ - "defmt-parser", - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "defmt-parser" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" -dependencies = [ - "thiserror 2.0.21", -] - -[[package]] -name = "der" -version = "0.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" -dependencies = [ - "const-oid 0.9.6", - "der_derive", - "flagset", - "zeroize", -] - -[[package]] -name = "der" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a" -dependencies = [ - "const-oid 0.10.2", - "pem-rfc7468", - "zeroize", -] - -[[package]] -name = "der_derive" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "deranged" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" -dependencies = [ - "serde_core", -] - -[[package]] -name = "derive_more" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" -dependencies = [ - "derive_more-impl", -] - -[[package]] -name = "derive_more-impl" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" -dependencies = [ - "proc-macro2", - "quote", - "rustc_version", - "syn 2.0.119", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.4", - "crypto-common 0.1.7", -] - -[[package]] -name = "digest" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" -dependencies = [ - "block-buffer 0.12.1", - "const-oid 0.10.2", - "crypto-common 0.2.2", - "ctutils", -] - -[[package]] -name = "directories" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs" -version = "7.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.61.2", -] - -[[package]] -name = "dispatch2" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" -dependencies = [ - "bitflags 2.13.2", - "block2", - "libc", - "objc2", -] - -[[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.9", -] - -[[package]] -name = "dlopen2" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4" -dependencies = [ - "dlopen2_derive", - "libc", - "once_cell", - "winapi", -] - -[[package]] -name = "dlopen2_derive" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "dom_query" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc" -dependencies = [ - "bit-set", - "cssparser", - "foldhash", - "html5ever", - "precomputed-hash", - "selectors", - "tendril", -] - -[[package]] -name = "dpi" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" -dependencies = [ - "serde", -] - -[[package]] -name = "dtoa" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" - -[[package]] -name = "dtoa-short" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" -dependencies = [ - "dtoa", -] - -[[package]] -name = "dunce" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" - -[[package]] -name = "dyn-clone" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" - -[[package]] -name = "either" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" - -[[package]] -name = "embed-resource" -version = "3.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f" -dependencies = [ - "cc", - "memchr", - "rustc_version", - "toml 1.1.8+spec-1.1.0", - "vswhom", - "winreg", -] - -[[package]] -name = "embed_plist" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" - -[[package]] -name = "encoding_rs" -version = "0.8.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" -dependencies = [ - "cfg-if", - "core_detect", - "multiversion_no_op", - "rustversion", - "scopeguard", - "simdutf8", -] - -[[package]] -name = "endi" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" - -[[package]] -name = "enumflags2" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" -dependencies = [ - "enumflags2_derive", - "serde", -] - -[[package]] -name = "enumflags2_derive" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "equivalent" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" - -[[package]] -name = "erased-serde" -version = "0.4.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" -dependencies = [ - "serde", - "serde_core", - "typeid", -] - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "event-listener" -version = "5.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" -dependencies = [ - "parking", - "pin-project-lite", -] - -[[package]] -name = "event-listener-strategy" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" -dependencies = [ - "event-listener", - "pin-project-lite", -] - -[[package]] -name = "fallible-iterator" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" - -[[package]] -name = "fallible-iterator" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" - -[[package]] -name = "fallible-streaming-iterator" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" - -[[package]] -name = "fastrand" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" - -[[package]] -name = "fdeflate" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" -dependencies = [ - "simd-adler32", -] - -[[package]] -name = "field-offset" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" -dependencies = [ - "memoffset", - "rustc_version", -] - -[[package]] -name = "filetime" -version = "0.2.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" -dependencies = [ - "cfg-if", - "libc", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" - -[[package]] -name = "flagset" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" - -[[package]] -name = "flate2" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" -dependencies = [ - "crc32fast", - "miniz_oxide 0.9.1", - "zlib-rs", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "foldhash" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" - -[[package]] -name = "foreign-types" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" -dependencies = [ - "foreign-types-macros", - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-macros" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "foreign-types-shared" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -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" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-executor" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" - -[[package]] -name = "futures-lite" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" -dependencies = [ - "fastrand", - "futures-core", - "futures-io", - "parking", - "pin-project-lite", -] - -[[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.9", -] - -[[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-timer" -version = "3.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "gdk" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" -dependencies = [ - "cairo-rs", - "gdk-pixbuf", - "gdk-sys", - "gio", - "glib", - "libc", - "pango", -] - -[[package]] -name = "gdk-pixbuf" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" -dependencies = [ - "gdk-pixbuf-sys", - "gio", - "glib", - "libc", - "once_cell", -] - -[[package]] -name = "gdk-pixbuf-sys" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" -dependencies = [ - "gio-sys", - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gdk-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" -dependencies = [ - "cairo-sys-rs", - "gdk-pixbuf-sys", - "gio-sys", - "glib-sys", - "gobject-sys", - "libc", - "pango-sys", - "pkg-config", - "system-deps", -] - -[[package]] -name = "gdkwayland-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" -dependencies = [ - "gdk-sys", - "glib-sys", - "gobject-sys", - "libc", - "pkg-config", - "system-deps", -] - -[[package]] -name = "gdkx11" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe" -dependencies = [ - "gdk", - "gdkx11-sys", - "gio", - "glib", - "libc", - "x11", -] - -[[package]] -name = "gdkx11-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" -dependencies = [ - "gdk-sys", - "glib-sys", - "libc", - "system-deps", - "x11", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" -dependencies = [ - "cfg-if", - "libc", - "wasi 0.9.0+wasi-snapshot-preview1", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "libc", - "wasi 0.11.1+wasi-snapshot-preview1", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "libc", - "r-efi 5.3.0", - "wasip2", -] - -[[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 6.0.0", - "rand_core 0.10.1", - "wasm-bindgen", -] - -[[package]] -name = "ghash" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" -dependencies = [ - "polyval", -] - -[[package]] -name = "gio" -version = "0.18.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-util", - "gio-sys", - "glib", - "libc", - "once_cell", - "pin-project-lite", - "smallvec", - "thiserror 1.0.69", -] - -[[package]] -name = "gio-sys" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", - "winapi", -] - -[[package]] -name = "glib" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" -dependencies = [ - "bitflags 2.13.2", - "futures-channel", - "futures-core", - "futures-executor", - "futures-task", - "futures-util", - "gio-sys", - "glib-macros", - "glib-sys", - "gobject-sys", - "libc", - "memchr", - "once_cell", - "smallvec", - "thiserror 1.0.69", -] - -[[package]] -name = "glib-macros" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" -dependencies = [ - "heck 0.4.1", - "proc-macro-crate 2.0.2", - "proc-macro-error", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "glib-sys" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" -dependencies = [ - "libc", - "system-deps", -] - -[[package]] -name = "glob" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" - -[[package]] -name = "gobject-sys" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" -dependencies = [ - "glib-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gtk" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" -dependencies = [ - "atk", - "cairo-rs", - "field-offset", - "futures-channel", - "gdk", - "gdk-pixbuf", - "gio", - "glib", - "gtk-sys", - "gtk3-macros", - "libc", - "pango", - "pkg-config", -] - -[[package]] -name = "gtk-sys" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" -dependencies = [ - "atk-sys", - "cairo-sys-rs", - "gdk-pixbuf-sys", - "gdk-sys", - "gio-sys", - "glib-sys", - "gobject-sys", - "libc", - "pango-sys", - "system-deps", -] - -[[package]] -name = "gtk3-macros" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" -dependencies = [ - "proc-macro-crate 1.3.1", - "proc-macro-error", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" -dependencies = [ - "foldhash", -] - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" -dependencies = [ - "allocator-api2", - "equivalent", - "foldhash", -] - -[[package]] -name = "hashlink" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" -dependencies = [ - "hashbrown 0.17.1", -] - -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hermit-abi" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "hmac" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" -dependencies = [ - "digest 0.11.3", -] - -[[package]] -name = "html5ever" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" -dependencies = [ - "log", - "markup5ever", -] - -[[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.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" -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 0.23.1", - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "httparse", - "hyper", - "ipnet", - "libc", - "percent-encoding", - "pin-project-lite", - "socket2", - "system-configuration", - "tokio", - "tower-service", - "tracing", - "windows-registry", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "ico" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371" -dependencies = [ - "byteorder", - "png 0.17.16", -] - -[[package]] -name = "icu_collections" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" - -[[package]] -name = "icu_properties" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" - -[[package]] -name = "icu_provider" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[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 = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", - "serde", -] - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown 0.17.1", - "serde", - "serde_core", -] - -[[package]] -name = "infer" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4" -dependencies = [ - "cfb", -] - -[[package]] -name = "inout" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f" -dependencies = [ - "block-padding", - "hybrid-array", -] - -[[package]] -name = "ipnet" -version = "2.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" - -[[package]] -name = "is-docker" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" -dependencies = [ - "once_cell", -] - -[[package]] -name = "is-wsl" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" -dependencies = [ - "is-docker", - "once_cell", -] - -[[package]] -name = "itertools" -version = "0.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "javascriptcore-rs" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" -dependencies = [ - "bitflags 1.3.2", - "glib", - "javascriptcore-rs-sys", -] - -[[package]] -name = "javascriptcore-rs-sys" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "jiff" -version = "0.2.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" -dependencies = [ - "defmt", - "jiff-core", - "jiff-static", - "jiff-tzdb-platform", - "log", - "portable-atomic", - "portable-atomic-util", - "serde_core", - "windows-link", -] - -[[package]] -name = "jiff-core" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" -dependencies = [ - "defmt", - "log", -] - -[[package]] -name = "jiff-static" -version = "0.2.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" -dependencies = [ - "jiff-core", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "jiff-tzdb" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" - -[[package]] -name = "jiff-tzdb-platform" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" -dependencies = [ - "jiff-tzdb", -] - -[[package]] -name = "jni" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" -dependencies = [ - "cesu8", - "cfg-if", - "combine", - "jni-sys 0.3.1", - "log", - "thiserror 1.0.69", - "walkdir", - "windows-sys 0.45.0", -] - -[[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 0.4.1", - "log", - "simd_cesu8", - "thiserror 2.0.21", - "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.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" -dependencies = [ - "jni-sys 0.4.1", -] - -[[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.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "json-patch" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" -dependencies = [ - "jsonptr", - "serde", - "serde_json", - "thiserror 2.0.21", -] - -[[package]] -name = "jsonptr" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "keyboard-types" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" -dependencies = [ - "bitflags 2.13.2", - "serde", -] - -[[package]] -name = "keyed_priority_queue" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee7893dab2e44ae5f9d0173f26ff4aa327c10b01b06a72b52dd9405b628640d" -dependencies = [ - "indexmap 2.14.2", -] - -[[package]] -name = "keyring" -version = "3.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" -dependencies = [ - "byteorder", - "dbus-secret-service", - "log", - "security-framework 2.11.1", - "security-framework 3.7.0", - "windows-sys 0.60.2", - "zeroize", -] - -[[package]] -name = "libappindicator" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" -dependencies = [ - "glib", - "gtk", - "gtk-sys", - "libappindicator-sys", - "log", -] - -[[package]] -name = "libappindicator-sys" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf" -dependencies = [ - "gtk-sys", - "libloading", - "once_cell", -] - -[[package]] -name = "libc" -version = "0.2.191" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" - -[[package]] -name = "libdbus-sys" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" -dependencies = [ - "pkg-config", -] - -[[package]] -name = "libloading" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" -dependencies = [ - "cfg-if", - "winapi", -] - -[[package]] -name = "libredox" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" -dependencies = [ - "libc", -] - -[[package]] -name = "libsqlite3-sys" -version = "0.39.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3" -dependencies = [ - "cc", - "pkg-config", - "vcpkg", -] - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[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.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" - -[[package]] -name = "lowquery" -version = "0.5.7" -dependencies = [ - "aes", - "cbc", - "chrono", - "directories", - "futures-util", - "keyring", - "mysql_async", - "oracledb", - "parking_lot", - "quick-xml", - "redis", - "rusqlite", - "rustls", - "rustls-native-certs", - "scylla", - "serde", - "serde_json", - "tauri", - "tauri-build", - "tauri-plugin-dialog", - "tauri-plugin-opener", - "tauri-plugin-process", - "tauri-plugin-updater", - "thiserror 2.0.21", - "tiberius", - "tokio", - "tokio-postgres", - "tokio-postgres-rustls", - "tokio-util", - "uuid", - "webpki-roots", - "winreg", -] - -[[package]] -name = "lru" -version = "0.18.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" -dependencies = [ - "hashbrown 0.17.1", -] - -[[package]] -name = "lz4_flex" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" -dependencies = [ - "twox-hash", -] - -[[package]] -name = "manyhow" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b33efb3ca6d3b07393750d4030418d594ab1139cee518f0dc88db70fec873587" -dependencies = [ - "manyhow-macros", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "manyhow-macros" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46fce34d199b78b6e6073abf984c9cf5fd3e9330145a93ee0738a7443e371495" -dependencies = [ - "proc-macro-utils", - "proc-macro2", - "quote", -] - -[[package]] -name = "markup5ever" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" -dependencies = [ - "log", - "tendril", - "web_atoms", -] - -[[package]] -name = "md-5" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" -dependencies = [ - "cfg-if", - "digest 0.11.3", -] - -[[package]] -name = "md5" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e6bcd6433cff03a4bfc3d9834d504467db1f1cf6d0ea765d37d330249ed629d" - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "memoffset" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" -dependencies = [ - "autocfg", -] - -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "minisign-verify" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce" - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "mio" -version = "1.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" -dependencies = [ - "libc", - "wasi 0.11.1+wasi-snapshot-preview1", - "windows-sys 0.61.2", -] - -[[package]] -name = "muda" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996" -dependencies = [ - "crossbeam-channel", - "dpi", - "gtk", - "keyboard-types", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", - "once_cell", - "png 0.18.1", - "serde", - "thiserror 2.0.21", - "windows-sys 0.61.2", -] - -[[package]] -name = "multiversion_no_op" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" - -[[package]] -name = "mysql-common-derive" -version = "0.32.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4db8a44120571277accfaa3f3d91e7d3989d601d817c2fc01a9391b86135666" -dependencies = [ - "darling 0.23.0", - "heck 0.5.0", - "manyhow", - "num-bigint", - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 2.0.119", - "termcolor", - "thiserror 2.0.21", -] - -[[package]] -name = "mysql_async" -version = "0.37.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40d11da0e2d9fad4640c9f9198ee431c6d68444568f83ef1f10f3367270071e4" -dependencies = [ - "arc-swap", - "bytes", - "crossbeam-queue", - "crossbeam-utils", - "flate2", - "futures-core", - "futures-sink", - "futures-util", - "keyed_priority_queue", - "lru", - "mysql_common", - "percent-encoding", - "rand 0.10.3", - "rustls", - "serde", - "socket2", - "thiserror 2.0.21", - "tokio", - "tokio-rustls", - "tokio-util", - "twox-hash", - "url", - "webpki-roots", -] - -[[package]] -name = "mysql_common" -version = "0.37.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f27695f286b461da077b8c2f72f47feaa04ce3c3f9c0976257410e90e21208a" -dependencies = [ - "base64 0.22.1", - "bitflags 2.13.2", - "btoi", - "byteorder", - "bytes", - "crc32fast", - "flate2", - "getrandom 0.3.4", - "mysql-common-derive", - "num-bigint", - "num-traits", - "regex", - "saturating", - "serde", - "serde_json", - "sha1", - "sha2 0.10.9", - "thiserror 2.0.21", - "uuid", -] - -[[package]] -name = "ndk" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" -dependencies = [ - "bitflags 2.13.2", - "jni-sys 0.3.1", - "log", - "ndk-sys", - "num_enum", - "raw-window-handle", - "thiserror 1.0.69", -] - -[[package]] -name = "ndk-context" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" - -[[package]] -name = "ndk-sys" -version = "0.6.0+11769913" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" -dependencies = [ - "jni-sys 0.3.1", -] - -[[package]] -name = "new_debug_unreachable" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" - -[[package]] -name = "nix" -version = "0.31.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" -dependencies = [ - "bitflags 2.13.2", - "cfg-if", - "cfg_aliases", - "libc", -] - -[[package]] -name = "num-bigint" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-conv" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" - -[[package]] -name = "num-integer" -version = "0.1.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_enum" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" -dependencies = [ - "num_enum_derive", - "rustversion", -] - -[[package]] -name = "num_enum_derive" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" -dependencies = [ - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "objc2" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" -dependencies = [ - "objc2-encode", - "objc2-exception-helper", -] - -[[package]] -name = "objc2-app-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" -dependencies = [ - "bitflags 2.13.2", - "block2", - "objc2", - "objc2-core-foundation", - "objc2-foundation", - "objc2-quartz-core", -] - -[[package]] -name = "objc2-cloud-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-foundation", -] - -[[package]] -name = "objc2-core-data" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" -dependencies = [ - "objc2", - "objc2-foundation", -] - -[[package]] -name = "objc2-core-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" -dependencies = [ - "bitflags 2.13.2", - "dispatch2", - "objc2", -] - -[[package]] -name = "objc2-core-graphics" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" -dependencies = [ - "bitflags 2.13.2", - "dispatch2", - "objc2", - "objc2-core-foundation", - "objc2-io-surface", -] - -[[package]] -name = "objc2-core-image" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" -dependencies = [ - "objc2", - "objc2-foundation", -] - -[[package]] -name = "objc2-core-location" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" -dependencies = [ - "objc2", - "objc2-foundation", -] - -[[package]] -name = "objc2-core-text" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-core-foundation", - "objc2-core-graphics", -] - -[[package]] -name = "objc2-encode" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" - -[[package]] -name = "objc2-exception-helper" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a" -dependencies = [ - "cc", -] - -[[package]] -name = "objc2-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" -dependencies = [ - "bitflags 2.13.2", - "block2", - "libc", - "objc2", - "objc2-core-foundation", -] - -[[package]] -name = "objc2-io-surface" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-core-foundation", -] - -[[package]] -name = "objc2-osa-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-app-kit", - "objc2-foundation", -] - -[[package]] -name = "objc2-quartz-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-core-foundation", - "objc2-foundation", -] - -[[package]] -name = "objc2-system-configuration" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" -dependencies = [ - "objc2-core-foundation", -] - -[[package]] -name = "objc2-ui-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" -dependencies = [ - "bitflags 2.13.2", - "block2", - "objc2", - "objc2-cloud-kit", - "objc2-core-data", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-core-image", - "objc2-core-location", - "objc2-core-text", - "objc2-foundation", - "objc2-quartz-core", - "objc2-user-notifications", -] - -[[package]] -name = "objc2-user-notifications" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" -dependencies = [ - "objc2", - "objc2-foundation", -] - -[[package]] -name = "objc2-web-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" -dependencies = [ - "bitflags 2.13.2", - "block2", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "open" -version = "5.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa576c76302b7b808eecc68061e67336c47833ef9d22caa74dda10fa9675eebc" -dependencies = [ - "dunce", - "is-wsl", - "libc", -] - -[[package]] -name = "openssl-probe" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" - -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - -[[package]] -name = "oracledb" -version = "26.0.0-beta.4" -dependencies = [ - "aes", - "base16ct", - "base64ct", - "cbc", - "chrono", - "pbkdf2", - "pkcs8", - "rand 0.10.3", - "rustls", - "sha2 0.11.1", - "uuid", - "webpki-roots", - "whoami", -] - -[[package]] -name = "ordered-stream" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" -dependencies = [ - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "osakit" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b" -dependencies = [ - "objc2", - "objc2-foundation", - "objc2-osa-kit", - "serde", - "serde_json", - "thiserror 2.0.21", -] - -[[package]] -name = "pango" -version = "0.18.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" -dependencies = [ - "gio", - "glib", - "libc", - "once_cell", - "pango-sys", -] - -[[package]] -name = "pango-sys" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "parking" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" - -[[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 = "pbkdf2" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" -dependencies = [ - "digest 0.11.3", - "hmac", -] - -[[package]] -name = "pem-rfc7468" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" -dependencies = [ - "base64ct", -] - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "phf" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" -dependencies = [ - "phf_macros", - "phf_shared", - "serde", -] - -[[package]] -name = "phf_codegen" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" -dependencies = [ - "phf_generator", - "phf_shared", -] - -[[package]] -name = "phf_generator" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" -dependencies = [ - "fastrand", - "phf_shared", -] - -[[package]] -name = "phf_macros" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "phf_shared" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "piper" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" -dependencies = [ - "atomic-waker", - "fastrand", - "futures-io", -] - -[[package]] -name = "pkcs5" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63d440a804ec8d6fafbb6b84471e013286658d373248927692ab3366686220ca" -dependencies = [ - "aes", - "aes-gcm", - "cbc", - "der 0.8.2", - "pbkdf2", - "rand_core 0.10.1", - "scrypt", - "sha2 0.11.1", - "spki 0.8.1", -] - -[[package]] -name = "pkcs8" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" -dependencies = [ - "der 0.8.2", - "pkcs5", - "rand_core 0.10.1", - "spki 0.8.1", -] - -[[package]] -name = "pkg-config" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" - -[[package]] -name = "plist" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb" -dependencies = [ - "base64 0.23.1", - "indexmap 2.14.2", - "quick-xml", - "serde", - "time", -] - -[[package]] -name = "png" -version = "0.17.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" -dependencies = [ - "bitflags 1.3.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "png" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" -dependencies = [ - "bitflags 2.13.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "polling" -version = "3.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" -dependencies = [ - "cfg-if", - "concurrent-queue", - "hermit-abi", - "pin-project-lite", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "polyval" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" -dependencies = [ - "cpubits", - "cpufeatures 0.3.1", - "universal-hash", -] - -[[package]] -name = "portable-atomic" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" - -[[package]] -name = "portable-atomic-util" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" -dependencies = [ - "portable-atomic", -] - -[[package]] -name = "postgres-protocol" -version = "0.6.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08808e3c483c46e999108051c78334f473d5adb59d78bb80a1268c7e6aa6c514" -dependencies = [ - "base64 0.22.1", - "byteorder", - "bytes", - "fallible-iterator 0.2.0", - "hmac", - "md-5", - "memchr", - "rand 0.10.3", - "sha2 0.11.1", - "stringprep", -] - -[[package]] -name = "postgres-types" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "851ca9db4932932d69f3ea811b1abe63087a0f740a47692619dd40d4899b68be" -dependencies = [ - "bytes", - "chrono", - "fallible-iterator 0.2.0", - "postgres-protocol", - "serde_core", - "serde_json", - "uuid", -] - -[[package]] -name = "potential_utf" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" -dependencies = [ - "zerovec", -] - -[[package]] -name = "powerfmt" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" - -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "precomputed-hash" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" - -[[package]] -name = "pretty-hex" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a65843dfefbafd3c879c683306959a6de478443ffe9c9adf02f5976432402d7" - -[[package]] -name = "proc-macro-crate" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" -dependencies = [ - "once_cell", - "toml_edit 0.19.15", -] - -[[package]] -name = "proc-macro-crate" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24" -dependencies = [ - "toml_datetime 0.6.3", - "toml_edit 0.20.2", -] - -[[package]] -name = "proc-macro-crate" -version = "3.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" -dependencies = [ - "toml_edit 0.25.17+spec-1.1.0", -] - -[[package]] -name = "proc-macro-error" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" -dependencies = [ - "proc-macro-error-attr", - "proc-macro2", - "quote", - "syn 1.0.109", - "version_check", -] - -[[package]] -name = "proc-macro-error-attr" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" -dependencies = [ - "proc-macro2", - "quote", - "version_check", -] - -[[package]] -name = "proc-macro-utils" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eeaf08a13de400bc215877b5bdc088f241b12eb42f0a548d3390dc1c56bb7071" -dependencies = [ - "proc-macro2", - "quote", - "smallvec", -] - -[[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 = "quick-xml" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" -dependencies = [ - "memchr", -] - -[[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 = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[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.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" -dependencies = [ - "getrandom 0.1.16", - "libc", - "rand_chacha 0.2.2", - "rand_core 0.5.1", - "rand_hc", -] - -[[package]] -name = "rand" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.5", -] - -[[package]] -name = "rand" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" -dependencies = [ - "chacha20", - "getrandom 0.4.3", - "rand_core 0.10.1", -] - -[[package]] -name = "rand_chacha" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" -dependencies = [ - "ppv-lite86", - "rand_core 0.5.1", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_core" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" -dependencies = [ - "getrandom 0.1.16", -] - -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - -[[package]] -name = "rand_core" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" - -[[package]] -name = "rand_hc" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" -dependencies = [ - "rand_core 0.5.1", -] - -[[package]] -name = "rand_pcg" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b48ac3f7ffaab7fac4d2376632268aa5f89abdb55f7ebf8f4d11fffccb2320f7" -dependencies = [ - "rand_core 0.9.5", -] - -[[package]] -name = "raw-window-handle" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" - -[[package]] -name = "redis" -version = "1.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5b98ae99461e02895c3a96a25dbe4d852a3d5e5b815d31d5d9e4b5344d99e9" -dependencies = [ - "arcstr", - "async-lock", - "bytes", - "cfg-if", - "combine", - "futures-util", - "itoa", - "percent-encoding", - "pin-project-lite", - "rustls", - "rustls-native-certs", - "ryu", - "socket2", - "tokio", - "tokio-rustls", - "tokio-util", - "url", - "webpki-roots", - "xxhash-rust", -] - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "redox_users" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" -dependencies = [ - "libredox", - "thiserror 2.0.21", -] - -[[package]] -name = "ref-cast" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "regex" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "reqwest" -version = "0.13.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" -dependencies = [ - "base64 0.23.1", - "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "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 = "rfd" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672" -dependencies = [ - "block2", - "dispatch2", - "glib-sys", - "gobject-sys", - "gtk-sys", - "js-sys", - "log", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", - "raw-window-handle", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "windows-sys 0.60.2", -] - -[[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 = "rsqlite-vfs" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" -dependencies = [ - "hashbrown 0.16.1", - "thiserror 2.0.21", -] - -[[package]] -name = "rusqlite" -version = "0.41.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594" -dependencies = [ - "bitflags 2.13.2", - "fallible-iterator 0.3.0", - "fallible-streaming-iterator", - "hashlink", - "libsqlite3-sys", - "smallvec", - "sqlite-wasm-rs", -] - -[[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 = "rustix" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" -dependencies = [ - "bitflags 2.13.2", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls" -version = "0.23.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" -dependencies = [ - "aws-lc-rs", - "log", - "once_cell", - "ring", - "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 3.7.0", -] - -[[package]] -name = "rustls-pki-types" -version = "1.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" -dependencies = [ - "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 0.10.1", - "core-foundation-sys", - "jni 0.22.4", - "log", - "once_cell", - "rustls", - "rustls-native-certs", - "rustls-platform-verifier-android", - "rustls-webpki", - "security-framework 3.7.0", - "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.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" -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 = "salsa20" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c" -dependencies = [ - "cfg-if", - "cipher", -] - -[[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 = "saturating" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" - -[[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 = "schemars" -version = "0.8.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" -dependencies = [ - "dyn-clone", - "indexmap 1.9.3", - "schemars_derive", - "serde", - "serde_json", - "url", - "uuid", -] - -[[package]] -name = "schemars" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" -dependencies = [ - "dyn-clone", - "ref-cast", - "serde", - "serde_json", -] - -[[package]] -name = "schemars" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" -dependencies = [ - "dyn-clone", - "ref-cast", - "serde", - "serde_json", -] - -[[package]] -name = "schemars_derive" -version = "0.8.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" -dependencies = [ - "proc-macro2", - "quote", - "serde_derive_internals", - "syn 2.0.119", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "scrypt" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d87af57419b594aa23fa95f09f0e06d80d84ba01c26148c43844cad6ff4485f0" -dependencies = [ - "cfg-if", - "pbkdf2", - "salsa20", - "sha2 0.11.1", -] - -[[package]] -name = "scylla" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29eebcb7e34257f8ce01aaa1469644825bd4b4995d401c362be65d994e3feaa3" -dependencies = [ - "arc-swap", - "async-trait", - "bytes", - "chrono", - "dashmap", - "futures", - "hashbrown 0.17.1", - "itertools", - "rand 0.9.5", - "rand_pcg", - "rustls", - "scylla-cql", - "scylla-cql-core", - "serde", - "serde_json", - "smallvec", - "socket2", - "thiserror 2.0.21", - "tokio", - "tokio-rustls", - "tracing", - "uuid", -] - -[[package]] -name = "scylla-cql" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a398b0e78fb3872c4d5afc74e461d6b80dd69d030e13ddc7442e5f32c482e0da" -dependencies = [ - "byteorder", - "bytes", - "chrono", - "itertools", - "lz4_flex", - "scylla-cql-core", - "snap", - "stable_deref_trait", - "thiserror 2.0.21", - "tokio", - "uuid", - "yoke", -] - -[[package]] -name = "scylla-cql-core" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72ca9de2eb08d04a9c85002ac179c51353c91152cd2cd58fc3d7cbc1eee8ab16" -dependencies = [ - "byteorder", - "bytes", - "chrono", - "itertools", - "scylla-macros", - "thiserror 2.0.21", - "uuid", -] - -[[package]] -name = "scylla-macros" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c82c9c67cb4912cefc8cb2a68ebdcbe0273b66510c2bb06581ae6b68d98498aa" -dependencies = [ - "darling 0.24.1", - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "secrecy" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a" -dependencies = [ - "zeroize", -] - -[[package]] -name = "security-framework" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.9.4", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework" -version = "3.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.10.1", - "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 = "selectors" -version = "0.38.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d" -dependencies = [ - "bitflags 2.13.2", - "cssparser", - "derive_more", - "log", - "new_debug_unreachable", - "phf", - "phf_codegen", - "precomputed-hash", - "rustc-hash", - "servo_arc", - "smallvec", -] - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" -dependencies = [ - "serde", - "serde_core", -] - -[[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-untagged" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" -dependencies = [ - "erased-serde", - "serde", - "serde_core", - "typeid", -] - -[[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.9", -] - -[[package]] -name = "serde_derive_internals" -version = "0.29.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "foldhash", - "indexmap 2.14.2", - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_repr" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "serde_spanned" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" -dependencies = [ - "serde", -] - -[[package]] -name = "serde_spanned" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" -dependencies = [ - "serde_core", -] - -[[package]] -name = "serde_with" -version = "3.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" -dependencies = [ - "base64 0.23.1", - "bs58", - "chrono", - "hex", - "indexmap 1.9.3", - "indexmap 2.14.2", - "jiff", - "schemars 0.9.0", - "schemars 1.2.3", - "serde_core", - "serde_json", - "serde_with_macros", - "time", -] - -[[package]] -name = "serde_with_macros" -version = "3.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" -dependencies = [ - "darling 0.24.1", - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "serialize-to-javascript" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5" -dependencies = [ - "serde", - "serde_json", - "serialize-to-javascript-impl", -] - -[[package]] -name = "serialize-to-javascript-impl" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "servo_arc" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" -dependencies = [ - "stable_deref_trait", -] - -[[package]] -name = "sha1" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - -[[package]] -name = "sha2" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.1", - "digest 0.11.3", -] - -[[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-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - -[[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 = "siphasher" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" - -[[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.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" - -[[package]] -name = "snap" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886" - -[[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 = "softbuffer" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" -dependencies = [ - "bytemuck", - "js-sys", - "ndk", - "objc2", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-foundation", - "objc2-quartz-core", - "raw-window-handle", - "redox_syscall", - "tracing", - "wasm-bindgen", - "web-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "soup3" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" -dependencies = [ - "futures-channel", - "gio", - "glib", - "libc", - "soup3-sys", -] - -[[package]] -name = "soup3-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" -dependencies = [ - "gio-sys", - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "spki" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" -dependencies = [ - "base64ct", - "der 0.7.10", -] - -[[package]] -name = "spki" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" -dependencies = [ - "base64ct", - "der 0.8.2", -] - -[[package]] -name = "sqlite-wasm-rs" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" -dependencies = [ - "cc", - "js-sys", - "rsqlite-vfs", - "wasm-bindgen", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "static_vcruntime" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7" - -[[package]] -name = "string_cache" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" -dependencies = [ - "new_debug_unreachable", - "parking_lot", - "phf_shared", - "precomputed-hash", -] - -[[package]] -name = "string_cache_codegen" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro2", - "quote", -] - -[[package]] -name = "stringprep" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" -dependencies = [ - "unicode-bidi", - "unicode-normalization", - "unicode-properties", -] - -[[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 = "swift-rs" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cefd87076fd385308ee4aff597256c902f1fbb4d031de1558efc12f8ffefadd9" -dependencies = [ - "base64 0.21.7", - "serde", - "serde_json", -] - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "unicode-ident", -] - -[[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.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" -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.9", -] - -[[package]] -name = "system-configuration" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" -dependencies = [ - "bitflags 2.13.2", - "core-foundation 0.9.4", - "system-configuration-sys", -] - -[[package]] -name = "system-configuration-sys" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "system-deps" -version = "6.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" -dependencies = [ - "cfg-expr", - "heck 0.5.0", - "pkg-config", - "toml 0.8.2", - "version-compare", -] - -[[package]] -name = "tao" -version = "0.37.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400" -dependencies = [ - "bitflags 2.13.2", - "block2", - "core-foundation 0.10.1", - "core-graphics", - "crossbeam-channel", - "dbus", - "dispatch2", - "dlopen2", - "dpi", - "gdkwayland-sys", - "gdkx11-sys", - "gtk", - "jni 0.21.1", - "libc", - "log", - "ndk", - "ndk-context", - "ndk-sys", - "objc2", - "objc2-app-kit", - "objc2-foundation", - "objc2-ui-kit", - "parking_lot", - "percent-encoding", - "raw-window-handle", - "tao-macros", - "unicode-segmentation", - "url", - "windows", - "windows-core", - "windows-version", - "x11-dl", -] - -[[package]] -name = "tao-macros" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "tar" -version = "0.4.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" -dependencies = [ - "filetime", - "libc", - "xattr", -] - -[[package]] -name = "target-lexicon" -version = "0.12.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" - -[[package]] -name = "tauri" -version = "2.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f316751027fc2644221d1a448564d519efb07067fda584879d9cda966391d212" -dependencies = [ - "anyhow", - "bytes", - "cookie", - "dirs", - "dunce", - "embed_plist", - "getrandom 0.3.4", - "glob", - "gtk", - "heck 0.5.0", - "http", - "jni 0.21.1", - "libc", - "log", - "mime", - "muda", - "objc2", - "objc2-app-kit", - "objc2-foundation", - "objc2-ui-kit", - "objc2-web-kit", - "percent-encoding", - "plist", - "raw-window-handle", - "reqwest", - "serde", - "serde_json", - "serde_repr", - "serialize-to-javascript", - "swift-rs", - "tauri-build", - "tauri-macros", - "tauri-runtime", - "tauri-runtime-wry", - "tauri-utils", - "thiserror 2.0.21", - "tokio", - "tray-icon", - "url", - "webkit2gtk", - "webview2-com", - "window-vibrancy", - "windows", -] - -[[package]] -name = "tauri-build" -version = "2.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "641dd5fd297c99ab92717b0428cca5b9c6f960b2ac96ca131b3eebc9d70b8ddc" -dependencies = [ - "anyhow", - "cargo_toml", - "dirs", - "glob", - "heck 0.5.0", - "json-patch", - "schemars 0.8.22", - "semver", - "serde", - "serde_json", - "static_vcruntime", - "strsim", - "tauri-utils", - "tauri-winres", - "walkdir", -] - -[[package]] -name = "tauri-codegen" -version = "2.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6585c5b536c00f039d12ce70a9755172d5423bbcfd3969863baa70314c3e02f" -dependencies = [ - "base64 0.23.1", - "brotli", - "ico", - "json-patch", - "plist", - "png 0.18.1", - "proc-macro2", - "quote", - "semver", - "serde", - "serde_json", - "sha2 0.10.9", - "syn 2.0.119", - "tauri-utils", - "thiserror 2.0.21", - "time", - "url", - "uuid", - "walkdir", -] - -[[package]] -name = "tauri-macros" -version = "2.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2e83a0cfa1bae376e8fbbdc0b1692707aed50cd6072ce85cae4789af5d6c19f" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn 2.0.119", - "tauri-codegen", - "tauri-utils", -] - -[[package]] -name = "tauri-plugin" -version = "2.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67fb21a77e8f94e8beb3325e583102488659365af0a3948b7ea244c5b779c291" -dependencies = [ - "anyhow", - "glob", - "plist", - "schemars 0.8.22", - "serde", - "serde_json", - "tauri-utils", - "walkdir", -] - -[[package]] -name = "tauri-plugin-dialog" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7461aaacf1901915ea7b9f5cd74f8224a351ed96af0a62c07fce934003cb34b" -dependencies = [ - "log", - "raw-window-handle", - "rfd", - "serde", - "serde_json", - "tauri", - "tauri-plugin", - "tauri-plugin-fs", - "thiserror 2.0.21", - "url", -] - -[[package]] -name = "tauri-plugin-fs" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d58eb1d4984e535f47a642ffec09a2da6f5c18a12b5902d12126cb7626d628b" -dependencies = [ - "anyhow", - "dunce", - "glob", - "log", - "objc2-foundation", - "percent-encoding", - "schemars 0.8.22", - "serde", - "serde_json", - "serde_repr", - "tauri", - "tauri-plugin", - "tauri-utils", - "thiserror 2.0.21", - "toml 1.1.8+spec-1.1.0", - "url", -] - -[[package]] -name = "tauri-plugin-opener" -version = "2.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53810be1b4fed22bb6ac3f4cab5a2b80d9391d1af436bda145607532bc0bb219" -dependencies = [ - "dunce", - "glob", - "objc2-app-kit", - "objc2-foundation", - "open", - "schemars 0.8.22", - "serde", - "serde_json", - "tauri", - "tauri-plugin", - "thiserror 2.0.21", - "url", - "windows", - "zbus", -] - -[[package]] -name = "tauri-plugin-process" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74ae3d8549ae564c0397377373e262f340908eb23a5b9fbe03f2a00007dc0038" -dependencies = [ - "tauri", - "tauri-plugin", -] - -[[package]] -name = "tauri-plugin-updater" -version = "2.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d957abbcb3f9f6c76d22a3a0f012f30880640d0bccb5634d2b12a9937e4c872b" -dependencies = [ - "base64 0.23.1", - "dirs", - "flate2", - "futures-util", - "http", - "infer", - "libc", - "log", - "minisign-verify", - "osakit", - "percent-encoding", - "reqwest", - "rustls", - "semver", - "serde", - "serde_json", - "tar", - "tauri", - "tauri-plugin", - "tempfile", - "thiserror 2.0.21", - "time", - "tokio", - "url", - "windows-sys 0.61.2", - "zip", -] - -[[package]] -name = "tauri-runtime" -version = "2.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9" -dependencies = [ - "cookie", - "dpi", - "gtk", - "http", - "jni 0.21.1", - "objc2", - "objc2-ui-kit", - "objc2-web-kit", - "raw-window-handle", - "serde", - "serde_json", - "tauri-utils", - "thiserror 2.0.21", - "url", - "webkit2gtk", - "webview2-com", - "windows", -] - -[[package]] -name = "tauri-runtime-wry" -version = "2.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d61892587aea2a85245bcaec98c6fe46268874c0a0deae5535fb71ca7b93eae" -dependencies = [ - "gtk", - "http", - "jni 0.21.1", - "log", - "objc2", - "objc2-app-kit", - "once_cell", - "percent-encoding", - "raw-window-handle", - "softbuffer", - "tao", - "tauri-runtime", - "tauri-utils", - "url", - "webkit2gtk", - "webview2-com", - "windows", - "wry", -] - -[[package]] -name = "tauri-utils" -version = "2.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3" -dependencies = [ - "anyhow", - "brotli", - "cargo_metadata", - "ctor", - "dom_query", - "dunce", - "glob", - "http", - "infer", - "json-patch", - "log", - "memchr", - "phf", - "plist", - "proc-macro2", - "quote", - "regex", - "schemars 0.8.22", - "semver", - "serde", - "serde-untagged", - "serde_json", - "serde_with", - "swift-rs", - "thiserror 2.0.21", - "toml 1.1.8+spec-1.1.0", - "url", - "urlpattern", - "uuid", - "walkdir", -] - -[[package]] -name = "tauri-winres" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c52bb6904475a6ca662f15ef787f18ade61d5740a1ee12c45d3b748efdb6f796" -dependencies = [ - "dunce", - "embed-resource", - "toml 1.1.8+spec-1.1.0", -] - -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.3", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "tendril" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" -dependencies = [ - "new_debug_unreachable", -] - -[[package]] -name = "termcolor" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - -[[package]] -name = "thiserror" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" -dependencies = [ - "thiserror-impl 2.0.21", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[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.9", -] - -[[package]] -name = "tiberius" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e07324791de2bdaed058af4aa433a0b5ec5c0beac407a9797419c19805df2415" -dependencies = [ - "async-trait", - "asynchronous-codec", - "byteorder", - "bytes", - "connection-string", - "encoding_rs", - "enumflags2", - "futures-timer", - "futures-util", - "libc", - "num-traits", - "once_cell", - "pin-project-lite", - "pretty-hex", - "rustls-native-certs", - "rustls-pki-types", - "rustls-webpki", - "secrecy", - "thiserror 2.0.21", - "tiberius-macros", - "tokio", - "tokio-rustls", - "tokio-util", - "tracing", - "uuid", - "winauth", - "zeroize", -] - -[[package]] -name = "tiberius-macros" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "907fed5ea55695d902cc3359fffa4a35021dfa9b95ab4eb9c8376d42ffb9eec8" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "time" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" -dependencies = [ - "deranged", - "num-conv", - "powerfmt", - "serde_core", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" - -[[package]] -name = "time-macros" -version = "0.2.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" -dependencies = [ - "num-conv", - "time-core", -] - -[[package]] -name = "tinystr" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tinyvec" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" - -[[package]] -name = "tls_codec" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" -dependencies = [ - "tls_codec_derive", - "zeroize", -] - -[[package]] -name = "tls_codec_derive" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "tokio" -version = "1.54.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" -dependencies = [ - "bytes", - "libc", - "mio", - "pin-project-lite", - "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.9", -] - -[[package]] -name = "tokio-postgres" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a528f7d280f6d5b9cd149635c8705b0dd049754bc67d81d31fa25169a93809d3" -dependencies = [ - "async-trait", - "byteorder", - "bytes", - "fallible-iterator 0.2.0", - "futures-channel", - "futures-util", - "log", - "parking_lot", - "percent-encoding", - "phf", - "pin-project-lite", - "postgres-protocol", - "postgres-types", - "rand 0.10.3", - "socket2", - "tokio", - "tokio-util", - "whoami", -] - -[[package]] -name = "tokio-postgres-rustls" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27d684bad428a0f2481f42241f821db42c54e2dc81d8c00db8536c506b0a0144" -dependencies = [ - "const-oid 0.9.6", - "ring", - "rustls", - "tokio", - "tokio-postgres", - "tokio-rustls", - "x509-cert", -] - -[[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-io", - "futures-sink", - "libc", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "toml" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" -dependencies = [ - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.3", - "toml_edit 0.20.2", -] - -[[package]] -name = "toml" -version = "1.1.8+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" -dependencies = [ - "indexmap 2.14.2", - "serde_core", - "serde_spanned 1.1.2", - "toml_datetime 1.1.2+spec-1.1.0", - "toml_parser", - "toml_writer", - "winnow 1.0.4", -] - -[[package]] -name = "toml_datetime" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_datetime" -version = "1.1.2+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" -dependencies = [ - "serde_core", -] - -[[package]] -name = "toml_edit" -version = "0.19.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" -dependencies = [ - "indexmap 2.14.2", - "toml_datetime 0.6.3", - "winnow 0.5.40", -] - -[[package]] -name = "toml_edit" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" -dependencies = [ - "indexmap 2.14.2", - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.3", - "winnow 0.5.40", -] - -[[package]] -name = "toml_edit" -version = "0.25.17+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" -dependencies = [ - "indexmap 2.14.2", - "toml_datetime 1.1.2+spec-1.1.0", - "toml_parser", - "winnow 1.0.4", -] - -[[package]] -name = "toml_parser" -version = "1.1.5+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" -dependencies = [ - "winnow 1.0.4", -] - -[[package]] -name = "toml_writer" -version = "1.1.3+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" - -[[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 2.13.2", - "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 = [ - "log", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[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 = "tray-icon" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" -dependencies = [ - "crossbeam-channel", - "dirs", - "libappindicator", - "muda", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-foundation", - "once_cell", - "png 0.18.1", - "serde", - "thiserror 2.0.21", - "windows-sys 0.61.2", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "twox-hash" -version = "2.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" - -[[package]] -name = "typed-path" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" - -[[package]] -name = "typeid" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "uds_windows" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" -dependencies = [ - "memoffset", - "tempfile", - "windows-sys 0.61.2", -] - -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - -[[package]] -name = "unicode-ident" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" - -[[package]] -name = "unicode-normalization" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-properties" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" - -[[package]] -name = "unicode-segmentation" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" - -[[package]] -name = "universal-hash" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" -dependencies = [ - "crypto-common 0.2.2", - "ctutils", -] - -[[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.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", - "serde_derive", -] - -[[package]] -name = "urlpattern" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b" -dependencies = [ - "icu_properties", - "regex", - "serde", - "url", -] - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "uuid" -version = "1.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" -dependencies = [ - "getrandom 0.4.3", - "js-sys", - "serde_core", - "wasm-bindgen", -] - -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - -[[package]] -name = "version-compare" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "vswhom" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" -dependencies = [ - "libc", - "vswhom-sys", -] - -[[package]] -name = "vswhom-sys" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" -dependencies = [ - "cc", - "libc", -] - -[[package]] -name = "walkdir" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" -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.9.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasi" -version = "0.14.7+wasi-0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" -dependencies = [ - "wasip2", -] - -[[package]] -name = "wasip2" -version = "1.0.4+wasi-0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" -dependencies = [ - "wit-bindgen", -] - -[[package]] -name = "wasite" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66fe902b4a6b8028a753d5424909b764ccf79b7a209eac9bf97e59cda9f71a42" -dependencies = [ - "wasi 0.14.7+wasi-0.2.4", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.129" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.79" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" -dependencies = [ - "js-sys", - "tokio", - "wasm-bindgen", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.129" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.129" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.9", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.129" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" -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.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" -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 = "web_atoms" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" -dependencies = [ - "phf", - "phf_codegen", - "string_cache", - "string_cache_codegen", -] - -[[package]] -name = "webkit2gtk" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793" -dependencies = [ - "bitflags 1.3.2", - "cairo-rs", - "gdk", - "gdk-sys", - "gio", - "gio-sys", - "glib", - "glib-sys", - "gobject-sys", - "gtk", - "gtk-sys", - "javascriptcore-rs", - "libc", - "once_cell", - "soup3", - "webkit2gtk-sys", -] - -[[package]] -name = "webkit2gtk-sys" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5" -dependencies = [ - "bitflags 1.3.2", - "cairo-sys-rs", - "gdk-sys", - "gio-sys", - "glib-sys", - "gobject-sys", - "gtk-sys", - "javascriptcore-rs-sys", - "libc", - "pkg-config", - "soup3-sys", - "system-deps", -] - -[[package]] -name = "webpki-root-certs" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "webpki-roots" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "webview2-com" -version = "0.39.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6" -dependencies = [ - "webview2-com-macros", - "webview2-com-sys", - "windows", - "windows-core", -] - -[[package]] -name = "webview2-com-macros" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "webview2-com-sys" -version = "0.39.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb" -dependencies = [ - "thiserror 2.0.21", - "windows", - "windows-core", -] - -[[package]] -name = "whoami" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" -dependencies = [ - "libc", - "libredox", - "objc2-system-configuration", - "wasite", - "web-sys", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[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 = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "winauth" -version = "0.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e03c9d0fde636447315ff38695b14c85c6ccc738ade05a400a3ce568a557021" -dependencies = [ - "base64 0.10.1", - "bitflags 1.3.2", - "byteorder", - "md5", - "rand 0.7.3", - "winapi", -] - -[[package]] -name = "window-vibrancy" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580" -dependencies = [ - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", - "objc2-quartz-core", - "raw-window-handle", - "windows-sys 0.61.2", - "windows-version", -] - -[[package]] -name = "windows" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" -dependencies = [ - "windows-collections", - "windows-core", - "windows-future", - "windows-numerics", -] - -[[package]] -name = "windows-collections" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" -dependencies = [ - "windows-core", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-future" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" -dependencies = [ - "windows-core", - "windows-link", - "windows-threading", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-numerics" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" -dependencies = [ - "windows-core", - "windows-link", -] - -[[package]] -name = "windows-registry" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" -dependencies = [ - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", -] - -[[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.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", -] - -[[package]] -name = "windows-threading" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-version" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - -[[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_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" - -[[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_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - -[[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_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - -[[package]] -name = "windows_i686_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" - -[[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_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" - -[[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_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - -[[package]] -name = "winnow" -version = "0.5.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" -dependencies = [ - "memchr", -] - -[[package]] -name = "winnow" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" -dependencies = [ - "memchr", -] - -[[package]] -name = "winreg" -version = "0.56.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" -dependencies = [ - "cfg-if", - "windows-sys 0.61.2", -] - -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - -[[package]] -name = "writeable" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" - -[[package]] -name = "wry" -version = "0.57.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0" -dependencies = [ - "base64 0.22.1", - "block2", - "cookie", - "crossbeam-channel", - "dirs", - "dom_query", - "dpi", - "dunce", - "gdkx11", - "gtk", - "http", - "javascriptcore-rs", - "jni 0.21.1", - "libc", - "ndk", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", - "objc2-ui-kit", - "objc2-web-kit", - "once_cell", - "percent-encoding", - "raw-window-handle", - "sha2 0.10.9", - "soup3", - "tao-macros", - "thiserror 2.0.21", - "url", - "webkit2gtk", - "webkit2gtk-sys", - "webview2-com", - "windows", - "windows-core", - "windows-version", - "x11-dl", -] - -[[package]] -name = "x11" -version = "2.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" -dependencies = [ - "libc", - "pkg-config", -] - -[[package]] -name = "x11-dl" -version = "2.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" -dependencies = [ - "libc", - "once_cell", - "pkg-config", -] - -[[package]] -name = "x509-cert" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" -dependencies = [ - "const-oid 0.9.6", - "der 0.7.10", - "spki 0.7.3", - "tls_codec", -] - -[[package]] -name = "xattr" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" -dependencies = [ - "libc", - "rustix", -] - -[[package]] -name = "xxhash-rust" -version = "0.8.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7" - -[[package]] -name = "yoke" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" -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.9", - "synstructure", -] - -[[package]] -name = "zbus" -version = "5.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" -dependencies = [ - "async-broadcast", - "async-executor", - "async-io", - "async-lock", - "async-process", - "async-recursion", - "async-task", - "async-trait", - "blocking", - "enumflags2", - "event-listener", - "futures-core", - "futures-lite", - "hex", - "libc", - "ordered-stream", - "rustix", - "serde", - "serde_repr", - "tracing", - "uds_windows", - "uuid", - "windows-sys 0.61.2", - "winnow 1.0.4", - "zbus_macros", - "zbus_names", - "zvariant", -] - -[[package]] -name = "zbus_macros" -version = "5.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" -dependencies = [ - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 3.0.9", - "zbus_names", - "zvariant", - "zvariant_utils", -] - -[[package]] -name = "zbus_names" -version = "4.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" -dependencies = [ - "serde", - "winnow 1.0.4", - "zvariant", -] - -[[package]] -name = "zcheapstr" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" -dependencies = [ - "serde", -] - -[[package]] -name = "zerocopy" -version = "0.8.63" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.63" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[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.9", - "synstructure", -] - -[[package]] -name = "zeroize" -version = "1.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[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.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "zip" -version = "9.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302" -dependencies = [ - "constant_time_eq", - "crc32fast", - "getrandom 0.4.3", - "indexmap 2.14.2", - "libc", - "memchr", - "nix", - "typed-path", - "windows-sys 0.61.2", - "zeroize", -] - -[[package]] -name = "zlib-rs" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" - -[[package]] -name = "zvariant" -version = "5.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" -dependencies = [ - "endi", - "enumflags2", - "serde", - "winnow 1.0.4", - "zcheapstr", - "zvariant_derive", - "zvariant_utils", -] - -[[package]] -name = "zvariant_derive" -version = "5.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" -dependencies = [ - "proc-macro-crate 3.5.0", - "proc-macro2", - "quote", - "syn 3.0.9", - "zvariant_utils", -] - -[[package]] -name = "zvariant_utils" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "syn 3.0.9", - "winnow 1.0.4", -] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml deleted file mode 100644 index 9132677..0000000 --- a/src-tauri/Cargo.toml +++ /dev/null @@ -1,75 +0,0 @@ -[package] -name = "lowquery" -version = "0.5.7" -description = "Lightweight SQL client for multiple databases" -authors = ["LowBloat"] -license = "AGPL-3.0-only" -repository = "https://github.com/LowBloat/LowQuery" -edition = "2021" -rust-version = "1.89" - -[lib] -# The `_lib` suffix avoids a name clash between the binary and the library on Windows. -name = "lowquery_lib" -crate-type = ["staticlib", "cdylib", "rlib"] - -[build-dependencies] -tauri-build = { version = "2", features = [] } - -[dependencies] -tauri = { version = "2", features = [] } -tauri-plugin-dialog = "2" -tauri-plugin-updater = "2" -tauri-plugin-process = "2" -tauri-plugin-opener = "2" -serde = { version = "1", features = ["derive"] } -serde_json = { version = "1", features = ["preserve_order", "raw_value"] } -tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util", "io-std"] } -thiserror = "2" -uuid = { version = "1", features = ["v4", "serde"] } -directories = "6" -parking_lot = "0.12" -chrono = { version = "0.4", default-features = false, features = ["std", "clock"] } -# PostgreSQL: native async protocol, TLS via rustls. -tokio-postgres = { version = "0.7", features = ["with-chrono-0_4", "with-serde_json-1", "with-uuid-1"] } -tokio-postgres-rustls = "0.13" -rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs", "std", "tls12"] } -webpki-roots = "1" -rustls-native-certs = "0.8" -futures-util = { version = "0.3", default-features = false, features = ["std"] } -# Oracle: official pure-Rust driver (thin mode), no Oracle Client needed. -oracledb = "=26.0.0-beta.4" -# Passwords in the OS credential store. -# MySQL and MariaDB: native protocol, TLS through rustls. -mysql_async = { version = "0.37", default-features = false, features = ["default-rustls"] } -# SQL Server: TDS protocol, TLS through rustls, named instances via SQL Browser. -tiberius = { version = "0.13", default-features = false, features = ["tds80", "rustls", "sql-browser-tokio", "winauth"] } -tokio-util = { version = "0.7", features = ["compat"] } -# Redis: RESP protocol over tokio, TLS through rustls. -redis = { version = "1.7", default-features = false, features = ["aio", "tokio-comp", "tokio-rustls-comp", "tls-rustls-insecure", "tls-rustls-webpki-roots"] } -# Apache Cassandra: native CQL protocol (v4/v5), TLS through rustls. -scylla = { version = "1.9", default-features = false, features = ["rustls-023"] } -# SQLite: embedded engine compiled into the app. -rusqlite = { version = "0.41", features = ["bundled", "column_decltype", "column_metadata"] } -keyring = { version = "=3.6.3", features = ["apple-native", "windows-native", "sync-secret-service"] } -# DBeaver import: credentials-config.json is AES-128-CBC. -aes = "0.9" -cbc = "0.2" -# DataGrip and SQL Developer import: XML connection files. -quick-xml = "0.42" - -# Oracle homes registered by Windows installers. -[target.'cfg(windows)'.dependencies] -winreg = "0.56" - -[profile.release] -codegen-units = 1 -lto = true -opt-level = 3 -panic = "abort" -strip = true - -# oracledb 26.0.0-beta.4 with two parser fixes for duplicate-column bit vectors -# (see vendor/oracledb/LOWQUERY.md). Remove once a release includes them. -[patch.crates-io] -oracledb = { path = "vendor/oracledb" } diff --git a/src-tauri/build.rs b/src-tauri/build.rs deleted file mode 100644 index d860e1e..0000000 --- a/src-tauri/build.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - tauri_build::build() -} diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json deleted file mode 100644 index 242d38f..0000000 --- a/src-tauri/capabilities/default.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "default", - "description": "Main window permissions", - "windows": [ - "main" - ], - "permissions": [ - "core:default", - "core:window:allow-minimize", - "core:window:allow-toggle-maximize", - "core:window:allow-close", - "core:window:allow-start-dragging", - "dialog:allow-save", - "dialog:allow-open", - "updater:default", - "process:allow-restart", - "process:allow-exit", - "opener:default" - ] -} diff --git a/src-tauri/deny.toml b/src-tauri/deny.toml deleted file mode 100644 index 36cc6f2..0000000 --- a/src-tauri/deny.toml +++ /dev/null @@ -1,30 +0,0 @@ -# cargo-deny configuration: `cargo deny --manifest-path src-tauri/Cargo.toml check advisories bans sources` -# Run weekly and on dependency changes by .github/workflows/security.yml. - -[graph] -all-features = false - -[advisories] -# Known vulnerabilities always fail. Unmaintained notices are reported only for -# crates we depend on directly; transitive ones (gtk/zbus stacks pulled in by -# Tauri) are tracked through upstream updates. -unmaintained = "workspace" -yanked = "warn" -ignore = [ - # zip < 9 extraction (SUID bits, symlinks out of the target, permissions - # through symlinks). Only tauri-plugin-updater 2.14 (the latest) uses zip, - # pinned to 4.x, and it unzips Windows update packages only after checking - # their minisign signature against LowQuery's update key, so a crafted - # archive needs that key. Drop these when the plugin moves to zip >= 9. - { id = "RUSTSEC-2026-0367", reason = "zip via tauri-plugin-updater; packages are signature-checked before extraction" }, - { id = "RUSTSEC-2026-0368", reason = "zip via tauri-plugin-updater; packages are signature-checked before extraction" }, - { id = "RUSTSEC-2026-0369", reason = "zip via tauri-plugin-updater; packages are signature-checked before extraction" }, -] - -[bans] -multiple-versions = "warn" -wildcards = "deny" - -[sources] -unknown-registry = "deny" -unknown-git = "deny" diff --git a/src-tauri/icons/64x64.png b/src-tauri/icons/64x64.png deleted file mode 100644 index f129491..0000000 Binary files a/src-tauri/icons/64x64.png and /dev/null differ diff --git a/src-tauri/icons/Square107x107Logo.png b/src-tauri/icons/Square107x107Logo.png deleted file mode 100644 index 3a21d84..0000000 Binary files a/src-tauri/icons/Square107x107Logo.png and /dev/null differ diff --git a/src-tauri/icons/Square142x142Logo.png b/src-tauri/icons/Square142x142Logo.png deleted file mode 100644 index 2e1aba9..0000000 Binary files a/src-tauri/icons/Square142x142Logo.png and /dev/null differ diff --git a/src-tauri/icons/Square150x150Logo.png b/src-tauri/icons/Square150x150Logo.png deleted file mode 100644 index 258c9f2..0000000 Binary files a/src-tauri/icons/Square150x150Logo.png and /dev/null differ diff --git a/src-tauri/icons/Square284x284Logo.png b/src-tauri/icons/Square284x284Logo.png deleted file mode 100644 index 43ebc7c..0000000 Binary files a/src-tauri/icons/Square284x284Logo.png and /dev/null differ diff --git a/src-tauri/icons/Square30x30Logo.png b/src-tauri/icons/Square30x30Logo.png deleted file mode 100644 index 71f5d4e..0000000 Binary files a/src-tauri/icons/Square30x30Logo.png and /dev/null differ diff --git a/src-tauri/icons/Square310x310Logo.png b/src-tauri/icons/Square310x310Logo.png deleted file mode 100644 index 89769ae..0000000 Binary files a/src-tauri/icons/Square310x310Logo.png and /dev/null differ diff --git a/src-tauri/icons/Square44x44Logo.png b/src-tauri/icons/Square44x44Logo.png deleted file mode 100644 index 417404e..0000000 Binary files a/src-tauri/icons/Square44x44Logo.png and /dev/null differ diff --git a/src-tauri/icons/Square71x71Logo.png b/src-tauri/icons/Square71x71Logo.png deleted file mode 100644 index f198174..0000000 Binary files a/src-tauri/icons/Square71x71Logo.png and /dev/null differ diff --git a/src-tauri/icons/Square89x89Logo.png b/src-tauri/icons/Square89x89Logo.png deleted file mode 100644 index 2432bc0..0000000 Binary files a/src-tauri/icons/Square89x89Logo.png and /dev/null differ diff --git a/src-tauri/icons/StoreLogo.png b/src-tauri/icons/StoreLogo.png deleted file mode 100644 index a9554c0..0000000 Binary files a/src-tauri/icons/StoreLogo.png and /dev/null differ diff --git a/src-tauri/icons/icon.png b/src-tauri/icons/icon.png deleted file mode 100644 index b743a82..0000000 Binary files a/src-tauri/icons/icon.png and /dev/null differ diff --git a/src-tauri/icons/icon.svg b/src-tauri/icons/icon.svg deleted file mode 100644 index 7086dbe..0000000 --- a/src-tauri/icons/icon.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src-tauri/src/ai_setup.rs b/src-tauri/src/ai_setup.rs deleted file mode 100644 index 65dae6d..0000000 --- a/src-tauri/src/ai_setup.rs +++ /dev/null @@ -1,357 +0,0 @@ -//! Setting up AI clients to start `lowquery mcp`: the command to run, the -//! configuration each client expects, and adding LowQuery to the JSON -//! configuration files of the clients that have one. - -use std::path::{Path, PathBuf}; - -use serde::Serialize; -use serde_json::{json, Map, Value}; - -use crate::error::{AppError, AppResult}; - -/// Name of the server entry in client configurations. -const SERVER_NAME: &str = "lowquery"; - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct AiSetup { - /// Executable that runs the MCP server (` mcp`). - pub command: String, - pub args: Vec, - pub clients: Vec, -} - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct AiClient { - pub id: &'static str, - pub name: &'static str, - /// Configuration file LowQuery can update, when the client has one. - pub config_path: Option, - /// The client seems installed (its configuration folder exists). - pub installed: bool, - /// The configuration already starts this LowQuery. - pub configured: bool, - /// What to paste or run, for clients configured by hand. - pub snippet: String, - /// "json", "toml" or "shell", for highlighting. - pub snippet_kind: &'static str, -} - -/// How a client's JSON file lists servers. -#[derive(Clone, Copy)] -enum JsonStyle { - /// `{ "mcpServers": { name: { command, args } } }` (Claude Desktop, - /// Cursor, Windsurf, Gemini CLI). - McpServers, - /// `{ "servers": { name: { type: "stdio", command, args } } }` (VS Code). - VsCode, -} - -struct JsonClient { - id: &'static str, - name: &'static str, - style: JsonStyle, - /// Candidate files in order; the first whose folder exists is used. - paths: Vec, -} - -/// The executable to start. An AppImage runs from a temporary mount, so -/// its own path (`$APPIMAGE`) is the stable one. -pub fn server_command() -> AppResult { - if let Ok(appimage) = std::env::var("APPIMAGE") { - if !appimage.is_empty() { - return Ok(appimage); - } - } - let exe = std::env::current_exe()?; - Ok(exe.display().to_string()) -} - -fn home() -> PathBuf { - directories::BaseDirs::new() - .map(|d| d.home_dir().to_path_buf()) - .unwrap_or_default() -} - -fn config_root() -> PathBuf { - directories::BaseDirs::new() - .map(|d| d.config_dir().to_path_buf()) - .unwrap_or_default() -} - -fn json_clients() -> Vec { - let home = home(); - let config = config_root(); - let mut claude = Vec::new(); - // The Microsoft Store build keeps its files in a virtualized folder. - if cfg!(windows) { - if let Some(local) = directories::BaseDirs::new().map(|d| d.data_local_dir().to_path_buf()) - { - if let Ok(entries) = std::fs::read_dir(local.join("Packages")) { - for e in entries.flatten() { - if e.file_name().to_string_lossy().starts_with("Claude_") { - claude.push( - e.path() - .join("LocalCache/Roaming/Claude/claude_desktop_config.json"), - ); - } - } - } - } - } - claude.push(config.join("Claude").join("claude_desktop_config.json")); - vec![ - JsonClient { - id: "claude-desktop", - name: "Claude Desktop", - style: JsonStyle::McpServers, - paths: claude, - }, - JsonClient { - id: "cursor", - name: "Cursor", - style: JsonStyle::McpServers, - paths: vec![home.join(".cursor").join("mcp.json")], - }, - JsonClient { - id: "vscode", - name: "VS Code", - style: JsonStyle::VsCode, - paths: vec![config.join("Code").join("User").join("mcp.json")], - }, - JsonClient { - id: "windsurf", - name: "Windsurf", - style: JsonStyle::McpServers, - paths: vec![home - .join(".codeium") - .join("windsurf") - .join("mcp_config.json")], - }, - JsonClient { - id: "gemini", - name: "Gemini CLI", - style: JsonStyle::McpServers, - paths: vec![home.join(".gemini").join("settings.json")], - }, - ] -} - -fn pick_path(paths: &[PathBuf]) -> Option<&PathBuf> { - paths - .iter() - .find(|p| p.parent().is_some_and(Path::exists)) - .or(paths.last()) -} - -fn entry(style: JsonStyle, command: &str) -> Value { - match style { - JsonStyle::McpServers => json!({ "command": command, "args": ["mcp"] }), - JsonStyle::VsCode => json!({ "type": "stdio", "command": command, "args": ["mcp"] }), - } -} - -fn servers_key(style: JsonStyle) -> &'static str { - match style { - JsonStyle::McpServers => "mcpServers", - JsonStyle::VsCode => "servers", - } -} - -fn snippet(style: JsonStyle, command: &str) -> String { - let doc = json!({ servers_key(style): { SERVER_NAME: entry(style, command) } }); - serde_json::to_string_pretty(&doc).unwrap_or_default() -} - -/// Whether the file's server entry already starts `command`. -fn is_configured(path: &Path, style: JsonStyle, command: &str) -> bool { - let Ok(text) = std::fs::read_to_string(path) else { - return false; - }; - let Ok(doc) = serde_json::from_str::(&text) else { - return false; - }; - doc.get(servers_key(style)) - .and_then(|s| s.get(SERVER_NAME)) - .and_then(|e| e.get("command")) - .and_then(Value::as_str) - .is_some_and(|c| c == command) -} - -fn quote_shell(s: &str) -> String { - if s.chars() - .all(|c| c.is_ascii_alphanumeric() || "/\\:._-".contains(c)) - { - s.to_string() - } else { - format!("\"{}\"", s.replace('"', "\\\"")) - } -} - -fn toml_string(s: &str) -> String { - format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) -} - -pub fn setup() -> AppResult { - let command = server_command()?; - let mut clients: Vec = json_clients() - .into_iter() - .map(|c| { - let path = pick_path(&c.paths).cloned(); - let installed = path - .as_ref() - .and_then(|p| p.parent()) - .is_some_and(Path::exists); - AiClient { - id: c.id, - name: c.name, - configured: path - .as_ref() - .is_some_and(|p| is_configured(p, c.style, &command)), - config_path: path.map(|p| p.display().to_string()), - installed, - snippet: snippet(c.style, &command), - snippet_kind: "json", - } - }) - .collect(); - let shell_cmd = quote_shell(&command); - clients.insert( - 1, - AiClient { - id: "claude-code", - name: "Claude Code", - config_path: None, - installed: home().join(".claude").exists(), - configured: false, - snippet: format!("claude mcp add --scope user {SERVER_NAME} -- {shell_cmd} mcp"), - snippet_kind: "shell", - }, - ); - clients.push(AiClient { - id: "codex", - name: "Codex", - config_path: None, - installed: home().join(".codex").exists(), - configured: false, - snippet: format!( - "[mcp_servers.{SERVER_NAME}]\ncommand = {}\nargs = [\"mcp\"]", - toml_string(&command) - ), - snippet_kind: "toml", - }); - Ok(AiSetup { - command, - args: vec!["mcp".into()], - clients, - }) -} - -/// Adds (or updates) the LowQuery entry in a client's JSON configuration, -/// keeping everything else. The previous file is kept as -/// `.lowquery-backup`. -pub fn connect_client(id: &str) -> AppResult { - let command = server_command()?; - let client = json_clients() - .into_iter() - .find(|c| c.id == id) - .ok_or_else(|| AppError::invalid("This client is configured by hand."))?; - let path = pick_path(&client.paths) - .cloned() - .ok_or_else(|| AppError::invalid("Could not find the client configuration folder."))?; - write_entry(&path, client.style, &command)?; - Ok(path.display().to_string()) -} - -fn write_entry(path: &Path, style: JsonStyle, command: &str) -> AppResult<()> { - let mut doc = match std::fs::read_to_string(path) { - Ok(text) if text.trim().is_empty() => Value::Object(Map::new()), - Ok(text) => { - let text = text.trim_start_matches('\u{feff}'); - serde_json::from_str::(text).map_err(|_| { - AppError::invalid( - "The configuration file is not plain JSON (it may have comments). Add the snippet by hand.", - ) - })? - } - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Value::Object(Map::new()), - Err(e) => return Err(e.into()), - }; - let root = doc - .as_object_mut() - .ok_or_else(|| AppError::invalid("The configuration file does not hold a JSON object."))?; - let servers = root - .entry(servers_key(style)) - .or_insert_with(|| Value::Object(Map::new())); - let servers = servers.as_object_mut().ok_or_else(|| { - AppError::invalid("The servers section of the configuration is not an object.") - })?; - servers.insert(SERVER_NAME.into(), entry(style, command)); - if path.exists() { - let mut backup = path.as_os_str().to_owned(); - backup.push(".lowquery-backup"); - std::fs::copy(path, PathBuf::from(backup))?; - } else if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - let tmp = path.with_extension("lowquery-tmp"); - std::fs::write(&tmp, serde_json::to_string_pretty(&doc)? + "\n")?; - std::fs::rename(&tmp, path)?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn adds_entry_and_keeps_the_rest() { - let dir = std::env::temp_dir().join(format!("lq-ai-{}", uuid::Uuid::new_v4())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("claude_desktop_config.json"); - std::fs::write( - &path, - r#"{"theme":"dark","mcpServers":{"other":{"command":"x"}},"zeta":1}"#, - ) - .unwrap(); - write_entry( - &path, - JsonStyle::McpServers, - r"C:\Apps\LowQuery\lowquery.exe", - ) - .unwrap(); - let doc: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); - let keys: Vec<&String> = doc.as_object().unwrap().keys().collect(); - assert_eq!(keys, ["theme", "mcpServers", "zeta"]); - assert_eq!(doc["mcpServers"]["other"]["command"], "x"); - assert_eq!(doc["mcpServers"]["lowquery"]["args"][0], "mcp"); - assert!(is_configured( - &path, - JsonStyle::McpServers, - r"C:\Apps\LowQuery\lowquery.exe" - )); - assert!(dir - .join("claude_desktop_config.json.lowquery-backup") - .exists()); - - let vs = dir.join("mcp.json"); - write_entry(&vs, JsonStyle::VsCode, "/usr/bin/lowquery").unwrap(); - let doc: Value = serde_json::from_str(&std::fs::read_to_string(&vs).unwrap()).unwrap(); - assert_eq!(doc["servers"]["lowquery"]["type"], "stdio"); - - std::fs::write(&vs, "{ // comment\n}").unwrap(); - assert!(write_entry(&vs, JsonStyle::VsCode, "x").is_err()); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn snippets_quote_paths() { - assert_eq!(quote_shell("/usr/bin/lowquery"), "/usr/bin/lowquery"); - assert_eq!( - quote_shell(r"C:\Program Files\LowQuery\lowquery.exe"), - r#""C:\Program Files\LowQuery\lowquery.exe""# - ); - assert_eq!(toml_string(r"C:\a"), r#""C:\\a""#); - } -} diff --git a/src-tauri/src/drivers/cassandra.rs b/src-tauri/src/drivers/cassandra.rs deleted file mode 100644 index 53d1979..0000000 --- a/src-tauri/src/drivers/cassandra.rs +++ /dev/null @@ -1,2619 +0,0 @@ -//! Apache Cassandra session over the native CQL protocol, through the -//! `scylla` driver (it speaks to Apache Cassandra 3.x, 4.x and 5.x as well). -//! -//! - Every statement is sent unprepared as text, like cqlsh does. Rows are -//! read with paging: the page size comes from the row limit and reading -//! stops at `max_rows + 1`, so a `SELECT` on a big table never streams -//! everything to show a few rows. -//! - Values keep their exact CQL text (`varint` and `decimal` keep every -//! digit, floats are shortest round-trip, blobs are `0x...`). Collections, -//! tuples, UDTs and vectors are written as valid CQL literals, so a cell can -//! be pasted into an `INSERT` or `UPDATE` as it is. -//! - There are no transactions: the session is always in autocommit mode and -//! `BEGIN BATCH ... APPLY BATCH` is just one statement. Saving edits from -//! the grid sends one logged batch. -//! - CQL has no server-side cancel. `cancel` drops the request future, so the -//! interface gets its answer at once, but the coordinator keeps working -//! until its own request timeout. -//! - Server warnings (tombstone thresholds, large batches, aggregations -//! without a partition key) arrive as messages, like PostgreSQL notices. -//! - Requests run at consistency `LOCAL_ONE`, the cqlsh default. TLS uses -//! rustls; with the local datacenter set, only its nodes get requests. -//! - The schema comes from `system_schema` (and `system_virtual_schema` for -//! the virtual keyspaces of 4.0+), which every 3.0+ server has. -//! `DESCRIBE` is a cqlsh command, not part of the protocol, so the CREATE -//! statements are built from the catalog. - -use std::collections::HashMap; -use std::fmt::Write as _; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use futures_util::StreamExt; -use parking_lot::Mutex; -use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; -use rustls::client::WebPkiServerVerifier; -use rustls::pki_types::{CertificateDer, ServerName, UnixTime}; -use rustls::{CertificateError, DigitallySignedStruct, SignatureScheme}; -use scylla::client::execution_profile::ExecutionProfile; -use scylla::client::session::Session as Cql; -use scylla::client::session_builder::SessionBuilder; -use scylla::errors::{ - DbError, ExecutionError, IntoRowsResultError, NewSessionError, NextPageError, NextRowError, - PagerExecutionError, RequestAttemptError, RequestError, -}; -use scylla::frame::response::result::{CollectionType, ColumnType, NativeType}; -use scylla::policies::load_balancing::DefaultPolicy; -use scylla::response::PagingState; -use scylla::statement::{Consistency, Statement}; -use scylla::value::{CqlValue, Row}; -use tokio::sync::Notify; - -use super::{first_keywords, RowSink, StreamEvent, TxState, STREAM_BATCH}; -use crate::error::{AppError, AppResult, ErrorKind}; -use crate::model::{ - ApplyRequest, ApplyResult, ColumnInfo, ConnectionProfile, DbColumn, DbObject, EditColumn, - EditTarget, ExecRequest, ExecResult, RowChange, SslMode, ValueKind, -}; - -const DEFAULT_PORT: u16 = 9042; -const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); -/// TLS attempt of `prefer`: a server without TLS gives up early and the -/// session falls back to plain TCP. -const PREFER_TLS_TIMEOUT: Duration = Duration::from_secs(8); -/// Largest page asked for in one request. -const PAGE_CAP: usize = 5000; -/// Page size of the catalog queries. -const CATALOG_PAGE: i32 = 1000; -const BINARY_PREVIEW_BYTES: usize = 32 * 1024; - -/// Keyspaces that belong to the server, listed after the user's. -const SYSTEM_KEYSPACES: &[&str] = &[ - "system", - "system_schema", - "system_auth", - "system_distributed", - "system_traces", - "system_views", - "system_virtual_schema", -]; -const VIRTUAL_KEYSPACES: &[&str] = &["system_views", "system_virtual_schema"]; - -pub struct CassSession { - cql: Cql, - busy: AtomicBool, - cancel: Arc, - /// Key information per table, for result editing. Cleared by any - /// statement that is not a SELECT. - tables: Mutex>>, - pub server_version: String, - pub current_user: Option, - pub current_schema: Option, -} - -pub async fn connect( - profile: &ConnectionProfile, - password: Option<&str>, -) -> AppResult { - // rustls has more than one crypto provider compiled in. - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - - let port = if profile.port == 0 { - DEFAULT_PORT - } else { - profile.port - }; - let contact_points: Vec = profile - .host - .split(',') - .map(str::trim) - .filter(|h| !h.is_empty()) - .map(|h| contact_point(h, port)) - .collect(); - if contact_points.is_empty() { - return Err(AppError::invalid("Enter at least one contact point.")); - } - - let build = |tls: Option>| { - let mut builder = SessionBuilder::new() - .known_nodes(&contact_points) - .connection_timeout(CONNECT_TIMEOUT) - .fetch_schema_metadata(false) - .default_execution_profile_handle(execution_profile(&profile.datacenter)); - let keyspace = profile.database.trim(); - if !keyspace.is_empty() { - builder = builder.use_keyspace(keyspace, true); - } - let user = profile.user.trim(); - if !user.is_empty() { - builder = builder.user(user, password.unwrap_or_default()); - } - if let Some(config) = tls { - builder = builder.tls_context(Some(config)); - } - async move { builder.build().await } - }; - - let cql = match profile.ssl_mode { - SslMode::Disable => build(None).await, - SslMode::Prefer => { - let attempt = tokio::time::timeout( - PREFER_TLS_TIMEOUT, - build(Some(tls_config(SslMode::Prefer)?)), - ) - .await; - match attempt { - Ok(Ok(cql)) => Ok(cql), - Ok(Err(e)) if is_auth_text(&chain(&e)) => Err(e), - _ => build(None).await, - } - } - SslMode::Require => build(Some(tls_config(SslMode::Require)?)).await, - SslMode::VerifyFull => build(Some(tls_config(SslMode::VerifyFull)?)).await, - } - .map_err(connect_error)?; - - let version = fetch(&cql, "SELECT release_version FROM system.local") - .await - .ok() - .and_then(|f| f.rows.into_iter().next()) - .and_then(|mut r| r.pop().flatten()) - .and_then(|v| text_of(&Some(v))); - let user = profile.user.trim(); - Ok(CassSession { - current_schema: cql.get_keyspace().map(|k| (*k).clone()), - cql, - busy: AtomicBool::new(false), - cancel: Arc::new(Notify::new()), - tables: Mutex::new(HashMap::new()), - server_version: match version { - Some(v) => format!("Apache Cassandra {v}"), - None => "Apache Cassandra".into(), - }, - current_user: (!user.is_empty()).then(|| user.to_string()), - }) -} - -/// `host` or `host:port` as the driver wants it; a bare IPv6 address is -/// bracketed. -fn contact_point(host: &str, default_port: u16) -> String { - if host.starts_with('[') { - return if host.contains("]:") { - host.to_string() - } else { - format!("{host}:{default_port}") - }; - } - match host.matches(':').count() { - 0 => format!("{host}:{default_port}"), - 1 => host.to_string(), - _ => format!("[{host}]:{default_port}"), - } -} - -/// Requests go to the local datacenter only, when one is named. -fn execution_profile( - datacenter: &str, -) -> scylla::client::execution_profile::ExecutionProfileHandle { - let mut policy = DefaultPolicy::builder(); - let dc = datacenter.trim(); - if !dc.is_empty() { - policy = policy - .prefer_datacenter(dc.to_string()) - .permit_dc_failover(false); - } - ExecutionProfile::builder() - .load_balancing_policy(policy.build()) - .consistency(Consistency::LocalOne) - // The server's own timeouts apply; Cancel stops waiting. - .request_timeout(None) - .build() - .into_handle() -} - -// --------------------------------------------------------------------------- -// TLS - -fn tls_config(mode: SslMode) -> AppResult> { - if mode != SslMode::VerifyFull { - // `prefer` and `require` encrypt without validating the certificate, - // as everywhere else in the app. - return super::postgres::tls_config(mode).map(Arc::new); - } - let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); - let mut roots = rustls::RootCertStore::empty(); - roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); - for cert in rustls_native_certs::load_native_certs().certs { - let _ = roots.add(cert); - } - let inner = WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider.clone()) - .build() - .map_err(|e| AppError::internal(e.to_string()))?; - let config = rustls::ClientConfig::builder_with_provider(provider) - .with_safe_default_protocol_versions() - .map_err(|e| AppError::internal(e.to_string()))? - .dangerous() - .with_custom_certificate_verifier(Arc::new(ChainVerifier(inner))) - .with_no_client_auth(); - Ok(Arc::new(config)) -} - -/// Validates the chain, expiry and signatures against the trusted roots but -/// not the host name: the driver connects to the addresses the cluster -/// reports (`system.peers`), which certificates rarely list. -#[derive(Debug)] -struct ChainVerifier(Arc); - -impl ServerCertVerifier for ChainVerifier { - fn verify_server_cert( - &self, - end_entity: &CertificateDer<'_>, - intermediates: &[CertificateDer<'_>], - server_name: &ServerName<'_>, - ocsp_response: &[u8], - now: UnixTime, - ) -> Result { - match self - .0 - .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now) - { - Err(rustls::Error::InvalidCertificate( - CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. }, - )) => Ok(ServerCertVerified::assertion()), - other => other, - } - } - - fn verify_tls12_signature( - &self, - message: &[u8], - cert: &CertificateDer<'_>, - dss: &DigitallySignedStruct, - ) -> Result { - self.0.verify_tls12_signature(message, cert, dss) - } - - fn verify_tls13_signature( - &self, - message: &[u8], - cert: &CertificateDer<'_>, - dss: &DigitallySignedStruct, - ) -> Result { - self.0.verify_tls13_signature(message, cert, dss) - } - - fn supported_verify_schemes(&self) -> Vec { - self.0.supported_verify_schemes() - } -} - -// --------------------------------------------------------------------------- -// Queries - -/// Rows of a catalog query, values as the driver decoded them. -struct Fetched { - names: Vec, - rows: Vec>>, -} - -impl Fetched { - fn index(&self, name: &str) -> Option { - self.names.iter().position(|n| n == name) - } - - fn get<'a>(&self, row: &'a [Option], name: &str) -> Option<&'a CqlValue> { - self.index(name) - .and_then(|i| row.get(i)) - .and_then(Option::as_ref) - } - - fn text(&self, row: &[Option], name: &str) -> Option { - self.index(name).and_then(|i| row.get(i)).and_then(text_of) - } -} - -fn text_of(v: &Option) -> Option { - match v { - Some(CqlValue::Text(s) | CqlValue::Ascii(s)) => Some(s.clone()), - _ => None, - } -} - -fn text_list(v: Option<&CqlValue>) -> Vec { - match v { - Some(CqlValue::List(items) | CqlValue::Set(items)) => items - .iter() - .filter_map(|i| text_of(&Some(i.clone()))) - .collect(), - _ => Vec::new(), - } -} - -/// Runs a catalog statement and reads every page. -async fn fetch(cql: &Cql, sql: &str) -> AppResult { - let mut names; - let mut rows = Vec::new(); - let mut state = PagingState::start(); - loop { - let statement = Statement::new(sql).with_page_size(CATALOG_PAGE); - let (result, flow) = cql - .query_single_page(statement, &[], state) - .await - .map_err(|e| map_execution(e, Some(sql)))?; - let page = result.into_rows_result().map_err(|e| match e { - IntoRowsResultError::ResultNotRows(_) => { - AppError::internal("The catalog statement returned no rows.") - } - other => AppError::internal(other.to_string()), - })?; - names = page - .column_specs() - .iter() - .map(|c| c.name().to_string()) - .collect(); - for row in page - .rows::() - .map_err(|e| AppError::internal(e.to_string()))? - { - rows.push(row.map_err(|e| AppError::internal(e.to_string()))?.columns); - } - match flow.into_paging_control_flow() { - std::ops::ControlFlow::Break(()) => break, - std::ops::ControlFlow::Continue(next) => state = next, - } - } - Ok(Fetched { names, rows }) -} - -/// Names a catalog query matches on, as a CQL string literal. -fn lit(s: &str) -> String { - format!("'{}'", s.replace('\'', "''")) -} - -fn is_virtual(keyspace: &str) -> bool { - VIRTUAL_KEYSPACES.contains(&keyspace) -} - -fn is_system(keyspace: &str) -> bool { - SYSTEM_KEYSPACES.contains(&keyspace) || keyspace.starts_with("system_") -} - -/// One result column: what the editor needs to know about its origin. -struct ResultColumn { - name: String, - keyspace: String, - table: String, -} - -struct TableMeta { - columns: Vec, - view: bool, -} - -impl CassSession { - /// Cassandra 3.x, whose table options differ from 4.0 and later. - fn legacy(&self) -> bool { - self.server_version.starts_with("Apache Cassandra 3.") - } - - pub fn tx_state(&self) -> TxState { - TxState { - autocommit: true, - in_transaction: false, - } - } - - pub async fn execute(&self, req: &ExecRequest) -> AppResult { - self.busy.store(true, Ordering::SeqCst); - let cancelled = self.cancel.notified(); - tokio::pin!(cancelled); - cancelled.as_mut().enable(); - let outcome = tokio::select! { - r = self.run(req) => r, - () = &mut cancelled => Err(AppError::new(ErrorKind::Cancelled, "Cancelled.")), - }; - self.busy.store(false, Ordering::SeqCst); - outcome - } - - /// CQL cannot ask the server to stop a request: the wait ends here and the - /// coordinator finishes (or times out) on its own. - pub async fn cancel(&self) -> AppResult<()> { - if self.busy.load(Ordering::SeqCst) { - self.cancel.notify_waiters(); - } - Ok(()) - } - - pub async fn set_autocommit(&self, on: bool) -> AppResult { - if on { - Ok(self.tx_state()) - } else { - Err(AppError::invalid( - "Cassandra has no transactions: every statement commits on its own.", - )) - } - } - - pub async fn end_transaction(&self, _commit: bool) -> AppResult { - Err(AppError::invalid( - "Cassandra has no transactions: every statement commits on its own.", - )) - } - - async fn run(&self, req: &ExecRequest) -> AppResult { - let started = Instant::now(); - let sql = req.sql.as_str(); - let limit = req.max_rows; - let mut result = ExecResult::default(); - let mut columns: Option> = None; - let mut origins: Vec = Vec::new(); - let mut rows: Vec>> = Vec::new(); - let mut state = PagingState::start(); - loop { - let size = if limit == 0 { - PAGE_CAP - } else { - (limit + 1 - rows.len().min(limit + 1)).clamp(1, PAGE_CAP) - }; - let statement = Statement::new(sql).with_page_size(size as i32); - let (page, flow) = self - .cql - .query_single_page(statement, &[], state) - .await - .map_err(|e| map_execution(e, Some(sql)))?; - match page.into_rows_result() { - Ok(page) => { - for w in page.warnings() { - result.notices.push(format!("WARNING: {w}")); - } - if columns.is_none() { - columns = Some( - page.column_specs() - .iter() - .map(|c| ColumnInfo { - name: c.name().to_string(), - type_name: type_name(c.typ()), - kind: column_kind(c.typ()), - }) - .collect(), - ); - origins = page - .column_specs() - .iter() - .map(|c| ResultColumn { - name: c.name().to_string(), - keyspace: c.table_spec().ks_name().to_string(), - table: c.table_spec().table_name().to_string(), - }) - .collect(); - } - let iter = page - .rows::() - .map_err(|e| AppError::internal(e.to_string()))?; - for row in iter { - let row = row.map_err(|e| AppError::internal(e.to_string()))?; - rows.push(row.columns.iter().map(cell).collect()); - } - } - Err(IntoRowsResultError::ResultNotRows(page)) => { - for w in page.warnings() { - result.notices.push(format!("WARNING: {w}")); - } - break; - } - Err(e) => return Err(AppError::internal(e.to_string())), - } - if limit > 0 && rows.len() > limit { - break; - } - match flow.into_paging_control_flow() { - std::ops::ControlFlow::Break(()) => break, - std::ops::ControlFlow::Continue(next) => state = next, - } - } - if limit > 0 && rows.len() > limit { - rows.truncate(limit); - result.truncated = true; - } - - let is_select = first_keywords(sql, 1).first().map(String::as_str) == Some("SELECT"); - if !is_select { - self.tables.lock().clear(); - } - if let Some(cols) = columns { - let (editable, reason) = self.editable(sql, is_select, &origins).await; - result.editable = editable; - result.read_only_reason = reason; - result.columns = Some(cols); - result.rows = rows; - } - result.elapsed_ms = started.elapsed().as_millis() as u64; - Ok(result) - } - - pub async fn list_schemas(&self) -> AppResult> { - let mut names: Vec = fetch( - &self.cql, - "SELECT keyspace_name FROM system_schema.keyspaces", - ) - .await? - .rows - .into_iter() - .filter_map(|mut r| r.pop().and_then(|v| text_of(&v))) - .collect(); - // Virtual keyspaces exist from Cassandra 4.0. - if let Ok(f) = fetch( - &self.cql, - "SELECT keyspace_name FROM system_virtual_schema.keyspaces", - ) - .await - { - names.extend( - f.rows - .into_iter() - .filter_map(|mut r| r.pop().and_then(|v| text_of(&v))), - ); - } - names.sort(); - names.dedup(); - names.sort_by_key(|n| is_system(n)); - Ok(names) - } - - pub async fn list_objects(&self, schema: &str) -> AppResult> { - let ks = lit(schema); - let mut out = Vec::new(); - let mut add = |kind: &str, names: Vec| { - let mut names = names; - names.sort(); - out.extend(names.into_iter().map(|name| DbObject { - name, - kind: kind.into(), - })); - }; - let names_of = |f: Fetched, column: &str| -> Vec { - f.rows.iter().filter_map(|r| f.text(r, column)).collect() - }; - if is_virtual(schema) { - let f = fetch( - &self.cql, - &format!( - "SELECT table_name FROM system_virtual_schema.tables WHERE keyspace_name = {ks}" - ), - ) - .await?; - add("table", names_of(f, "table_name")); - return Ok(out); - } - let f = fetch( - &self.cql, - &format!("SELECT table_name FROM system_schema.tables WHERE keyspace_name = {ks}"), - ) - .await?; - add("table", names_of(f, "table_name")); - let f = fetch( - &self.cql, - &format!("SELECT view_name FROM system_schema.views WHERE keyspace_name = {ks}"), - ) - .await?; - add("matview", names_of(f, "view_name")); - let f = fetch( - &self.cql, - &format!("SELECT type_name FROM system_schema.types WHERE keyspace_name = {ks}"), - ) - .await?; - add("type", names_of(f, "type_name")); - for (kind, table, column) in [ - ("function", "functions", "function_name"), - ("aggregate", "aggregates", "aggregate_name"), - ] { - let f = fetch( - &self.cql, - &format!( - "SELECT {column}, argument_types FROM system_schema.{table} WHERE keyspace_name = {ks}" - ), - ) - .await?; - let names = f - .rows - .iter() - .filter_map(|r| { - let name = f.text(r, column)?; - Some(format!( - "{name}({})", - text_list(f.get(r, "argument_types")).join(", ") - )) - }) - .collect(); - add(kind, names); - } - let f = fetch( - &self.cql, - &format!("SELECT index_name FROM system_schema.indexes WHERE keyspace_name = {ks}"), - ) - .await?; - add("index", names_of(f, "index_name")); - Ok(out) - } - - pub async fn list_columns(&self, schema: &str, table: &str) -> AppResult> { - let (ks, t) = (lit(schema), lit(table)); - let f = if is_virtual(schema) { - fetch( - &self.cql, - &format!( - "SELECT column_name, type, kind, position FROM system_virtual_schema.columns \ - WHERE keyspace_name = {ks} AND table_name = {t}" - ), - ) - .await? - } else { - fetch( - &self.cql, - &format!( - "SELECT column_name, type, kind, position FROM system_schema.columns \ - WHERE keyspace_name = {ks} AND table_name = {t}" - ), - ) - .await? - }; - let mut cols: Vec<(u8, i32, DbColumn)> = f - .rows - .iter() - .filter_map(|r| { - let name = f.text(r, "column_name")?; - let kind = f.text(r, "kind").unwrap_or_default().to_ascii_lowercase(); - let position = match f.get(r, "position") { - Some(CqlValue::Int(p)) => *p, - _ => 0, - }; - let (order, role) = match kind.as_str() { - "partition_key" => (0, "partition"), - "clustering" => (1, "clustering"), - "static" => (2, "static"), - _ => (3, "regular"), - }; - let key = order < 2; - Some(( - order, - if key { position } else { 0 }, - DbColumn { - name, - type_name: f.text(r, "type").unwrap_or_default(), - nullable: !key, - primary_key: key, - default_value: None, - key_role: Some(role.into()), - }, - )) - }) - .collect(); - cols.sort_by(|a, b| (a.0, a.1, &a.2.name).cmp(&(b.0, b.1, &b.2.name))); - Ok(cols.into_iter().map(|c| c.2).collect()) - } - - /// Runs a query and sends its rows to `sink` in batches, one page at a time. - pub async fn stream(&self, sql: &str, sink: RowSink) -> AppResult { - let statement = Statement::new(sql).with_page_size(STREAM_BATCH as i32); - let pager = self - .cql - .query_iter(statement, &[]) - .await - .map_err(map_pager)?; - let info: Vec = pager - .column_specs() - .iter() - .map(|c| ColumnInfo { - name: c.name().to_string(), - type_name: type_name(c.typ()), - kind: column_kind(c.typ()), - }) - .collect(); - if info.is_empty() { - return Err(AppError::invalid("The statement returns no rows.")); - } - sink.send(StreamEvent::Columns(info)) - .await - .map_err(|_| super::stream_stopped())?; - let mut rows = pager - .rows_stream::() - .map_err(|e| AppError::internal(e.to_string()))?; - let mut total = 0u64; - let mut batch = Vec::with_capacity(STREAM_BATCH); - while let Some(row) = rows.next().await { - let row = row.map_err(map_next_row)?; - batch.push(super::full_values(|| { - row.columns.iter().map(cell).collect::>() - })); - total += 1; - if batch.len() == STREAM_BATCH { - let full = std::mem::replace(&mut batch, Vec::with_capacity(STREAM_BATCH)); - sink.send(StreamEvent::Rows(full)) - .await - .map_err(|_| super::stream_stopped())?; - } - } - if !batch.is_empty() { - sink.send(StreamEvent::Rows(batch)) - .await - .map_err(|_| super::stream_stopped())?; - } - Ok(total) - } - - // ----------------------------------------------------------------------- - // Result editing - - /// The table behind a result, when each row can be addressed by its full - /// primary key. - async fn editable( - &self, - sql: &str, - is_select: bool, - origins: &[ResultColumn], - ) -> (Option, Option) { - let reason = |text: &str| (None, Some(text.to_string())); - if !is_select { - return reason("Only the rows of a SELECT can be edited."); - } - let Some(first) = origins.first() else { - return reason("The result has no columns."); - }; - if origins - .iter() - .any(|c| (&c.keyspace, &c.table) != (&first.keyspace, &first.table)) - { - return reason("The result does not come from a single table."); - } - if is_system(&first.keyspace) { - return reason("System tables are read-only."); - } - if has_alias(sql) { - return reason("Columns with an alias (AS) cannot be matched to the table."); - } - let meta = match self.table_meta(&first.keyspace, &first.table).await { - Ok(m) => m, - Err(_) => return reason("The table's key could not be read."), - }; - if meta.view { - return reason("Materialized views cannot be edited."); - } - if meta.columns.iter().any(|c| c.type_name == "counter") { - return reason("Counter tables cannot be edited in the grid."); - } - let mut key = Vec::new(); - let mut missing = Vec::new(); - for c in meta.columns.iter().filter(|c| c.primary_key) { - match origins.iter().position(|o| o.name == c.name) { - Some(i) => key.push(i), - None => missing.push(quote_name(&c.name)), - } - } - if key.is_empty() && missing.is_empty() { - return reason("The table has no primary key."); - } - if !missing.is_empty() { - return reason(&format!( - "The result must include the whole primary key (missing {}).", - missing.join(", ") - )); - } - let columns = origins - .iter() - .map(|o| { - meta.columns - .iter() - .find(|c| c.name == o.name) - .map(|c| EditColumn { - name: c.name.clone(), - type_name: c.type_name.clone(), - }) - }) - .collect(); - ( - Some(EditTarget { - schema: Some(first.keyspace.clone()), - table: first.table.clone(), - columns, - key, - }), - None, - ) - } - - async fn table_meta(&self, keyspace: &str, table: &str) -> AppResult> { - let id = (keyspace.to_string(), table.to_string()); - if let Some(m) = self.tables.lock().get(&id) { - return Ok(m.clone()); - } - let columns = self.list_columns(keyspace, table).await?; - let views = fetch( - &self.cql, - &format!( - "SELECT view_name FROM system_schema.views WHERE keyspace_name = {} AND view_name = {}", - lit(keyspace), - lit(table) - ), - ) - .await?; - let meta = Arc::new(TableMeta { - columns, - view: !views.rows.is_empty(), - }); - self.tables.lock().insert(id, meta.clone()); - Ok(meta) - } - - /// Saves the grid's changes as one logged batch, which Cassandra applies - /// completely or not at all. CQL writes are upserts, so an UPDATE or - /// DELETE whose row was removed meanwhile does not fail: the counts are - /// the statements sent. - pub async fn apply_changes(&self, req: &ApplyRequest) -> AppResult { - let (statements, mut result) = plan_changes(&req.target, &req.changes)?; - let started = Instant::now(); - let sql = match statements.len() { - 0 => return Ok(result), - 1 => statements[0].clone(), - _ => format!("BEGIN BATCH\n{};\nAPPLY BATCH", statements.join(";\n")), - }; - self.execute(&ExecRequest { sql, max_rows: 0 }).await?; - result.elapsed_ms = started.elapsed().as_millis() as u64; - Ok(result) - } - - // ----------------------------------------------------------------------- - // DDL - - pub async fn object_ddl(&self, schema: &str, name: &str, kind: &str) -> AppResult { - match kind { - "keyspace" => self.keyspace_ddl(name).await, - "table" => self.table_ddl(schema, name).await, - "matview" => self.view_ddl(schema, name).await, - "type" => self.type_ddl(schema, name).await, - "function" => self.function_ddl(schema, name).await, - "aggregate" => self.aggregate_ddl(schema, name).await, - "index" => self.index_ddl(schema, name).await, - other => Err(AppError::invalid(format!( - "LowQuery cannot script a {other} on Cassandra." - ))), - } - } - - async fn keyspace_ddl(&self, name: &str) -> AppResult { - let f = fetch( - &self.cql, - &format!( - "SELECT * FROM system_schema.keyspaces WHERE keyspace_name = {}", - lit(name) - ), - ) - .await?; - let Some(row) = f.rows.first() else { - return Ok(String::new()); - }; - let replication = f - .get(row, "replication") - .map_or_else(|| "{}".to_string(), literal); - let durable = f - .get(row, "durable_writes") - .map_or_else(|| "true".to_string(), literal); - Ok(format!( - "CREATE KEYSPACE {} WITH replication = {replication}\n AND durable_writes = {durable};\n", - quote_name(name) - )) - } - - async fn type_ddl(&self, keyspace: &str, name: &str) -> AppResult { - let f = fetch( - &self.cql, - &format!( - "SELECT * FROM system_schema.types WHERE keyspace_name = {} AND type_name = {}", - lit(keyspace), - lit(name) - ), - ) - .await?; - let Some(row) = f.rows.first() else { - return Ok(String::new()); - }; - let names = text_list(f.get(row, "field_names")); - let types = text_list(f.get(row, "field_types")); - let fields: Vec = names - .iter() - .zip(&types) - .map(|(n, t)| format!(" {} {t}", quote_name(n))) - .collect(); - Ok(format!( - "CREATE TYPE {}.{} (\n{}\n);\n", - quote_name(keyspace), - quote_name(name), - fields.join(",\n") - )) - } - - async fn table_ddl(&self, keyspace: &str, name: &str) -> AppResult { - let f = fetch( - &self.cql, - &format!( - "SELECT * FROM system_schema.tables WHERE keyspace_name = {} AND table_name = {}", - lit(keyspace), - lit(name) - ), - ) - .await?; - let Some(row) = f.rows.first() else { - return Ok(String::new()); - }; - let mut out = String::new(); - let columns = self.catalog_columns(keyspace, name).await?; - write_create( - &mut out, - &format!("CREATE TABLE {}.{}", quote_name(keyspace), quote_name(name)), - &columns, - &table_options(&f, row, self.legacy()), - ); - out.push('\n'); - for statement in self.index_statements(keyspace, Some(name), None).await? { - out.push_str(&statement); - out.push('\n'); - } - Ok(out) - } - - async fn view_ddl(&self, keyspace: &str, name: &str) -> AppResult { - let f = fetch( - &self.cql, - &format!( - "SELECT * FROM system_schema.views WHERE keyspace_name = {} AND view_name = {}", - lit(keyspace), - lit(name) - ), - ) - .await?; - let Some(row) = f.rows.first() else { - return Ok(String::new()); - }; - let columns = self.catalog_columns(keyspace, name).await?; - let base = f.text(row, "base_table_name").unwrap_or_default(); - let all = matches!( - f.get(row, "include_all_columns"), - Some(CqlValue::Boolean(true)) - ); - let select = if all { - "*".to_string() - } else { - columns - .iter() - .map(|c| quote_name(&c.name)) - .collect::>() - .join(", ") - }; - let header = format!( - "CREATE MATERIALIZED VIEW {}.{} AS\n SELECT {select}\n FROM {}.{}\n WHERE {}", - quote_name(keyspace), - quote_name(name), - quote_name(keyspace), - quote_name(&base), - f.text(row, "where_clause").unwrap_or_default() - ); - let mut out = String::new(); - write_primary_key( - &mut out, - &header, - &columns, - &table_options(&f, row, self.legacy()), - ); - Ok(out) - } - - async fn catalog_columns(&self, keyspace: &str, table: &str) -> AppResult> { - let f = fetch( - &self.cql, - &format!( - "SELECT column_name, type, kind, position, clustering_order \ - FROM system_schema.columns WHERE keyspace_name = {} AND table_name = {}", - lit(keyspace), - lit(table) - ), - ) - .await?; - let mut cols: Vec = f - .rows - .iter() - .filter_map(|r| { - Some(CatalogColumn { - name: f.text(r, "column_name")?, - type_name: f.text(r, "type")?, - kind: f.text(r, "kind").unwrap_or_default().to_ascii_lowercase(), - position: match f.get(r, "position") { - Some(CqlValue::Int(p)) => *p, - _ => 0, - }, - descending: f - .text(r, "clustering_order") - .is_some_and(|o| o.eq_ignore_ascii_case("desc")), - }) - }) - .collect(); - cols.sort_by(|a, b| (a.rank(), a.position, &a.name).cmp(&(b.rank(), b.position, &b.name))); - Ok(cols) - } - - /// CREATE INDEX statements of a table (or the one index named `only`). - async fn index_statements( - &self, - keyspace: &str, - table: Option<&str>, - only: Option<&str>, - ) -> AppResult> { - let f = fetch( - &self.cql, - &format!( - "SELECT * FROM system_schema.indexes WHERE keyspace_name = {}", - lit(keyspace) - ), - ) - .await?; - let mut out = Vec::new(); - for row in &f.rows { - let (Some(index), Some(on)) = (f.text(row, "index_name"), f.text(row, "table_name")) - else { - continue; - }; - if table.is_some_and(|t| t != on) || only.is_some_and(|o| o != index) { - continue; - } - let kind = f.text(row, "kind").unwrap_or_default(); - let mut options: Vec<(String, String)> = match f.get(row, "options") { - Some(CqlValue::Map(m)) => m - .iter() - .filter_map(|(k, v)| { - Some((text_of(&Some(k.clone()))?, text_of(&Some(v.clone()))?)) - }) - .collect(), - _ => Vec::new(), - }; - let target = options - .iter() - .position(|(k, _)| k == "target") - .map(|i| options.remove(i).1) - .unwrap_or_default(); - let class = options - .iter() - .position(|(k, _)| k == "class_name") - .map(|i| options.remove(i).1); - let mut statement = format!( - "CREATE {}INDEX {} ON {}.{} ({target})", - if kind == "CUSTOM" { "CUSTOM " } else { "" }, - quote_name(&index), - quote_name(keyspace), - quote_name(&on) - ); - if let Some(class) = class { - let _ = write!(statement, " USING {}", quote_str(&class)); - if !options.is_empty() { - options.sort(); - let pairs: Vec = options - .iter() - .map(|(k, v)| format!("{}: {}", quote_str(k), quote_str(v))) - .collect(); - let _ = write!(statement, " WITH OPTIONS = {{{}}}", pairs.join(", ")); - } - } - statement.push(';'); - out.push(statement); - } - Ok(out) - } - - async fn index_ddl(&self, keyspace: &str, name: &str) -> AppResult { - Ok(self - .index_statements(keyspace, None, Some(name)) - .await? - .join("\n")) - } - - /// Functions and aggregates are named `name(argument types)` in the tree. - async fn routine_row( - &self, - table: &str, - column: &str, - keyspace: &str, - name: &str, - ) -> AppResult> { - let (bare, args) = match name.split_once('(') { - Some((b, rest)) => (b, rest.trim_end_matches(')')), - None => (name, ""), - }; - let f = fetch( - &self.cql, - &format!( - "SELECT * FROM system_schema.{table} WHERE keyspace_name = {} AND {column} = {}", - lit(keyspace), - lit(bare) - ), - ) - .await?; - let found = f - .rows - .iter() - .position(|r| text_list(f.get(r, "argument_types")).join(", ") == args.trim()); - Ok(found.map(|i| (f, i))) - } - - async fn function_ddl(&self, keyspace: &str, name: &str) -> AppResult { - let Some((f, i)) = self - .routine_row("functions", "function_name", keyspace, name) - .await? - else { - return Ok(String::new()); - }; - let row = &f.rows[i]; - let args: Vec = text_list(f.get(row, "argument_names")) - .iter() - .zip(text_list(f.get(row, "argument_types"))) - .map(|(n, t)| format!("{} {t}", quote_name(n))) - .collect(); - let on_null = if matches!( - f.get(row, "called_on_null_input"), - Some(CqlValue::Boolean(true)) - ) { - "CALLED ON NULL INPUT" - } else { - "RETURNS NULL ON NULL INPUT" - }; - let body = f.text(row, "body").unwrap_or_default(); - Ok(format!( - "CREATE OR REPLACE FUNCTION {}.{} ({})\n {on_null}\n RETURNS {}\n LANGUAGE {}\n AS {};\n", - quote_name(keyspace), - quote_name(f.text(row, "function_name").as_deref().unwrap_or(name)), - args.join(", "), - f.text(row, "return_type").unwrap_or_default(), - f.text(row, "language").unwrap_or_default(), - dollar_body(&body) - )) - } - - async fn aggregate_ddl(&self, keyspace: &str, name: &str) -> AppResult { - let Some((f, i)) = self - .routine_row("aggregates", "aggregate_name", keyspace, name) - .await? - else { - return Ok(String::new()); - }; - let row = &f.rows[i]; - let mut out = format!( - "CREATE OR REPLACE AGGREGATE {}.{} ({})\n SFUNC {}\n STYPE {}", - quote_name(keyspace), - quote_name(f.text(row, "aggregate_name").as_deref().unwrap_or(name)), - text_list(f.get(row, "argument_types")).join(", "), - quote_name(&f.text(row, "state_func").unwrap_or_default()), - f.text(row, "state_type").unwrap_or_default() - ); - if let Some(fin) = f.text(row, "final_func") { - let _ = write!(out, "\n FINALFUNC {}", quote_name(&fin)); - } - if let Some(init) = f.text(row, "initcond") { - let _ = write!(out, "\n INITCOND {init}"); - } - out.push_str(";\n"); - Ok(out) - } -} - -struct CatalogColumn { - name: String, - type_name: String, - /// `partition_key`, `clustering`, `static` or `regular`. - kind: String, - position: i32, - descending: bool, -} - -impl CatalogColumn { - fn rank(&self) -> u8 { - match self.kind.as_str() { - "partition_key" => 0, - "clustering" => 1, - "static" => 2, - _ => 3, - } - } -} - -/// Options a `CREATE TABLE`/`CREATE MATERIALIZED VIEW` can carry, in the -/// order cqlsh writes them, taken from the row the catalog holds. -fn table_options(f: &Fetched, row: &[Option], legacy: bool) -> Vec { - const OPTIONS: &[&str] = &[ - "additional_write_policy", - "allow_auto_snapshot", - "bloom_filter_fp_chance", - "caching", - "comment", - "compaction", - "compression", - "crc_check_chance", - "default_time_to_live", - "gc_grace_seconds", - "incremental_backups", - "max_index_interval", - "memtable", - "memtable_flush_period_in_ms", - "min_index_interval", - "read_repair", - "speculative_retry", - ]; - // Cassandra 3.x still has the read repair chances that 4.0 removed (it - // refuses them as options). - let legacy_options: &[&str] = if legacy { - &["dclocal_read_repair_chance", "read_repair_chance"] - } else { - &[] - }; - OPTIONS - .iter() - .chain(legacy_options) - .filter_map(|name| { - let value = f.get(row, name)?; - Some(format!("{name} = {}", literal(value))) - }) - .collect() -} - -fn write_create(out: &mut String, header: &str, columns: &[CatalogColumn], options: &[String]) { - let _ = writeln!(out, "{header} ("); - for c in columns { - let _ = writeln!( - out, - " {} {}{},", - quote_name(&c.name), - c.type_name, - if c.kind == "static" { " static" } else { "" } - ); - } - let _ = write!(out, " PRIMARY KEY ({})\n)", primary_key(columns)); - write_with(out, columns, options); -} - -/// Materialized views list their key after the select, not in a column list. -fn write_primary_key( - out: &mut String, - header: &str, - columns: &[CatalogColumn], - options: &[String], -) { - let _ = write!(out, "{header}\n PRIMARY KEY ({})", primary_key(columns)); - write_with(out, columns, options); -} - -fn write_with(out: &mut String, columns: &[CatalogColumn], options: &[String]) { - let clustering: Vec = columns - .iter() - .filter(|c| c.kind == "clustering") - .map(|c| { - format!( - "{} {}", - quote_name(&c.name), - if c.descending { "DESC" } else { "ASC" } - ) - }) - .collect(); - let mut parts = Vec::new(); - if !clustering.is_empty() { - parts.push(format!("CLUSTERING ORDER BY ({})", clustering.join(", "))); - } - parts.extend(options.iter().cloned()); - for (i, part) in parts.iter().enumerate() { - let _ = write!( - out, - "{}{part}", - if i == 0 { "\n WITH " } else { "\n AND " } - ); - } - out.push_str(";\n"); -} - -/// `(a, b), c, d` for a table keyed by (a, b) with clustering columns c, d. -fn primary_key(columns: &[CatalogColumn]) -> String { - let partition: Vec = columns - .iter() - .filter(|c| c.kind == "partition_key") - .map(|c| quote_name(&c.name)) - .collect(); - let clustering: Vec = columns - .iter() - .filter(|c| c.kind == "clustering") - .map(|c| quote_name(&c.name)) - .collect(); - let head = if partition.len() == 1 { - partition[0].clone() - } else { - format!("({})", partition.join(", ")) - }; - std::iter::once(head) - .chain(clustering) - .collect::>() - .join(", ") -} - -/// A function body as `$$...$$`, or a quoted string when it holds `$$`. -fn dollar_body(body: &str) -> String { - if body.contains("$$") { - quote_str(body) - } else { - format!("$${body}$$") - } -} - -// --------------------------------------------------------------------------- -// Edits - -fn plan_changes( - target: &EditTarget, - changes: &[RowChange], -) -> AppResult<(Vec, ApplyResult)> { - let table = match &target.schema { - Some(schema) => format!("{}.{}", quote_name(schema), quote_name(&target.table)), - None => quote_name(&target.table), - }; - let key_columns: Vec<&EditColumn> = target - .key - .iter() - .map(|&i| column_at(target, i)) - .collect::>()?; - let condition = |key: &[Option]| -> AppResult { - if key.len() != key_columns.len() { - return Err(AppError::invalid("The row's key is incomplete.")); - } - key_columns - .iter() - .zip(key) - .map(|(c, v)| match v { - Some(v) => Ok(format!( - "{} = {}", - quote_name(&c.name), - cql_literal(&c.type_name, Some(v)) - )), - None => Err(AppError::invalid(format!( - "The key column {} is empty.", - c.name - ))), - }) - .collect::>>() - .map(|parts| parts.join(" AND ")) - }; - let mut statements = Vec::new(); - let mut result = ApplyResult::default(); - for change in changes { - match change { - RowChange::Update { values, .. } if values.is_empty() => {} - RowChange::Update { key, values } => { - let mut sets = Vec::with_capacity(values.len()); - for v in values { - let c = column_at(target, v.column)?; - if key_columns.iter().any(|k| k.name == c.name) { - return Err(AppError::invalid(format!( - "{} is part of the primary key, which CQL cannot update. \ - Delete the row and insert it again.", - c.name - ))); - } - sets.push(format!( - "{} = {}", - quote_name(&c.name), - cql_literal(&c.type_name, v.value.as_deref()) - )); - } - statements.push(format!( - "UPDATE {table} SET {} WHERE {}", - sets.join(", "), - condition(key)? - )); - result.updated += 1; - } - RowChange::Delete { key } => { - statements.push(format!("DELETE FROM {table} WHERE {}", condition(key)?)); - result.deleted += 1; - } - RowChange::Insert { values } => { - if values.is_empty() { - return Err(AppError::invalid("Enter a value for the new row.")); - } - let mut names = Vec::with_capacity(values.len()); - let mut literals = Vec::with_capacity(values.len()); - for v in values { - let c = column_at(target, v.column)?; - names.push(quote_name(&c.name)); - literals.push(cql_literal(&c.type_name, v.value.as_deref())); - } - statements.push(format!( - "INSERT INTO {table} ({}) VALUES ({})", - names.join(", "), - literals.join(", ") - )); - result.inserted += 1; - } - } - } - Ok((statements, result)) -} - -fn column_at(target: &EditTarget, index: usize) -> AppResult<&EditColumn> { - target - .columns - .get(index) - .and_then(Option::as_ref) - .ok_or_else(|| { - AppError::invalid(format!( - "Column {} is not a column of the table and cannot be saved.", - index + 1 - )) - }) -} - -/// True when the text has the word `AS` outside strings, quoted names and -/// comments. -fn has_alias(sql: &str) -> bool { - let b = sql.as_bytes(); - let mut i = 0; - let mut word = String::new(); - let mut found = false; - let mut flush = |word: &mut String| { - if word.eq_ignore_ascii_case("as") { - found = true; - } - word.clear(); - }; - while i < b.len() { - let c = b[i]; - if c == b'\'' || c == b'"' { - flush(&mut word); - i += 1; - while i < b.len() { - if b[i] == c { - if b.get(i + 1) == Some(&c) { - i += 1; - } else { - break; - } - } - i += 1; - } - } else if c == b'$' && b.get(i + 1) == Some(&b'$') { - flush(&mut word); - i = sql[i + 2..].find("$$").map_or(b.len(), |p| i + 2 + p + 1); - } else if (c == b'-' && b.get(i + 1) == Some(&b'-')) - || (c == b'/' && b.get(i + 1) == Some(&b'/')) - { - flush(&mut word); - while i < b.len() && b[i] != b'\n' { - i += 1; - } - } else if c == b'/' && b.get(i + 1) == Some(&b'*') { - flush(&mut word); - i = sql[i + 2..].find("*/").map_or(b.len(), |p| i + 2 + p + 1); - } else if c.is_ascii_alphanumeric() || c == b'_' { - word.push(c as char); - } else { - flush(&mut word); - } - i += 1; - } - flush(&mut word); - found -} - -// --------------------------------------------------------------------------- -// Names and types - -/// CQL's reserved words (Cassandra 3.0 to 5.0): they need quotes as names. -const RESERVED: &[&str] = &[ - "ADD", - "ALLOW", - "ALTER", - "AND", - "APPLY", - "ASC", - "AUTHORIZE", - "BATCH", - "BEGIN", - "BY", - "COLUMNFAMILY", - "CREATE", - "DEFAULT", - "DELETE", - "DESC", - "DESCRIBE", - "DROP", - "ENTRIES", - "EXECUTE", - "FROM", - "FULL", - "GRANT", - "IF", - "IN", - "INDEX", - "INFINITY", - "INSERT", - "INTO", - "IS", - "KEYSPACE", - "LIMIT", - "MATERIALIZED", - "MODIFY", - "NAN", - "NORECURSIVE", - "NOT", - "NULL", - "OF", - "ON", - "OR", - "ORDER", - "PRIMARY", - "RENAME", - "REPLACE", - "REVOKE", - "SCHEMA", - "SELECT", - "SET", - "TABLE", - "TO", - "TOKEN", - "TRUNCATE", - "UNLOGGED", - "UPDATE", - "USE", - "USING", - "VIEW", - "WHERE", - "WITH", -]; - -/// An identifier as CQL reads it back: bare when it is lowercase and not a -/// reserved word, otherwise double-quoted. -pub fn quote_name(name: &str) -> String { - let bare = name.bytes().next().is_some_and(|c| c.is_ascii_lowercase()) - && name - .bytes() - .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_') - && !RESERVED.contains(&name.to_ascii_uppercase().as_str()); - if bare { - name.to_string() - } else { - format!("\"{}\"", name.replace('"', "\"\"")) - } -} - -fn quote_str(s: &str) -> String { - format!("'{}'", s.replace('\'', "''")) -} - -fn native_name(t: &NativeType) -> &'static str { - match t { - NativeType::Ascii => "ascii", - NativeType::Boolean => "boolean", - NativeType::Blob => "blob", - NativeType::Counter => "counter", - NativeType::Date => "date", - NativeType::Decimal => "decimal", - NativeType::Double => "double", - NativeType::Duration => "duration", - NativeType::Float => "float", - NativeType::Int => "int", - NativeType::BigInt => "bigint", - NativeType::Text => "text", - NativeType::Timestamp => "timestamp", - NativeType::Inet => "inet", - NativeType::SmallInt => "smallint", - NativeType::TinyInt => "tinyint", - NativeType::Time => "time", - NativeType::Timeuuid => "timeuuid", - NativeType::Uuid => "uuid", - NativeType::Varint => "varint", - _ => "custom", - } -} - -/// The type as `system_schema` writes it: `list`, -/// `frozen>`, `vector`, a UDT by its name. -fn type_name(t: &ColumnType<'_>) -> String { - let frozen = |frozen: bool, inner: String| { - if frozen { - format!("frozen<{inner}>") - } else { - inner - } - }; - match t { - ColumnType::Native(n) => native_name(n).into(), - ColumnType::Collection { frozen: f, typ } => frozen( - *f, - match typ { - CollectionType::List(e) => format!("list<{}>", type_name(e)), - CollectionType::Set(e) => format!("set<{}>", type_name(e)), - CollectionType::Map(k, v) => format!("map<{}, {}>", type_name(k), type_name(v)), - _ => "custom".into(), - }, - ), - ColumnType::Vector { typ, dimensions } => { - format!("vector<{}, {dimensions}>", type_name(typ)) - } - ColumnType::UserDefinedType { - frozen: f, - definition, - } => frozen(*f, quote_name(&definition.name)), - ColumnType::Tuple(items) => format!( - "tuple<{}>", - items.iter().map(type_name).collect::>().join(", ") - ), - _ => "custom".into(), - } -} - -fn column_kind(t: &ColumnType<'_>) -> ValueKind { - match t { - ColumnType::Native(n) => match n { - NativeType::TinyInt - | NativeType::SmallInt - | NativeType::Int - | NativeType::BigInt - | NativeType::Varint - | NativeType::Decimal - | NativeType::Float - | NativeType::Double - | NativeType::Counter => ValueKind::Number, - NativeType::Boolean => ValueKind::Bool, - NativeType::Timestamp | NativeType::Date | NativeType::Time | NativeType::Duration => { - ValueKind::Temporal - } - NativeType::Blob => ValueKind::Binary, - NativeType::Text - | NativeType::Ascii - | NativeType::Uuid - | NativeType::Timeuuid - | NativeType::Inet => ValueKind::Text, - _ => ValueKind::Other, - }, - _ => ValueKind::Other, - } -} - -// --------------------------------------------------------------------------- -// Values - -/// A value as the grid shows it: text as it is, everything else as its CQL -/// text (collections and UDTs as valid CQL literals). -fn cell(v: &Option) -> Option { - let v = v.as_ref()?; - Some(match v { - CqlValue::Text(s) | CqlValue::Ascii(s) => s.clone(), - CqlValue::Timestamp(_) | CqlValue::Date(_) | CqlValue::Time(_) | CqlValue::Inet(_) => { - plain(v) - } - CqlValue::Blob(bytes) => blob(bytes, super::binary_limit(BINARY_PREVIEW_BYTES)), - CqlValue::Empty => String::new(), - other => literal(other), - }) -} - -/// The text of a temporal value or an address, unquoted. -fn plain(v: &CqlValue) -> String { - match v { - CqlValue::Timestamp(t) => timestamp_text(t.0), - CqlValue::Date(d) => date_text(i64::from(d.0) - (1 << 31)), - CqlValue::Time(t) => time_text(t.0), - CqlValue::Inet(ip) => ip.to_string(), - _ => String::new(), - } -} - -/// `0x00ff`, cut to `limit` bytes with the full size noted. -fn blob(bytes: &[u8], limit: usize) -> String { - let shown = &bytes[..bytes.len().min(limit)]; - let mut s = String::with_capacity(shown.len() * 2 + 2); - s.push_str("0x"); - for b in shown { - let _ = write!(s, "{b:02x}"); - } - if bytes.len() > shown.len() { - let _ = write!(s, "… ({} bytes)", bytes.len()); - } - s -} - -/// A value as a CQL literal, as it is written inside a collection. -fn literal(v: &CqlValue) -> String { - match v { - CqlValue::Text(s) | CqlValue::Ascii(s) => quote_str(s), - CqlValue::Boolean(b) => b.to_string(), - CqlValue::TinyInt(n) => n.to_string(), - CqlValue::SmallInt(n) => n.to_string(), - CqlValue::Int(n) => n.to_string(), - CqlValue::BigInt(n) => n.to_string(), - CqlValue::Counter(c) => c.0.to_string(), - CqlValue::Float(f) => float_text(f64::from(*f), &f.to_string(), &format!("{f:e}")), - CqlValue::Double(d) => float_text(*d, &d.to_string(), &format!("{d:e}")), - CqlValue::Varint(n) => integer_text(n.as_signed_bytes_be_slice()), - CqlValue::Decimal(d) => { - let (bytes, scale) = d.as_signed_be_bytes_slice_and_exponent(); - decimal_text(&integer_text(bytes), scale) - } - CqlValue::Uuid(u) => u.to_string(), - CqlValue::Timeuuid(u) => u.to_string(), - CqlValue::Blob(bytes) => blob(bytes, usize::MAX), - CqlValue::Timestamp(_) | CqlValue::Date(_) | CqlValue::Time(_) | CqlValue::Inet(_) => { - quote_str(&plain(v)) - } - CqlValue::Duration(d) => duration_text(d.months, d.days, d.nanoseconds), - CqlValue::List(items) | CqlValue::Vector(items) => { - format!( - "[{}]", - items.iter().map(literal).collect::>().join(", ") - ) - } - CqlValue::Set(items) => { - format!( - "{{{}}}", - items.iter().map(literal).collect::>().join(", ") - ) - } - CqlValue::Map(pairs) => format!( - "{{{}}}", - pairs - .iter() - .map(|(k, v)| format!("{}: {}", literal(k), literal(v))) - .collect::>() - .join(", ") - ), - CqlValue::Tuple(items) => format!( - "({})", - items - .iter() - .map(|i| i.as_ref().map_or_else(|| "null".into(), literal)) - .collect::>() - .join(", ") - ), - CqlValue::UserDefinedType { fields, .. } => format!( - "{{{}}}", - fields - .iter() - .map(|(n, v)| format!( - "{}: {}", - quote_name(n), - v.as_ref().map_or_else(|| "null".into(), literal) - )) - .collect::>() - .join(", ") - ), - _ => "null".into(), - } -} - -/// Shortest round-trip text; very large or small magnitudes use an exponent. -fn float_text(value: f64, plain: &str, exponent: &str) -> String { - if value.is_nan() { - "NaN".into() - } else if value.is_infinite() { - if value > 0.0 { "Infinity" } else { "-Infinity" }.into() - } else if value != 0.0 && (value.abs() >= 1e16 || value.abs() < 1e-5) { - exponent.to_string() - } else { - plain.to_string() - } -} - -/// Decimal digits of a two's complement big-endian integer. -fn integer_text(bytes: &[u8]) -> String { - let negative = bytes.first().is_some_and(|b| b & 0x80 != 0); - let mut magnitude = bytes.to_vec(); - if negative { - // Negate: invert and add one. - let mut carry = true; - for b in magnitude.iter_mut().rev() { - *b = !*b; - if carry { - let (n, c) = b.overflowing_add(1); - *b = n; - carry = c; - } - } - } - // Base 2^32 limbs, most significant first. - let pad = (4 - magnitude.len() % 4) % 4; - let mut limbs: Vec = std::iter::repeat_n(0u8, pad) - .chain(magnitude) - .collect::>() - .chunks(4) - .map(|c| u32::from_be_bytes([c[0], c[1], c[2], c[3]])) - .collect(); - let mut parts: Vec = Vec::new(); - while limbs.iter().any(|&l| l != 0) { - let mut rem = 0u64; - for limb in &mut limbs { - let cur = (rem << 32) | u64::from(*limb); - *limb = (cur / 1_000_000_000) as u32; - rem = cur % 1_000_000_000; - } - parts.push(rem as u32); - let zeros = limbs.iter().take_while(|&&l| l == 0).count(); - limbs.drain(..zeros); - } - let Some(top) = parts.pop() else { - return "0".into(); - }; - let mut out = String::new(); - if negative { - out.push('-'); - } - let _ = write!(out, "{top}"); - for part in parts.iter().rev() { - let _ = write!(out, "{part:09}"); - } - out -} - -/// `unscaled × 10^-scale` the way Java's `BigDecimal.toString` writes it: -/// plain when the exponent allows, scientific otherwise. -fn decimal_text(unscaled: &str, scale: i32) -> String { - let (sign, digits) = match unscaled.strip_prefix('-') { - Some(d) => ("-", d), - None => ("", unscaled), - }; - let adjusted = -i64::from(scale) + digits.len() as i64 - 1; - if scale == 0 { - return unscaled.to_string(); - } - if scale > 0 && adjusted >= -6 { - let scale = scale as usize; - return if digits.len() > scale { - let (int, frac) = digits.split_at(digits.len() - scale); - format!("{sign}{int}.{frac}") - } else { - format!("{sign}0.{}{digits}", "0".repeat(scale - digits.len())) - }; - } - let (head, rest) = digits.split_at(1); - let mantissa = if rest.is_empty() { - head.to_string() - } else { - format!("{head}.{rest}") - }; - format!( - "{sign}{mantissa}E{}{adjusted}", - if adjusted >= 0 { "+" } else { "" } - ) -} - -/// Year, month and day of a day count since 1970-01-01. -fn civil_from_days(days: i64) -> (i64, u32, u32) { - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z.rem_euclid(146_097); - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let day = (doy - (153 * mp + 2) / 5 + 1) as u32; - let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32; - let year = yoe + era * 400 + i64::from(month <= 2); - (year, month, day) -} - -fn date_text(days: i64) -> String { - let (y, m, d) = civil_from_days(days); - if y < 0 { - format!("-{:04}-{m:02}-{d:02}", -y) - } else { - format!("{y:04}-{m:02}-{d:02}") - } -} - -/// `2024-05-06 07:08:09.123+0000`. -fn timestamp_text(millis: i64) -> String { - let secs = millis.div_euclid(1000); - let ms = millis.rem_euclid(1000); - let day = secs.div_euclid(86_400); - let tod = secs.rem_euclid(86_400); - format!( - "{} {:02}:{:02}:{:02}.{ms:03}+0000", - date_text(day), - tod / 3600, - tod % 3600 / 60, - tod % 60 - ) -} - -/// `07:08:09.123456789`. -fn time_text(nanos: i64) -> String { - let secs = nanos.div_euclid(1_000_000_000); - let frac = nanos.rem_euclid(1_000_000_000); - format!( - "{:02}:{:02}:{:02}.{frac:09}", - secs / 3600, - secs % 3600 / 60, - secs % 60 - ) -} - -/// `1y2mo3d4h5m6s7ms8us9ns`, the form CQL reads back. -fn duration_text(months: i32, days: i32, nanos: i64) -> String { - let negative = months < 0 || days < 0 || nanos < 0; - let months = i64::from(months).unsigned_abs(); - let days = i64::from(days).unsigned_abs(); - let nanos = nanos.unsigned_abs(); - let mut out = String::new(); - let mut put = |n: u64, unit: &str| { - if n > 0 { - let _ = write!(out, "{n}{unit}"); - } - }; - put(months / 12, "y"); - put(months % 12, "mo"); - put(days, "d"); - put(nanos / 3_600_000_000_000, "h"); - put(nanos / 60_000_000_000 % 60, "m"); - put(nanos / 1_000_000_000 % 60, "s"); - put(nanos / 1_000_000 % 1000, "ms"); - put(nanos / 1000 % 1000, "us"); - put(nanos % 1000, "ns"); - if out.is_empty() { - out.push_str("0s"); - } - if negative { - out.insert(0, '-'); - } - out -} - -/// A cell's text as a CQL literal for a column of `type_name` (the type as -/// `system_schema` writes it). Numbers, booleans, uuids, blobs and durations -/// are bare, text and temporal values quoted; collections, tuples, vectors and -/// UDTs are already CQL literals in cell text and stay as they are. `None` is -/// `null`. -pub fn cql_literal(type_name: &str, value: Option<&str>) -> String { - let Some(v) = value else { - return "null".into(); - }; - let mut t = type_name.trim().to_ascii_lowercase(); - while let Some(inner) = t - .strip_prefix("frozen<") - .and_then(|rest| rest.strip_suffix('>')) - { - t = inner.trim().to_string(); - } - let trimmed = v.trim(); - let bare = match t.as_str() { - "tinyint" | "smallint" | "int" | "bigint" | "varint" | "decimal" | "float" | "double" - | "counter" => is_number(trimmed).then(|| trimmed.to_string()), - "boolean" => match trimmed.to_ascii_lowercase().as_str() { - b @ ("true" | "false") => Some(b.to_string()), - _ => None, - }, - "uuid" | "timeuuid" => is_uuid(trimmed).then(|| trimmed.to_string()), - "blob" => is_blob(trimmed).then(|| trimmed.to_string()), - "duration" => (!trimmed.is_empty() && !trimmed.contains(char::is_whitespace)) - .then(|| trimmed.to_string()), - "text" | "varchar" | "ascii" | "inet" | "timestamp" | "date" | "time" => { - return quote_str(v); - } - // Collections, tuples, vectors and UDTs. - _ => return v.to_string(), - }; - bare.unwrap_or_else(|| quote_str(v)) -} - -fn is_number(v: &str) -> bool { - if matches!(v, "NaN" | "Infinity" | "-Infinity") { - return true; - } - let body = v.strip_prefix(['-', '+']).unwrap_or(v); - let (mantissa, exponent) = match body.find(['e', 'E']) { - Some(i) => (&body[..i], Some(&body[i + 1..])), - None => (body, None), - }; - let digits = mantissa.replacen('.', "", 1); - !digits.is_empty() - && digits.bytes().all(|b| b.is_ascii_digit()) - && mantissa.matches('.').count() <= 1 - && exponent.is_none_or(|e| { - let e = e.strip_prefix(['-', '+']).unwrap_or(e); - !e.is_empty() && e.bytes().all(|b| b.is_ascii_digit()) - }) -} - -fn is_uuid(v: &str) -> bool { - v.len() == 36 - && v.bytes().enumerate().all(|(i, b)| { - if matches!(i, 8 | 13 | 18 | 23) { - b == b'-' - } else { - b.is_ascii_hexdigit() - } - }) -} - -fn is_blob(v: &str) -> bool { - v.strip_prefix("0x") - .is_some_and(|h| h.len() % 2 == 0 && h.bytes().all(|b| b.is_ascii_hexdigit())) -} - -// --------------------------------------------------------------------------- -// Errors - -/// Every message in the chain of an error, joined. -fn chain(e: &dyn std::error::Error) -> String { - let mut text = e.to_string(); - let mut source = e.source(); - while let Some(s) = source { - let part = s.to_string(); - if !text.contains(&part) { - text.push_str(": "); - text.push_str(&part); - } - source = s.source(); - } - text -} - -fn is_auth_text(text: &str) -> bool { - let t = text.to_ascii_lowercase(); - t.contains("authenticat") || t.contains("credentials") || t.contains("username and/or password") -} - -fn connect_error(e: NewSessionError) -> AppError { - let text = chain(&e); - let mut err = AppError::connection(match &e { - NewSessionError::EmptyKnownNodesList => "Enter at least one contact point.".to_string(), - _ => text.clone(), - }); - if is_auth_text(&text) { - err.code = Some("AuthenticationError".into()); - } - err -} - -/// The server's error behind a failed request, when there is one. -fn attempt_error(e: &RequestAttemptError) -> Option<(&DbError, &str)> { - match e { - RequestAttemptError::DbError(db, message) => Some((db, message)), - _ => None, - } -} - -/// `line 1:7 no viable alternative at input ...` as a 0-based character -/// offset into `sql`. -fn error_position(sql: &str, message: &str) -> Option { - let rest = &message[message.find("line ")? + 5..]; - let (line, rest) = rest.split_once(':')?; - let line: usize = line.trim().parse().ok()?; - let col: usize = rest - .chars() - .take_while(char::is_ascii_digit) - .collect::() - .parse() - .ok()?; - let before: usize = sql - .split('\n') - .take(line.checked_sub(1)?) - .map(|l| l.chars().count() + 1) - .sum(); - Some(before + col) -} - -fn db_error(db: &DbError, message: &str, sql: Option<&str>) -> AppError { - let debug = format!("{db:?}"); - let code: String = debug - .chars() - .take_while(|c| c.is_ascii_alphanumeric()) - .collect(); - let kind = match db { - DbError::AuthenticationError => ErrorKind::Connection, - _ => ErrorKind::Database, - }; - let mut err = AppError::new(kind, message); - err.code = Some(code); - if matches!(db, DbError::SyntaxError) { - err.position = sql.and_then(|s| error_position(s, message)); - } - err -} - -fn timeout_error(d: Duration) -> AppError { - AppError::new( - ErrorKind::Database, - format!("The request took longer than {} ms.", d.as_millis()), - ) -} - -fn map_request(e: &RequestError, sql: Option<&str>) -> AppError { - match e { - RequestError::LastAttemptError(a) => match attempt_error(a) { - Some((db, message)) => db_error(db, message, sql), - None => AppError::connection(chain(a)), - }, - RequestError::RequestTimeout(d) => timeout_error(*d), - RequestError::EmptyPlan => no_node(), - other => AppError::connection(chain(other)), - } -} - -fn no_node() -> AppError { - AppError::connection( - "No node accepts requests. If a local datacenter is set, check its name: only its nodes are used.", - ) -} - -fn map_execution(e: ExecutionError, sql: Option<&str>) -> AppError { - match &e { - ExecutionError::LastAttemptError(a) => match attempt_error(a) { - Some((db, message)) => db_error(db, message, sql), - None => AppError::connection(chain(a)), - }, - ExecutionError::RequestTimeout(d) => timeout_error(*d), - ExecutionError::EmptyPlan => no_node(), - ExecutionError::BadQuery(_) => AppError::invalid(e.to_string()), - ExecutionError::ConnectionPoolError(_) => AppError::connection(chain(&e)), - _ => AppError::new(ErrorKind::Database, chain(&e)), - } -} - -fn map_next_page(e: &NextPageError) -> AppError { - match e { - NextPageError::RequestFailure(r) => map_request(r, None), - other => AppError::new(ErrorKind::Database, chain(other)), - } -} - -fn map_next_row(e: NextRowError) -> AppError { - match &e { - NextRowError::NextPageError(p) => map_next_page(p), - other => AppError::internal(other.to_string()), - } -} - -fn map_pager(e: PagerExecutionError) -> AppError { - match &e { - PagerExecutionError::NextPageError(p) => map_next_page(p), - other => AppError::new(ErrorKind::Database, chain(other)), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use scylla::value::{ - Counter, CqlDate, CqlDecimal, CqlDuration, CqlTime, CqlTimestamp, CqlTimeuuid, CqlVarint, - }; - - fn text(s: &str) -> CqlValue { - CqlValue::Text(s.into()) - } - - #[test] - fn integers_keep_every_digit() { - assert_eq!(integer_text(&[]), "0"); - assert_eq!(integer_text(&[0]), "0"); - assert_eq!(integer_text(&[0x7f]), "127"); - assert_eq!(integer_text(&[0xff]), "-1"); - assert_eq!(integer_text(&[0x80]), "-128"); - assert_eq!(integer_text(&[0x00, 0xff]), "255"); - // 2^64 and -(2^64) - 1 - assert_eq!( - integer_text(&[0x01, 0, 0, 0, 0, 0, 0, 0, 0]), - "18446744073709551616" - ); - assert_eq!( - integer_text(&[0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), - "-18446744073709551617" - ); - // 123456789012345678901234567890 - let n = CqlVarint::from_signed_bytes_be(vec![ - 0x01, 0x8e, 0xe9, 0x0f, 0xf6, 0xc3, 0x73, 0xe0, 0xee, 0x4e, 0x3f, 0x0a, 0xd2, - ]); - assert_eq!( - literal(&CqlValue::Varint(n)), - "123456789012345678901234567890" - ); - } - - #[test] - fn decimals_are_exact() { - assert_eq!(decimal_text("12345", 2), "123.45"); - assert_eq!(decimal_text("-5", 3), "-0.005"); - assert_eq!(decimal_text("0", 2), "0.00"); - assert_eq!(decimal_text("7", 0), "7"); - assert_eq!(decimal_text("1", -3), "1E+3"); - assert_eq!(decimal_text("-12", -3), "-1.2E+4"); - assert_eq!(decimal_text("1", 10), "1E-10"); - let d = CqlDecimal::from_signed_be_bytes_and_exponent(vec![0x30, 0x39], 2); - assert_eq!(literal(&CqlValue::Decimal(d)), "123.45"); - } - - #[test] - fn floats_round_trip() { - assert_eq!(literal(&CqlValue::Double(0.1)), "0.1"); - assert_eq!(literal(&CqlValue::Float(0.1)), "0.1"); - assert_eq!(literal(&CqlValue::Double(1.0)), "1"); - assert_eq!(literal(&CqlValue::Double(f64::NAN)), "NaN"); - assert_eq!(literal(&CqlValue::Double(f64::INFINITY)), "Infinity"); - assert_eq!(literal(&CqlValue::Double(f64::NEG_INFINITY)), "-Infinity"); - assert_eq!(literal(&CqlValue::Double(1.5e300)), "1.5e300"); - assert_eq!(literal(&CqlValue::Double(1e-7)), "1e-7"); - assert_eq!(literal(&CqlValue::Double(0.0)), "0"); - } - - #[test] - fn temporal_values() { - assert_eq!( - cell(&Some(CqlValue::Timestamp(CqlTimestamp(0)))).unwrap(), - "1970-01-01 00:00:00.000+0000" - ); - assert_eq!( - timestamp_text(1_714_979_289_123), - "2024-05-06 07:08:09.123+0000" - ); - assert_eq!(timestamp_text(-1), "1969-12-31 23:59:59.999+0000"); - assert_eq!(date_text(0), "1970-01-01"); - assert_eq!(date_text(19_849), "2024-05-06"); - assert_eq!( - cell(&Some(CqlValue::Date(CqlDate(1 << 31)))).unwrap(), - "1970-01-01" - ); - assert_eq!( - cell(&Some(CqlValue::Time(CqlTime(25_689_123_456_789)))).unwrap(), - "07:08:09.123456789" - ); - assert_eq!( - literal(&CqlValue::Timestamp(CqlTimestamp(0))), - "'1970-01-01 00:00:00.000+0000'" - ); - } - - #[test] - fn durations_read_back() { - assert_eq!(duration_text(0, 0, 0), "0s"); - assert_eq!( - duration_text(14, 3, 14_706_007_008_009), - "1y2mo3d4h5m6s7ms8us9ns" - ); - assert_eq!(duration_text(-1, -2, -3_000_000_000), "-1mo2d3s"); - assert_eq!( - literal(&CqlValue::Duration(CqlDuration { - months: 1, - days: 0, - nanoseconds: 0 - })), - "1mo" - ); - } - - #[test] - fn scalars() { - assert_eq!(cell(&None), None); - assert_eq!(cell(&Some(text("it's"))).unwrap(), "it's"); - assert_eq!(literal(&text("it's")), "'it''s'"); - assert_eq!(cell(&Some(CqlValue::Boolean(true))).unwrap(), "true"); - assert_eq!(cell(&Some(CqlValue::Counter(Counter(-4)))).unwrap(), "-4"); - assert_eq!(cell(&Some(CqlValue::Blob(vec![0, 255]))).unwrap(), "0x00ff"); - assert_eq!(cell(&Some(CqlValue::Blob(vec![]))).unwrap(), "0x"); - assert_eq!( - cell(&Some(CqlValue::Inet("127.0.0.1".parse().unwrap()))).unwrap(), - "127.0.0.1" - ); - assert_eq!(literal(&CqlValue::Inet("::1".parse().unwrap())), "'::1'"); - let id = uuid::Uuid::parse_str("123e4567-e89b-12d3-a456-426614174000").unwrap(); - assert_eq!( - cell(&Some(CqlValue::Uuid(id))).unwrap(), - "123e4567-e89b-12d3-a456-426614174000" - ); - assert_eq!( - cell(&Some(CqlValue::Timeuuid(CqlTimeuuid::from(id)))).unwrap(), - "123e4567-e89b-12d3-a456-426614174000" - ); - } - - #[test] - fn composites_are_cql_literals() { - let list = CqlValue::List(vec![CqlValue::Int(1), CqlValue::Int(2)]); - assert_eq!(cell(&Some(list)).unwrap(), "[1, 2]"); - let set = CqlValue::Set(vec![text("a"), text("b'")]); - assert_eq!(cell(&Some(set)).unwrap(), "{'a', 'b'''}"); - let map = CqlValue::Map(vec![(text("a"), CqlValue::Int(1))]); - assert_eq!(cell(&Some(map)).unwrap(), "{'a': 1}"); - let tuple = CqlValue::Tuple(vec![Some(CqlValue::Int(1)), Some(text("x")), None]); - assert_eq!(cell(&Some(tuple)).unwrap(), "(1, 'x', null)"); - let udt = CqlValue::UserDefinedType { - keyspace: "ks".into(), - name: "address".into(), - fields: vec![ - ("street".into(), Some(text("Main"))), - ("Zip".into(), Some(CqlValue::Int(12345))), - ("floor".into(), None), - ], - }; - assert_eq!( - cell(&Some(udt)).unwrap(), - "{street: 'Main', \"Zip\": 12345, floor: null}" - ); - let vector = CqlValue::Vector(vec![CqlValue::Float(0.5), CqlValue::Float(1.5)]); - assert_eq!(cell(&Some(vector)).unwrap(), "[0.5, 1.5]"); - let nested = CqlValue::Map(vec![( - text("k"), - CqlValue::List(vec![CqlValue::Blob(vec![1])]), - )]); - assert_eq!(literal(&nested), "{'k': [0x01]}"); - } - - #[test] - fn blob_preview_is_cut() { - let bytes = vec![0xab; 10]; - assert_eq!(blob(&bytes, 4), "0xabababab… (10 bytes)"); - assert_eq!(blob(&bytes, usize::MAX).len(), 22); - } - - #[test] - fn literals_follow_the_column_type() { - assert_eq!(cql_literal("int", Some("42")), "42"); - assert_eq!( - cql_literal("varint", Some("-12345678901234567890")), - "-12345678901234567890" - ); - assert_eq!(cql_literal("double", Some("NaN")), "NaN"); - assert_eq!(cql_literal("decimal", Some("1.50")), "1.50"); - assert_eq!(cql_literal("boolean", Some("TRUE")), "true"); - assert_eq!(cql_literal("text", Some("it's")), "'it''s'"); - assert_eq!(cql_literal("ascii", Some("x")), "'x'"); - assert_eq!( - cql_literal("timestamp", Some("2024-05-06 07:08:09.123+0000")), - "'2024-05-06 07:08:09.123+0000'" - ); - assert_eq!(cql_literal("date", Some("2024-05-06")), "'2024-05-06'"); - assert_eq!(cql_literal("time", Some("07:08:09")), "'07:08:09'"); - assert_eq!(cql_literal("inet", Some("::1")), "'::1'"); - assert_eq!( - cql_literal("uuid", Some("123e4567-e89b-12d3-a456-426614174000")), - "123e4567-e89b-12d3-a456-426614174000" - ); - assert_eq!(cql_literal("blob", Some("0x00ff")), "0x00ff"); - assert_eq!(cql_literal("duration", Some("1mo2d")), "1mo2d"); - assert_eq!(cql_literal("int", None), "null"); - // Not a value of the type: quoted, so the server explains the error. - assert_eq!(cql_literal("int", Some("abc")), "'abc'"); - assert_eq!(cql_literal("blob", Some("xyz")), "'xyz'"); - // Collections, tuples, UDTs and vectors are literals already. - assert_eq!(cql_literal("list", Some("[1, 2]")), "[1, 2]"); - assert_eq!( - cql_literal("frozen>", Some("{'a': 1}")), - "{'a': 1}" - ); - assert_eq!(cql_literal("frozen
", Some("{zip: 1}")), "{zip: 1}"); - assert_eq!( - cql_literal("tuple", Some("(1, 'x')")), - "(1, 'x')" - ); - assert_eq!( - cql_literal("vector", Some("[0.5, 1.5]")), - "[0.5, 1.5]" - ); - assert_eq!(cql_literal("FROZEN>", Some("['a']")), "['a']"); - } - - #[test] - fn names_are_quoted_when_needed() { - assert_eq!(quote_name("users"), "users"); - assert_eq!(quote_name("user_id2"), "user_id2"); - assert_eq!(quote_name("Users"), "\"Users\""); - assert_eq!(quote_name("2fast"), "\"2fast\""); - assert_eq!(quote_name("select"), "\"select\""); - assert_eq!(quote_name("a\"b"), "\"a\"\"b\""); - assert_eq!(quote_name("with space"), "\"with space\""); - assert_eq!(quote_name(""), "\"\""); - } - - #[test] - fn type_names() { - assert_eq!(type_name(&ColumnType::Native(NativeType::Int)), "int"); - let list = ColumnType::Collection { - frozen: false, - typ: CollectionType::List(Box::new(ColumnType::Native(NativeType::Text))), - }; - assert_eq!(type_name(&list), "list"); - let map = ColumnType::Collection { - frozen: true, - typ: CollectionType::Map( - Box::new(ColumnType::Native(NativeType::Text)), - Box::new(ColumnType::Native(NativeType::Int)), - ), - }; - assert_eq!(type_name(&map), "frozen>"); - assert_eq!(column_kind(&map), ValueKind::Other); - assert_eq!( - type_name(&ColumnType::Vector { - typ: Box::new(ColumnType::Native(NativeType::Float)), - dimensions: 3 - }), - "vector" - ); - assert_eq!( - type_name(&ColumnType::Tuple(vec![ - ColumnType::Native(NativeType::Int), - ColumnType::Native(NativeType::Text) - ])), - "tuple" - ); - assert_eq!( - column_kind(&ColumnType::Native(NativeType::Varint)), - ValueKind::Number - ); - assert_eq!( - column_kind(&ColumnType::Native(NativeType::Blob)), - ValueKind::Binary - ); - assert_eq!( - column_kind(&ColumnType::Native(NativeType::Uuid)), - ValueKind::Text - ); - assert_eq!( - column_kind(&ColumnType::Native(NativeType::Timestamp)), - ValueKind::Temporal - ); - assert_eq!( - column_kind(&ColumnType::Native(NativeType::Boolean)), - ValueKind::Bool - ); - } - - #[test] - fn contact_points() { - assert_eq!(contact_point("db1", 9042), "db1:9042"); - assert_eq!(contact_point("db1:9043", 9042), "db1:9043"); - assert_eq!(contact_point("::1", 9042), "[::1]:9042"); - assert_eq!(contact_point("[::1]", 9042), "[::1]:9042"); - assert_eq!(contact_point("[::1]:9043", 9042), "[::1]:9043"); - } - - #[test] - fn syntax_error_positions() { - let sql = "SELECT *\nFROM WHERE"; - let message = "line 2:6 no viable alternative at input 'WHERE'"; - // "SELECT *" is 8 chars plus the newline, then column 6. - assert_eq!(error_position(sql, message), Some(15)); - assert_eq!(error_position("x", "line 1:0 mismatched input"), Some(0)); - assert_eq!(error_position("x", "Unknown table"), None); - } - - #[test] - fn aliases_are_found_outside_strings() { - assert!(has_alias("SELECT id AS key FROM t")); - assert!(has_alias("select id as key from t")); - assert!(!has_alias("SELECT id FROM t WHERE name = 'a as b'")); - assert!(!has_alias("SELECT \"as\", assigned FROM t -- as x\n")); - assert!(!has_alias("SELECT id FROM base")); - } - - #[test] - fn primary_keys_and_options() { - let col = |name: &str, kind: &str, position: i32, descending: bool| CatalogColumn { - name: name.into(), - type_name: "int".into(), - kind: kind.into(), - position, - descending, - }; - let columns = vec![ - col("a", "partition_key", 0, false), - col("b", "partition_key", 1, false), - col("c", "clustering", 0, true), - col("d", "regular", -1, false), - ]; - assert_eq!(primary_key(&columns), "(a, b), c"); - assert_eq!(primary_key(&columns[1..]), "b, c"); - let mut out = String::new(); - write_create( - &mut out, - "CREATE TABLE ks.t", - &columns, - &[ - "comment = ''".to_string(), - "gc_grace_seconds = 864000".to_string(), - ], - ); - assert_eq!( - out, - "CREATE TABLE ks.t (\n a int,\n b int,\n c int,\n d int,\n \ - PRIMARY KEY ((a, b), c)\n)\n WITH CLUSTERING ORDER BY (c DESC)\n \ - AND comment = ''\n AND gc_grace_seconds = 864000;\n" - ); - assert_eq!(dollar_body("return a;"), "$$return a;$$"); - assert_eq!(dollar_body("a $$ b"), "'a $$ b'"); - } - - fn target() -> EditTarget { - let col = |name: &str, ty: &str| { - Some(EditColumn { - name: name.into(), - type_name: ty.into(), - }) - }; - EditTarget { - schema: Some("My Ks".into()), - table: "items".into(), - columns: vec![ - col("id", "int"), - col("day", "date"), - col("tags", "set"), - None, - ], - key: vec![0, 1], - } - } - - #[test] - fn edits_become_cql() { - use crate::model::CellValue; - let changes = vec![ - RowChange::Update { - key: vec![Some("1".into()), Some("2024-05-06".into())], - values: vec![CellValue { - column: 2, - value: Some("{'a', 'b'}".into()), - }], - }, - RowChange::Delete { - key: vec![Some("2".into()), Some("2024-05-07".into())], - }, - RowChange::Insert { - values: vec![ - CellValue { - column: 0, - value: Some("3".into()), - }, - CellValue { - column: 1, - value: Some("2024-05-08".into()), - }, - CellValue { - column: 2, - value: None, - }, - ], - }, - ]; - let (statements, result) = plan_changes(&target(), &changes).unwrap(); - assert_eq!( - statements, - [ - "UPDATE \"My Ks\".items SET tags = {'a', 'b'} WHERE id = 1 AND day = '2024-05-06'", - "DELETE FROM \"My Ks\".items WHERE id = 2 AND day = '2024-05-07'", - "INSERT INTO \"My Ks\".items (id, day, tags) VALUES (3, '2024-05-08', null)", - ] - ); - assert_eq!((result.updated, result.deleted, result.inserted), (1, 1, 1)); - } - - #[test] - fn edits_refuse_key_changes_and_expressions() { - use crate::model::CellValue; - let key = vec![Some("1".into()), Some("2024-05-06".into())]; - let change = |column| RowChange::Update { - key: key.clone(), - values: vec![CellValue { - column, - value: Some("5".into()), - }], - }; - let err = plan_changes(&target(), &[change(0)]).unwrap_err(); - assert!(err.message.contains("primary key"), "{err}"); - let err = plan_changes(&target(), &[change(3)]).unwrap_err(); - assert!(err.message.contains("not a column"), "{err}"); - let short = RowChange::Delete { - key: vec![Some("1".into())], - }; - assert!(plan_changes(&target(), &[short]).is_err()); - let null_key = RowChange::Delete { - key: vec![Some("1".into()), None], - }; - assert!(plan_changes(&target(), &[null_key]).is_err()); - } -} diff --git a/src-tauri/src/drivers/cassandra_tests.rs b/src-tauri/src/drivers/cassandra_tests.rs deleted file mode 100644 index 5459869..0000000 --- a/src-tauri/src/drivers/cassandra_tests.rs +++ /dev/null @@ -1,705 +0,0 @@ -//! Tests of the Cassandra driver against a real server. They only run with -//! these environment variables (all but the host are optional): -//! -//! `LQ_CASSANDRA_HOST`, `LQ_CASSANDRA_PORT` (9042), `LQ_CASSANDRA_USER`, -//! `LQ_CASSANDRA_PASSWORD`, `LQ_CASSANDRA_DC` -//! -//! `cargo test --lib cassandra -- --ignored --test-threads=1` - -use std::time::Duration; - -use super::{RowSink, Session, StreamEvent}; -use crate::error::ErrorKind; -use crate::model::{ - ApplyRequest, CellValue, ConnectionProfile, Engine, ExecRequest, ExecResult, RowChange, - SslMode, ValueKind, -}; - -fn env(name: &str) -> Option { - std::env::var(name).ok().filter(|v| !v.is_empty()) -} - -async fn open() -> Option { - let host = env("LQ_CASSANDRA_HOST")?; - let profile = ConnectionProfile { - name: "test".into(), - engine: Engine::Cassandra, - host, - port: env("LQ_CASSANDRA_PORT") - .and_then(|p| p.parse().ok()) - .unwrap_or(9042), - user: env("LQ_CASSANDRA_USER").unwrap_or_default(), - datacenter: env("LQ_CASSANDRA_DC").unwrap_or_default(), - ssl_mode: SslMode::Disable, - ..Default::default() - }; - let password = env("LQ_CASSANDRA_PASSWORD"); - Some( - Session::open(&profile, password.as_deref()) - .await - .expect("connection"), - ) -} - -async fn run(s: &Session, sql: &str, max_rows: usize) -> ExecResult { - s.execute(&ExecRequest { - sql: sql.into(), - max_rows, - }) - .await - .unwrap_or_else(|e| panic!("{sql}: {e}")) -} - -async fn keyspace(s: &Session, name: &str) { - run(s, &format!("DROP KEYSPACE IF EXISTS {name}"), 0).await; - run( - s, - &format!( - "CREATE KEYSPACE {name} WITH replication = \ - {{'class': 'SimpleStrategy', 'replication_factor': 1}}" - ), - 0, - ) - .await; -} - -fn row(r: &ExecResult) -> Vec { - r.rows[0] - .iter() - .map(|v| v.clone().unwrap_or_else(|| "".into())) - .collect() -} - -fn value(column: usize, v: Option<&str>) -> CellValue { - CellValue { - column, - value: v.map(str::to_string), - } -} - -#[tokio::test] -#[ignore] -async fn cassandra_types_limits_and_errors() { - let Some(s) = open().await else { - return; - }; - assert!( - s.server_version().starts_with("Apache Cassandra "), - "{}", - s.server_version() - ); - assert!(s.tx_state().autocommit && !s.tx_state().in_transaction); - assert!(s.set_autocommit(false).await.is_err()); - assert!(s.end_transaction(true).await.is_err()); - - keyspace(&s, "lq_types").await; - run( - &s, - "CREATE TYPE lq_types.addr (street text, zip int, tags set)", - 0, - ) - .await; - run( - &s, - "CREATE TABLE lq_types.t ( - id int PRIMARY KEY, a ascii, b bigint, bl blob, bo boolean, d date, de decimal, - du double, dur duration, f float, i inet, s smallint, t text, ti time, - ts timestamp, tu timeuuid, ty tinyint, u uuid, v varint, - l list, st set, m map>>, - tp tuple, ad frozen, n int)", - 0, - ) - .await; - run( - &s, - "INSERT INTO lq_types.t (id, a, b, bl, bo, d, de, du, dur, f, i, s, t, ti, ts, tu, ty, u, v, - l, st, m, tp, ad) VALUES ( - 1, 'ascii', 9223372036854775807, 0x00ff10, true, '2024-05-06', - 12345678901234567890.123456789, 0.1, 1y2mo3d4h5m6s7ms8us9ns, 1.5, '::1', -32768, - 'it''s é', '07:08:09.123456789', '2024-05-06 07:08:09.123+0000', - 50554d6e-29bb-11e5-b345-feff819cdc9f, -128, 123e4567-e89b-12d3-a456-426614174000, - -123456789012345678901234567890, - [1, 2, 3], {'b', 'a''x'}, {'k': [1, 2]}, (7, 'x', false), - {street: 'Main', zip: 12345, tags: {'p', 'q'}})", - 0, - ) - .await; - let r = run(&s, "SELECT * FROM lq_types.t", 100).await; - let columns = r.columns.clone().unwrap(); - let by = |name: &str| columns.iter().position(|c| c.name == name).unwrap(); - let cells = row(&r); - let cell = |name: &str| cells[by(name)].as_str(); - assert_eq!(cell("a"), "ascii"); - assert_eq!(cell("b"), "9223372036854775807"); - assert_eq!(cell("bl"), "0x00ff10"); - assert_eq!(cell("bo"), "true"); - assert_eq!(cell("d"), "2024-05-06"); - assert_eq!(cell("de"), "12345678901234567890.123456789"); - assert_eq!(cell("du"), "0.1"); - assert_eq!(cell("dur"), "1y2mo3d4h5m6s7ms8us9ns"); - assert_eq!(cell("f"), "1.5"); - assert_eq!(cell("i"), "::1"); - assert_eq!(cell("s"), "-32768"); - assert_eq!(cell("t"), "it's é"); - assert_eq!(cell("ti"), "07:08:09.123456789"); - assert_eq!(cell("ts"), "2024-05-06 07:08:09.123+0000"); - assert_eq!(cell("tu"), "50554d6e-29bb-11e5-b345-feff819cdc9f"); - assert_eq!(cell("ty"), "-128"); - assert_eq!(cell("u"), "123e4567-e89b-12d3-a456-426614174000"); - assert_eq!(cell("v"), "-123456789012345678901234567890"); - assert_eq!(cell("l"), "[1, 2, 3]"); - assert_eq!(cell("st"), "{'a''x', 'b'}"); - assert_eq!(cell("m"), "{'k': [1, 2]}"); - assert_eq!(cell("tp"), "(7, 'x', false)"); - assert_eq!(cell("ad"), "{street: 'Main', zip: 12345, tags: {'p', 'q'}}"); - assert_eq!(cell("n"), ""); - let type_of = |name: &str| columns[by(name)].type_name.clone(); - assert_eq!(type_of("l"), "list"); - // Result metadata does not say which collections and UDTs are frozen. - assert_eq!(type_of("m"), "map>"); - assert_eq!(type_of("tp"), "tuple"); - assert_eq!(type_of("ad"), "addr"); - assert_eq!(type_of("v"), "varint"); - assert_eq!(columns[by("de")].kind, ValueKind::Number); - assert_eq!(columns[by("bl")].kind, ValueKind::Binary); - assert_eq!(columns[by("ts")].kind, ValueKind::Temporal); - assert_eq!(columns[by("st")].kind, ValueKind::Other); - - // Every composite cell is a literal the server reads back. - run( - &s, - &format!( - "INSERT INTO lq_types.t (id, l, st, m, tp, ad) VALUES (2, {}, {}, {}, {}, {})", - cell("l"), - cell("st"), - cell("m"), - cell("tp"), - cell("ad") - ), - 0, - ) - .await; - let again = run( - &s, - "SELECT l, st, m, tp, ad FROM lq_types.t WHERE id = 2", - 10, - ) - .await; - assert_eq!( - row(&again), - [cell("l"), cell("st"), cell("m"), cell("tp"), cell("ad")] - ); - - // Counters are not editable. - run( - &s, - "CREATE TABLE lq_types.c (id int PRIMARY KEY, n counter)", - 0, - ) - .await; - run(&s, "UPDATE lq_types.c SET n = n + 5 WHERE id = 1", 0).await; - let c = run(&s, "SELECT id, n FROM lq_types.c", 10).await; - assert_eq!(c.columns.as_ref().unwrap()[1].type_name, "counter"); - assert_eq!(row(&c), ["1", "5"]); - assert!(c.read_only_reason.as_deref().unwrap().contains("Counter")); - - // The row limit is applied by paging. - run( - &s, - "CREATE TABLE lq_types.many (id int PRIMARY KEY, v int)", - 0, - ) - .await; - for i in 0..120 { - run( - &s, - &format!("INSERT INTO lq_types.many (id, v) VALUES ({i}, {i})"), - 0, - ) - .await; - } - let r = run(&s, "SELECT id FROM lq_types.many", 10).await; - assert_eq!(r.rows.len(), 10); - assert!(r.truncated); - let r = run(&s, "SELECT id FROM lq_types.many", 120).await; - assert_eq!(r.rows.len(), 120); - assert!(!r.truncated); - let r = run(&s, "SELECT id FROM lq_types.many", 0).await; - assert_eq!(r.rows.len(), 120); - assert!(!r.truncated); - - // Statements without rows. - let r = run(&s, "INSERT INTO lq_types.many (id, v) VALUES (500, 1)", 10).await; - assert!(r.columns.is_none() && r.rows.is_empty()); - // A conditional write answers with [applied]. - let r = run( - &s, - "INSERT INTO lq_types.many (id, v) VALUES (500, 2) IF NOT EXISTS", - 10, - ) - .await; - assert_eq!(r.columns.as_ref().unwrap()[0].name, "[applied]"); - assert_eq!(r.rows[0][0].as_deref(), Some("false")); - // A batch is one statement. - run( - &s, - "BEGIN BATCH - INSERT INTO lq_types.many (id, v) VALUES (501, 1); - INSERT INTO lq_types.many (id, v) VALUES (502, 1); - APPLY BATCH", - 0, - ) - .await; - let r = run( - &s, - "SELECT count(*) FROM lq_types.many WHERE id IN (501, 502)", - 10, - ) - .await; - assert_eq!(row(&r), ["2"]); - - // Errors carry the server's code; a syntax error has a position. - let err = s - .execute(&ExecRequest { - sql: "SELECT * FROM lq_types.nope".into(), - max_rows: 10, - }) - .await - .unwrap_err(); - assert_eq!(err.kind, ErrorKind::Database); - assert_eq!(err.code.as_deref(), Some("Invalid"), "{err}"); - let err = s - .execute(&ExecRequest { - sql: "SELEC * FROM lq_types.t".into(), - max_rows: 10, - }) - .await - .unwrap_err(); - assert_eq!(err.code.as_deref(), Some("SyntaxError"), "{err}"); - assert!(err.position.is_some(), "{err}"); - - // USE sticks to the session. - run(&s, "USE lq_types", 0).await; - let r = run(&s, "SELECT count(*) FROM c", 10).await; - assert_eq!(row(&r), ["1"]); - - // Warnings of the server come back as notices (Cassandra 4.0 and later - // warn about aggregations without a partition key). - let r = run(&s, "SELECT count(*) FROM lq_types.many", 10).await; - assert_eq!(row(&r), ["123"]); - if !s.server_version().contains("Cassandra 3.") { - assert!( - r.notices - .iter() - .any(|n| n.starts_with("WARNING: ") && n.contains("partition key")), - "{:?}", - r.notices - ); - } - - // A filtering scan works. - let r = run( - &s, - "SELECT * FROM lq_types.many WHERE v = 5 ALLOW FILTERING", - 10, - ) - .await; - assert_eq!(r.rows.len(), 1); - - if s.server_version().contains("Cassandra 5") { - run( - &s, - "CREATE TABLE lq_types.vec (id int PRIMARY KEY, e vector)", - 0, - ) - .await; - run( - &s, - "INSERT INTO lq_types.vec (id, e) VALUES (1, [0.5, 1.5, -2])", - 0, - ) - .await; - let r = run(&s, "SELECT e FROM lq_types.vec", 10).await; - assert_eq!(r.columns.as_ref().unwrap()[0].type_name, "vector"); - assert_eq!(row(&r), ["[0.5, 1.5, -2]"]); - } - run(&s, "DROP KEYSPACE lq_types", 0).await; -} - -#[tokio::test] -#[ignore] -async fn cassandra_schema_ddl_and_stream() { - let Some(s) = open().await else { - return; - }; - keyspace(&s, "lq_schema").await; - run(&s, "CREATE TYPE lq_schema.addr (street text, zip int)", 0).await; - run( - &s, - "CREATE TABLE lq_schema.\"Items\" ( - tenant text, day date, seq int, \"Name\" text, tags set, home frozen, - total decimal static, - PRIMARY KEY ((tenant, day), seq) - ) WITH CLUSTERING ORDER BY (seq DESC) AND comment = 'it''s here' - AND gc_grace_seconds = 3600", - 0, - ) - .await; - run( - &s, - "CREATE INDEX lq_items_name ON lq_schema.\"Items\" (\"Name\")", - 0, - ) - .await; - // User-defined functions are off unless cassandra.yaml enables them. - let functions = s - .execute(&ExecRequest { - sql: "CREATE FUNCTION lq_schema.plus (a int, b int) CALLED ON NULL INPUT \ - RETURNS int LANGUAGE java AS 'return a + b;'" - .into(), - max_rows: 0, - }) - .await - .is_ok(); - - let schemas = s.list_schemas().await.unwrap(); - let user = schemas.iter().position(|n| n == "lq_schema").unwrap(); - let system = schemas.iter().position(|n| n == "system").unwrap(); - assert!(user < system, "user keyspaces come first: {schemas:?}"); - - let objects = s.list_objects("lq_schema").await.unwrap(); - let has = |kind: &str, name: &str| objects.iter().any(|o| o.kind == kind && o.name == name); - assert!(has("table", "Items"), "{objects:?}"); - assert!(has("type", "addr")); - assert!(has("index", "lq_items_name")); - assert!( - !functions || has("function", "plus(int, int)"), - "{objects:?}" - ); - - let columns = s.list_columns("lq_schema", "Items").await.unwrap(); - let shape: Vec<(String, String, bool)> = columns - .iter() - .map(|c| (c.name.clone(), c.key_role.clone().unwrap(), c.primary_key)) - .collect(); - assert_eq!( - shape, - [ - ("tenant".into(), "partition".into(), true), - ("day".into(), "partition".into(), true), - ("seq".into(), "clustering".into(), true), - ("total".into(), "static".into(), false), - ("Name".into(), "regular".into(), false), - ("home".into(), "regular".into(), false), - ("tags".into(), "regular".into(), false), - ] - ); - assert_eq!(columns[5].type_name, "frozen"); - assert_eq!(columns[6].type_name, "set"); - - // The table's DDL recreates it, indexes included. - let ddl = s.object_ddl("lq_schema", "Items", "table").await.unwrap(); - assert!(ddl.contains("CREATE TABLE lq_schema.\"Items\" ("), "{ddl}"); - assert!(ddl.contains("total decimal static"), "{ddl}"); - assert!(ddl.contains("PRIMARY KEY ((tenant, day), seq)"), "{ddl}"); - assert!(ddl.contains("CLUSTERING ORDER BY (seq DESC)"), "{ddl}"); - assert!(ddl.contains("comment = 'it''s here'"), "{ddl}"); - assert!(ddl.contains("CREATE INDEX lq_items_name ON"), "{ddl}"); - run(&s, "DROP TABLE lq_schema.\"Items\"", 0).await; - for statement in super::ddl_fixtures::statements(&ddl, "cassandra") { - run(&s, &statement, 0).await; - } - let again = s.list_columns("lq_schema", "Items").await.unwrap(); - assert_eq!( - serde_json::to_value(&again).unwrap(), - serde_json::to_value(&columns).unwrap() - ); - - let ddl = s.object_ddl("lq_schema", "addr", "type").await.unwrap(); - assert!(ddl.contains("CREATE TYPE lq_schema.addr ("), "{ddl}"); - let ddl = s - .object_ddl("lq_schema", "lq_items_name", "index") - .await - .unwrap(); - assert!( - ddl.starts_with("CREATE INDEX lq_items_name ON lq_schema.\"Items\""), - "{ddl}" - ); - if functions { - let ddl = s - .object_ddl("lq_schema", "plus(int, int)", "function") - .await - .unwrap(); - assert!( - ddl.contains("CREATE OR REPLACE FUNCTION lq_schema.plus (a int, b int)"), - "{ddl}" - ); - assert!(ddl.contains("$$return a + b;$$"), "{ddl}"); - run(&s, "DROP FUNCTION lq_schema.plus(int, int)", 0).await; - run(&s, &ddl, 0).await; - } - let ddl = s - .object_ddl("lq_schema", "lq_schema", "keyspace") - .await - .unwrap(); - assert!( - ddl.starts_with("CREATE KEYSPACE lq_schema WITH replication = {"), - "{ddl}" - ); - assert!(s.object_ddl("lq_schema", "x", "sequence").await.is_err()); - - // Materialized views exist only where the server enables them. - run( - &s, - "CREATE TABLE lq_schema.base (id int, day int, v text, PRIMARY KEY (id, day))", - 0, - ) - .await; - let view = s - .execute(&ExecRequest { - sql: "CREATE MATERIALIZED VIEW lq_schema.by_day AS SELECT * FROM lq_schema.base \ - WHERE day IS NOT NULL AND id IS NOT NULL PRIMARY KEY (day, id)" - .into(), - max_rows: 0, - }) - .await; - if view.is_ok() { - let objects = s.list_objects("lq_schema").await.unwrap(); - assert!(objects - .iter() - .any(|o| o.kind == "matview" && o.name == "by_day")); - let ddl = s - .object_ddl("lq_schema", "by_day", "matview") - .await - .unwrap(); - assert!( - ddl.contains("CREATE MATERIALIZED VIEW lq_schema.by_day AS"), - "{ddl}" - ); - assert!(ddl.contains("PRIMARY KEY (day, id)"), "{ddl}"); - run( - &s, - "INSERT INTO lq_schema.base (id, day, v) VALUES (1, 2, 'x')", - 0, - ) - .await; - let r = run(&s, "SELECT * FROM lq_schema.by_day", 10).await; - assert!(r.editable.is_none() && r.read_only_reason.is_some()); - } - - // Streaming reads every row, a page at a time. - for i in 0..1200 { - run( - &s, - &format!("INSERT INTO lq_schema.base (id, day, v) VALUES ({i}, 1, 'v{i}')"), - 0, - ) - .await; - } - let (tx, mut rx) = tokio::sync::mpsc::channel(4); - let sink: RowSink = tx; - let reader = tokio::spawn(async move { - let mut columns = 0; - let mut rows = 0; - while let Some(event) = rx.recv().await { - match event { - StreamEvent::Columns(c) => columns = c.len(), - StreamEvent::Rows(r) => rows += r.len(), - } - } - (columns, rows) - }); - let total = s - .stream("SELECT id, day, v FROM lq_schema.base", sink) - .await - .unwrap(); - assert_eq!(total, 1200); - assert_eq!(reader.await.unwrap(), (3, 1200)); - // A reader that goes away stops the stream. - let (tx, rx) = tokio::sync::mpsc::channel(1); - drop(rx); - let err = s - .stream("SELECT id FROM lq_schema.base", tx) - .await - .unwrap_err(); - assert_eq!(err.kind, ErrorKind::Cancelled); - - run(&s, "DROP KEYSPACE lq_schema", 0).await; -} - -#[tokio::test] -#[ignore] -async fn cassandra_result_editing() { - let Some(s) = open().await else { - return; - }; - keyspace(&s, "lq_edit").await; - run( - &s, - "CREATE TABLE lq_edit.items (tenant text, day date, seq int, name text, tags set, - PRIMARY KEY (tenant, day, seq))", - 0, - ) - .await; - run( - &s, - "INSERT INTO lq_edit.items (tenant, day, seq, name, tags) - VALUES ('a', '2024-05-06', 1, 'one', {'x'})", - 0, - ) - .await; - run( - &s, - "INSERT INTO lq_edit.items (tenant, day, seq, name, tags) - VALUES ('a', '2024-05-06', 2, 'two', null)", - 0, - ) - .await; - - let r = run( - &s, - "SELECT tenant, day, seq, name, tags FROM lq_edit.items", - 100, - ) - .await; - assert!(r.read_only_reason.is_none(), "{:?}", r.read_only_reason); - let target = r.editable.clone().expect("editable"); - assert_eq!(target.schema.as_deref(), Some("lq_edit")); - assert_eq!(target.table, "items"); - assert_eq!(target.key, [0, 1, 2]); - assert_eq!(target.columns[4].as_ref().unwrap().type_name, "set"); - - // Without the whole key, with an alias, or from system tables: read-only. - let r = run(&s, "SELECT tenant, name FROM lq_edit.items", 100).await; - assert!(r.editable.is_none()); - assert!(r.read_only_reason.unwrap().contains("primary key")); - let r = run( - &s, - "SELECT tenant, day, seq, name AS n FROM lq_edit.items", - 100, - ) - .await; - assert!(r.editable.is_none()); - let r = run(&s, "SELECT keyspace_name FROM system_schema.keyspaces", 100).await; - assert!(r.editable.is_none() && r.read_only_reason.is_some()); - - let key = |seq: &str| { - vec![ - Some("a".to_string()), - Some("2024-05-06".to_string()), - Some(seq.to_string()), - ] - }; - let changes = vec![ - RowChange::Update { - key: key("1"), - values: vec![value(3, Some("it's one")), value(4, Some("{'x', 'y'}"))], - }, - RowChange::Delete { key: key("2") }, - RowChange::Insert { - values: vec![ - value(0, Some("b")), - value(1, Some("2024-05-07")), - value(2, Some("3")), - value(3, Some("three")), - ], - }, - ]; - let saved = s - .apply_changes(&ApplyRequest { - target: target.clone(), - changes, - }) - .await - .unwrap(); - assert_eq!((saved.updated, saved.deleted, saved.inserted), (1, 1, 1)); - assert!(!saved.in_transaction); - let r = run(&s, "SELECT seq, name, tags FROM lq_edit.items", 100).await; - let mut rows: Vec> = r - .rows - .iter() - .map(|r| { - r.iter() - .map(|v| v.clone().unwrap_or_else(|| "".into())) - .collect() - }) - .collect(); - rows.sort(); - assert_eq!( - rows, - [["1", "it's one", "{'x', 'y'}"], ["3", "three", ""]] - ); - - // A batch the server refuses changes nothing. - let bad = s - .apply_changes(&ApplyRequest { - target, - changes: vec![ - RowChange::Delete { key: key("1") }, - RowChange::Delete { - key: vec![ - Some("a".into()), - Some("not a date".into()), - Some("1".into()), - ], - }, - ], - }) - .await; - assert!(bad.is_err()); - let r = run(&s, "SELECT count(*) FROM lq_edit.items", 10).await; - assert_eq!(row(&r), ["2"]); - run(&s, "DROP KEYSPACE lq_edit", 0).await; -} - -#[tokio::test] -#[ignore] -async fn cassandra_ddl_fixtures() { - let Some(s) = open().await else { - return; - }; - keyspace(&s, "lq_cql").await; - super::ddl_fixtures::check(&s, "cassandra", "lq_cql").await; - run(&s, "DROP KEYSPACE lq_cql", 0).await; -} - -#[tokio::test] -#[ignore] -async fn cassandra_cancel_stops_waiting() { - let Some(s) = open().await else { - return; - }; - let s = std::sync::Arc::new(s); - // Nothing runs: cancel is harmless. - s.cancel().await.unwrap(); - keyspace(&s, "lq_cancel").await; - run( - &s, - "CREATE TABLE lq_cancel.t (id int PRIMARY KEY, v int)", - 0, - ) - .await; - let running = { - let s = s.clone(); - tokio::spawn(async move { - // Statements in a row, so one is in flight when the cancel comes. - for i in 0..100_000 { - let sql = format!("INSERT INTO lq_cancel.t (id, v) VALUES ({i}, 1)"); - if let Err(e) = s.execute(&ExecRequest { sql, max_rows: 0 }).await { - return Some(e); - } - } - None - }) - }; - // Cancel only acts on a request in flight: keep asking until one stops. - while !running.is_finished() { - tokio::time::sleep(Duration::from_millis(50)).await; - s.cancel().await.unwrap(); - } - let err = running.await.unwrap().expect("cancelled"); - assert_eq!(err.kind, ErrorKind::Cancelled); - // The session still works. - run(&s, "SELECT count(*) FROM lq_cancel.t", 10).await; - run(&s, "DROP KEYSPACE lq_cancel", 0).await; -} diff --git a/src-tauri/src/drivers/ddl_fixtures.rs b/src-tauri/src/drivers/ddl_fixtures.rs deleted file mode 100644 index 9b3e549..0000000 --- a/src-tauri/src/drivers/ddl_fixtures.rs +++ /dev/null @@ -1,123 +0,0 @@ -//! Runs the statements the sidebar menus and the table designer write -//! (`src/lib/sql/ddl.ts`) against a real database, and checks that the DDL -//! each driver reads from its catalog (`object_ddl`) recreates the object. -//! The steps come from `src/lib/sql/ddl.fixtures.json`, which the frontend -//! tests keep in step with `ddl.ts`. - -use super::Session; -use crate::model::ExecRequest; - -const FIXTURES: &str = include_str!("../../../src/lib/sql/ddl.fixtures.json"); - -async fn run(s: &Session, sql: &str) -> crate::error::AppResult { - s.execute(&ExecRequest { - sql: sql.into(), - max_rows: 100, - }) - .await -} - -/// Statements of a DDL script: lines ending in `;` close a statement (the -/// fixtures hold no routine bodies), SQL Server batches end at `GO`. Parts -/// that are only comments are left out. -pub(crate) fn statements(ddl: &str, dialect: &str) -> Vec { - let mut out = Vec::new(); - let mut current = String::new(); - for line in ddl.lines() { - let trimmed = line.trim(); - if dialect == "sqlserver" { - if trimmed.eq_ignore_ascii_case("GO") { - out.push(std::mem::take(&mut current)); - } else { - current.push_str(line); - current.push('\n'); - } - continue; - } - current.push_str(line); - current.push('\n'); - if trimmed.ends_with(';') { - let stmt = std::mem::take(&mut current); - out.push(stmt.trim().trim_end_matches(';').to_string()); - } - } - out.push(current); - out.into_iter() - .filter(|s| { - s.lines() - .any(|l| !l.trim().is_empty() && !l.trim_start().starts_with("--")) - }) - .collect() -} - -/// `dialect` as in the frontend: `postgres`, `oracle`, `mysql`, `sqlserver` -/// or `sqlite`. `schema` replaces the fixtures' placeholder schema. -pub async fn check(s: &Session, dialect: &str, schema: &str) { - let fixtures: serde_json::Value = serde_json::from_str(FIXTURES).expect("ddl fixtures"); - let d = &fixtures["dialects"][dialect]; - let token = d["schema"].as_str().expect("schema placeholder"); - let sql_of = |v: &serde_json::Value| v.as_str().expect("sql").replace(token, schema); - let cleanup = d["cleanup"].as_array().expect("cleanup"); - for sql in cleanup { - let _ = run(s, &sql_of(sql)).await; - } - - for step in d["steps"].as_array().expect("steps") { - let label = step["label"].as_str().unwrap_or_default(); - if let Some(rt) = step.get("roundTrip") { - let name = rt["name"].as_str().expect("name"); - let kind = rt["kind"].as_str().expect("kind"); - let ddl = s - .object_ddl(schema, name, kind) - .await - .unwrap_or_else(|e| panic!("{dialect}, {label}: {e}")); - let columns = |cols: Vec| serde_json::to_value(cols).unwrap(); - let before = columns(s.list_columns(schema, name).await.expect("columns")); - let drop = sql_of(&rt["drop"]); - run(s, &drop) - .await - .unwrap_or_else(|e| panic!("{dialect}, {label}: {e}\n{drop}")); - for stmt in statements(&ddl, dialect) { - run(s, &stmt) - .await - .unwrap_or_else(|e| panic!("{dialect}, {label}: {e}\n{stmt}\n\nfrom:\n{ddl}")); - } - let after = columns(s.list_columns(schema, name).await.expect("columns")); - assert_eq!(after, before, "{dialect}, {label}:\n{ddl}"); - } else if let Some(def) = step.get("ddl") { - let name = def["name"].as_str().expect("name"); - let ddl = s - .object_ddl(schema, name, def["kind"].as_str().expect("kind")) - .await - .unwrap_or_else(|e| panic!("{dialect}, {label}: {e}")); - let wanted = def["contains"].as_str().expect("contains"); - assert!( - ddl.to_lowercase().contains(wanted), - "{dialect}, {label}: {wanted} not in\n{ddl}" - ); - } else { - let sql = sql_of(&step["sql"]); - let result = run(s, &sql) - .await - .unwrap_or_else(|e| panic!("{dialect}, {label}: {e}\n{sql}")); - if let Some(rows) = step.get("rows") { - let expected: Vec = rows - .as_array() - .expect("rows") - .iter() - .map(|v| v.as_str().unwrap_or_default().to_string()) - .collect(); - let got: Vec = result - .rows - .iter() - .map(|row| row[0].clone().unwrap_or_default()) - .collect(); - assert_eq!(got, expected, "{dialect}, {label}:\n{sql}"); - } - } - } - - for sql in cleanup { - let _ = run(s, &sql_of(sql)).await; - } -} diff --git a/src-tauri/src/drivers/integration_tests.rs b/src-tauri/src/drivers/integration_tests.rs deleted file mode 100644 index 64557e7..0000000 --- a/src-tauri/src/drivers/integration_tests.rs +++ /dev/null @@ -1,689 +0,0 @@ -//! Tests against real servers. They only run with these environment variables: -//! -//! PostgreSQL: `LQ_PG_HOST`, `LQ_PG_PORT`, `LQ_PG_USER`, `LQ_PG_PASSWORD`, `LQ_PG_DB` -//! Oracle: `LQ_ORA_HOST`, `LQ_ORA_PORT`, `LQ_ORA_SERVICE`, `LQ_ORA_USER`, `LQ_ORA_PASSWORD` -//! -//! `cargo test -- --ignored --test-threads=1` - -use super::Session; -use crate::error::ErrorKind; -use crate::model::{ConnectionProfile, Engine, ExecRequest, OracleConnectType, SslMode}; - -fn env(name: &str) -> Option { - std::env::var(name).ok().filter(|v| !v.is_empty()) -} - -fn pg_profile() -> Option<(ConnectionProfile, Option)> { - let host = env("LQ_PG_HOST")?; - Some(( - ConnectionProfile { - name: "test".into(), - engine: Engine::Postgres, - host, - port: env("LQ_PG_PORT") - .and_then(|p| p.parse().ok()) - .unwrap_or(5432), - user: env("LQ_PG_USER").unwrap_or_else(|| "postgres".into()), - database: env("LQ_PG_DB").unwrap_or_else(|| "postgres".into()), - ssl_mode: SslMode::Prefer, - ..Default::default() - }, - env("LQ_PG_PASSWORD"), - )) -} - -fn ora_profile() -> Option<(ConnectionProfile, Option)> { - let host = env("LQ_ORA_HOST")?; - Some(( - ConnectionProfile { - name: "test".into(), - engine: Engine::Oracle, - host, - port: env("LQ_ORA_PORT") - .and_then(|p| p.parse().ok()) - .unwrap_or(1521), - user: env("LQ_ORA_USER")?, - database: env("LQ_ORA_SERVICE").unwrap_or_else(|| "FREEPDB1".into()), - oracle_connect_type: OracleConnectType::Service, - ..Default::default() - }, - env("LQ_ORA_PASSWORD"), - )) -} - -fn req(sql: &str, max_rows: usize) -> ExecRequest { - ExecRequest { - sql: sql.into(), - max_rows, - } -} - -async fn one_row(s: &Session, sql: &str) -> Vec> { - let r = s - .execute(&req(sql, 10)) - .await - .unwrap_or_else(|e| panic!("{sql}: {e}")); - r.rows.into_iter().next().expect("one row") -} - -#[tokio::test] -async fn refused_connections_fail_fast() { - for engine in [ - Engine::Postgres, - Engine::Oracle, - Engine::Mysql, - Engine::Sqlserver, - ] { - let profile = ConnectionProfile { - name: "x".into(), - engine, - host: "127.0.0.1".into(), - port: 1, - user: "x".into(), - database: "x".into(), - ..Default::default() - }; - let started = std::time::Instant::now(); - let err = match Session::open(&profile, Some("x")).await { - Ok(_) => panic!("{engine:?}: connected to a closed port"), - Err(e) => e, - }; - assert_eq!(err.kind, ErrorKind::Connection, "{engine:?}: {err}"); - assert!(started.elapsed().as_secs() < 20, "{engine:?} took too long"); - } -} - -#[tokio::test] -#[ignore] -async fn postgres_types_limits_and_transactions() { - let Some((profile, pw)) = pg_profile() else { - return; - }; - let s = Session::open(&profile, pw.as_deref()) - .await - .expect("connection"); - - let row = one_row( - &s, - "SELECT 1::int2, 2::int4, 3::int8, 1.50::numeric(10,2), 'NaN'::numeric, - 12345678901234567890.123456789::numeric, 1.5::float4, 'Infinity'::float8, - true, 'texto'::text, NULL::text, '2024-02-29'::date, 'infinity'::date, - '2024-02-29 13:45:10.25'::timestamp, '1 year 2 mons 3 days 04:05:06'::interval, - '{\"a\": [1, 2]}'::jsonb, 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::uuid, - '\\xdeadbeef'::bytea, ARRAY[1, NULL, 3], ARRAY['a b', 'c'], - '[1,10)'::int4range, '192.168.0.1/24'::inet, '13:00:01'::time, - ROW(1, 'x'), 12.34::money", - ) - .await; - let v: Vec<&str> = row.iter().map(|c| c.as_deref().unwrap_or("NULL")).collect(); - assert_eq!( - v, - [ - "1", - "2", - "3", - "1.50", - "NaN", - "12345678901234567890.123456789", - "1.5", - "Infinity", - "true", - "texto", - "NULL", - "2024-02-29", - "infinity", - "2024-02-29 13:45:10.25", - "1 year 2 mons 3 days 04:05:06", - "{\"a\": [1, 2]}", - "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", - "\\xdeadbeef", - "{1,NULL,3}", - "{\"a b\",c}", - "[1,10)", - "192.168.0.1/24", - "13:00:01", - "(1,x)", - "12.34", - ] - ); - - // Row limit via portal. - let r = s - .execute(&req("SELECT g FROM generate_series(1, 1000) g", 100)) - .await - .unwrap(); - assert_eq!(r.rows.len(), 100); - assert!(r.truncated); - let r = s - .execute(&req("SELECT g FROM generate_series(1, 100) g", 100)) - .await - .unwrap(); - assert!(!r.truncated); - - // Error position. - let e = s - .execute(&req("SELECT * FROM missing_table", 10)) - .await - .unwrap_err(); - assert_eq!(e.code.as_deref(), Some("42P01")); - assert_eq!(e.position, Some(14)); - - // Server NOTICE. - let r = s - .execute(&req("DO $$ BEGIN RAISE NOTICE 'olá %', 42; END $$", 0)) - .await - .unwrap(); - assert!( - r.notices.iter().any(|n| n.contains("olá 42")), - "{:?}", - r.notices - ); - - // Manual transaction: rollback undoes, commit persists. - s.execute(&req("CREATE TEMP TABLE lq_t (id int)", 0)) - .await - .unwrap(); - s.set_autocommit(false).await.unwrap(); - let r = s - .execute(&req("INSERT INTO lq_t VALUES (1), (2)", 0)) - .await - .unwrap(); - assert_eq!(r.rows_affected, Some(2)); - assert!(r.in_transaction); - let r = s - .execute(&req("SELECT count(*) FROM lq_t", 0)) - .await - .unwrap(); - assert_eq!(r.rows[0][0].as_deref(), Some("2")); - assert!(!s.end_transaction(false).await.unwrap().in_transaction); - let r = s - .execute(&req("SELECT count(*) FROM lq_t", 0)) - .await - .unwrap(); - assert_eq!(r.rows[0][0].as_deref(), Some("0")); - s.execute(&req("INSERT INTO lq_t VALUES (3)", 0)) - .await - .unwrap(); - s.end_transaction(true).await.unwrap(); - s.set_autocommit(true).await.unwrap(); - let r = s - .execute(&req("SELECT count(*) FROM lq_t", 0)) - .await - .unwrap(); - assert_eq!(r.rows[0][0].as_deref(), Some("1")); - - // An error inside a manual transaction rolls back and frees the session. - s.set_autocommit(false).await.unwrap(); - s.execute(&req("INSERT INTO lq_t VALUES (4)", 0)) - .await - .unwrap(); - assert!(s.execute(&req("SELECT 1/0", 0)).await.is_err()); - assert!(!s.tx_state().in_transaction); - let r = s - .execute(&req("SELECT count(*) FROM lq_t", 0)) - .await - .unwrap(); - assert_eq!(r.rows[0][0].as_deref(), Some("1")); - s.end_transaction(false).await.unwrap(); - - // Metadata. - let schemas = s.list_schemas().await.unwrap(); - assert!(schemas.iter().any(|x| x == "pg_catalog")); - let objects = s.list_objects("pg_catalog").await.unwrap(); - assert!(objects - .iter() - .any(|o| o.name == "pg_class" && o.kind == "table")); - let cols = s.list_columns("pg_catalog", "pg_class").await.unwrap(); - assert!(cols.iter().any(|c| c.name == "oid")); -} - -#[tokio::test] -#[ignore] -async fn postgres_cancel_interrupts_query() { - let Some((profile, pw)) = pg_profile() else { - return; - }; - let s = std::sync::Arc::new( - Session::open(&profile, pw.as_deref()) - .await - .expect("connection"), - ); - let runner = { - let s = s.clone(); - tokio::spawn(async move { s.execute(&req("SELECT pg_sleep(30)", 0)).await }) - }; - tokio::time::sleep(std::time::Duration::from_millis(500)).await; - s.cancel().await.unwrap(); - let err = runner.await.unwrap().unwrap_err(); - assert_eq!(err.kind, ErrorKind::Cancelled, "{err}"); -} - -#[tokio::test] -#[ignore] -async fn oracle_types_limits_and_output() { - let Some((profile, pw)) = ora_profile() else { - return; - }; - let s = Session::open(&profile, pw.as_deref()) - .await - .expect("connection"); - - let row = one_row( - &s, - "select 1, 1.5, 12345678901234567890.123456789, cast(null as varchar2(10)), 'texto', - date '2024-02-29', timestamp '2024-02-29 13:45:10.25', - hextoraw('DEADBEEF'), interval '3' day, to_clob('clob'), binary_double_infinity - from dual;", - ) - .await; - let v: Vec<&str> = row.iter().map(|c| c.as_deref().unwrap_or("NULL")).collect(); - assert_eq!(v[0], "1"); - assert_eq!(v[1], "1.5"); - assert_eq!(v[2], "12345678901234567890.123456789"); - assert_eq!(v[3], "NULL"); - assert_eq!(v[4], "texto"); - assert_eq!(v[5], "2024-02-29 00:00:00"); - assert!(v[6].starts_with("2024-02-29 13:45:10.25"), "{}", v[6]); - assert_eq!(v[7], "DEADBEEF"); - assert_eq!(v[9], "clob"); - assert_eq!(v[10], "Inf"); - - let r = s - .execute(&req("select level from dual connect by level <= 1000", 100)) - .await - .unwrap(); - assert_eq!(r.rows.len(), 100); - assert!(r.truncated); - - let e = s - .execute(&req("select * from missing_table", 10)) - .await - .unwrap_err(); - assert_eq!(e.code.as_deref(), Some("ORA-00942")); - - let r = s - .execute(&req( - "begin dbms_output.put_line('olá'); dbms_output.put_line('mundo'); end;\n/", - 0, - )) - .await - .unwrap(); - assert_eq!(r.notices, ["olá", "mundo"]); - - let schemas = s.list_schemas().await.unwrap(); - assert!(!schemas.is_empty()); -} - -/// ERP tables (Protheus `SA1010` and the like) have hundreds of columns, many -/// of them blank in every row, so the server sends rows with repeated-column -/// bit vectors and responses that span many packets. Servers before 26ai do -/// not mark the end of a response, which makes the driver parse those -/// responses packet by packet. -#[tokio::test] -#[ignore] -async fn oracle_wide_rows_with_repeated_values() { - let Some((profile, pw)) = ora_profile() else { - return; - }; - let s = Session::open(&profile, pw.as_deref()) - .await - .expect("connection"); - const COLS: usize = 200; - const ROWS: usize = 3000; - // Column c: blank (repeated in every row), distinct per row, runs of - // seven equal values, or a number that alternates. - let expr = |c: usize| match c % 4 { - 0 => "rpad(' ', 10)".to_string(), - 1 => format!("'V' || level || '_{c}'"), - 2 => "to_char(trunc(level / 7))".to_string(), - _ => format!("mod(level, 2) * {c}"), - }; - let expected = |row: usize, c: usize| -> String { - let level = row + 1; - match c % 4 { - 0 => " ".repeat(10), - 1 => format!("V{level}_{c}"), - 2 => (level / 7).to_string(), - _ => ((level % 2) * c).to_string(), - } - }; - for (table, lob) in [("lq_wide", false), ("lq_wide_lob", true)] { - let _ = s - .execute(&req(&format!("drop table {table} purge"), 0)) - .await; - let mut ddl: Vec = (0..COLS) - .map(|c| { - let ty = if c % 4 == 3 { "number" } else { "varchar2(40)" }; - format!("c{c} {ty}") - }) - .collect(); - ddl.push("d_e_l_e_t_ varchar2(1)".into()); - ddl.push("r_e_c_n_o_ number primary key".into()); - if lob { - ddl.push("memo blob".into()); - } - s.execute(&req( - &format!("create table {table} ({})", ddl.join(", ")), - 0, - )) - .await - .unwrap(); - let cols: Vec = (0..COLS).map(|c| format!("c{c}")).collect(); - let vals: Vec = (0..COLS).map(expr).collect(); - s.execute(&req( - &format!( - "insert into {table} ({}, d_e_l_e_t_, r_e_c_n_o_) - select {}, ' ', level from dual connect by level <= {ROWS}", - cols.join(", "), - vals.join(", ") - ), - 0, - )) - .await - .unwrap(); - s.execute(&req("commit", 0)).await.unwrap(); - - let sql = format!("select * from {table} order by r_e_c_n_o_"); - // Twice: the second run reuses the cached statement without a describe. - for (limit, attempt) in [(500, 1), (500, 2), (200, 1), (0, 1)] { - let r = s - .execute(&req(&sql, limit)) - .await - .unwrap_or_else(|e| panic!("{table} limit {limit} run {attempt}: {e}")); - let n = if limit == 0 { ROWS } else { limit }; - assert_eq!(r.rows.len(), n, "{table} limit {limit}"); - for (i, row) in r.rows.iter().enumerate() { - assert_eq!(row[COLS + 1].as_deref(), Some((i + 1).to_string().as_str())); - for c in [0, 1, 2, 3, 98, 99, 101, 102, 199] { - assert_eq!( - row[c].as_deref(), - Some(expected(i, c).as_str()), - "{table} row {} column c{c}", - i + 1 - ); - } - } - } - // The session is still usable afterwards. - assert_eq!( - one_row(&s, &format!("select count(*) from {table}")).await[0].as_deref(), - Some(ROWS.to_string().as_str()) - ); - s.execute(&req(&format!("drop table {table} purge"), 0)) - .await - .unwrap(); - } -} - -/// Queries returning CLOBs run again and again in one session, through the -/// driver's statement cache. LOBs are fetched as text, which takes a define -/// round trip on the first run. ORA-01002 (fetch out of sequence) followed -/// when that run failed, and when the server parsed and described the query -/// again on a later run. -#[tokio::test] -#[ignore] -async fn oracle_clob_queries_run_repeatedly() { - let Some((profile, pw)) = ora_profile() else { - return; - }; - let s = Session::open(&profile, pw.as_deref()) - .await - .expect("connection"); - let schema = profile.user.to_uppercase(); - let _ = s.execute(&req("drop table lq_clob purge", 0)).await; - s.execute(&req( - "create table lq_clob (id number primary key, doc clob)", - 0, - )) - .await - .unwrap(); - // Values longer than 4000 characters, which no VARCHAR2 define can hold. - s.execute(&req( - "insert into lq_clob - select level, to_clob(rpad('a', 4000, 'a')) || rpad('b', 4000, 'b') || level - from dual connect by level <= 3", - 0, - )) - .await - .unwrap(); - s.execute(&req("commit", 0)).await.unwrap(); - - let long_doc = |id: usize| format!("{}{}{id}", "a".repeat(4000), "b".repeat(4000)); - type Check = Box>])>; - let queries: [(&str, Check); 4] = [ - ( - "select dbms_metadata.get_ddl('TABLE', 'LQ_CLOB') from dual", - Box::new(|rows| { - assert_eq!(rows.len(), 1); - let ddl = rows[0][0].as_deref().unwrap_or_default(); - assert!( - ddl.contains("CREATE TABLE") && ddl.contains("LQ_CLOB"), - "{ddl}" - ); - }), - ), - ( - "select to_clob('LowQuery ' || level) from dual connect by level <= 3", - Box::new(|rows| { - let got: Vec<_> = rows.iter().map(|r| r[0].clone()).collect(); - let want: Vec<_> = (1..=3).map(|i| Some(format!("LowQuery {i}"))).collect(); - assert_eq!(got, want); - }), - ), - ( - "select id, doc from lq_clob order by id", - Box::new(move |rows| { - assert_eq!(rows.len(), 3); - for (i, row) in rows.iter().enumerate() { - assert_eq!(row[0].as_deref(), Some((i + 1).to_string().as_str())); - assert_eq!(row[1].as_deref(), Some(long_doc(i + 1).as_str())); - } - }), - ), - // The first row only: the cursor is left open with rows to fetch. - ( - "select doc from lq_clob order by id", - Box::new(move |rows| { - assert_eq!(rows.len(), 1); - assert_eq!(rows[0][0].as_deref(), Some(long_doc(1).as_str())); - }), - ), - ]; - // New statistics invalidate the cursors on LQ_CLOB, as statistics - // feedback does on its own: the next run parses the query again and the - // server describes its columns again, as CLOB. - let invalidate = - "begin dbms_stats.gather_table_stats(user, 'LQ_CLOB', no_invalidate => false); end;"; - for (n, (sql, check)) in queries.iter().enumerate() { - let limit = if n == 3 { 1 } else { 100 }; - for run in 1..=5 { - if run == 3 { - s.execute(&req(invalidate, 0)).await.unwrap(); - } - let r = s - .execute(&req(sql, limit)) - .await - .unwrap_or_else(|e| panic!("{sql}: run {run}: {e}")); - check(&r.rows); - } - } - // A query that fails while its LOB column is defined (ORA-01476 here), - // then succeeds once the data changes. - let _ = s.execute(&req("drop table lq_clob_flag purge", 0)).await; - s.execute(&req("create table lq_clob_flag (n number)", 0)) - .await - .unwrap(); - s.execute(&req("insert into lq_clob_flag values (0)", 0)) - .await - .unwrap(); - s.execute(&req("commit", 0)).await.unwrap(); - let flagged = "select to_clob('n=' || (select 1 / n from lq_clob_flag)) from dual"; - for run in 1..=2 { - let err = s.execute(&req(flagged, 100)).await.unwrap_err(); - assert!(err.to_string().contains("ORA-01476"), "run {run}: {err}"); - } - s.execute(&req("update lq_clob_flag set n = 1", 0)) - .await - .unwrap(); - s.execute(&req("commit", 0)).await.unwrap(); - for _ in 3..=5 { - assert_eq!(one_row(&s, flagged).await[0].as_deref(), Some("n=1")); - } - s.execute(&req("drop table lq_clob_flag purge", 0)) - .await - .unwrap(); - // Show DDL reads DBMS_METADATA with binds, five times in a row; the - // table has no comments, so one of its queries fails every time. - for run in 1..=5 { - let ddl = s - .object_ddl(&schema, "LQ_CLOB", "table") - .await - .unwrap_or_else(|e| panic!("Show DDL run {run}: {e}")); - assert!(ddl.contains("LQ_CLOB"), "{ddl}"); - } - // The session is still usable afterwards. - assert_eq!( - one_row(&s, "select count(*) from lq_clob").await[0].as_deref(), - Some("3") - ); - s.execute(&req("drop table lq_clob purge", 0)) - .await - .unwrap(); -} - -#[tokio::test] -#[ignore] -async fn oracle_connects_through_tns_alias() { - let Some((base, pw)) = ora_profile() else { - return; - }; - // A Latin-1 tnsnames.ora with a domain-qualified alias, as corporate - // files often are. - let dir = std::env::temp_dir().join(format!("lq-tns-it-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let mut file = b"# Produ\xe7\xe3o\n".to_vec(); - file.extend_from_slice( - format!( - "LQTEST.WORLD =\n (DESCRIPTION =\n (ADDRESS = (PROTOCOL = TCP)(HOST = {})(PORT = {}))\n (CONNECT_DATA = (SERVICE_NAME = {}))\n )\n", - base.host, base.port, base.database - ) - .as_bytes(), - ); - std::fs::write(dir.join("tnsnames.ora"), file).unwrap(); - std::fs::write(dir.join("sqlnet.ora"), "NAMES.DEFAULT_DOMAIN = WORLD\n").unwrap(); - - // Folder chosen in the profile. - let profile = ConnectionProfile { - oracle_connect_type: OracleConnectType::Tns, - tns_alias: "lqtest".into(), - config_dir: Some(dir.display().to_string()), - ..base.clone() - }; - let s = Session::open(&profile, pw.as_deref()) - .await - .expect("connection via folder"); - assert_eq!( - one_row(&s, "select 1 from dual").await[0].as_deref(), - Some("1") - ); - - // Automatic discovery through TNS_ADMIN. - std::env::set_var("TNS_ADMIN", &dir); - let auto = ConnectionProfile { - config_dir: None, - ..profile.clone() - }; - let s = Session::open(&auto, pw.as_deref()) - .await - .expect("connection via TNS_ADMIN"); - assert_eq!( - one_row(&s, "select 2 from dual").await[0].as_deref(), - Some("2") - ); - - // Unknown alias names the files that were searched. - let missing = ConnectionProfile { - tns_alias: "nope".into(), - ..auto - }; - let err = match Session::open(&missing, pw.as_deref()).await { - Ok(_) => panic!("unknown alias connected"), - Err(e) => e, - }; - assert!(err.message.contains("tnsnames.ora"), "{err}"); - std::env::remove_var("TNS_ADMIN"); - let _ = std::fs::remove_dir_all(&dir); -} - -#[tokio::test] -#[ignore] -async fn postgres_result_view_sql() { - let Some((profile, pw)) = pg_profile() else { - return; - }; - let s = Session::open(&profile, pw.as_deref()) - .await - .expect("connection"); - super::view_fixtures::check(&s, "postgres").await; -} - -#[tokio::test] -#[ignore] -async fn oracle_result_view_sql() { - let Some((profile, pw)) = ora_profile() else { - return; - }; - let s = Session::open(&profile, pw.as_deref()) - .await - .expect("connection"); - super::view_fixtures::check(&s, "oracle").await; -} - -#[tokio::test] -#[ignore] -async fn postgres_ddl_sql() { - let Some((profile, pw)) = pg_profile() else { - return; - }; - let s = Session::open(&profile, pw.as_deref()) - .await - .expect("connection"); - super::ddl_fixtures::check(&s, "postgres", "public").await; -} - -#[tokio::test] -#[ignore] -async fn oracle_ddl_sql() { - let Some((profile, pw)) = ora_profile() else { - return; - }; - let s = Session::open(&profile, pw.as_deref()) - .await - .expect("connection"); - let schema = profile.user.to_uppercase(); - super::ddl_fixtures::check(&s, "oracle", &schema).await; -} - -#[tokio::test] -#[ignore] -async fn postgres_export_import_round_trip() { - let Some((profile, pw)) = pg_profile() else { - return; - }; - let s = Session::open(&profile, pw.as_deref()) - .await - .expect("connection"); - crate::transfer::round_trip::check(&s, "public").await; -} - -#[tokio::test] -#[ignore] -async fn oracle_export_import_round_trip() { - let Some((profile, pw)) = ora_profile() else { - return; - }; - let s = Session::open(&profile, pw.as_deref()) - .await - .expect("connection"); - crate::transfer::round_trip::check(&s, &profile.user.to_uppercase()).await; -} diff --git a/src-tauri/src/drivers/mod.rs b/src-tauri/src/drivers/mod.rs deleted file mode 100644 index 116d61c..0000000 --- a/src-tauri/src/drivers/mod.rs +++ /dev/null @@ -1,301 +0,0 @@ -pub mod cassandra; -#[cfg(test)] -mod cassandra_tests; -#[cfg(test)] -pub(crate) mod ddl_fixtures; -#[cfg(test)] -mod integration_tests; -pub mod mysql; -pub mod oracle; -pub mod pg_value; -pub mod postgres; -pub mod redis_db; -pub mod sqlite; -pub mod sqlserver; -pub mod tns; -#[cfg(test)] -mod view_fixtures; - -use std::cell::Cell; - -use crate::error::{AppError, AppResult, ErrorKind}; -use crate::model::{ - ApplyRequest, ApplyResult, ColumnInfo, ConnectionProfile, DbColumn, DbObject, Engine, - ExecRequest, ExecResult, -}; - -/// What [`Session::stream`] sends: the columns first, then rows in batches. -#[derive(Debug)] -pub enum StreamEvent { - Columns(Vec), - Rows(Vec>>), -} - -pub type RowSink = tokio::sync::mpsc::Sender; - -/// Rows per [`StreamEvent::Rows`] batch. -pub const STREAM_BATCH: usize = 500; - -thread_local! { - static FULL_VALUES: Cell = const { Cell::new(false) }; -} - -/// Runs `f` with values formatted in full: binary values are not cut to the -/// grid's preview size. Formatting is synchronous, so a thread-local flag -/// covers it in async and blocking drivers alike. -pub fn full_values(f: impl FnOnce() -> T) -> T { - FULL_VALUES.with(|flag| { - let previous = flag.replace(true); - let out = f(); - flag.set(previous); - out - }) -} - -/// Bytes of a binary value shown as text: `preview` in the grid, all of -/// them inside [`full_values`]. -pub fn binary_limit(preview: usize) -> usize { - if FULL_VALUES.with(Cell::get) { - usize::MAX - } else { - preview - } -} - -/// The reader of a stream went away (the export was cancelled). -pub fn stream_stopped() -> AppError { - AppError::new(ErrorKind::Cancelled, "Cancelled.") -} - -#[derive(Debug, Clone, Copy, serde::Serialize)] -#[serde(rename_all = "camelCase")] -pub struct TxState { - pub autocommit: bool, - pub in_transaction: bool, -} - -/// An open connection. Each query tab has its own, so transactions do not -/// mix across tabs. -/// -/// Every driver session exposes the same surface, used through [`dispatch!`]: -/// `server_version`, `current_user` and `current_schema` fields, and -/// `tx_state`, `execute`, `cancel`, `set_autocommit`, `end_transaction`, -/// `list_schemas`, `list_objects`, `list_columns` and `object_ddl` methods with the -/// signatures used below. Rules every driver follows are in -/// docs/ARCHITECTURE.md. -#[allow( - clippy::large_enum_variant, - reason = "one per tab, created once and kept behind an Arc; boxing only adds indirection" -)] -pub enum Session { - Postgres(postgres::PgSession), - Oracle(oracle::OraSession), - /// MySQL and MariaDB share the protocol and the driver. - Mysql(mysql::MySession), - SqlServer(sqlserver::MsSession), - Sqlite(sqlite::LiteSession), - Redis(redis_db::RedisSession), - Cassandra(cassandra::CassSession), -} - -macro_rules! dispatch { - ($session:expr, $s:ident => $body:expr) => { - match $session { - Session::Postgres($s) => $body, - Session::Oracle($s) => $body, - Session::Mysql($s) => $body, - Session::SqlServer($s) => $body, - Session::Sqlite($s) => $body, - Session::Redis($s) => $body, - Session::Cassandra($s) => $body, - } - }; -} - -impl Session { - pub async fn open(profile: &ConnectionProfile, password: Option<&str>) -> AppResult { - Ok(match profile.engine { - Engine::Postgres => Session::Postgres(postgres::connect(profile, password).await?), - Engine::Oracle => Session::Oracle(oracle::connect(profile, password).await?), - Engine::Mysql | Engine::Mariadb => { - Session::Mysql(mysql::connect(profile, password).await?) - } - Engine::Sqlserver => Session::SqlServer(sqlserver::connect(profile, password).await?), - Engine::Sqlite => Session::Sqlite(sqlite::connect(profile).await?), - Engine::Redis => Session::Redis(redis_db::connect(profile, password).await?), - Engine::Cassandra => Session::Cassandra(cassandra::connect(profile, password).await?), - }) - } - - pub fn engine(&self) -> Engine { - match self { - Session::Postgres(_) => Engine::Postgres, - Session::Oracle(_) => Engine::Oracle, - Session::Mysql(s) => s.engine, - Session::SqlServer(_) => Engine::Sqlserver, - Session::Sqlite(_) => Engine::Sqlite, - Session::Redis(_) => Engine::Redis, - Session::Cassandra(_) => Engine::Cassandra, - } - } - - pub fn server_version(&self) -> &str { - dispatch!(self, s => &s.server_version) - } - - pub fn current_user(&self) -> Option { - dispatch!(self, s => s.current_user.clone()) - } - - pub fn current_schema(&self) -> Option { - dispatch!(self, s => s.current_schema.clone()) - } - - pub fn tx_state(&self) -> TxState { - dispatch!(self, s => s.tx_state()) - } - - pub async fn execute(&self, req: &ExecRequest) -> AppResult { - if req.sql.trim().is_empty() { - return Err(AppError::invalid("Nothing to execute.")); - } - dispatch!(self, s => s.execute(req).await) - } - - pub async fn cancel(&self) -> AppResult<()> { - dispatch!(self, s => s.cancel().await) - } - - pub async fn set_autocommit(&self, on: bool) -> AppResult { - dispatch!(self, s => s.set_autocommit(on).await) - } - - pub async fn end_transaction(&self, commit: bool) -> AppResult { - dispatch!(self, s => s.end_transaction(commit).await) - } - - pub async fn list_schemas(&self) -> AppResult> { - dispatch!(self, s => s.list_schemas().await) - } - - /// Applies grid edits as one unit: with autocommit on they commit - /// together or not at all; with autocommit off they join the open - /// transaction. - pub async fn apply_changes(&self, req: &ApplyRequest) -> AppResult { - if req.changes.is_empty() { - return Ok(ApplyResult { - in_transaction: self.tx_state().in_transaction, - ..Default::default() - }); - } - if req.target.key.is_empty() { - return Err(AppError::invalid( - "This result has no key to identify its rows.", - )); - } - match self { - Session::Postgres(s) => s.apply_changes(req).await, - Session::Oracle(s) => s.apply_changes(req).await, - Session::Mysql(s) => s.apply_changes(req).await, - Session::SqlServer(s) => s.apply_changes(req).await, - Session::Sqlite(s) => s.apply_changes(req).await, - Session::Redis(_) => Err(AppError::invalid( - "Redis replies cannot be edited in the grid.", - )), - Session::Cassandra(s) => s.apply_changes(req).await, - } - } - - pub async fn list_objects(&self, schema: &str) -> AppResult> { - dispatch!(self, s => s.list_objects(schema).await) - } - - pub async fn list_columns(&self, schema: &str, table: &str) -> AppResult> { - dispatch!(self, s => s.list_columns(schema, table).await) - } - - /// Runs a query and sends its rows to `sink` in batches, with values in - /// full, without keeping them in memory. Returns the number of rows. - /// Stops with a cancelled error when the receiver is dropped. - pub async fn stream(&self, sql: &str, sink: RowSink) -> AppResult { - match self { - Session::Postgres(s) => s.stream(sql, sink).await, - Session::Oracle(s) => s.stream(sql, sink).await, - Session::Mysql(s) => s.stream(sql, sink).await, - Session::SqlServer(s) => s.stream(sql, sink).await, - Session::Sqlite(s) => s.stream(sql, sink).await, - Session::Redis(_) => Err(AppError::invalid("Redis keys cannot be exported yet.")), - Session::Cassandra(s) => s.stream(sql, sink).await, - } - } - - /// The statements that create an object, read from the database's own - /// catalog. `kind` is one of the [`DbObject`] kinds. - pub async fn object_ddl(&self, schema: &str, name: &str, kind: &str) -> AppResult { - let ddl = match self { - Session::Postgres(s) => s.object_ddl(schema, name, kind).await?, - Session::Oracle(s) => s.object_ddl(schema, name, kind).await?, - Session::Mysql(s) => s.object_ddl(schema, name, kind).await?, - Session::SqlServer(s) => s.object_ddl(schema, name, kind).await?, - Session::Sqlite(s) => s.object_ddl(schema, name, kind).await?, - Session::Redis(_) => { - return Err(AppError::invalid("Redis keys have no DDL.")); - } - Session::Cassandra(s) => s.object_ddl(schema, name, kind).await?, - }; - if ddl.trim().is_empty() { - return Err(AppError::not_found(format!( - "The database returned no definition for {name}. It may be encrypted, or this user may lack the privilege to read it." - ))); - } - Ok(ddl) - } -} - -/// First words of the statement, uppercased, skipping whitespace and -/// comments. Stops at the first punctuation. -pub fn first_keywords(sql: &str, n: usize) -> Vec { - let bytes = sql.as_bytes(); - let mut i = 0; - let mut words = Vec::new(); - while i < bytes.len() && words.len() < n { - let c = bytes[i]; - if c.is_ascii_whitespace() { - i += 1; - } else if c == b'-' && bytes.get(i + 1) == Some(&b'-') { - while i < bytes.len() && bytes[i] != b'\n' { - i += 1; - } - } else if c == b'/' && bytes.get(i + 1) == Some(&b'*') { - i += 2; - while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') { - i += 1; - } - i += 2; - } else if c.is_ascii_alphabetic() || c == b'_' { - let start = i; - while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') { - i += 1; - } - words.push(sql[start..i].to_ascii_uppercase()); - } else { - break; - } - } - words -} - -#[cfg(test)] -mod tests { - use super::first_keywords; - - #[test] - fn keywords_skip_comments() { - assert_eq!( - first_keywords("-- x\n /* y */ begin transaction", 2), - ["BEGIN", "TRANSACTION"] - ); - assert_eq!(first_keywords(" select(1)", 3), ["SELECT"]); - assert!(first_keywords("", 2).is_empty()); - } -} diff --git a/src-tauri/src/drivers/mysql.rs b/src-tauri/src/drivers/mysql.rs deleted file mode 100644 index 6a24705..0000000 --- a/src-tauri/src/drivers/mysql.rs +++ /dev/null @@ -1,2926 +0,0 @@ -//! MySQL and MariaDB session over `mysql_async` (native protocol). -//! -//! - Statements run through the text protocol: the server formats every -//! value itself, so DECIMAL, DATETIME(6), zero dates and BIGINT UNSIGNED -//! arrive exactly as the server prints them. -//! - Statements that return rows run with `sql_select_limit` set to the row -//! limit + 1, so the server stops sending rows at the limit; it is restored -//! right after. -//! - The transaction state comes from the server status flags -//! (`SERVER_STATUS_IN_TRANS`, `SERVER_STATUS_AUTOCOMMIT`). -//! - Warnings are read with `SHOW WARNINGS` when the statement reports any. -//! - Cancel sends `KILL QUERY` over a separate short-lived connection. -//! - Grid editing: the result column metadata names the schema, table and -//! column behind each value (empty for expressions); the table type, column -//! types and unique keys come from `information_schema` in one round trip -//! and are cached per session. Changes run as prepared statements with text -//! parameters, which the server converts to the column type. - -use std::collections::HashMap; -use std::fmt::Write as _; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use mysql_async::consts::{ColumnFlags, ColumnType, StatusFlags}; -use mysql_async::prelude::Queryable; -use mysql_async::{Column, Conn, DriverError, IoError, Opts, OptsBuilder, SslOpts, Value}; -use parking_lot::Mutex; - -use super::{first_keywords, RowSink, StreamEvent, TxState, STREAM_BATCH}; -use crate::error::{AppError, AppResult, ErrorKind}; -use crate::model::{ - ApplyRequest, ApplyResult, CellValue, ColumnInfo, ConnectionProfile, DbColumn, DbObject, - EditColumn, EditTarget, Engine, ExecRequest, ExecResult, RowChange, SslMode, ValueKind, -}; - -const CONNECT_TIMEOUT: Duration = Duration::from_secs(15); -const BINARY_PREVIEW_BYTES: usize = 32 * 1024; -const MAX_WARNINGS: usize = 100; -/// Character set number of `binary` (BLOB, BINARY, VARBINARY). -const BINARY_CHARSET: u16 = 63; -/// `ER_QUERY_INTERRUPTED`. -const QUERY_INTERRUPTED: u16 = 1317; - -pub struct MySession { - conn: tokio::sync::Mutex, - /// Options that opened the session, reused by `cancel`. - opts: Opts, - connection_id: u32, - busy: AtomicBool, - cancel_requested: AtomicBool, - state: Mutex, - /// Catalog facts per (schema, table) for grid editing; cleared by DDL. - catalog: Mutex>>, - pub engine: Engine, - pub server_version: String, - pub current_user: Option, - pub current_schema: Option, -} - -pub async fn connect(profile: &ConnectionProfile, password: Option<&str>) -> AppResult { - // rustls has more than one crypto provider compiled in; mysql_async - // builds its TLS config with the process default. - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - - let database = profile.database.trim(); - let base = OptsBuilder::default() - .ip_or_hostname(profile.host.trim()) - .tcp_port(if profile.port == 0 { - 3306 - } else { - profile.port - }) - .user(Some(profile.user.trim())) - .pass(password) - .db_name((!database.is_empty()).then_some(database)) - .prefer_socket(false) - .tcp_keepalive(Some(Duration::from_secs(60))) - .connect_attribute("program_name", "LowQuery"); - - let (mut conn, opts) = match profile.ssl_mode { - SslMode::Disable => open(base.into()).await?, - SslMode::Prefer => match open(base.clone().ssl_opts(lenient_tls()).into()).await { - Err(Open::Failed(e)) if tls_unavailable(&e) => open(base.into()).await?, - other => other?, - }, - SslMode::Require => open(base.ssl_opts(lenient_tls()).into()).await?, - SslMode::VerifyFull => open(base.ssl_opts(strict_tls()).into()).await?, - }; - - let row: Option<(Option, Option, Option)> = conn - .query_first("SELECT VERSION(), CURRENT_USER(), DATABASE()") - .await - .map_err(connect_error)?; - let (version, current_user, current_schema) = row.unwrap_or_default(); - let flags = status(&conn).unwrap_or(StatusFlags::SERVER_STATUS_AUTOCOMMIT); - - Ok(MySession { - connection_id: conn.id(), - conn: tokio::sync::Mutex::new(conn), - opts, - busy: AtomicBool::new(false), - cancel_requested: AtomicBool::new(false), - state: Mutex::new(tx_state_from(flags)), - catalog: Mutex::new(HashMap::new()), - engine: profile.engine, - server_version: product_version(version.as_deref().unwrap_or_default()), - current_user, - current_schema, - }) -} - -enum Open { - Failed(mysql_async::Error), - TimedOut, -} - -impl From for AppError { - fn from(e: Open) -> Self { - match e { - Open::Failed(e) => connect_error(e), - Open::TimedOut => AppError::connection("Timed out connecting to the server."), - } - } -} - -async fn open(opts: Opts) -> Result<(Conn, Opts), Open> { - match tokio::time::timeout(CONNECT_TIMEOUT, Conn::new(opts.clone())).await { - Ok(Ok(conn)) => Ok((conn, opts)), - Ok(Err(e)) => Err(Open::Failed(e)), - Err(_) => Err(Open::TimedOut), - } -} - -/// `prefer` falls back to plain TCP when the server has no TLS or the -/// handshake fails, like libpq. -fn tls_unavailable(e: &mysql_async::Error) -> bool { - matches!( - e, - mysql_async::Error::Driver(DriverError::NoClientSslFlagFromServer) - | mysql_async::Error::Io(IoError::Tls(_)) - ) -} - -/// Encrypts without validating the certificate (`prefer`/`require`). -fn lenient_tls() -> SslOpts { - SslOpts::default() - .with_danger_accept_invalid_certs(true) - .with_danger_skip_domain_validation(true) -} - -/// Validates the certificate against the bundled roots and the OS store. -fn strict_tls() -> SslOpts { - let mut store = rustls::RootCertStore::empty(); - let native: Vec> = rustls_native_certs::load_native_certs() - .certs - .into_iter() - // Certificates rustls cannot parse would fail the whole connection. - .filter(|c| store.add(c.clone()).is_ok()) - .map(|c| c.to_vec()) - .collect(); - SslOpts::default().with_root_certs(native.into_iter().map(Into::into).collect()) -} - -/// `MySQL 8.4.2` or `MariaDB 11.4.2`, from `VERSION()`. -pub fn product_version(version: &str) -> String { - let v = version.trim(); - let mariadb = v.to_ascii_lowercase().contains("mariadb"); - // Old MariaDB servers prefix the version with `5.5.5-` for compatibility. - let v = if mariadb { - v.strip_prefix("5.5.5-").unwrap_or(v) - } else { - v - }; - let number = v.split('-').next().unwrap_or(v); - format!("{} {number}", if mariadb { "MariaDB" } else { "MySQL" }) -} - -fn status(conn: &Conn) -> Option { - conn.last_ok_packet().map(|ok| ok.status_flags()) -} - -fn tx_state_from(flags: StatusFlags) -> TxState { - TxState { - autocommit: flags.contains(StatusFlags::SERVER_STATUS_AUTOCOMMIT), - in_transaction: flags.contains(StatusFlags::SERVER_STATUS_IN_TRANS), - } -} - -/// Drops the trailing `;` (the UI may keep it) and whitespace. -fn prepare_sql(sql: &str) -> &str { - let mut text = sql.trim_end(); - while let Some(stripped) = text.strip_suffix(';') { - text = stripped.trim_end(); - } - text -} - -/// Statements whose top-level SELECT `sql_select_limit` applies to. -fn is_select_like(sql: &str) -> bool { - match first_keywords(sql, 1).first().map(String::as_str) { - Some(w) => matches!(w, "SELECT" | "WITH" | "TABLE" | "VALUES"), - None => skip_comments(sql).starts_with('('), - } -} - -fn skip_comments(sql: &str) -> &str { - let mut s = sql.trim_start(); - loop { - if s.starts_with("--") || s.starts_with('#') { - s = s.find('\n').map_or("", |i| &s[i + 1..]).trim_start(); - } else if let Some(rest) = s.strip_prefix("/*") { - s = rest.find("*/").map_or("", |i| &rest[i + 2..]).trim_start(); - } else { - return s; - } - } -} - -#[derive(Default)] -struct Collected { - columns: Option>, - rows: Vec>>, - truncated: bool, - affected: Option, - warnings: u16, -} - -/// Reads every result set: the first one with columns is kept (up to -/// `max_rows`), the others are drained; affected rows are summed. -async fn read_results( - conn: &mut Conn, - sql: &str, - max_rows: usize, -) -> Result { - let mut out = Collected::default(); - let mut result = conn.query_iter(sql).await?; - while let Some(columns) = result.columns() { - if columns.is_empty() { - *out.affected.get_or_insert(0) += result.affected_rows(); - out.warnings = out.warnings.max(result.warnings()); - result.next().await?; - continue; - } - let keep = out.columns.is_none(); - if keep { - out.columns = Some(columns.clone()); - } - while let Some(row) = result.next().await? { - if !keep { - continue; - } - if max_rows > 0 && out.rows.len() >= max_rows { - out.truncated = true; - continue; - } - out.rows.push( - columns - .iter() - .zip(row.unwrap()) - .map(|(c, v)| cell(c, v)) - .collect(), - ); - } - out.warnings = out.warnings.max(result.warnings()); - } - // Surfaces an error from a later result set (inside a CALL, for example). - result.drop_result().await?; - Ok(out) -} - -impl MySession { - /// Applies grid edits. With autocommit on they run in their own - /// transaction; otherwise they join the session's transaction behind a - /// savepoint, so a failure undoes only them and the transaction stays - /// open. - pub async fn apply_changes(&self, req: &ApplyRequest) -> AppResult { - // Bad input is rejected before anything runs. - let statements = req - .changes - .iter() - .enumerate() - .map(|(i, c)| build_change(&req.target, self.engine, c).map_err(|e| at_row(e, i))) - .collect::>>()?; - - let mut conn = self.conn.lock().await; - if conn.is_disconnected() { - return Err(AppError::connection( - "The connection to the server was closed.", - )); - } - let state = *self.state.lock(); - let own = state.autocommit && !state.in_transaction; - let started = Instant::now(); - self.cancel_requested.store(false, Ordering::SeqCst); - self.busy.store(true, Ordering::SeqCst); - let outcome = apply_in_transaction(&mut conn, req, self.engine, statements, own).await; - self.busy.store(false, Ordering::SeqCst); - self.refresh_state(&mut conn).await; - drop(conn); - - let mut result = outcome?; - result.elapsed_ms = started.elapsed().as_millis() as u64; - result.in_transaction = self.state.lock().in_transaction; - Ok(result) - } - - /// Editable target of a row-returning result, or why it is read-only. - /// Never fails the query: catalog errors end in a read-only reason. - async fn detect_target( - &self, - conn: &mut Conn, - sql: &str, - columns: &[Column], - ) -> Result { - if !may_be_editable(sql) { - return Err(NOT_A_TABLE.into()); - } - let origins: Vec> = columns.iter().map(origin).collect(); - let (schema, table) = single_table(&origins)?; - let info = self - .table_info(conn, &schema, &table) - .await - .map_err(|_| UNKNOWN_TABLE.to_string())?; - edit_target(schema, table, &info, &origins) - } - - /// Table type, columns and unique keys, cached per session. - async fn table_info( - &self, - conn: &mut Conn, - schema: &str, - table: &str, - ) -> Result, mysql_async::Error> { - let key = (schema.to_string(), table.to_string()); - if let Some(info) = self.catalog.lock().get(&key) { - return Ok(info.clone()); - } - let mut result = conn.query_iter(catalog_sql(schema, table)).await?; - let tables: Vec = result.collect().await?; - let columns: Vec = result.collect().await?; - let keys: Vec = result.collect().await?; - result.drop_result().await?; - let info = Arc::new(TableInfo::from_rows( - &texts(tables), - &texts(columns), - &texts(keys), - )); - self.catalog.lock().insert(key, info.clone()); - Ok(info) - } - - pub fn tx_state(&self) -> TxState { - *self.state.lock() - } - - pub async fn execute(&self, req: &ExecRequest) -> AppResult { - let mut conn = self.conn.lock().await; - if conn.is_disconnected() { - return Err(AppError::connection( - "The connection to the server was closed.", - )); - } - self.cancel_requested.store(false, Ordering::SeqCst); - self.busy.store(true, Ordering::SeqCst); - let outcome = self.run(&mut conn, req).await; - self.busy.store(false, Ordering::SeqCst); - self.refresh_state(&mut conn).await; - drop(conn); - - let mut result = outcome?; - if result.columns.is_some() && self.cancel_requested.swap(false, Ordering::SeqCst) { - // `SELECT SLEEP(n)` interrupted by KILL QUERY returns a row - // instead of an error. - let mut err = AppError::new(ErrorKind::Cancelled, "Query execution was interrupted"); - err.code = Some(format!("{QUERY_INTERRUPTED} (70100)")); - return Err(err); - } - result.in_transaction = self.state.lock().in_transaction; - Ok(result) - } - - async fn run(&self, conn: &mut Conn, req: &ExecRequest) -> AppResult { - let sql = prepare_sql(&req.sql); - let limit = req.max_rows > 0 && is_select_like(sql); - if limit { - conn.query_drop(format!( - "SET SESSION sql_select_limit = {}", - req.max_rows.saturating_add(1) - )) - .await - .map_err(map_error)?; - } - - let started = Instant::now(); - let outcome = read_results(conn, sql, req.max_rows).await; - let elapsed_ms = started.elapsed().as_millis() as u64; - - let notices = match &outcome { - Ok(c) if c.warnings > 0 => read_warnings(conn).await, - _ => Vec::new(), - }; - if limit { - let _ = conn - .query_drop("SET SESSION sql_select_limit = DEFAULT") - .await; - } - if is_ddl(sql) { - self.catalog.lock().clear(); - } - - let collected = outcome.map_err(|e| { - let mut err = map_error(e); - if err.kind == ErrorKind::Database { - err.position = error_position(sql, &err.message); - } - err - })?; - let columns = collected.columns.as_ref().map(|cols| { - cols.iter() - .map(|c| ColumnInfo { - name: c.name_str().into_owned(), - type_name: type_name(c.column_type(), c.flags(), c.character_set()), - kind: value_kind(c.column_type(), c.character_set()), - }) - .collect() - }); - let (editable, read_only_reason) = match &collected.columns { - Some(_) if self.cancel_requested.load(Ordering::SeqCst) => (None, None), - Some(cols) => match self.detect_target(conn, sql, cols).await { - Ok(target) => (Some(target), None), - Err(reason) => (None, Some(reason)), - }, - None => (None, None), - }; - Ok(ExecResult { - columns, - rows: collected.rows, - truncated: collected.truncated, - rows_affected: collected.affected, - elapsed_ms, - notices, - in_transaction: false, - editable, - read_only_reason, - }) - } - - /// Reads the transaction state from the last OK packet. After an error - /// there is none, so a no-op statement fetches fresh flags. - async fn refresh_state(&self, conn: &mut Conn) { - if status(conn).is_none() && !conn.is_disconnected() { - let _ = conn.query_drop("DO 0").await; - } - if let Some(flags) = status(conn) { - *self.state.lock() = tx_state_from(flags); - } - } - - pub async fn cancel(&self) -> AppResult<()> { - if !self.busy.load(Ordering::SeqCst) { - return Ok(()); - } - self.cancel_requested.store(true, Ordering::SeqCst); - let (mut conn, _) = open(self.opts.clone()).await?; - let killed = conn - .query_drop(format!("KILL QUERY {}", self.connection_id)) - .await - .map_err(map_error); - let _ = conn.disconnect().await; - killed - } - - pub async fn set_autocommit(&self, on: bool) -> AppResult { - // Turning autocommit on commits the open transaction (server rule). - self.control(if on { - "SET autocommit = 1" - } else { - "SET autocommit = 0" - }) - .await - } - - pub async fn end_transaction(&self, commit: bool) -> AppResult { - self.control(if commit { "COMMIT" } else { "ROLLBACK" }) - .await - } - - async fn control(&self, sql: &str) -> AppResult { - let mut conn = self.conn.lock().await; - let outcome = conn.query_drop(sql).await.map_err(map_error); - self.refresh_state(&mut conn).await; - outcome?; - Ok(*self.state.lock()) - } - - pub async fn list_schemas(&self) -> AppResult> { - let current = self - .query_rows("SELECT DATABASE()", Vec::new()) - .await? - .into_iter() - .next() - .and_then(|r| r.into_iter().next()) - .unwrap_or_default(); - let mut names: Vec = self - .query_rows( - "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA", - Vec::new(), - ) - .await? - .into_iter() - .filter_map(|r| r.into_iter().next()) - .collect(); - names.sort_by_cached_key(|n| { - let rank = if *n == current { - 0 - } else if is_system_schema(n) { - 2 - } else { - 1 - }; - (rank, n.to_lowercase()) - }); - Ok(names) - } - - pub async fn list_objects(&self, schema: &str) -> AppResult> { - let rows = self - .query_rows( - "SELECT TABLE_NAME, - CASE TABLE_TYPE WHEN 'VIEW' THEN 'view' WHEN 'SYSTEM VIEW' THEN 'view' - WHEN 'SEQUENCE' THEN 'sequence' ELSE 'table' END - FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? - UNION ALL - SELECT ROUTINE_NAME, CASE ROUTINE_TYPE WHEN 'FUNCTION' THEN 'function' - ELSE 'procedure' END - FROM information_schema.ROUTINES - WHERE ROUTINE_SCHEMA = ? AND ROUTINE_TYPE IN ('FUNCTION', 'PROCEDURE')", - vec![schema.to_string(), schema.to_string()], - ) - .await?; - let mut objects: Vec = rows - .into_iter() - .map(|mut r| DbObject { - kind: r.pop().unwrap_or_default(), - name: r.pop().unwrap_or_default(), - }) - .collect(); - objects.sort_by(|a, b| (&a.kind, &a.name).cmp(&(&b.kind, &b.name))); - Ok(objects) - } - - pub async fn list_columns(&self, schema: &str, table: &str) -> AppResult> { - let rows = self - .query_rows( - "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, - COLUMN_DEFAULT IS NULL, COLUMN_DEFAULT, EXTRA - FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? - ORDER BY ORDINAL_POSITION", - vec![schema.to_string(), table.to_string()], - ) - .await?; - let mariadb = self.engine == Engine::Mariadb; - Ok(rows - .into_iter() - .map(|r| DbColumn { - name: r[0].clone(), - type_name: r[1].clone(), - nullable: r[2] == "YES", - primary_key: r[3] == "PRI", - default_value: (r[4] == "0") - .then(|| default_expr(&r[5], &r[6], mariadb)) - .flatten(), - key_role: None, - }) - .collect()) - } - - /// Reads the rows of a query as the server sends them, in batches. - pub async fn stream(&self, sql: &str, sink: RowSink) -> AppResult { - let mut conn = self.conn.lock().await; - let mut result = conn.query_iter(sql).await.map_err(map_error)?; - let cols = result - .columns() - .filter(|c| !c.is_empty()) - .ok_or_else(|| AppError::invalid("The statement returns no rows."))?; - let info = cols - .iter() - .map(|c| ColumnInfo { - name: c.name_str().into_owned(), - type_name: type_name(c.column_type(), c.flags(), c.character_set()), - kind: value_kind(c.column_type(), c.character_set()), - }) - .collect(); - sink.send(StreamEvent::Columns(info)) - .await - .map_err(|_| super::stream_stopped())?; - let mut total = 0u64; - let mut batch = Vec::with_capacity(STREAM_BATCH); - while let Some(row) = result.next().await.map_err(map_error)? { - batch.push(super::full_values(|| { - cols.iter() - .zip(row.unwrap()) - .map(|(c, v)| cell(c, v)) - .collect::>() - })); - total += 1; - if batch.len() == STREAM_BATCH { - let full = std::mem::replace(&mut batch, Vec::with_capacity(STREAM_BATCH)); - sink.send(StreamEvent::Rows(full)) - .await - .map_err(|_| super::stream_stopped())?; - } - } - result.drop_result().await.map_err(map_error)?; - if !batch.is_empty() { - sink.send(StreamEvent::Rows(batch)) - .await - .map_err(|_| super::stream_stopped())?; - } - Ok(total) - } - - /// `SHOW CREATE` output, with routines and triggers between `DELIMITER` - /// lines so the script runs as written. - pub async fn object_ddl(&self, schema: &str, name: &str, kind: &str) -> AppResult { - let target = format!("{}.{}", quote_ident(schema), quote_ident(name)); - let (what, column) = match kind { - "table" => ("TABLE", 1), - "view" => ("VIEW", 1), - "sequence" => ("SEQUENCE", 1), - "function" => ("FUNCTION", 2), - "procedure" => ("PROCEDURE", 2), - _ => { - return Err(AppError::invalid(format!( - "LowQuery cannot script a {kind} on this server." - ))) - } - }; - let def = self - .show_create(&format!("SHOW CREATE {what} {target}"), column) - .await?; - if def.trim().is_empty() { - return Ok(def); - } - let mut out = if matches!(kind, "function" | "procedure") { - format!("DELIMITER $$\n{def}$$\nDELIMITER ;\n") - } else { - format!("{def};\n") - }; - if kind == "table" { - let triggers = self - .query_rows( - "SELECT TRIGGER_NAME FROM information_schema.TRIGGERS - WHERE EVENT_OBJECT_SCHEMA = ? AND EVENT_OBJECT_TABLE = ? - ORDER BY ACTION_ORDER, TRIGGER_NAME", - vec![schema.to_string(), name.to_string()], - ) - .await?; - if !triggers.is_empty() { - out.push_str("\nDELIMITER $$\n"); - for t in triggers { - let sql = format!( - "SHOW CREATE TRIGGER {}.{}", - quote_ident(schema), - quote_ident(&t[0]) - ); - out.push_str(&format!("{}$$\n", self.show_create(&sql, 2).await?)); - } - out.push_str("DELIMITER ;\n"); - } - } - Ok(out) - } - - /// One column of a `SHOW CREATE ...` row (text protocol: not every - /// server prepares SHOW statements). - async fn show_create(&self, sql: &str, column: usize) -> AppResult { - let mut conn = self.conn.lock().await; - let rows: Vec = conn.query(sql).await.map_err(map_error)?; - Ok(texts(rows) - .into_iter() - .next() - .and_then(|r| r.into_iter().nth(column).flatten()) - .unwrap_or_default()) - } - - /// Metadata query through a prepared statement, every value as text. - async fn query_rows(&self, sql: &str, params: Vec) -> AppResult>> { - let mut conn = self.conn.lock().await; - let rows: Vec = conn.exec(sql, params).await.map_err(map_error)?; - Ok(rows - .into_iter() - .map(|row| row.unwrap().into_iter().map(plain_text).collect()) - .collect()) - } -} - -/// `COLUMN_DEFAULT` as an SQL expression. MariaDB already writes literals -/// quoted (and a NULL default as `NULL`); MySQL writes the bare value and marks -/// expressions with `DEFAULT_GENERATED`. -fn default_expr(value: &str, extra: &str, mariadb: bool) -> Option { - if mariadb { - return (!value.eq_ignore_ascii_case("NULL")).then(|| value.to_string()); - } - if extra.to_ascii_uppercase().contains("DEFAULT_GENERATED") { - let lower = value.to_ascii_lowercase(); - let bare = ["current_timestamp", "now(", "localtime", "current_date"] - .iter() - .any(|p| lower.starts_with(p)); - return Some(if bare { - value.to_string() - } else { - format!("({value})") - }); - } - if value.starts_with("b'") { - return Some(value.to_string()); - } - Some(format!( - "'{}'", - value.replace('\\', "\\\\").replace('\'', "''") - )) -} - -fn is_system_schema(name: &str) -> bool { - matches!( - name.to_ascii_lowercase().as_str(), - "mysql" | "information_schema" | "performance_schema" | "sys" - ) -} - -fn plain_text(v: Value) -> String { - match v { - Value::NULL => String::new(), - Value::Bytes(b) => String::from_utf8_lossy(&b).into_owned(), - other => other.as_sql(true), - } -} - -/// `Level Code: Message` lines from `SHOW WARNINGS`. -async fn read_warnings(conn: &mut Conn) -> Vec { - let rows: Vec<(String, u32, String)> = conn - .query(format!("SHOW WARNINGS LIMIT {MAX_WARNINGS}")) - .await - .unwrap_or_default(); - rows.into_iter() - .map(|(level, code, message)| format!("{level} {code}: {message}")) - .collect() -} - -fn cell(col: &Column, value: Value) -> Option { - match value { - Value::NULL => None, - Value::Bytes(b) => Some(format_bytes(col.column_type(), col.character_set(), &b)), - // The text protocol only sends bytes; kept for completeness. - other => Some(other.as_sql(true)), - } -} - -/// Formats a text-protocol value. The server already printed numbers and -/// dates (zero dates included); binary strings become `0x...` and BIT a -/// number. -pub fn format_bytes(t: ColumnType, charset: u16, bytes: &[u8]) -> String { - use ColumnType::*; - match t { - MYSQL_TYPE_BIT if bytes.len() <= 8 => bytes - .iter() - .fold(0u64, |acc, b| (acc << 8) | u64::from(*b)) - .to_string(), - MYSQL_TYPE_JSON => String::from_utf8_lossy(bytes).into_owned(), - MYSQL_TYPE_VECTOR if bytes.len().is_multiple_of(4) => { - let items: Vec = bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| f32::from_le_bytes(*c).to_string()) - .collect(); - format!("[{}]", items.join(",")) - } - MYSQL_TYPE_GEOMETRY | MYSQL_TYPE_BIT | MYSQL_TYPE_VECTOR => hex(bytes), - _ if is_string_type(t) && charset == BINARY_CHARSET => hex(bytes), - _ => String::from_utf8_lossy(bytes).into_owned(), - } -} - -fn is_string_type(t: ColumnType) -> bool { - use ColumnType::*; - matches!( - t, - MYSQL_TYPE_VARCHAR - | MYSQL_TYPE_VAR_STRING - | MYSQL_TYPE_STRING - | MYSQL_TYPE_TINY_BLOB - | MYSQL_TYPE_MEDIUM_BLOB - | MYSQL_TYPE_LONG_BLOB - | MYSQL_TYPE_BLOB - ) -} - -/// `0x` + uppercase hexadecimal, the way the mysql client shows binary data. -fn hex(bytes: &[u8]) -> String { - let shown = &bytes[..bytes.len().min(super::binary_limit(BINARY_PREVIEW_BYTES))]; - let mut s = String::with_capacity(2 + shown.len() * 2); - s.push_str("0x"); - for b in shown { - let _ = write!(s, "{b:02X}"); - } - if bytes.len() > shown.len() { - let _ = write!(s, "… ({} bytes)", bytes.len()); - } - s -} - -pub fn value_kind(t: ColumnType, charset: u16) -> ValueKind { - use ColumnType::*; - match t { - MYSQL_TYPE_TINY - | MYSQL_TYPE_SHORT - | MYSQL_TYPE_INT24 - | MYSQL_TYPE_LONG - | MYSQL_TYPE_LONGLONG - | MYSQL_TYPE_DECIMAL - | MYSQL_TYPE_NEWDECIMAL - | MYSQL_TYPE_FLOAT - | MYSQL_TYPE_DOUBLE - | MYSQL_TYPE_BIT => ValueKind::Number, - MYSQL_TYPE_DATE - | MYSQL_TYPE_NEWDATE - | MYSQL_TYPE_TIME - | MYSQL_TYPE_TIME2 - | MYSQL_TYPE_DATETIME - | MYSQL_TYPE_DATETIME2 - | MYSQL_TYPE_TIMESTAMP - | MYSQL_TYPE_TIMESTAMP2 - | MYSQL_TYPE_YEAR => ValueKind::Temporal, - MYSQL_TYPE_JSON => ValueKind::Json, - MYSQL_TYPE_GEOMETRY => ValueKind::Binary, - _ if is_string_type(t) && charset == BINARY_CHARSET => ValueKind::Binary, - _ if is_string_type(t) || matches!(t, MYSQL_TYPE_ENUM | MYSQL_TYPE_SET) => ValueKind::Text, - _ => ValueKind::Other, - } -} - -/// Type name from the result metadata (`INT UNSIGNED`, `VARBINARY`...). -pub fn type_name(t: ColumnType, flags: ColumnFlags, charset: u16) -> String { - use ColumnType::*; - let binary = charset == BINARY_CHARSET; - let name = match t { - MYSQL_TYPE_DECIMAL | MYSQL_TYPE_NEWDECIMAL => "DECIMAL", - MYSQL_TYPE_TINY => "TINYINT", - MYSQL_TYPE_SHORT => "SMALLINT", - MYSQL_TYPE_INT24 => "MEDIUMINT", - MYSQL_TYPE_LONG => "INT", - MYSQL_TYPE_LONGLONG => "BIGINT", - MYSQL_TYPE_FLOAT => "FLOAT", - MYSQL_TYPE_DOUBLE => "DOUBLE", - MYSQL_TYPE_NULL => "NULL", - MYSQL_TYPE_TIMESTAMP | MYSQL_TYPE_TIMESTAMP2 => "TIMESTAMP", - MYSQL_TYPE_DATE | MYSQL_TYPE_NEWDATE => "DATE", - MYSQL_TYPE_TIME | MYSQL_TYPE_TIME2 => "TIME", - MYSQL_TYPE_DATETIME | MYSQL_TYPE_DATETIME2 => "DATETIME", - MYSQL_TYPE_YEAR => "YEAR", - MYSQL_TYPE_BIT => "BIT", - MYSQL_TYPE_JSON => "JSON", - MYSQL_TYPE_VECTOR => "VECTOR", - MYSQL_TYPE_GEOMETRY => "GEOMETRY", - MYSQL_TYPE_ENUM => "ENUM", - MYSQL_TYPE_SET => "SET", - MYSQL_TYPE_STRING if flags.contains(ColumnFlags::ENUM_FLAG) => "ENUM", - MYSQL_TYPE_STRING if flags.contains(ColumnFlags::SET_FLAG) => "SET", - MYSQL_TYPE_STRING if binary => "BINARY", - MYSQL_TYPE_STRING => "CHAR", - MYSQL_TYPE_VARCHAR | MYSQL_TYPE_VAR_STRING if binary => "VARBINARY", - MYSQL_TYPE_VARCHAR | MYSQL_TYPE_VAR_STRING => "VARCHAR", - MYSQL_TYPE_TINY_BLOB | MYSQL_TYPE_MEDIUM_BLOB | MYSQL_TYPE_LONG_BLOB | MYSQL_TYPE_BLOB - if binary => - { - "BLOB" - } - MYSQL_TYPE_TINY_BLOB | MYSQL_TYPE_MEDIUM_BLOB | MYSQL_TYPE_LONG_BLOB | MYSQL_TYPE_BLOB => { - "TEXT" - } - _ => "UNKNOWN", - }; - let numeric = matches!(value_kind(t, charset), ValueKind::Number) && t != MYSQL_TYPE_BIT; - if numeric && flags.contains(ColumnFlags::UNSIGNED_FLAG) { - format!("{name} UNSIGNED") - } else { - name.to_string() - } -} - -const NOT_A_TABLE: &str = "Read-only: only rows from a table can be edited."; -const SEVERAL_TABLES: &str = "Read-only: the result combines columns from several tables."; -const UNKNOWN_TABLE: &str = "Read-only: the table behind this result could not be read."; -const PREVIEW: &str = "This value is only a preview and cannot be saved."; -/// Savepoint that bounds grid edits inside the user's transaction. -const SAVEPOINT: &str = "lq_apply"; - -/// Statements that change the structure the editing cache describes. -fn is_ddl(sql: &str) -> bool { - matches!( - first_keywords(sql, 1).first().map(String::as_str), - Some("CREATE" | "ALTER" | "DROP" | "RENAME") - ) -} - -/// Plain queries whose metadata can name a single source table. -fn may_be_editable(sql: &str) -> bool { - is_select_like(sql) - && first_keywords(sql, 1).first().map(String::as_str) != Some("VALUES") - && !has_set_operation(sql) -} - -/// Whether the statement combines queries (`UNION`, `INTERSECT`, `EXCEPT`): -/// the column metadata does not say which query each row came from. -fn has_set_operation(sql: &str) -> bool { - let b = sql.as_bytes(); - let mut i = 0; - while i < b.len() { - let c = b[i]; - match c { - b'\'' | b'"' | b'`' => { - i += 1; - while i < b.len() && b[i] != c { - if b[i] == b'\\' && c != b'`' { - i += 1; - } - i += 1; - } - i += 1; - } - b'#' => { - while i < b.len() && b[i] != b'\n' { - i += 1; - } - } - b'-' if b.get(i + 1) == Some(&b'-') - && b.get(i + 2).is_none_or(|n| n.is_ascii_whitespace()) => - { - while i < b.len() && b[i] != b'\n' { - i += 1; - } - } - b'/' if b.get(i + 1) == Some(&b'*') => { - i += 2; - while i < b.len() && !(b[i] == b'*' && b.get(i + 1) == Some(&b'/')) { - i += 1; - } - i += 2; - } - _ if c.is_ascii_alphanumeric() || c == b'_' || c == b'$' => { - let start = i; - while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] == b'$') - { - i += 1; - } - let word = &sql[start..i]; - if ["UNION", "INTERSECT", "EXCEPT"] - .iter() - .any(|k| word.eq_ignore_ascii_case(k)) - { - return true; - } - } - _ => i += 1, - } - } - false -} - -/// Where a result column comes from, as the protocol reports it. -#[derive(Debug, Clone, PartialEq)] -struct Origin { - schema: String, - /// Table alias in the query (tells a self-join apart). - alias: String, - table: String, - column: String, -} - -/// `None` for expressions, aggregates and literals (no original table). -fn origin(c: &Column) -> Option { - if c.org_table_ref().is_empty() || c.org_name_ref().is_empty() { - return None; - } - Some(Origin { - schema: c.schema_str().into_owned(), - alias: c.table_str().into_owned(), - table: c.org_table_str().into_owned(), - column: c.org_name_str().into_owned(), - }) -} - -/// The one (schema, table) every base column of the result comes from. -fn single_table(origins: &[Option]) -> Result<(String, String), String> { - let mut found: Option<&Origin> = None; - for o in origins.iter().flatten() { - match found { - None => found = Some(o), - Some(f) if f.schema == o.schema && f.table == o.table && f.alias == o.alias => {} - Some(_) => return Err(SEVERAL_TABLES.into()), - } - } - match found { - // Derived and temporary result tables have no schema. - Some(f) if !f.schema.is_empty() => Ok((f.schema.clone(), f.table.clone())), - _ => Err(NOT_A_TABLE.into()), - } -} - -/// Catalog facts about one table. -#[derive(Debug, Default)] -struct TableInfo { - /// `BASE TABLE`, `VIEW`...; empty when the table was not found. - table_type: String, - columns: Vec, - /// Unique indexes (`PRIMARY` included) with their columns in key order; - /// `None` is an expression key part. - keys: Vec<(String, Vec>)>, -} - -#[derive(Debug)] -struct TableColumn { - name: String, - /// `COLUMN_TYPE`, as in DDL: `int unsigned`, `varbinary(16)`, `bit(5)`. - column_type: String, - nullable: bool, - generated: bool, -} - -impl TableInfo { - /// From the three result sets of [`catalog_sql`]. - fn from_rows( - tables: &[Vec>], - columns: &[Vec>], - keys: &[Vec>], - ) -> Self { - let text = |r: &[Option], i: usize| r.get(i).cloned().flatten().unwrap_or_default(); - let mut info = TableInfo { - table_type: tables.first().map(|r| text(r, 0)).unwrap_or_default(), - ..Default::default() - }; - for r in columns { - let extra = text(r, 3).to_ascii_uppercase(); - info.columns.push(TableColumn { - name: text(r, 0), - column_type: text(r, 1), - nullable: text(r, 2) == "YES", - generated: [ - "VIRTUAL GENERATED", - "STORED GENERATED", - "PERSISTENT GENERATED", - ] - .iter() - .any(|g| extra.contains(g)), - }); - } - for r in keys { - let name = text(r, 0); - let part = r.get(1).cloned().flatten(); - match info.keys.last_mut() { - Some((last, parts)) if *last == name => parts.push(part), - _ => info.keys.push((name, vec![part])), - } - } - info - } - - fn column(&self, name: &str) -> Option<&TableColumn> { - self.columns.iter().find(|c| same_column(&c.name, name)) - } -} - -/// Column names are case-insensitive in MySQL and MariaDB. -fn same_column(a: &str, b: &str) -> bool { - a == b || a.to_lowercase() == b.to_lowercase() -} - -/// Three statements in one round trip: table type, columns, unique keys. -fn catalog_sql(schema: &str, table: &str) -> String { - let filter = format!( - "TABLE_SCHEMA = {} AND TABLE_NAME = {}", - string_literal(schema), - string_literal(table) - ); - format!( - "SELECT TABLE_TYPE FROM information_schema.TABLES WHERE {filter};\n\ - SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, EXTRA FROM information_schema.COLUMNS \ - WHERE {filter} ORDER BY ORDINAL_POSITION;\n\ - SELECT INDEX_NAME, COLUMN_NAME FROM information_schema.STATISTICS \ - WHERE {filter} AND NON_UNIQUE = 0 ORDER BY INDEX_NAME, SEQ_IN_INDEX" - ) -} - -/// String literal that reads the same whatever `sql_mode` says about -/// backslashes: hexadecimal with a character set introducer. -fn string_literal(s: &str) -> String { - let mut out = String::with_capacity(12 + s.len() * 2); - out.push_str("_utf8mb4 X'"); - for b in s.as_bytes() { - let _ = write!(out, "{b:02X}"); - } - out.push('\''); - out -} - -fn texts(rows: Vec) -> Vec>> { - rows.into_iter() - .map(|row| { - row.unwrap() - .into_iter() - .map(|v| match v { - Value::NULL => None, - v => Some(plain_text(v)), - }) - .collect() - }) - .collect() -} - -/// The edit target once the source table is known: its primary key (or, -/// without one, a unique key on NOT NULL columns) must be in the result. -fn edit_target( - schema: String, - table: String, - info: &TableInfo, - origins: &[Option], -) -> Result { - // `SYSTEM VERSIONED`: MariaDB tables that keep row history. - if !matches!(info.table_type.as_str(), "BASE TABLE" | "SYSTEM VERSIONED") { - return Err(NOT_A_TABLE.into()); - } - let primary = info.keys.iter().find(|(name, _)| name == "PRIMARY"); - let candidates: Vec<&Vec>> = match primary { - Some((_, parts)) => vec![parts], - None => info - .keys - .iter() - .map(|(_, parts)| parts) - .filter(|parts| { - parts.iter().all(|p| { - p.as_deref() - .and_then(|name| info.column(name)) - .is_some_and(|c| !c.nullable) - }) - }) - .collect(), - }; - let Some(first) = candidates.first() else { - return Err(format!("Read-only: table {table} has no primary key.")); - }; - let position = |name: &str| { - origins - .iter() - .position(|o| o.as_ref().is_some_and(|o| same_column(&o.column, name))) - }; - let key = candidates.iter().find_map(|parts| { - parts - .iter() - .map(|p| p.as_deref().and_then(position)) - .collect::>>() - }); - let Some(key) = key else { - let names: Vec<&str> = first.iter().flatten().map(String::as_str).collect(); - let what = if primary.is_some() { - "primary key" - } else { - "key" - }; - return Err(format!( - "Read-only: add the {what} columns ({}) to the query to edit rows.", - names.join(", ") - )); - }; - let columns = origins - .iter() - .enumerate() - .map(|(i, o)| { - let c = info.column(&o.as_ref()?.column)?; - // Generated columns cannot be written; key columns still need - // their name for the WHERE clause. - if c.generated && !key.contains(&i) { - return None; - } - Some(EditColumn { - name: c.name.clone(), - type_name: c.column_type.clone(), - }) - }) - .collect(); - Ok(EditTarget { - schema: Some(schema), - table, - columns, - key, - }) -} - -/// How a grid value is sent for a column type (`COLUMN_TYPE`). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Conversion { - /// Text parameter; the server converts it to the column type. - Text, - /// TINYINT(1)/BOOLEAN: also accepts `true` and `false`. - Bool, - /// Binary strings and geometry, shown as `0x...`: sent as hex to UNHEX(). - Hex, - /// BIT, shown as a number: sent as an integer. - Bit, - /// VECTOR, shown as `[1.5,-2]`. - Vector, -} - -fn conversion(column_type: &str) -> Conversion { - let t = column_type.trim().to_ascii_lowercase(); - let base = t.split(['(', ' ']).next().unwrap_or_default(); - match base { - "binary" | "varbinary" | "tinyblob" | "blob" | "mediumblob" | "longblob" | "geometry" - | "point" | "linestring" | "polygon" | "multipoint" | "multilinestring" - | "multipolygon" | "geometrycollection" | "geomcollection" => Conversion::Hex, - "bit" => Conversion::Bit, - "vector" => Conversion::Vector, - "bool" | "boolean" => Conversion::Bool, - "tinyint" if t.starts_with("tinyint(1)") => Conversion::Bool, - _ => Conversion::Text, - } -} - -/// SQL for one bound value of the given conversion. -fn placeholder(conv: Conversion, engine: Engine) -> &'static str { - match conv { - Conversion::Hex => "UNHEX(?)", - Conversion::Vector if engine == Engine::Mariadb => "VEC_FromText(?)", - Conversion::Vector => "STRING_TO_VECTOR(?)", - _ => "?", - } -} - -/// Parameter for a grid value shown by [`format_bytes`]. -fn bind_value(conv: Conversion, text: &str) -> AppResult { - match conv { - Conversion::Text | Conversion::Vector => Ok(Value::Bytes(text.as_bytes().to_vec())), - Conversion::Bool => { - let t = text.trim(); - let v = if t.eq_ignore_ascii_case("true") { - "1" - } else if t.eq_ignore_ascii_case("false") { - "0" - } else { - text - }; - Ok(Value::Bytes(v.as_bytes().to_vec())) - } - Conversion::Hex => { - if text.contains("… (") { - return Err(AppError::invalid(PREVIEW)); - } - let t = text.trim(); - let digits = t - .strip_prefix("0x") - .or_else(|| t.strip_prefix("0X")) - .unwrap_or(t); - if !digits.len().is_multiple_of(2) || !digits.bytes().all(|b| b.is_ascii_hexdigit()) { - return Err(AppError::invalid( - "Binary values are written in hexadecimal, like 0x00FF.", - )); - } - Ok(Value::Bytes(digits.as_bytes().to_vec())) - } - Conversion::Bit => parse_bit(text).map(Value::UInt).ok_or_else(|| { - AppError::invalid("BIT values are written as a number, like 5, or as 0x05 or b'101'.") - }), - } -} - -/// `21`, `0x15` or `b'10101'`. -fn parse_bit(text: &str) -> Option { - let t = text.trim(); - if let Some(h) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) { - return (!h.is_empty() && h.len() <= 16) - .then(|| u64::from_str_radix(h, 16).ok()) - .flatten(); - } - if let Some(bits) = t - .strip_prefix("b'") - .or_else(|| t.strip_prefix("B'")) - .and_then(|r| r.strip_suffix('\'')) - { - return (!bits.is_empty() && bits.len() <= 64) - .then(|| u64::from_str_radix(bits, 2).ok()) - .flatten(); - } - t.parse().ok() -} - -/// Backtick-quoted identifier. -fn quote_ident(name: &str) -> String { - format!("`{}`", name.replace('`', "``")) -} - -fn table_ref(target: &EditTarget) -> String { - match target.schema.as_deref().filter(|s| !s.is_empty()) { - Some(schema) => format!("{}.{}", quote_ident(schema), quote_ident(&target.table)), - None => quote_ident(&target.table), - } -} - -fn edit_column(target: &EditTarget, index: usize) -> AppResult<&EditColumn> { - target - .columns - .get(index) - .and_then(Option::as_ref) - .ok_or_else(|| { - AppError::invalid(format!( - "Column {} of the result cannot be edited.", - index + 1 - )) - }) -} - -/// One prepared statement for a grid change. -#[derive(Debug, PartialEq)] -struct Statement { - sql: String, - params: Vec, -} - -/// Values per table column; a column given twice keeps the last value. -fn assignments<'a>( - target: &'a EditTarget, - values: &'a [CellValue], -) -> AppResult)>> { - let mut out: Vec<(&EditColumn, Option<&str>)> = Vec::new(); - for v in values { - let col = edit_column(target, v.column)?; - let value = v.value.as_deref(); - match out - .iter_mut() - .find(|(c, _)| same_column(&c.name, &col.name)) - { - Some(slot) => slot.1 = value, - None => out.push((col, value)), - } - } - Ok(out) -} - -/// ` WHERE k1 = ? AND k2 IS NULL`, with the key values in `params`. -fn push_where( - sql: &mut String, - params: &mut Vec, - target: &EditTarget, - engine: Engine, - key: &[Option], -) -> AppResult<()> { - if key.len() != target.key.len() { - return Err(AppError::invalid( - "The row key does not match the result's key columns.", - )); - } - for (n, (&index, value)) in target.key.iter().zip(key).enumerate() { - let col = edit_column(target, index)?; - sql.push_str(if n == 0 { " WHERE " } else { " AND " }); - sql.push_str("e_ident(&col.name)); - match value { - None => sql.push_str(" IS NULL"), - Some(v) => { - let conv = conversion(&col.type_name); - let _ = write!(sql, " = {}", placeholder(conv, engine)); - params.push(bind_value(conv, v)?); - } - } - } - Ok(()) -} - -/// The statement for one change; `None` when an update changes nothing. -fn build_change( - target: &EditTarget, - engine: Engine, - change: &RowChange, -) -> AppResult> { - let table = table_ref(target); - let mut params = Vec::new(); - let value = |col: &EditColumn, v: Option<&str>, params: &mut Vec| { - let conv = conversion(&col.type_name); - params.push(match v { - None => Value::NULL, - Some(v) => bind_value(conv, v)?, - }); - AppResult::Ok(placeholder(conv, engine)) - }; - let sql = match change { - RowChange::Update { key, values } => { - let set = assignments(target, values)?; - if set.is_empty() { - return Ok(None); - } - let mut sql = format!("UPDATE {table} SET "); - for (n, (col, v)) in set.into_iter().enumerate() { - if n > 0 { - sql.push_str(", "); - } - let p = value(col, v, &mut params)?; - let _ = write!(sql, "{} = {p}", quote_ident(&col.name)); - } - push_where(&mut sql, &mut params, target, engine, key)?; - sql - } - RowChange::Delete { key } => { - let mut sql = format!("DELETE FROM {table}"); - push_where(&mut sql, &mut params, target, engine, key)?; - sql - } - RowChange::Insert { values } => { - let set = assignments(target, values)?; - if set.is_empty() { - format!("INSERT INTO {table} () VALUES ()") - } else { - let mut names = Vec::new(); - let mut holders = Vec::new(); - for (col, v) in set { - names.push(quote_ident(&col.name)); - holders.push(value(col, v, &mut params)?); - } - format!( - "INSERT INTO {table} ({}) VALUES ({})", - names.join(", "), - holders.join(", ") - ) - } - } - }; - Ok(Some(Statement { sql, params })) -} - -/// Adds the 1-based row number to an error about one change. -fn at_row(mut e: AppError, index: usize) -> AppError { - if e.detail.is_none() { - e.detail = Some(format!("Row {} was not saved.", index + 1)); - } - e -} - -/// Rows an UPDATE matched, from the OK packet's info text -/// (`Rows matched: 1 Changed: 0 Warnings: 0`; translated servers keep the -/// order). Affected rows count only changed rows. -fn matched_rows(info: &str) -> Option { - let start = info.find(|c: char| c.is_ascii_digit())?; - let digits: String = info[start..] - .chars() - .take_while(char::is_ascii_digit) - .collect(); - digits.parse().ok() -} - -fn check_matched(index: usize, matched: u64) -> AppResult<()> { - let row = index + 1; - let message = match matched { - 1 => return Ok(()), - 0 => format!( - "Row {row} was not saved: 0 rows matched its key (changed or removed by someone else)." - ), - n => format!("Row {row} was not saved: {n} rows matched its key, which must match one."), - }; - Err(AppError::new(ErrorKind::Database, message)) -} - -/// Runs the changes between `START TRANSACTION` and `COMMIT` (`own`) or -/// inside a savepoint of the open transaction; any error undoes them all. -async fn apply_in_transaction( - conn: &mut Conn, - req: &ApplyRequest, - engine: Engine, - statements: Vec>, - own: bool, -) -> AppResult { - let begin = if own { - "START TRANSACTION".to_string() - } else { - format!("SAVEPOINT {SAVEPOINT}") - }; - conn.query_drop(begin).await.map_err(map_error)?; - let outcome = run_changes(conn, req, engine, statements).await; - let end = match (&outcome, own) { - (Ok(_), true) => "COMMIT".to_string(), - (Ok(_), false) => format!("RELEASE SAVEPOINT {SAVEPOINT}"), - (Err(_), true) => "ROLLBACK".to_string(), - (Err(_), false) => format!("ROLLBACK TO SAVEPOINT {SAVEPOINT}"), - }; - let ended = conn.query_drop(end).await.map_err(map_error); - let result = match outcome { - Ok(result) => result, - Err(e) => { - if !own { - let _ = conn - .query_drop(format!("RELEASE SAVEPOINT {SAVEPOINT}")) - .await; - } - return Err(e); - } - }; - if let Err(e) = ended { - if own { - let _ = conn.query_drop("ROLLBACK").await; - } - return Err(e); - } - Ok(result) -} - -async fn run_changes( - conn: &mut Conn, - req: &ApplyRequest, - engine: Engine, - statements: Vec>, -) -> AppResult { - let mut out = ApplyResult::default(); - for (i, (change, statement)) in req.changes.iter().zip(statements).enumerate() { - let Some(Statement { sql, params }) = statement else { - continue; - }; - conn.exec_drop(sql, params) - .await - .map_err(|e| at_row(map_error(e), i))?; - let affected = conn.affected_rows(); - match change { - RowChange::Insert { .. } => out.inserted += 1, - RowChange::Delete { .. } => { - check_matched(i, affected)?; - out.deleted += 1; - } - RowChange::Update { key, .. } => { - let matched = match affected { - 1 => 1, - // Unchanged values: ask how many rows the key matched. - _ => match matched_rows(&conn.info()) { - Some(n) => n, - None => count_rows(conn, &req.target, engine, key) - .await - .map_err(|e| at_row(e, i))?, - }, - }; - check_matched(i, matched)?; - out.updated += 1; - } - } - } - Ok(out) -} - -/// Rows with the given key (an UPDATE that changed nothing left it as is). -async fn count_rows( - conn: &mut Conn, - target: &EditTarget, - engine: Engine, - key: &[Option], -) -> AppResult { - let mut sql = format!("SELECT COUNT(*) FROM {}", table_ref(target)); - let mut params = Vec::new(); - push_where(&mut sql, &mut params, target, engine, key)?; - let n: Option = conn.exec_first(sql, params).await.map_err(map_error)?; - Ok(n.unwrap_or(0)) -} - -/// Position (0-based, in characters) of a syntax error, from MySQL's -/// `... near '' at line N`. The quoted text is the -/// statement from the error on, cut at 80 characters. -pub fn error_position(sql: &str, message: &str) -> Option { - let start = message.find(" near '")? + " near '".len(); - let end = message.rfind("' at line ")?; - if end < start { - return None; - } - let snippet = &message[start..end]; - let line: usize = message[end + "' at line ".len()..] - .chars() - .take_while(char::is_ascii_digit) - .collect::() - .parse() - .ok()?; - let byte = if snippet.is_empty() { - // The statement ended too early. - sql.trim_end().len() - } else if sql.ends_with(snippet) { - sql.len() - snippet.len() - } else { - let mut line_start = 0; - for _ in 1..line { - line_start += sql[line_start..].find('\n')? + 1; - } - line_start + sql[line_start..].find(snippet)? - }; - Some(sql[..byte].chars().count()) -} - -/// Errors while opening a session are connection errors (access denied is -/// 1045, or 1044 for the database; both keep their code). -fn connect_error(e: mysql_async::Error) -> AppError { - let mut err = map_error(e); - err.kind = ErrorKind::Connection; - err -} - -pub fn map_error(e: mysql_async::Error) -> AppError { - use mysql_async::Error as E; - match e { - E::Server(s) => { - let kind = if s.code == QUERY_INTERRUPTED { - ErrorKind::Cancelled - } else { - ErrorKind::Database - }; - let mut err = AppError::new(kind, s.message.trim_end()); - err.code = Some(if s.state.is_empty() { - s.code.to_string() - } else { - format!("{} ({})", s.code, s.state) - }); - err - } - E::Driver(DriverError::ConnectionClosed) => { - AppError::connection("The connection to the server was closed.") - } - E::Url(u) => AppError::invalid(u.to_string()), - E::Other(o) => AppError::new(ErrorKind::Database, o.to_string()), - other => { - let mut message = other.to_string(); - let mut source = std::error::Error::source(&other); - while let Some(s) = source { - let text = s.to_string(); - if !message.contains(&text) { - message.push_str(": "); - message.push_str(&text); - } - source = s.source(); - } - AppError::connection(message) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn column_defaults_become_sql() { - // MySQL: bare values, expressions marked DEFAULT_GENERATED. - assert_eq!(default_expr("it's", "", false).as_deref(), Some("'it''s'")); - assert_eq!(default_expr("0", "", false).as_deref(), Some("'0'")); - assert_eq!(default_expr("b'1'", "", false).as_deref(), Some("b'1'")); - assert_eq!( - default_expr("CURRENT_TIMESTAMP", "DEFAULT_GENERATED", false).as_deref(), - Some("CURRENT_TIMESTAMP") - ); - assert_eq!( - default_expr("uuid()", "DEFAULT_GENERATED", false).as_deref(), - Some("(uuid())") - ); - // MariaDB: already SQL, with NULL spelled out. - assert_eq!(default_expr("'x'", "", true).as_deref(), Some("'x'")); - assert_eq!(default_expr("NULL", "", true), None); - } - - #[test] - fn finds_syntax_error_position() { - let msg = |near: &str, line: usize| { - format!( - "You have an error in your SQL syntax; check the manual that corresponds to your \ - MySQL server version for the right syntax to use near '{near}' at line {line}" - ) - }; - let sql = "SELECT *\nFROMM lq_x"; - assert_eq!(error_position(sql, &msg("FROMM lq_x", 2)), Some(9)); - // Cut snippet: located from the reported line on. - let sql = "select 1 x,\n 2 y fromm t where a = 'é' and b = 1"; - let near = "fromm t where"; - assert_eq!(error_position(sql, &msg(near, 2)), Some(18)); - // Earlier text on the same line equal to a short suffix. - assert_eq!(error_position("select 1 +", &msg("", 1)), Some(10)); - let sql = "select 'é', 1 1"; - assert_eq!(error_position(sql, &msg("1", 1)), Some(14)); - assert_eq!( - error_position(sql, "Unknown column 'x' in 'field list'"), - None - ); - // Quotes inside the snippet. - let sql = "selec 'a' from t"; - assert_eq!(error_position(sql, &msg("selec 'a' from t", 1)), Some(0)); - } - - #[test] - fn formats_values() { - use ColumnType::*; - assert_eq!( - format_bytes(MYSQL_TYPE_BLOB, 63, &[0, 0xff, 0x10]), - "0x00FF10" - ); - assert_eq!( - format_bytes(MYSQL_TYPE_VAR_STRING, 63, b"\xca\xfe"), - "0xCAFE" - ); - assert_eq!( - format_bytes(MYSQL_TYPE_VAR_STRING, 255, "ação".as_bytes()), - "ação" - ); - assert_eq!(format_bytes(MYSQL_TYPE_BLOB, 255, b"text"), "text"); - assert_eq!(format_bytes(MYSQL_TYPE_BIT, 63, &[0x15]), "21"); - assert_eq!(format_bytes(MYSQL_TYPE_BIT, 63, &[1, 0]), "256"); - assert_eq!( - format_bytes(MYSQL_TYPE_JSON, 63, br#"{"a": 1}"#), - r#"{"a": 1}"# - ); - assert_eq!( - format_bytes(MYSQL_TYPE_NEWDECIMAL, 63, b"12345678901234567890.123456789"), - "12345678901234567890.123456789" - ); - assert_eq!( - format_bytes(MYSQL_TYPE_DATETIME, 63, b"0000-00-00 00:00:00"), - "0000-00-00 00:00:00" - ); - let mut v = 1.5f32.to_le_bytes().to_vec(); - v.extend_from_slice(&(-2f32).to_le_bytes()); - assert_eq!(format_bytes(MYSQL_TYPE_VECTOR, 63, &v), "[1.5,-2]"); - let big = vec![0u8; BINARY_PREVIEW_BYTES + 1]; - assert!(format_bytes(MYSQL_TYPE_BLOB, 63, &big) - .ends_with(&format!("… ({} bytes)", BINARY_PREVIEW_BYTES + 1))); - } - - #[test] - fn names_and_kinds() { - use ColumnType::*; - let none = ColumnFlags::empty(); - assert_eq!( - type_name(MYSQL_TYPE_LONGLONG, ColumnFlags::UNSIGNED_FLAG, 63), - "BIGINT UNSIGNED" - ); - assert_eq!(type_name(MYSQL_TYPE_VAR_STRING, none, 63), "VARBINARY"); - assert_eq!(type_name(MYSQL_TYPE_VAR_STRING, none, 255), "VARCHAR"); - assert_eq!(type_name(MYSQL_TYPE_BLOB, none, 63), "BLOB"); - assert_eq!(type_name(MYSQL_TYPE_BLOB, none, 45), "TEXT"); - assert_eq!( - type_name(MYSQL_TYPE_STRING, ColumnFlags::ENUM_FLAG, 45), - "ENUM" - ); - assert_eq!(value_kind(MYSQL_TYPE_NEWDECIMAL, 63), ValueKind::Number); - assert_eq!(value_kind(MYSQL_TYPE_DATETIME, 63), ValueKind::Temporal); - assert_eq!(value_kind(MYSQL_TYPE_JSON, 63), ValueKind::Json); - assert_eq!(value_kind(MYSQL_TYPE_BLOB, 63), ValueKind::Binary); - assert_eq!(value_kind(MYSQL_TYPE_BLOB, 255), ValueKind::Text); - } - - #[test] - fn versions_and_statement_kinds() { - assert_eq!(product_version("8.4.2"), "MySQL 8.4.2"); - assert_eq!(product_version("8.0.36-0ubuntu0.22.04.1"), "MySQL 8.0.36"); - assert_eq!(product_version("11.4.2-MariaDB-ubu2404"), "MariaDB 11.4.2"); - assert_eq!(product_version("5.5.5-10.6.12-MariaDB"), "MariaDB 10.6.12"); - assert!(is_select_like(" select 1")); - assert!(is_select_like("WITH x AS (SELECT 1) SELECT * FROM x")); - assert!(is_select_like( - "-- c\n# d\n/* e */ (SELECT 1) UNION (SELECT 2)" - )); - assert!(!is_select_like("UPDATE t SET a = 1")); - assert!(!is_select_like("CALL p()")); - assert_eq!(prepare_sql("select 1 ;\n "), "select 1"); - } - - #[test] - fn spots_set_operations_and_ddl() { - assert!(has_set_operation("select a from t union select a from u")); - assert!(has_set_operation("(SELECT 1)\nINTERSECT\n(SELECT 2)")); - assert!(!has_set_operation( - "select 'union', \"except\", `intersect` from t" - )); - assert!(!has_set_operation("select 'it\\'s union' from t")); - assert!(!has_set_operation( - "select a -- union\n, b # except\n /* intersect */ from reunion" - )); - // `1--1` is arithmetic, not a comment. - assert!(has_set_operation("select 1--1\nunion select 2")); - assert!(may_be_editable("select * from t")); - assert!(!may_be_editable("values row(1)")); - assert!(!may_be_editable("show tables")); - assert!(!may_be_editable("select 1 union select 2")); - assert!(is_ddl("alter table t add primary key (id)")); - assert!(!is_ddl("select 1")); - } - - fn o(alias: &str, table: &str, column: &str) -> Option { - Some(Origin { - schema: "db".into(), - alias: alias.into(), - table: table.into(), - column: column.into(), - }) - } - - fn rows(items: &[&[Option<&str>]]) -> Vec>> { - items - .iter() - .map(|r| r.iter().map(|v| v.map(str::to_string)).collect()) - .collect() - } - - fn info(keys: &[&[Option<&str>]]) -> TableInfo { - TableInfo::from_rows( - &rows(&[&[Some("BASE TABLE")]]), - &rows(&[ - &[Some("id"), Some("int"), Some("NO"), Some("auto_increment")], - &[Some("code"), Some("varchar(10)"), Some("NO"), Some("")], - &[Some("Name"), Some("varchar(20)"), Some("YES"), Some("")], - &[ - Some("up"), - Some("varchar(20)"), - Some("YES"), - Some("VIRTUAL GENERATED"), - ], - ]), - &rows(keys), - ) - } - - #[test] - fn finds_the_single_source_table() { - assert_eq!( - single_table(&[o("t", "t", "id"), None, o("t", "t", "name")]), - Ok(("db".into(), "t".into())) - ); - assert_eq!( - single_table(&[o("a", "t", "id"), o("b", "t", "id")]).unwrap_err(), - SEVERAL_TABLES - ); - assert_eq!( - single_table(&[o("t", "t", "id"), o("u", "u", "id")]).unwrap_err(), - SEVERAL_TABLES - ); - assert_eq!(single_table(&[None, None]).unwrap_err(), NOT_A_TABLE); - let mut derived = o("x", "x", "id"); - derived.as_mut().unwrap().schema.clear(); - assert_eq!(single_table(&[derived]).unwrap_err(), NOT_A_TABLE); - } - - #[test] - fn builds_edit_targets() { - let pk = info(&[&[Some("PRIMARY"), Some("id")]]); - let origins = [ - o("t", "t", "name"), - None, - o("t", "t", "ID"), - o("t", "t", "up"), - ]; - let t = edit_target("db".into(), "t".into(), &pk, &origins).unwrap(); - assert_eq!(t.key, [2]); - assert_eq!(t.schema.as_deref(), Some("db")); - let c = t.columns[0].as_ref().unwrap(); - assert_eq!( - (c.name.as_str(), c.type_name.as_str()), - ("Name", "varchar(20)") - ); - assert!(t.columns[1].is_none()); - assert_eq!(t.columns[2].as_ref().unwrap().name, "id"); - // Generated columns stay read-only. - assert!(t.columns[3].is_none()); - - let e = edit_target("db".into(), "t".into(), &pk, &[o("t", "t", "code")]).unwrap_err(); - assert_eq!( - e, - "Read-only: add the primary key columns (id) to the query to edit rows." - ); - - let none = info(&[]); - let e = edit_target("db".into(), "t".into(), &none, &origins).unwrap_err(); - assert_eq!(e, "Read-only: table t has no primary key."); - - // Without a primary key: unique keys on NOT NULL columns only. - let unique = info(&[ - &[Some("a_name"), Some("Name")], - &[Some("b_code"), Some("code")], - &[Some("b_code"), Some("id")], - ]); - let t = edit_target( - "db".into(), - "t".into(), - &unique, - &[o("t", "t", "id"), o("t", "t", "Name"), o("t", "t", "code")], - ) - .unwrap(); - assert_eq!(t.key, [2, 0]); - let e = edit_target("db".into(), "t".into(), &unique, &[o("t", "t", "id")]).unwrap_err(); - assert_eq!( - e, - "Read-only: add the key columns (code, id) to the query to edit rows." - ); - let nullable = info(&[&[Some("a_name"), Some("Name")]]); - let e = edit_target("db".into(), "t".into(), &nullable, &origins).unwrap_err(); - assert_eq!(e, "Read-only: table t has no primary key."); - // Expression key parts are unusable. - let functional = info(&[&[Some("f"), None]]); - assert!(edit_target("db".into(), "t".into(), &functional, &origins).is_err()); - - let mut view = info(&[&[Some("PRIMARY"), Some("id")]]); - view.table_type = "VIEW".into(); - let e = edit_target("db".into(), "t".into(), &view, &origins).unwrap_err(); - assert_eq!(e, NOT_A_TABLE); - let missing = TableInfo::default(); - assert_eq!( - edit_target("db".into(), "t".into(), &missing, &origins).unwrap_err(), - NOT_A_TABLE - ); - } - - #[test] - fn catalog_query_uses_hex_literals() { - assert_eq!(string_literal("a'b\\"), "_utf8mb4 X'6127625C'"); - assert_eq!(string_literal(""), "_utf8mb4 X''"); - let sql = catalog_sql("db", "t"); - assert_eq!(sql.matches("TABLE_SCHEMA = _utf8mb4 X'6462'").count(), 3); - assert_eq!(sql.matches(';').count(), 2); - } - - #[test] - fn converts_values() { - use Conversion::*; - assert_eq!(conversion("varbinary(16)"), Hex); - assert_eq!(conversion("LONGBLOB"), Hex); - assert_eq!(conversion("point"), Hex); - assert_eq!(conversion("bit(5)"), Bit); - assert_eq!(conversion("tinyint(1)"), Bool); - assert_eq!(conversion("tinyint(1) unsigned"), Bool); - assert_eq!(conversion("tinyint(4)"), Text); - assert_eq!(conversion("bigint unsigned"), Text); - assert_eq!(conversion("json"), Text); - assert_eq!(conversion("vector(3)"), Vector); - assert_eq!(conversion("blob_like_name"), Text); - - let bytes = |v: AppResult| match v.unwrap() { - Value::Bytes(b) => String::from_utf8(b).unwrap(), - other => panic!("{other:?}"), - }; - assert_eq!(bytes(bind_value(Hex, "0x00FF10")), "00FF10"); - assert_eq!(bytes(bind_value(Hex, "cafe")), "cafe"); - assert_eq!(bytes(bind_value(Hex, "0x")), ""); - assert_eq!(bind_value(Hex, "0x0").unwrap_err().kind, ErrorKind::Invalid); - assert_eq!( - bind_value(Hex, "0xZZ").unwrap_err().kind, - ErrorKind::Invalid - ); - let preview = format_bytes( - ColumnType::MYSQL_TYPE_BLOB, - BINARY_CHARSET, - &vec![0u8; BINARY_PREVIEW_BYTES + 1], - ); - let e = bind_value(Hex, &preview).unwrap_err(); - assert_eq!((e.kind, e.message.as_str()), (ErrorKind::Invalid, PREVIEW)); - assert_eq!(bind_value(Bit, "21").unwrap(), Value::UInt(21)); - assert_eq!(bind_value(Bit, "0x15").unwrap(), Value::UInt(21)); - assert_eq!(bind_value(Bit, "b'10101'").unwrap(), Value::UInt(21)); - assert_eq!( - bind_value(Bit, "18446744073709551615").unwrap(), - Value::UInt(u64::MAX) - ); - assert!(bind_value(Bit, "x").is_err()); - assert_eq!(bytes(bind_value(Bool, "TRUE")), "1"); - assert_eq!(bytes(bind_value(Bool, "false")), "0"); - assert_eq!(bytes(bind_value(Bool, "1")), "1"); - let text = "it's \"x\"\n\\ … (3 bytes)"; - assert_eq!(bytes(bind_value(Text, text)), text); - assert_eq!(placeholder(Hex, Engine::Mysql), "UNHEX(?)"); - assert_eq!(placeholder(Vector, Engine::Mysql), "STRING_TO_VECTOR(?)"); - assert_eq!(placeholder(Vector, Engine::Mariadb), "VEC_FromText(?)"); - assert_eq!(placeholder(Text, Engine::Mysql), "?"); - } - - fn target() -> EditTarget { - let col = |name: &str, t: &str| { - Some(EditColumn { - name: name.into(), - type_name: t.into(), - }) - }; - EditTarget { - schema: Some("my db".into()), - table: "Order`s".into(), - columns: vec![ - col("Order Id", "int"), - col("data", "blob"), - None, - col("flags", "bit(3)"), - col("k2", "varchar(5)"), - ], - key: vec![0, 4], - } - } - - fn cv(column: usize, value: Option<&str>) -> CellValue { - CellValue { - column, - value: value.map(str::to_string), - } - } - - fn text(v: &str) -> Value { - Value::Bytes(v.as_bytes().to_vec()) - } - - #[test] - fn builds_change_statements() { - let t = target(); - let key = vec![Some("7".to_string()), None]; - let s = build_change( - &t, - Engine::Mysql, - &RowChange::Update { - key: key.clone(), - values: vec![cv(1, Some("0xCAFE")), cv(3, Some("5")), cv(1, None)], - }, - ) - .unwrap() - .unwrap(); - assert_eq!( - s.sql, - "UPDATE `my db`.`Order``s` SET `data` = UNHEX(?), `flags` = ? \ - WHERE `Order Id` = ? AND `k2` IS NULL" - ); - assert_eq!(s.params, [Value::NULL, Value::UInt(5), text("7")]); - - let s = build_change(&t, Engine::Mysql, &RowChange::Delete { key: key.clone() }) - .unwrap() - .unwrap(); - assert_eq!( - s.sql, - "DELETE FROM `my db`.`Order``s` WHERE `Order Id` = ? AND `k2` IS NULL" - ); - assert_eq!(s.params, [text("7")]); - - let s = build_change( - &t, - Engine::Mysql, - &RowChange::Insert { - values: vec![cv(4, Some("a'b")), cv(1, Some("0x00"))], - }, - ) - .unwrap() - .unwrap(); - assert_eq!( - s.sql, - "INSERT INTO `my db`.`Order``s` (`k2`, `data`) VALUES (?, UNHEX(?))" - ); - assert_eq!(s.params, [text("a'b"), text("00")]); - - let s = build_change(&t, Engine::Mysql, &RowChange::Insert { values: vec![] }) - .unwrap() - .unwrap(); - assert_eq!(s.sql, "INSERT INTO `my db`.`Order``s` () VALUES ()"); - assert!(s.params.is_empty()); - - let empty = RowChange::Update { - key: key.clone(), - values: vec![], - }; - assert!(build_change(&t, Engine::Mysql, &empty).unwrap().is_none()); - - // Expression columns and malformed keys are rejected. - let e = build_change( - &t, - Engine::Mysql, - &RowChange::Update { - key: key.clone(), - values: vec![cv(2, Some("x"))], - }, - ) - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - let e = build_change( - &t, - Engine::Mysql, - &RowChange::Delete { - key: vec![Some("7".into())], - }, - ) - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - let e = build_change( - &t, - Engine::Mysql, - &RowChange::Insert { - values: vec![cv(9, Some("x"))], - }, - ) - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - } - - #[test] - fn reads_matched_rows() { - assert_eq!( - matched_rows("Rows matched: 1 Changed: 0 Warnings: 0"), - Some(1) - ); - assert_eq!( - matched_rows("Rows matched: 0 Changed: 0 Warnings: 0"), - Some(0) - ); - assert_eq!(matched_rows(""), None); - assert!(check_matched(0, 1).is_ok()); - let e = check_matched(2, 0).unwrap_err(); - assert_eq!(e.kind, ErrorKind::Database); - assert_eq!( - e.message, - "Row 3 was not saved: 0 rows matched its key (changed or removed by someone else)." - ); - assert!(check_matched(0, 2).is_err()); - } - - // Integration tests: need a server. Variables: LQ_MYSQL_HOST, - // LQ_MYSQL_PORT, LQ_MYSQL_USER, LQ_MYSQL_PASSWORD, LQ_MYSQL_DB and - // LQ_MYSQL_ENGINE ("mysql" or "mariadb"). - - fn env(name: &str) -> Option { - std::env::var(name).ok().filter(|v| !v.is_empty()) - } - - fn profile() -> Option<(ConnectionProfile, Option)> { - let host = env("LQ_MYSQL_HOST")?; - let engine = if env("LQ_MYSQL_ENGINE").as_deref() == Some("mariadb") { - Engine::Mariadb - } else { - Engine::Mysql - }; - Some(( - ConnectionProfile { - name: "test".into(), - engine, - host, - port: env("LQ_MYSQL_PORT") - .and_then(|p| p.parse().ok()) - .unwrap_or(3306), - user: env("LQ_MYSQL_USER").unwrap_or_else(|| "root".into()), - database: env("LQ_MYSQL_DB").unwrap_or_else(|| "lowquery".into()), - ssl_mode: SslMode::Prefer, - ..Default::default() - }, - env("LQ_MYSQL_PASSWORD"), - )) - } - - async fn session() -> Option { - let (profile, password) = profile()?; - Some( - connect(&profile, password.as_deref()) - .await - .expect("connect"), - ) - } - - fn req(sql: &str, max_rows: usize) -> ExecRequest { - ExecRequest { - sql: sql.into(), - max_rows, - } - } - - async fn run(s: &MySession, sql: &str) -> ExecResult { - s.execute(&req(sql, 100)) - .await - .unwrap_or_else(|e| panic!("{sql}: {e}")) - } - - #[tokio::test] - #[ignore] - async fn connects_and_reports_version() { - let Some(s) = session().await else { return }; - let product = if s.engine == Engine::Mariadb { - "MariaDB " - } else { - "MySQL " - }; - assert!( - s.server_version.starts_with(product), - "{}", - s.server_version - ); - assert!(s.current_user.is_some()); - let (mut profile, _) = profile().unwrap(); - assert_eq!(s.current_schema.as_deref(), Some(profile.database.as_str())); - assert!(s.tx_state().autocommit); - assert!(!s.tx_state().in_transaction); - - profile.ssl_mode = SslMode::Require; - let e = match connect(&profile, Some("wrong password")).await { - Ok(_) => panic!("connected with a wrong password"), - Err(e) => e, - }; - assert_eq!(e.kind, ErrorKind::Connection); - assert_eq!(e.code.as_deref(), Some("1045 (28000)")); - } - - #[tokio::test] - #[ignore] - async fn formats_values_exactly() { - let Some(s) = session().await else { return }; - run(&s, "SET SESSION sql_mode = ''").await; - run( - &s, - "CREATE TEMPORARY TABLE lq_types (d DECIMAL(30,9), u BIGINT UNSIGNED, dt DATETIME(6), - j JSON, b BLOB, vb VARBINARY(4), n INT, bt BIT(5), e ENUM('x','y'), f DOUBLE, - z DATETIME, t VARCHAR(10))", - ) - .await; - let r = run( - &s, - "INSERT INTO lq_types VALUES (12345678901234567890.123456789, 18446744073709551615, - '2024-05-01 13:45:00.123456', '{\"a\": 1}', x'00FF10', x'CAFE', NULL, b'10101', 'y', - 1.5, '0000-00-00 00:00:00', 'ação')", - ) - .await; - assert_eq!(r.rows_affected, Some(1)); - let r = run(&s, "SELECT * FROM lq_types").await; - let row: Vec> = r.rows[0].iter().map(|c| c.as_deref()).collect(); - assert_eq!( - row, - [ - Some("12345678901234567890.123456789"), - Some("18446744073709551615"), - Some("2024-05-01 13:45:00.123456"), - Some("{\"a\": 1}"), - Some("0x00FF10"), - Some("0xCAFE"), - None, - Some("21"), - Some("y"), - Some("1.5"), - Some("0000-00-00 00:00:00"), - Some("ação"), - ] - ); - let cols = r.columns.unwrap(); - assert_eq!(cols[0].kind, ValueKind::Number); - assert_eq!(cols[1].type_name, "BIGINT UNSIGNED"); - assert_eq!(cols[2].kind, ValueKind::Temporal); - if s.engine == Engine::Mysql { - assert_eq!(cols[3].kind, ValueKind::Json); - } - assert_eq!(cols[4].kind, ValueKind::Binary); - assert_eq!(cols[11].kind, ValueKind::Text); - } - - #[tokio::test] - #[ignore] - async fn limits_rows_on_the_server() { - let Some(s) = session().await else { return }; - run(&s, "CREATE TEMPORARY TABLE lq_limit (n INT)").await; - let values: Vec = (1..=50).map(|i| format!("({i})")).collect(); - run( - &s, - &format!("INSERT INTO lq_limit VALUES {}", values.join(",")), - ) - .await; - - let r = s - .execute(&req("SELECT n FROM lq_limit ORDER BY n", 10)) - .await - .unwrap(); - assert_eq!(r.rows.len(), 10); - assert!(r.truncated); - let r = s.execute(&req("SELECT n FROM lq_limit", 50)).await.unwrap(); - assert_eq!(r.rows.len(), 50); - assert!(!r.truncated); - - // The limit does not leak into the next statements. - let r = s - .execute(&req("UPDATE lq_limit SET n = n + 1", 10)) - .await - .unwrap(); - assert_eq!(r.rows_affected, Some(50)); - let r = s.execute(&req("SELECT n FROM lq_limit", 0)).await.unwrap(); - assert_eq!(r.rows.len(), 50); - let r = run(&s, "SHOW VARIABLES LIKE 'sql_select_limit'").await; - assert_eq!(r.rows[0][1].as_deref(), Some("18446744073709551615")); - } - - #[tokio::test] - #[ignore] - async fn reports_errors_with_position() { - let Some(s) = session().await else { return }; - let e = s - .execute(&req("SELECT *\nFROMM lq_x", 10)) - .await - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Database); - assert_eq!(e.code.as_deref(), Some("1064 (42000)")); - assert_eq!(e.position, Some(9)); - let e = s - .execute(&req("SELECT * FROM lq_no_such_table", 10)) - .await - .unwrap_err(); - assert_eq!(e.code.as_deref(), Some("1146 (42S02)")); - // The session still works. - assert_eq!(run(&s, "SELECT 1").await.rows[0][0].as_deref(), Some("1")); - } - - #[tokio::test] - #[ignore] - async fn collects_warnings() { - let Some(s) = session().await else { return }; - let r = run(&s, "SELECT CAST('abc' AS SIGNED)").await; - assert!( - r.notices.iter().any(|n| n.starts_with("Warning 1292:")), - "{:?}", - r.notices - ); - let r = run(&s, "SELECT 1").await; - assert!(r.notices.is_empty()); - } - - #[tokio::test] - #[ignore] - async fn manual_transactions() { - let Some(s) = session().await else { return }; - run(&s, "DROP TABLE IF EXISTS lq_tx").await; - run(&s, "CREATE TABLE lq_tx (n INT) ENGINE = InnoDB").await; - - let st = s.set_autocommit(false).await.unwrap(); - assert!(!st.autocommit); - let r = run(&s, "INSERT INTO lq_tx VALUES (1)").await; - assert!(r.in_transaction); - let st = s.end_transaction(false).await.unwrap(); - assert!(!st.in_transaction); - assert_eq!( - run(&s, "SELECT COUNT(*) FROM lq_tx").await.rows[0][0].as_deref(), - Some("0") - ); - run(&s, "INSERT INTO lq_tx VALUES (2)").await; - let st = s.end_transaction(true).await.unwrap(); - assert!(!st.in_transaction); - run(&s, "INSERT INTO lq_tx VALUES (3)").await; - // Turning autocommit back on commits pending work. - let st = s.set_autocommit(true).await.unwrap(); - assert!(st.autocommit && !st.in_transaction); - assert_eq!( - run(&s, "SELECT COUNT(*) FROM lq_tx").await.rows[0][0].as_deref(), - Some("2") - ); - - // Explicit transaction in autocommit mode. - assert!(run(&s, "START TRANSACTION").await.in_transaction); - assert!(run(&s, "DELETE FROM lq_tx").await.in_transaction); - assert!(!run(&s, "ROLLBACK").await.in_transaction); - assert_eq!( - run(&s, "SELECT COUNT(*) FROM lq_tx").await.rows[0][0].as_deref(), - Some("2") - ); - run(&s, "DROP TABLE lq_tx").await; - } - - #[tokio::test] - #[ignore] - async fn cancels_a_running_query() { - let Some(s) = session().await else { return }; - let s = Arc::new(s); - let started = Instant::now(); - let running = { - let s = s.clone(); - tokio::spawn(async move { s.execute(&req("SELECT SLEEP(30)", 10)).await }) - }; - tokio::time::sleep(Duration::from_secs(1)).await; - s.cancel().await.unwrap(); - let e = running.await.unwrap().unwrap_err(); - assert_eq!(e.kind, ErrorKind::Cancelled); - assert!(started.elapsed() < Duration::from_secs(15)); - assert_eq!(run(&s, "SELECT 2").await.rows[0][0].as_deref(), Some("2")); - } - - #[tokio::test] - #[ignore] - async fn lists_metadata() { - let Some(s) = session().await else { return }; - let db = s.current_schema.clone().unwrap(); - for sql in [ - "DROP VIEW IF EXISTS lq_meta_v", - "DROP TABLE IF EXISTS lq_meta_t", - "DROP PROCEDURE IF EXISTS lq_meta_p", - "DROP FUNCTION IF EXISTS lq_meta_f", - "CREATE TABLE lq_meta_t (id INT NOT NULL PRIMARY KEY, name VARCHAR(20) NULL)", - "CREATE VIEW lq_meta_v AS SELECT id FROM lq_meta_t", - "CREATE PROCEDURE lq_meta_p() SELECT 1", - "CREATE FUNCTION lq_meta_f() RETURNS INT DETERMINISTIC RETURN 1", - ] { - run(&s, sql).await; - } - if s.engine == Engine::Mariadb { - run(&s, "CREATE OR REPLACE SEQUENCE lq_meta_s").await; - } - - let schemas = s.list_schemas().await.unwrap(); - assert_eq!(schemas[0], db); - let first_system = schemas.iter().position(|n| is_system_schema(n)).unwrap(); - assert!(schemas[first_system..].iter().all(|n| is_system_schema(n))); - - let objects = s.list_objects(&db).await.unwrap(); - let kind = |name: &str| { - objects - .iter() - .find(|o| o.name == name) - .map(|o| o.kind.as_str()) - }; - assert_eq!(kind("lq_meta_t"), Some("table")); - assert_eq!(kind("lq_meta_v"), Some("view")); - assert_eq!(kind("lq_meta_p"), Some("procedure")); - assert_eq!(kind("lq_meta_f"), Some("function")); - if s.engine == Engine::Mariadb { - assert_eq!(kind("lq_meta_s"), Some("sequence")); - } - - let cols = s.list_columns(&db, "lq_meta_t").await.unwrap(); - assert_eq!(cols.len(), 2); - assert_eq!(cols[0].name, "id"); - // MariaDB keeps the display width: int(11). - assert!( - cols[0].type_name.starts_with("int"), - "{}", - cols[0].type_name - ); - assert!(cols[0].primary_key && !cols[0].nullable); - assert_eq!(cols[1].type_name, "varchar(20)"); - assert!(!cols[1].primary_key && cols[1].nullable); - - // CALL: rows of the first result set plus the affected rows. - let r = run(&s, "CALL lq_meta_p()").await; - assert_eq!(r.rows[0][0].as_deref(), Some("1")); - assert!(r.rows_affected.is_some()); - } - - async fn editable(s: &MySession, sql: &str) -> EditTarget { - let r = run(s, sql).await; - assert!(r.read_only_reason.is_none(), "{sql}"); - r.editable - .unwrap_or_else(|| panic!("{sql}: not editable, no reason")) - } - - async fn read_only(s: &MySession, sql: &str) -> String { - let r = run(s, sql).await; - assert!(r.editable.is_none(), "{sql}: editable"); - r.read_only_reason - .unwrap_or_else(|| panic!("{sql}: no reason")) - } - - fn cells(items: &[(usize, Option<&str>)]) -> Vec { - items.iter().map(|(c, v)| cv(*c, *v)).collect() - } - - fn key(values: &[&str]) -> Vec> { - values.iter().map(|v| Some(v.to_string())).collect() - } - - async fn apply( - s: &MySession, - target: &EditTarget, - changes: Vec, - ) -> AppResult { - s.apply_changes(&ApplyRequest { - target: target.clone(), - changes, - }) - .await - } - - async fn texts_of(s: &MySession, sql: &str) -> Vec>> { - run(s, sql).await.rows - } - - #[tokio::test] - #[ignore] - async fn detects_editable_results() { - let Some(s) = session().await else { return }; - let db = s.current_schema.clone().unwrap(); - for sql in [ - "DROP VIEW IF EXISTS lq_edit_v", - "DROP TABLE IF EXISTS lq_edit_a, lq_edit_b, lq_edit_nokey, lq_edit_uk", - "CREATE TABLE lq_edit_a (id INT NOT NULL PRIMARY KEY, name VARCHAR(20), b_id INT)", - "CREATE TABLE lq_edit_b (id INT NOT NULL PRIMARY KEY, label VARCHAR(20))", - "CREATE TABLE lq_edit_nokey (n INT, m INT)", - "CREATE TABLE lq_edit_uk (a INT NOT NULL, b INT NOT NULL, c INT, UNIQUE KEY uk (b, a))", - "CREATE VIEW lq_edit_v AS SELECT id, name FROM lq_edit_a", - ] { - run(&s, sql).await; - } - - let t = editable(&s, "SELECT id, name, id * 2 AS dbl FROM lq_edit_a").await; - assert_eq!(t.schema.as_deref(), Some(db.as_str())); - assert_eq!(t.table, "lq_edit_a"); - assert_eq!(t.key, [0]); - let name = t.columns[1].as_ref().unwrap(); - assert_eq!( - (name.name.as_str(), name.type_name.as_str()), - ("name", "varchar(20)") - ); - assert!(t.columns[2].is_none()); - - let t = editable(&s, "SELECT name AS n, x.id FROM lq_edit_a x WHERE 1 = 0").await; - assert_eq!(t.key, [1]); - assert_eq!(t.columns[0].as_ref().unwrap().name, "name"); - - let t = editable(&s, "SELECT c, a, b FROM lq_edit_uk").await; - assert_eq!(t.key, [2, 1]); - - assert_eq!( - read_only( - &s, - "SELECT a.id, b.label FROM lq_edit_a a JOIN lq_edit_b b ON b.id = a.b_id" - ) - .await, - SEVERAL_TABLES - ); - assert_eq!( - read_only( - &s, - "SELECT a.id, b.id FROM lq_edit_a a JOIN lq_edit_a b ON a.id = b.id" - ) - .await, - SEVERAL_TABLES - ); - assert_eq!( - read_only(&s, "SELECT * FROM lq_edit_nokey").await, - "Read-only: table lq_edit_nokey has no primary key." - ); - assert_eq!( - read_only(&s, "SELECT name FROM lq_edit_a").await, - "Read-only: add the primary key columns (id) to the query to edit rows." - ); - assert_eq!( - read_only(&s, "SELECT COUNT(*) FROM lq_edit_a").await, - NOT_A_TABLE - ); - assert_eq!( - read_only( - &s, - "SELECT id FROM lq_edit_a UNION SELECT id FROM lq_edit_b" - ) - .await, - NOT_A_TABLE - ); - read_only(&s, "SHOW TABLES").await; - // A view is read-only, unless the server names its base table. - let r = run(&s, "SELECT * FROM lq_edit_v").await; - match &r.editable { - Some(t) => assert_eq!(t.table, "lq_edit_a"), - None => assert_eq!(r.read_only_reason.as_deref(), Some(NOT_A_TABLE)), - } - let r = run(&s, "UPDATE lq_edit_a SET name = name").await; - assert!(r.editable.is_none() && r.read_only_reason.is_none()); - - // DDL clears the cached catalog. - run(&s, "ALTER TABLE lq_edit_nokey ADD PRIMARY KEY (n)").await; - assert_eq!( - editable(&s, "SELECT m, n FROM lq_edit_nokey").await.key, - [1] - ); - - run(&s, "DROP VIEW lq_edit_v").await; - run( - &s, - "DROP TABLE lq_edit_a, lq_edit_b, lq_edit_nokey, lq_edit_uk", - ) - .await; - } - - #[tokio::test] - #[ignore] - async fn round_trips_every_type() { - let Some(s) = session().await else { return }; - run(&s, "DROP TABLE IF EXISTS lq_edit_types").await; - run( - &s, - "CREATE TABLE lq_edit_types (id INT AUTO_INCREMENT PRIMARY KEY, d DECIMAL(30,9), - i BIGINT, u BIGINT UNSIGNED, f DOUBLE, fl FLOAT, b BOOLEAN, dt DATE, - ts DATETIME(6), tz TIMESTAMP(3) NULL, tm TIME(6), y YEAR, txt TEXT, - vc VARCHAR(100), bin VARBINARY(16), bl BLOB, bt BIT(5), j JSON, - e ENUM('x','y'), n VARCHAR(5) NULL) DEFAULT CHARSET = utf8mb4", - ) - .await; - let target = editable(&s, "SELECT * FROM lq_edit_types").await; - assert_eq!( - target.columns[14].as_ref().unwrap().type_name, - "varbinary(16)" - ); - - let expected: Vec> = vec![ - Some("12345678901234567890.123456789"), - Some("-9223372036854775808"), - Some("18446744073709551615"), - Some("-1234.5678"), - Some("1.5"), - Some("1"), - Some("2024-02-29"), - Some("2024-05-01 13:45:00.123456"), - Some("2024-05-01 13:45:00.120"), - Some("-12:34:56.789000"), - Some("2024"), - Some("it's \"quoted\"\nline 2 \\ back"), - Some("ação 😀"), - Some("0x00FF10CA"), - Some("0xDEADBEEF"), - Some("21"), - Some("{\"a\": 1, \"b\": [true, null]}"), - Some("y"), - None, - ]; - let values: Vec<(usize, Option<&str>)> = expected - .iter() - .enumerate() - .map(|(i, v)| (i + 1, *v)) - .collect(); - let r = apply( - &s, - &target, - vec![RowChange::Insert { - values: cells(&values), - }], - ) - .await - .unwrap(); - assert_eq!((r.inserted, r.in_transaction), (1, false)); - - let rows = texts_of(&s, "SELECT * FROM lq_edit_types").await; - let shown: Vec> = rows[0][1..].iter().map(|v| v.as_deref()).collect(); - assert_eq!(shown, expected); - - // Every column saved with its own displayed text stays identical - // (nothing changes, so the server reports 0 affected rows). - let id = rows[0][0].clone().unwrap(); - let same: Vec<(usize, Option<&str>)> = rows[0] - .iter() - .enumerate() - .skip(1) - .map(|(i, v)| (i, v.as_deref())) - .collect(); - let r = apply( - &s, - &target, - vec![RowChange::Update { - key: key(&[&id]), - values: cells(&same), - }], - ) - .await - .unwrap(); - assert_eq!(r.updated, 1); - assert_eq!(texts_of(&s, "SELECT * FROM lq_edit_types").await, rows); - - // Changed values, committed for other sessions too. - let r = apply( - &s, - &target, - vec![RowChange::Update { - key: key(&[&id]), - values: cells(&[ - (15, Some("0x")), - (16, Some("2")), - (19, Some("ok")), - (6, None), - ]), - }], - ) - .await - .unwrap(); - assert_eq!((r.updated, r.in_transaction), (1, false)); - let other = session().await.unwrap(); - let rows = texts_of(&other, "SELECT bl, bt, n, b FROM lq_edit_types").await; - assert_eq!( - rows[0], - [ - Some("0x".to_string()), - Some("2".into()), - Some("ok".into()), - None - ] - ); - - let r = apply( - &s, - &target, - vec![ - RowChange::Insert { values: vec![] }, - RowChange::Delete { key: key(&[&id]) }, - ], - ) - .await - .unwrap(); - assert_eq!((r.inserted, r.deleted), (1, 1)); - let rows = texts_of(&other, "SELECT id, e, n FROM lq_edit_types").await; - assert_eq!(rows.len(), 1); - assert_ne!(rows[0][0].as_deref(), Some(id.as_str())); - run(&s, "DROP TABLE lq_edit_types").await; - } - - #[tokio::test] - #[ignore] - async fn failed_changes_roll_back() { - let Some(s) = session().await else { return }; - run(&s, "DROP TABLE IF EXISTS lq_edit_rb").await; - run( - &s, - "CREATE TABLE lq_edit_rb (id INT PRIMARY KEY, v VARCHAR(10), bl BLOB) ENGINE = InnoDB", - ) - .await; - run( - &s, - "INSERT INTO lq_edit_rb VALUES (1, 'a', NULL), (2, 'b', NULL)", - ) - .await; - let target = editable(&s, "SELECT id, v, bl FROM lq_edit_rb").await; - let before = texts_of(&s, "SELECT * FROM lq_edit_rb ORDER BY id").await; - - let e = apply( - &s, - &target, - vec![ - RowChange::Update { - key: key(&["1"]), - values: cells(&[(1, Some("changed"))]), - }, - RowChange::Delete { key: key(&["2"]) }, - RowChange::Update { - key: key(&["999"]), - values: cells(&[(1, Some("x"))]), - }, - ], - ) - .await - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Database); - assert_eq!( - e.message, - "Row 3 was not saved: 0 rows matched its key (changed or removed by someone else)." - ); - assert_eq!( - texts_of(&s, "SELECT * FROM lq_edit_rb ORDER BY id").await, - before - ); - assert!(!s.tx_state().in_transaction); - - // Server errors keep their code. - let e = apply( - &s, - &target, - vec![ - RowChange::Delete { key: key(&["1"]) }, - RowChange::Insert { - values: cells(&[(0, Some("2"))]), - }, - ], - ) - .await - .unwrap_err(); - assert_eq!(e.code.as_deref(), Some("1062 (23000)")); - assert_eq!(e.detail.as_deref(), Some("Row 2 was not saved.")); - assert_eq!( - texts_of(&s, "SELECT * FROM lq_edit_rb ORDER BY id").await, - before - ); - - // Previews never reach the server. - let e = apply( - &s, - &target, - vec![RowChange::Update { - key: key(&["1"]), - values: cells(&[(2, Some("0x0000… (40000 bytes)"))]), - }], - ) - .await - .unwrap_err(); - assert_eq!((e.kind, e.message.as_str()), (ErrorKind::Invalid, PREVIEW)); - assert_eq!(run(&s, "SELECT 1").await.rows[0][0].as_deref(), Some("1")); - run(&s, "DROP TABLE lq_edit_rb").await; - } - - #[tokio::test] - #[ignore] - async fn joins_the_manual_transaction() { - let Some(s) = session().await else { return }; - run(&s, "DROP TABLE IF EXISTS lq_edit_tx").await; - run( - &s, - "CREATE TABLE lq_edit_tx (id INT PRIMARY KEY) ENGINE = InnoDB", - ) - .await; - let target = editable(&s, "SELECT id FROM lq_edit_tx").await; - let insert = |id: &str| RowChange::Insert { - values: cells(&[(0, Some(id))]), - }; - let ids = |rows: Vec>>| -> Vec { - rows.into_iter().map(|r| r[0].clone().unwrap()).collect() - }; - - s.set_autocommit(false).await.unwrap(); - run(&s, "INSERT INTO lq_edit_tx VALUES (10)").await; - let r = apply(&s, &target, vec![insert("11")]).await.unwrap(); - assert!(r.in_transaction); - // A failure undoes only this batch; the transaction stays open. - let e = apply( - &s, - &target, - vec![insert("12"), RowChange::Delete { key: key(&["999"]) }], - ) - .await - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Database); - assert!(s.tx_state().in_transaction); - assert_eq!( - ids(texts_of(&s, "SELECT id FROM lq_edit_tx ORDER BY id").await), - ["10", "11"] - ); - s.end_transaction(false).await.unwrap(); - assert!(texts_of(&s, "SELECT id FROM lq_edit_tx").await.is_empty()); - - // First statement of a manual transaction. - s.end_transaction(false).await.unwrap(); - let r = apply(&s, &target, vec![insert("13")]).await.unwrap(); - assert!(r.in_transaction); - s.end_transaction(true).await.unwrap(); - s.set_autocommit(true).await.unwrap(); - - // An explicit transaction in autocommit mode is joined, not committed. - run(&s, "START TRANSACTION").await; - let r = apply(&s, &target, vec![insert("14")]).await.unwrap(); - assert!(r.in_transaction); - run(&s, "ROLLBACK").await; - assert_eq!(ids(texts_of(&s, "SELECT id FROM lq_edit_tx").await), ["13"]); - run(&s, "DROP TABLE lq_edit_tx").await; - } - - #[tokio::test] - #[ignore] - async fn edits_names_that_need_quoting() { - let Some(s) = session().await else { return }; - run(&s, "DROP TABLE IF EXISTS `lq_edit_Mixed Case`").await; - run( - &s, - "CREATE TABLE `lq_edit_Mixed Case` (`Order Id` INT NOT NULL PRIMARY KEY, - `Some Name` VARCHAR(20))", - ) - .await; - run(&s, "INSERT INTO `lq_edit_Mixed Case` VALUES (1, 'one')").await; - let target = editable( - &s, - "SELECT `Some Name` AS label, `Order Id` FROM `lq_edit_Mixed Case`", - ) - .await; - assert!(target.table.eq_ignore_ascii_case("lq_edit_Mixed Case")); - assert_eq!(target.key, [1]); - assert_eq!(target.columns[0].as_ref().unwrap().name, "Some Name"); - - let r = apply( - &s, - &target, - vec![ - RowChange::Update { - key: key(&["1"]), - values: cells(&[(0, Some("uno")), (1, Some("5"))]), - }, - RowChange::Insert { - values: cells(&[(1, Some("2")), (0, Some("two"))]), - }, - ], - ) - .await - .unwrap(); - assert_eq!((r.updated, r.inserted), (1, 1)); - let rows = texts_of(&s, "SELECT * FROM `lq_edit_Mixed Case` ORDER BY 1").await; - assert_eq!( - rows, - [ - [Some("2".to_string()), Some("two".into())], - [Some("5".into()), Some("uno".into())] - ] - ); - let r = apply(&s, &target, vec![RowChange::Delete { key: key(&["5"]) }]) - .await - .unwrap(); - assert_eq!(r.deleted, 1); - run(&s, "DROP TABLE `lq_edit_Mixed Case`").await; - } - - #[tokio::test] - #[ignore] - async fn result_view_sql() { - let Some((profile, password)) = profile() else { - return; - }; - let s = crate::drivers::Session::open(&profile, password.as_deref()) - .await - .expect("connect"); - crate::drivers::view_fixtures::check(&s, "mysql").await; - } - - #[tokio::test] - #[ignore] - async fn ddl_sql() { - let Some((profile, password)) = profile() else { - return; - }; - let s = crate::drivers::Session::open(&profile, password.as_deref()) - .await - .expect("connect"); - crate::drivers::ddl_fixtures::check(&s, "mysql", &profile.database).await; - } - - #[tokio::test] - #[ignore] - async fn export_import_round_trip() { - let Some((profile, password)) = profile() else { - return; - }; - let s = crate::drivers::Session::open(&profile, password.as_deref()) - .await - .expect("connect"); - crate::transfer::round_trip::check(&s, &profile.database).await; - } -} diff --git a/src-tauri/src/drivers/oracle.rs b/src-tauri/src/drivers/oracle.rs deleted file mode 100644 index 4e41e9e..0000000 --- a/src-tauri/src/drivers/oracle.rs +++ /dev/null @@ -1,3174 +0,0 @@ -//! Oracle session over the official `oracledb` driver (thin mode, pure Rust): -//! no Oracle Client/Instant Client needs to be installed. -//! -//! The driver is synchronous; each call runs in `spawn_blocking`. The row -//! limit is applied by tuning `prefetch_rows`/`fetch_array_size` and -//! stopping the cursor read, without fetching the rest from the server. - -use std::collections::HashMap; -use std::fmt::Write as _; -use std::sync::Arc; -use std::time::Instant; - -use oracledb::{ - Connection, JsonValue, Metadata, OracleNumber, OracleTimestamp, Row, Vector, VectorData, -}; -use parking_lot::Mutex; - -use super::{first_keywords, tns, RowSink, StreamEvent, TxState, STREAM_BATCH}; -use crate::error::{AppError, AppResult, ErrorKind}; -use crate::model::{ - ApplyRequest, ApplyResult, CellValue, ColumnInfo, ConnectionProfile, DbColumn, DbObject, - EditColumn, EditTarget, ExecRequest, ExecResult, OracleConnectType, OraclePrivilege, RowChange, - ValueKind, -}; - -const BINARY_PREVIEW_BYTES: usize = 32 * 1024; -const MAX_OUTPUT_LINES: usize = 5000; - -pub struct OraSession { - conn: Mutex>, - /// Opens a new connection with the same settings (see [`OraSession::reopen`]). - dial: Arc AppResult + Send + Sync>, - busy: tokio::sync::Mutex<()>, - state: Arc>, - /// Catalog lookups for editable results, per table as written. - tables: TableCache, - pub server_version: String, - pub current_user: Option, - pub current_schema: Option, -} - -/// Builds the address. Service and SID become full descriptors so they do -/// not depend on name resolution. -pub fn connect_string(profile: &ConnectionProfile) -> String { - let host = profile.host.trim(); - let port = if profile.port == 0 { - 1521 - } else { - profile.port - }; - let target = profile.database.trim(); - match profile.oracle_connect_type { - OracleConnectType::Service => format!( - "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={host})(PORT={port}))(CONNECT_DATA=(SERVICE_NAME={target})))" - ), - OracleConnectType::Sid => format!( - "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={host})(PORT={port}))(CONNECT_DATA=(SID={target})))" - ), - OracleConnectType::Tns => profile.tns_alias.trim().to_string(), - OracleConnectType::Custom => profile.connect_string.trim().to_string(), - } -} - -/// Connect string and network configuration folder for the driver. TNS -/// aliases are resolved to their descriptor here (see [`super::tns`]); the -/// folder still goes to the driver for `sqlnet.ora` settings. -fn network_target(profile: &ConnectionProfile) -> AppResult<(String, Option)> { - let own_dir = profile - .config_dir - .as_deref() - .filter(|d| !d.trim().is_empty()); - match profile.oracle_connect_type { - OracleConnectType::Tns => { - let (descriptor, dir) = tns::resolve(&profile.tns_alias, own_dir)?; - Ok((descriptor, Some(dir.display().to_string()))) - } - OracleConnectType::Custom => { - let target = connect_string(profile); - let dir = own_dir - .map(str::to_string) - .or_else(|| tns::default_dir().map(|d| d.display().to_string())); - // A bare name is an alias: resolve it here so Latin-1 files work. - let is_alias = !target.is_empty() && !target.contains(['(', '/', ':', '@', ' ']); - if is_alias { - if let Ok((descriptor, found)) = tns::resolve(&target, own_dir) { - return Ok((descriptor, Some(found.display().to_string()))); - } - } - Ok((target, dir)) - } - OracleConnectType::Service | OracleConnectType::Sid => { - Ok((connect_string(profile), own_dir.map(str::to_string))) - } - } -} - -/// Opens a connection and prepares the session (module name, DBMS_OUTPUT). -fn dial(profile: &ConnectionProfile, password: &str) -> AppResult { - let (target, config_dir) = network_target(profile)?; - let mut cfg = oracledb::Config::default(); - if let Some(dir) = &config_dir { - cfg = cfg.set_config_dir(dir); - } - cfg = cfg - .set_credentials(profile.user.trim(), password) - .set_program("LowQuery") - .map_err(connection_error)? - .set_connect_string(&target) - .map_err(connection_error)?; - if profile.oracle_privilege != OraclePrivilege::None { - cfg = cfg.set_auth_mode(profile.oracle_privilege.auth_mode()); - } - let conn = oracledb::connect(cfg).map_err(connection_error)?; - let _ = conn.set_module("LowQuery"); - // Enables DBMS_OUTPUT with no buffer limit. - conn.execute("begin dbms_output.enable(null); end;", &[]) - .map_err(map_error)?; - Ok(conn) -} - -pub async fn connect(profile: &ConnectionProfile, password: Option<&str>) -> AppResult { - let profile = profile.clone(); - let password = password.unwrap_or_default().to_string(); - blocking(move || { - let conn = dial(&profile, &password)?; - let row = conn - .query_row( - "select sys_context('USERENV', 'SESSION_USER'), sys_context('USERENV', 'CURRENT_SCHEMA') from dual", - &[], - ) - .map_err(map_error)?; - - let version = conn.version().map(|v| v.to_string()).unwrap_or_default(); - Ok(OraSession { - server_version: format!("Oracle {version}"), - current_user: row.get(0).map_err(map_error)?, - current_schema: row.get(1).map_err(map_error)?, - conn: Mutex::new(Arc::new(conn)), - dial: Arc::new(move || dial(&profile, &password)), - busy: tokio::sync::Mutex::new(()), - state: Arc::new(Mutex::new(TxState { autocommit: true, in_transaction: false })), - tables: TableCache::default(), - }) - }) - .await -} - -async fn blocking(f: F) -> AppResult -where - T: Send + 'static, - F: FnOnce() -> AppResult + Send + 'static, -{ - tauri::async_runtime::spawn_blocking(f) - .await - .map_err(|e| AppError::internal(e.to_string()))? -} - -/// Prepares the text for Oracle: strips the trailing SQL*Plus slash and the -/// trailing `;` of SQL statements. PL/SQL blocks keep the `;` (it is part of -/// `END;`). -pub fn prepare_sql(sql: &str) -> String { - let mut text = sql.trim_end().to_string(); - if let Some(stripped) = text.strip_suffix('/') { - // Only strips the slash when it is alone on the last line. - if stripped.ends_with('\n') || stripped.trim_end().is_empty() { - text = stripped.trim_end().to_string(); - } - } - if !is_plsql(&text) { - while let Some(stripped) = text.strip_suffix(';') { - text = stripped.trim_end().to_string(); - } - } - text -} - -/// Anonymous blocks and creation of PL/SQL units. -pub fn is_plsql(sql: &str) -> bool { - let kw = first_keywords(sql, 6); - let mut words = kw.iter().map(String::as_str).peekable(); - match words.next() { - Some("BEGIN" | "DECLARE") => true, - Some("CREATE") => { - if words.peek() == Some(&"OR") { - words.next(); - words.next(); // REPLACE - } - if matches!( - words.peek(), - Some(&"EDITIONABLE" | &"NONEDITIONABLE" | &"EDITIONING") - ) { - words.next(); - } - matches!( - words.next(), - Some( - "PROCEDURE" | "FUNCTION" | "PACKAGE" | "TRIGGER" | "TYPE" | "LIBRARY" | "JAVA" - ) - ) - } - _ => false, - } -} - -impl OraSession { - /// Runs `f` on the connection in a blocking task. When the driver loses - /// track of the server's reply, the connection is replaced. - async fn with_conn(&self, f: F) -> AppResult - where - T: Send + 'static, - F: FnOnce(&Connection) -> AppResult + Send + 'static, - { - let conn = self.conn.lock().clone(); - match blocking(move || f(&conn)).await { - Err(e) if e.kind == ErrorKind::Internal => Err(self.reopen(e).await), - result => result, - } - } - - /// After a protocol error the rest of the reply is still unread on the - /// socket and every later call would fail on it, so the session moves to - /// a new connection. The open transaction is lost with the old one. - async fn reopen(&self, cause: AppError) -> AppError { - let was_in_transaction = std::mem::take(&mut self.state.lock().in_transaction); - self.tables.lock().clear(); - let dial = self.dial.clone(); - let mut err = match blocking(move || dial()).await { - Ok(conn) => { - *self.conn.lock() = Arc::new(conn); - let mut message = String::from( - "The Oracle driver could not read the server's reply, so LowQuery reopened the connection.", - ); - if was_in_transaction { - message.push_str(" The open transaction was rolled back."); - } - AppError::new(ErrorKind::Database, message) - } - Err(e) => AppError::connection(format!( - "The Oracle driver could not read the server's reply, and reconnecting failed: {}", - e.message - )), - }; - err.detail = Some(cause.message); - err - } - - pub async fn apply_changes(&self, req: &ApplyRequest) -> AppResult { - let _busy = self.busy.lock().await; - let state = self.state.clone(); - let req = req.clone(); - self.with_conn(move |conn| apply_blocking(conn, &req, &state)) - .await - } - - pub fn tx_state(&self) -> TxState { - *self.state.lock() - } - - pub async fn execute(&self, req: &ExecRequest) -> AppResult { - let _busy = self.busy.lock().await; - let state = self.state.clone(); - let tables = self.tables.clone(); - let sql = prepare_sql(&req.sql); - let max_rows = req.max_rows; - self.with_conn(move |conn| execute_blocking(conn, &sql, max_rows, &state, &tables)) - .await - } - - pub async fn cancel(&self) -> AppResult<()> { - Err(AppError::invalid( - "The Oracle driver cannot interrupt a running call yet.", - )) - } - - pub async fn set_autocommit(&self, on: bool) -> AppResult { - if on && self.state.lock().in_transaction { - self.end_transaction(true).await?; - } - let mut st = self.state.lock(); - st.autocommit = on; - Ok(*st) - } - - pub async fn end_transaction(&self, commit: bool) -> AppResult { - let _busy = self.busy.lock().await; - self.with_conn(move |conn| { - if commit { - conn.commit() - } else { - conn.rollback() - } - .map_err(map_error) - }) - .await?; - let mut st = self.state.lock(); - st.in_transaction = false; - Ok(*st) - } - - pub async fn list_schemas(&self) -> AppResult> { - // Schemas with objects: the user's first, Oracle-maintained ones last. - // ORACLE_MAINTAINED only exists from 12c on. - let modern = self - .query_strings( - "select username from all_users u - where u.username = sys_context('USERENV', 'CURRENT_SCHEMA') - or exists (select 1 from all_objects o where o.owner = u.username) - order by case when username = sys_context('USERENV', 'CURRENT_SCHEMA') then 0 - when oracle_maintained = 'Y' then 2 else 1 end, username", - Vec::new(), - ) - .await; - match modern { - Ok(list) => Ok(list), - Err(_) => { - self.query_strings( - "select username from all_users u - where u.username = sys_context('USERENV', 'CURRENT_SCHEMA') - or exists (select 1 from all_objects o where o.owner = u.username) - order by case when username = sys_context('USERENV', 'CURRENT_SCHEMA') - then 0 else 1 end, username", - Vec::new(), - ) - .await - } - } - } - - pub async fn list_objects(&self, schema: &str) -> AppResult> { - let rows = self - .query_rows( - "select object_name, - case object_type when 'TABLE' then 'table' when 'VIEW' then 'view' - when 'MATERIALIZED VIEW' then 'matview' when 'SEQUENCE' then 'sequence' - when 'FUNCTION' then 'function' when 'PROCEDURE' then 'procedure' - when 'PACKAGE' then 'package' when 'TYPE' then 'type' - when 'SYNONYM' then 'synonym' end - from all_objects - where owner = :1 and object_type in ('TABLE','VIEW','MATERIALIZED VIEW','SEQUENCE', - 'FUNCTION','PROCEDURE','PACKAGE','TYPE','SYNONYM') - and object_name not like 'BIN$%' - and not (object_type = 'TABLE' and exists ( - select 1 from all_mviews m where m.owner = all_objects.owner - and m.mview_name = all_objects.object_name)) - order by 2, 1", - vec![schema.to_string()], - ) - .await?; - Ok(rows - .into_iter() - .map(|mut r| DbObject { - kind: r.pop().unwrap_or_default(), - name: r.pop().unwrap_or_default(), - }) - .collect()) - } - - pub async fn list_columns(&self, schema: &str, table: &str) -> AppResult> { - // DATA_DEFAULT is a LONG; the VARCHAR2 copy and IDENTITY_COLUMN - // arrived in 12.2, so older servers list the columns without defaults. - macro_rules! columns_sql { - ($default:literal) => { - concat!( - "select c.column_name, - case - when c.data_type in ('VARCHAR2','NVARCHAR2','CHAR','NCHAR','RAW') - then c.data_type || '(' || case when c.char_length > 0 then c.char_length else c.data_length end || ')' - when c.data_type = 'NUMBER' and c.data_precision is not null - then 'NUMBER(' || c.data_precision || - case when c.data_scale > 0 then ',' || c.data_scale end || ')' - else c.data_type end, - c.nullable, - case when exists ( - select 1 from all_constraints k - join all_cons_columns kc on kc.owner = k.owner - and kc.constraint_name = k.constraint_name - where k.owner = c.owner and k.table_name = c.table_name - and k.constraint_type = 'P' and kc.column_name = c.column_name) - then 'Y' else 'N' end, ", - $default, - " from all_tab_columns c - where c.owner = :1 and c.table_name = :2 - order by c.column_id" - ) - }; - } - let params = vec![schema.to_string(), table.to_string()]; - let rows = match self - .query_rows( - columns_sql!( - "case when c.identity_column = 'YES' then null else trim(c.data_default_vc) end" - ), - params.clone(), - ) - .await - { - Ok(rows) => rows, - Err(e) if e.kind == ErrorKind::Database => { - self.query_rows(columns_sql!("null"), params).await? - } - Err(e) => return Err(e), - }; - Ok(rows - .into_iter() - .map(|r| DbColumn { - name: r[0].clone(), - type_name: r[1].clone(), - nullable: r[2] == "Y", - primary_key: r[3] == "Y", - default_value: Some(r[4].clone()).filter(|d| !d.is_empty()), - key_role: None, - }) - .collect()) - } - - /// Reads the rows of a query in batches of [`STREAM_BATCH`]. - pub async fn stream(&self, sql: &str, sink: RowSink) -> AppResult { - let _busy = self.busy.lock().await; - let sql = sql.trim().trim_end_matches(';').to_string(); - self.with_conn(move |conn| { - let stmt = conn - .statement(&sql) - .map_err(map_error)? - .fetch_array_size(STREAM_BATCH as u32) - .prefetch_rows(STREAM_BATCH as u32) - .exclude_from_cache() - .build() - .map_err(map_error)?; - let cursor = stmt.query(&[]).map_err(map_error)?; - let cols: Vec = cursor.columns().to_vec(); - let info = cols - .iter() - .map(|c| ColumnInfo { - name: c.name().to_string(), - type_name: c.data_type(), - kind: value_kind(c), - }) - .collect(); - sink.blocking_send(StreamEvent::Columns(info)) - .map_err(|_| super::stream_stopped())?; - let mut total = 0u64; - let mut batch = Vec::with_capacity(STREAM_BATCH); - for row in cursor { - let row = row.map_err(map_error)?; - let cells = super::full_values(|| { - cols.iter() - .enumerate() - .map(|(i, col)| cell(&row, i, col)) - .collect::, _>>() - }) - .map_err(map_error)?; - batch.push(cells); - total += 1; - if batch.len() == STREAM_BATCH { - let full = std::mem::replace(&mut batch, Vec::with_capacity(STREAM_BATCH)); - sink.blocking_send(StreamEvent::Rows(full)) - .map_err(|_| super::stream_stopped())?; - } - } - if !batch.is_empty() { - sink.blocking_send(StreamEvent::Rows(batch)) - .map_err(|_| super::stream_stopped())?; - } - Ok(total) - }) - .await - } - - /// DDL from `DBMS_METADATA`, with a table's indexes (other than those - /// behind its keys), triggers and comments; PL/SQL units from their source. - pub async fn object_ddl(&self, schema: &str, name: &str, kind: &str) -> AppResult { - let object_type = match kind { - "table" => "TABLE", - "view" => "VIEW", - "matview" => "MATERIALIZED_VIEW", - "sequence" => "SEQUENCE", - "function" => "FUNCTION", - "procedure" => "PROCEDURE", - "package" => "PACKAGE", - "type" => "TYPE", - "synonym" => "SYNONYM", - _ => { - return Err(AppError::invalid(format!( - "LowQuery cannot script a {kind} on Oracle." - ))) - } - }; - let _busy = self.busy.lock().await; - if matches!(kind, "function" | "procedure" | "package" | "type") { - // PL/SQL units come from their stored source, as SQL Developer - // shows them, spec and body together. - let params = [ - schema.to_string(), - name.to_string(), - object_type.to_string(), - ]; - return self - .with_conn(move |conn| { - let mut out = String::new(); - for unit in [params[2].clone(), format!("{} BODY", params[2])] { - let lines = first_texts( - conn, - "select text from all_source - where owner = :1 and name = :2 and type = :3 - order by line", - &[params[0].clone(), params[1].clone(), unit], - )?; - if lines.is_empty() { - continue; - } - let source = lines.concat(); - out.push_str(&format!("CREATE OR REPLACE {}\n/\n\n", source.trim_end())); - } - Ok(out) - }) - .await; - } - let params = vec![ - object_type.to_string(), - name.to_string(), - schema.to_string(), - ]; - let table = kind == "table"; - self.with_conn(move |conn| { - conn.execute( - "begin - dbms_metadata.set_transform_param(dbms_metadata.session_transform, 'SQLTERMINATOR', true); - dbms_metadata.set_transform_param(dbms_metadata.session_transform, 'PRETTY', true); - dbms_metadata.set_transform_param(dbms_metadata.session_transform, 'STORAGE', false); - end;", - &[], - ) - .map_err(map_error)?; - let outcome = (|| { - let mut parts = first_texts( - conn, - "select dbms_metadata.get_ddl(:1, :2, :3) from dual", - ¶ms, - )?; - if table { - let owner_table = [params[2].clone(), params[1].clone()]; - for sql in [ - "select dbms_metadata.get_ddl('INDEX', i.index_name, i.owner) - from all_indexes i - where i.table_owner = :1 and i.table_name = :2 and i.index_type <> 'LOB' - and not exists ( - select 1 from all_constraints k - where k.owner = i.table_owner and k.table_name = i.table_name - and k.index_name = i.index_name and k.constraint_type in ('P', 'U')) - order by i.index_name", - "select dbms_metadata.get_ddl('TRIGGER', t.trigger_name, t.owner) - from all_triggers t - where t.table_owner = :1 and t.table_name = :2 - order by t.trigger_name", - ] { - parts.extend(first_texts(conn, sql, &owner_table)?); - } - // ORA-31608 when the table has no comments. - if let Ok(comments) = first_texts( - conn, - "select dbms_metadata.get_dependent_ddl('COMMENT', :1, :2) from dual", - &[params[1].clone(), params[2].clone()], - ) { - parts.extend(comments); - } - } - Ok(parts - .iter() - .map(|p| p.trim()) - .filter(|p| !p.is_empty()) - .collect::>() - .join("\n\n") - + "\n") - })(); - let _ = conn.execute( - "begin dbms_metadata.set_transform_param(dbms_metadata.session_transform, 'DEFAULT'); end;", - &[], - ); - outcome - }) - .await - } - - async fn query_strings( - &self, - sql: &'static str, - params: Vec, - ) -> AppResult> { - Ok(self - .query_rows(sql, params) - .await? - .into_iter() - .filter_map(|mut r| r.drain(..).next()) - .collect()) - } - - async fn query_rows( - &self, - sql: &'static str, - params: Vec, - ) -> AppResult>> { - let _busy = self.busy.lock().await; - self.with_conn(move |conn| { - let binds: Vec<&dyn oracledb::ToDbValue> = params - .iter() - .map(|p| p as &dyn oracledb::ToDbValue) - .collect(); - let cursor = conn - .statement(sql) - .map_err(map_error)? - .fetch_array_size(500) - .prefetch_rows(500) - .build() - .map_err(map_error)? - .query(&binds) - .map_err(map_error)?; - let mut out = Vec::new(); - for row in cursor { - let row = row.map_err(map_error)?; - let n = row.columns().len(); - let mut cells = Vec::with_capacity(n); - for i in 0..n { - cells.push( - row.get::>(i) - .map_err(map_error)? - .unwrap_or_default(), - ); - } - out.push(cells); - } - Ok(out) - }) - .await - } -} - -/// First column of every row, as text. -fn first_texts(conn: &Connection, sql: &str, params: &[String]) -> AppResult> { - let binds: Vec<&dyn oracledb::ToDbValue> = params - .iter() - .map(|p| p as &dyn oracledb::ToDbValue) - .collect(); - let cursor = conn - .statement(sql) - .map_err(map_error)? - .build() - .map_err(map_error)? - .query(&binds) - .map_err(map_error)?; - let mut out = Vec::new(); - for row in cursor { - let row = row.map_err(map_error)?; - out.push( - row.get::>(0) - .map_err(map_error)? - .unwrap_or_default(), - ); - } - Ok(out) -} - -fn execute_blocking( - conn: &Connection, - sql: &str, - max_rows: usize, - state: &Mutex, - tables: &TableCache, -) -> AppResult { - let started = Instant::now(); - let array = if max_rows == 0 { - 1000 - } else { - (max_rows + 1).min(1000) - } as u32; - let mut stmt = conn - .statement(sql) - .map_err(map_error)? - .fetch_array_size(array) - .prefetch_rows(array) - .build() - .map_err(map_error)?; - - let mut result = ExecResult::default(); - if stmt.is_query() { - let cursor = stmt.query(&[]).map_err(map_error)?; - let cols: Vec = cursor.columns().to_vec(); - result.columns = Some( - cols.iter() - .map(|c| ColumnInfo { - name: c.name().to_string(), - type_name: c.data_type(), - kind: value_kind(c), - }) - .collect(), - ); - for row in cursor { - if max_rows > 0 && result.rows.len() == max_rows { - result.truncated = true; - break; - } - let row = row.map_err(map_error)?; - let mut cells = Vec::with_capacity(cols.len()); - for (i, col) in cols.iter().enumerate() { - cells.push(cell(&row, i, col).map_err(map_error)?); - } - result.rows.push(cells); - } - match edit_target(conn, sql, &cols, tables) { - Ok(target) => result.editable = Some(target), - Err(reason) => result.read_only_reason = Some(reason), - } - } else { - let is_dml = stmt.is_dml(); - let is_plsql = stmt.is_plsql(); - let is_ddl = stmt.is_ddl(); - if !is_dml { - // DDL, ALTER SESSION (current schema) or PL/SQL may change what a - // table name resolves to. - tables.lock().clear(); - } - let exec = stmt.execute(&[]).map_err(map_error)?; - if is_dml { - result.rows_affected = Some(exec.rows_affected()); - } - let kw = first_keywords(sql, 2); - let first = kw.first().map(String::as_str).unwrap_or(""); - let mut st = state.lock(); - if (first == "COMMIT" || first == "ROLLBACK") && kw.get(1).map(String::as_str) != Some("TO") - { - st.in_transaction = false; - } else if is_ddl { - // DDL implicitly commits the transaction. - st.in_transaction = false; - } else if is_dml || is_plsql { - if st.autocommit { - conn.commit().map_err(map_error)?; - st.in_transaction = false; - } else { - st.in_transaction = true; - } - } - drop(st); - result.notices = read_dbms_output(conn); - } - result.elapsed_ms = started.elapsed().as_millis() as u64; - result.in_transaction = state.lock().in_transaction; - Ok(result) -} - -/// Reads the pending DBMS_OUTPUT lines. -fn read_dbms_output(conn: &Connection) -> Vec { - let mut lines = Vec::new(); - while lines.len() < MAX_OUTPUT_LINES { - // Positional binds follow the order the placeholders appear in the - // text, so :1 (line) must come before :2 (status). - let exec = conn.execute( - "declare l varchar2(32767); s integer; begin dbms_output.get_line(l, s); \ - :1 := substrb(l, 1, 3900); :2 := s; end;", - &[&oracledb::DB_TYPE_VARCHAR, &oracledb::DB_TYPE_NUMBER], - ); - let Ok(mut exec) = exec else { break }; - let row = exec.out_bind_data(); - let status: i64 = row.get::>(1).ok().flatten().unwrap_or(1); - if status != 0 { - break; - } - lines.push( - row.get::>(0) - .ok() - .flatten() - .unwrap_or_default(), - ); - } - lines -} - -fn value_kind(col: &Metadata) -> ValueKind { - match col.db_type().name() { - "DB_TYPE_NUMBER" - | "DB_TYPE_BINARY_INTEGER" - | "DB_TYPE_BINARY_DOUBLE" - | "DB_TYPE_BINARY_FLOAT" => ValueKind::Number, - "DB_TYPE_BOOLEAN" => ValueKind::Bool, - "DB_TYPE_DATE" - | "DB_TYPE_TIMESTAMP" - | "DB_TYPE_TIMESTAMP_TZ" - | "DB_TYPE_TIMESTAMP_LTZ" - | "DB_TYPE_INTERVAL_DS" - | "DB_TYPE_INTERVAL_YM" => ValueKind::Temporal, - "DB_TYPE_RAW" | "DB_TYPE_LONG_RAW" | "DB_TYPE_BLOB" => ValueKind::Binary, - "DB_TYPE_JSON" => ValueKind::Json, - _ if col.db_type().is_string_type() => ValueKind::Text, - _ => ValueKind::Other, - } -} - -fn cell(row: &Row, i: usize, col: &Metadata) -> Result, oracledb::Error> { - let name = col.db_type().name(); - Ok(match name { - "DB_TYPE_NUMBER" | "DB_TYPE_BINARY_INTEGER" => { - row.get::>(i)?.map(|n| n.to_string()) - } - "DB_TYPE_BINARY_DOUBLE" => row - .get::>(i)? - .map(|v| float(v.is_nan(), v.is_infinite(), v > 0.0, v.to_string())), - "DB_TYPE_BINARY_FLOAT" => row - .get::>(i)? - .map(|v| float(v.is_nan(), v.is_infinite(), v > 0.0, v.to_string())), - "DB_TYPE_BOOLEAN" => row - .get::>(i)? - .map(|b| if b { "TRUE" } else { "FALSE" }.to_string()), - "DB_TYPE_DATE" => row - .get::>(i)? - .map(|t| timestamp(&t, 0, false)), - "DB_TYPE_TIMESTAMP" | "DB_TYPE_TIMESTAMP_LTZ" => row - .get::>(i)? - .map(|t| timestamp(&t, col.scale(), false)), - "DB_TYPE_TIMESTAMP_TZ" => row - .get::>(i)? - .map(|t| timestamp(&t, col.scale(), true)), - "DB_TYPE_INTERVAL_DS" => row - .get::>(i)? - .map(|v| v.to_string()), - "DB_TYPE_INTERVAL_YM" => row - .get::>(i)? - .map(|v| v.to_string()), - "DB_TYPE_RAW" | "DB_TYPE_LONG_RAW" | "DB_TYPE_BLOB" => { - row.get::>>(i)?.map(|b| hex(&b)) - } - "DB_TYPE_JSON" => row.get::>(i)?.map(|j| { - let mut s = String::new(); - json(&j, &mut s); - s - }), - "DB_TYPE_VECTOR" => row.get::>(i)?.map(|v| vector(&v)), - "DB_TYPE_CURSOR" => Some("(cursor)".into()), - "DB_TYPE_BFILE" => Some("(bfile)".into()), - _ => match row.get::>(i) { - Ok(v) => v, - Err(_) => match row.get::>>(i) { - Ok(v) => v.map(|b| hex(&b)), - Err(_) => Some(format!("({})", col.data_type())), - }, - }, - }) -} - -/// BINARY_FLOAT/DOUBLE with the special names Oracle uses. -fn float(nan: bool, infinite: bool, positive: bool, text: String) -> String { - if nan { - "Nan".into() - } else if infinite { - if positive { - "Inf".into() - } else { - "-Inf".into() - } - } else { - text - } -} - -/// `2024-05-01 13:45:00[.123][ +03:00]`, with the column's fractional digits. -fn timestamp(t: &OracleTimestamp, scale: i8, with_tz: bool) -> String { - let local; - let t = if with_tz { - local = local_time(t); - &local - } else { - t - }; - let mut s = format!( - "{:04}-{:02}-{:02} {:02}:{:02}:{:02}", - t.year(), - t.month(), - t.day(), - t.hour(), - t.minute(), - t.second() - ); - let digits = scale.clamp(0, 9) as usize; - if digits > 0 { - let frac = format!("{:09}", t.nanoseconds()); - s.push('.'); - s.push_str(&frac[..digits]); - } - if with_tz { - let (h, m) = (t.tz_hour_offset(), t.tz_minute_offset()); - let sign = if h < 0 || m < 0 { '-' } else { '+' }; - let _ = write!(s, " {sign}{:02}:{:02}", h.unsigned_abs(), m.unsigned_abs()); - } - s -} - -/// The driver returns TIMESTAMP WITH TIME ZONE values as UTC date and time -/// plus the offset; this moves them to the local time of that offset. -fn local_time(t: &OracleTimestamp) -> OracleTimestamp { - use chrono::{Datelike, Timelike}; - let (h, m) = (t.tz_hour_offset(), t.tz_minute_offset()); - let minutes = i64::from(h) * 60 + i64::from(m); - let shifted = - chrono::NaiveDate::from_ymd_opt(t.year().into(), t.month().into(), t.day().into()) - .and_then(|d| d.and_hms_opt(t.hour().into(), t.minute().into(), t.second().into())) - .and_then(|dt| dt.checked_add_signed(chrono::Duration::minutes(minutes))); - match shifted { - Some(dt) => OracleTimestamp::new_timestamp_tz( - dt.year() as i16, - dt.month() as u8, - dt.day() as u8, - dt.hour() as u8, - dt.minute() as u8, - dt.second() as u8, - t.nanoseconds(), - h, - m, - ), - None => *t, - } -} - -/// Uppercase hexadecimal, the way SQL*Plus displays RAW. -fn hex(bytes: &[u8]) -> String { - let shown = &bytes[..bytes.len().min(super::binary_limit(BINARY_PREVIEW_BYTES))]; - let mut s = String::with_capacity(shown.len() * 2); - for b in shown { - let _ = write!(s, "{b:02X}"); - } - if bytes.len() > shown.len() { - let _ = write!(s, "… ({} bytes)", bytes.len()); - } - s -} - -fn vector(v: &Vector) -> String { - fn join(items: &[T]) -> String { - items - .iter() - .map(ToString::to_string) - .collect::>() - .join(",") - } - fn data(d: &VectorData) -> String { - match d { - VectorData::Float32(x) => join(x), - VectorData::Float64(x) => join(x), - VectorData::Int8(x) => join(x), - VectorData::Binary(x) => join(x), - } - } - match v { - Vector::Dense(d) => format!("[{}]", data(d)), - // Oracle's text format for sparse vectors: [dimensions,[indices],[values]] - Vector::Sparse(s) => format!( - "[{},[{}],[{}]]", - s.num_dimensions(), - join(s.indices()), - data(s.values()) - ), - } -} - -fn json(v: &JsonValue, out: &mut String) { - match v { - JsonValue::Null => out.push_str("null"), - JsonValue::Boolean(b) => out.push_str(if *b { "true" } else { "false" }), - JsonValue::Number(n) => out.push_str(&n.to_string()), - JsonValue::BinaryDouble(f) => out.push_str(&f.to_string()), - JsonValue::BinaryFloat(f) => out.push_str(&f.to_string()), - JsonValue::String(s) => out.push_str(&serde_json::to_string(s).unwrap_or_default()), - JsonValue::Timestamp(t) => { - let _ = write!(out, "\"{}\"", timestamp(t, 6, false)); - } - JsonValue::IntervalDS(i) => { - let _ = write!(out, "\"{i}\""); - } - JsonValue::IntervalYM(i) => { - let _ = write!(out, "\"{i}\""); - } - JsonValue::Raw(b) | JsonValue::JsonId(b) => { - let _ = write!(out, "\"{}\"", hex(b)); - } - JsonValue::Vector(v) => out.push_str(&vector(v)), - JsonValue::JsonArray(items) => { - out.push('['); - for (i, item) in items.iter().enumerate() { - if i > 0 { - out.push(','); - } - json(item, out); - } - out.push(']'); - } - JsonValue::JsonObject(map) => { - let mut keys: Vec<&String> = map.keys().collect(); - keys.sort(); - out.push('{'); - for (i, key) in keys.into_iter().enumerate() { - if i > 0 { - out.push(','); - } - out.push_str(&serde_json::to_string(key).unwrap_or_default()); - out.push(':'); - json(&map[key], out); - } - out.push('}'); - } - } -} - -// --------------------------------------------------------------------------- -// Editable results -// -// The thin protocol does not say which table a result column comes from, so -// the statement text is checked conservatively: one SELECT over exactly one -// table, with a select list of `*`, `alias.*` and plain columns. The table is -// resolved and its key read from the data dictionary in one query, cached -// per table name as written until DDL, ALTER SESSION or PL/SQL runs. -// --------------------------------------------------------------------------- - -const RO_TABLE: &str = "Read-only: only rows from a table can be edited."; -const RO_JOIN: &str = "Read-only: the result combines columns from several tables."; -const RO_GROUPED: &str = "Read-only: grouped or distinct rows cannot be edited."; -const RO_SET: &str = "Read-only: the result combines several queries."; -const RO_COMPLEX: &str = "Read-only: the query is too complex to map its rows to a table."; -const RO_UNKNOWN: &str = "Read-only: the table behind this result could not be identified."; -const RO_REMOTE: &str = "Read-only: tables over database links cannot be edited."; - -type TableCache = Arc, String), Arc>>>; - -enum Lookup { - Table(TableInfo), - ReadOnly(String), -} - -struct TableInfo { - owner: String, - name: String, - /// Visible columns in `select *` order. - columns: Vec, - key: Vec, - primary: bool, -} - -struct TableColumn { - name: String, - type_name: String, - nullable: bool, - generated: bool, -} - -#[derive(Debug, Clone, PartialEq)] -enum Tok { - /// Unquoted word, uppercased. - Word(String), - /// Quoted identifier, as written. - Quoted(String), - Str, - Num, - Punct(char), -} - -/// Tokens of a statement, without comments. `None` when a literal, quoted -/// identifier or comment is not closed. -fn lex(sql: &str) -> Option> { - let c: Vec = sql.chars().collect(); - let n = c.len(); - let mut out = Vec::new(); - let mut i = 0; - while i < n { - let ch = c[i]; - let next = c.get(i + 1).copied(); - if ch.is_whitespace() { - i += 1; - } else if ch == '-' && next == Some('-') { - while i < n && c[i] != '\n' { - i += 1; - } - } else if ch == '/' && next == Some('*') { - i += 2; - while i + 1 < n && !(c[i] == '*' && c[i + 1] == '/') { - i += 1; - } - if i + 1 >= n { - return None; - } - i += 2; - } else if ch == '\'' { - i = skip_string(&c, i)?; - out.push(Tok::Str); - } else if matches!(ch, 'q' | 'Q') && next == Some('\'') { - i = skip_q_string(&c, i + 1)?; - out.push(Tok::Str); - } else if matches!(ch, 'n' | 'N') && next == Some('\'') { - i = skip_string(&c, i + 1)?; - out.push(Tok::Str); - } else if matches!(ch, 'n' | 'N') - && matches!(next, Some('q' | 'Q')) - && c.get(i + 2) == Some(&'\'') - { - i = skip_q_string(&c, i + 2)?; - out.push(Tok::Str); - } else if ch == '"' { - let start = i + 1; - let end = start + c[start..].iter().position(|&x| x == '"')?; - if end == start { - return None; - } - out.push(Tok::Quoted(c[start..end].iter().collect())); - i = end + 1; - } else if ch.is_ascii_digit() || (ch == '.' && next.is_some_and(|d| d.is_ascii_digit())) { - while i < n && (c[i].is_ascii_digit() || c[i] == '.') { - i += 1; - } - if i < n && matches!(c[i], 'e' | 'E') { - let sign = usize::from(matches!(c.get(i + 1), Some('+' | '-'))); - if c.get(i + 1 + sign).is_some_and(char::is_ascii_digit) { - i += 1 + sign; - while i < n && c[i].is_ascii_digit() { - i += 1; - } - } - } - if i < n && matches!(c[i], 'f' | 'F' | 'd' | 'D') { - i += 1; - } - out.push(Tok::Num); - } else if ch.is_alphabetic() { - let start = i; - while i < n && (c[i].is_alphanumeric() || matches!(c[i], '_' | '$' | '#')) { - i += 1; - } - let word: String = c[start..i].iter().collect(); - out.push(Tok::Word(word.to_uppercase())); - } else { - out.push(Tok::Punct(ch)); - i += 1; - } - } - Some(out) -} - -/// End of a `'...'` literal that starts at `quote`. -fn skip_string(c: &[char], quote: usize) -> Option { - let mut i = quote + 1; - loop { - match c.get(i)? { - '\'' if c.get(i + 1) == Some(&'\'') => i += 2, - '\'' => return Some(i + 1), - _ => i += 1, - } - } -} - -/// End of a `q'[...]'` literal whose quote is at `quote`. -fn skip_q_string(c: &[char], quote: usize) -> Option { - let open = *c.get(quote + 1)?; - let close = match open { - '[' => ']', - '(' => ')', - '{' => '}', - '<' => '>', - x => x, - }; - let mut i = quote + 2; - loop { - if *c.get(i)? == close && c.get(i + 1) == Some(&'\'') { - return Some(i + 2); - } - i += 1; - } -} - -#[derive(Debug, PartialEq)] -enum SelItem { - /// `*` (no qualifier) or `q.*`. - Star(Vec), - Column { - qual: Vec, - name: String, - alias: Option, - }, - Expr, -} - -#[derive(Debug, PartialEq)] -struct SelectShape { - schema: Option, - table: String, - alias: Option, - items: Vec, -} - -impl SelectShape { - fn qualifier_matches(&self, qual: &[String]) -> bool { - match (qual, &self.alias, &self.schema) { - ([], _, _) => true, - ([q], Some(alias), _) => q == alias, - ([q], None, _) => *q == self.table, - ([s, q], None, Some(schema)) => s == schema && *q == self.table, - _ => false, - } - } -} - -fn name_tok(t: Option<&Tok>) -> Option { - match t? { - Tok::Word(w) | Tok::Quoted(w) => Some(w.clone()), - _ => None, - } -} - -fn word_at(toks: &[Tok], i: usize) -> Option<&str> { - match toks.get(i)? { - Tok::Word(w) => Some(w), - _ => None, - } -} - -/// Words that end the table reference instead of naming its alias. -const NOT_ALIAS: &[&str] = &[ - "WHERE", - "ORDER", - "FETCH", - "OFFSET", - "FOR", - "GROUP", - "HAVING", - "CONNECT", - "START", - "UNION", - "INTERSECT", - "MINUS", - "EXCEPT", - "JOIN", - "INNER", - "LEFT", - "RIGHT", - "FULL", - "CROSS", - "NATURAL", - "OUTER", - "PIVOT", - "UNPIVOT", - "MODEL", - "SAMPLE", - "PARTITION", - "SUBPARTITION", - "AS", - "VERSIONS", - "MATCH_RECOGNIZE", - "WINDOW", - "LIMIT", - "QUALIFY", - "APPLY", - "LATERAL", - "WITH", -]; - -/// Checks that the statement reads rows of one table and nothing else. -fn parse_select(sql: &str) -> Result { - let toks = lex(sql).ok_or(RO_COMPLEX)?; - match word_at(&toks, 0) { - Some("SELECT") => {} - _ => return Err(RO_TABLE), - } - let mut i = 1; - match word_at(&toks, i) { - Some("DISTINCT" | "UNIQUE") => return Err(RO_GROUPED), - Some("ALL") => i += 1, - _ => {} - } - - // Select list, up to FROM. - let mut items = Vec::new(); - let mut depth = 0usize; - let mut start = i; - loop { - match toks.get(i).ok_or(RO_TABLE)? { - Tok::Punct('(') => depth += 1, - Tok::Punct(')') => depth = depth.checked_sub(1).ok_or(RO_COMPLEX)?, - Tok::Punct(',') if depth == 0 => { - items.push(parse_item(&toks[start..i])); - start = i + 1; - } - Tok::Word(w) if depth == 0 && w == "FROM" => { - items.push(parse_item(&toks[start..i])); - break; - } - _ => {} - } - i += 1; - } - - // FROM [schema.]table [alias] - i += 1; - if toks.get(i) == Some(&Tok::Punct('(')) { - return Err(RO_TABLE); - } - let mut parts = vec![name_tok(toks.get(i)).ok_or(RO_COMPLEX)?]; - i += 1; - while toks.get(i) == Some(&Tok::Punct('.')) { - parts.push(name_tok(toks.get(i + 1)).ok_or(RO_COMPLEX)?); - i += 2; - } - if parts.len() > 2 { - return Err(RO_COMPLEX); - } - match toks.get(i) { - // Table functions, `only (...)`, `lateral (...)`. - Some(Tok::Punct('(')) => return Err(RO_TABLE), - Some(Tok::Punct('@')) => return Err(RO_REMOTE), - _ => {} - } - let mut alias = None; - match toks.get(i) { - Some(Tok::Quoted(a)) => { - alias = Some(a.clone()); - i += 1; - } - Some(Tok::Word(w)) if !NOT_ALIAS.contains(&w.as_str()) => { - alias = Some(w.clone()); - i += 1; - } - _ => {} - } - match toks.get(i) { - None => {} - Some(Tok::Word(w)) => match w.as_str() { - "WHERE" | "ORDER" | "FETCH" | "OFFSET" | "FOR" => {} - "JOIN" | "INNER" | "LEFT" | "RIGHT" | "FULL" | "CROSS" | "NATURAL" | "OUTER" - | "APPLY" => return Err(RO_JOIN), - "GROUP" | "HAVING" => return Err(RO_GROUPED), - "UNION" | "INTERSECT" | "MINUS" | "EXCEPT" => return Err(RO_SET), - _ => return Err(RO_COMPLEX), - }, - Some(Tok::Punct(',')) => return Err(RO_JOIN), - Some(_) => return Err(RO_COMPLEX), - } - - // The remaining clauses must not group, combine or walk the rows. - let rest = &toks[i..]; - let mut depth = 0usize; - for (j, t) in rest.iter().enumerate() { - match t { - Tok::Punct('(') => depth += 1, - Tok::Punct(')') => depth = depth.saturating_sub(1), - Tok::Word(w) if depth == 0 => match (w.as_str(), word_at(rest, j + 1)) { - ("GROUP", Some("BY")) | ("HAVING", _) => return Err(RO_GROUPED), - ("UNION" | "INTERSECT" | "MINUS" | "EXCEPT", _) => return Err(RO_SET), - ("CONNECT", Some("BY")) - | ("START", Some("WITH")) - | ("DIMENSION", Some("BY")) - | ("ORDER", Some("SIBLINGS")) => return Err(RO_COMPLEX), - _ => {} - }, - _ => {} - } - } - - let table = parts.pop().unwrap_or_default(); - Ok(SelectShape { - schema: parts.pop(), - table, - alias, - items, - }) -} - -/// One select-list item: `*`, `q.*`, a plain column with an optional alias, -/// or anything else. -fn parse_item(t: &[Tok]) -> SelItem { - if t == [Tok::Punct('*')] { - return SelItem::Star(Vec::new()); - } - let mut parts = Vec::new(); - let mut i = 0; - loop { - match t.get(i) { - Some(Tok::Word(w) | Tok::Quoted(w)) => parts.push(w.clone()), - Some(Tok::Punct('*')) if !parts.is_empty() && i + 1 == t.len() => { - return SelItem::Star(parts) - } - _ => return SelItem::Expr, - } - i += 1; - if t.get(i) == Some(&Tok::Punct('.')) { - i += 1; - } else { - break; - } - } - if parts.len() > 3 { - return SelItem::Expr; - } - let alias = match &t[i..] { - [] => None, - [Tok::Word(as_kw), a] if as_kw == "AS" => match name_tok(Some(a)) { - Some(a) => Some(a), - None => return SelItem::Expr, - }, - [a] => match name_tok(Some(a)) { - Some(a) => Some(a), - None => return SelItem::Expr, - }, - _ => return SelItem::Expr, - }; - let name = parts.pop().unwrap_or_default(); - SelItem::Column { - qual: parts, - name, - alias, - } -} - -/// Works out whether the rows of a query can be edited, and how. -fn edit_target( - conn: &Connection, - sql: &str, - cols: &[Metadata], - tables: &TableCache, -) -> Result { - let shape = parse_select(sql).map_err(str::to_string)?; - if shape.table == "DUAL" && shape.schema.as_deref().is_none_or(|s| s == "SYS") { - return Err(RO_TABLE.into()); - } - let cache_key = (shape.schema.clone(), shape.table.clone()); - let cached = tables.lock().get(&cache_key).cloned(); - let lookup = match cached { - Some(l) => l, - None => { - let l = Arc::new( - lookup_table(conn, shape.schema.as_deref(), &shape.table) - .map_err(|_| RO_UNKNOWN.to_string())?, - ); - tables.lock().insert(cache_key, l.clone()); - l - } - }; - let info = match &*lookup { - Lookup::Table(info) => info, - Lookup::ReadOnly(reason) => return Err(reason.clone()), - }; - let names: Vec<&str> = cols.iter().map(Metadata::name).collect(); - map_columns(&shape, info, &names) -} - -/// Maps result columns (by their names in the result) to table columns and -/// finds the key in the result. -fn map_columns( - shape: &SelectShape, - info: &TableInfo, - result_names: &[&str], -) -> Result { - let mismatch = || { - format!( - "Read-only: the result columns could not be matched to table {}.", - info.name - ) - }; - // Table column and the name the result should give it. - let mut mapped: Vec> = Vec::with_capacity(result_names.len()); - for item in &shape.items { - match item { - SelItem::Star(qual) => { - if !shape.qualifier_matches(qual) { - return Err(mismatch()); - } - mapped.extend(info.columns.iter().map(|c| Some((c, c.name.clone())))); - } - SelItem::Column { qual, name, alias } => { - let col = shape - .qualifier_matches(qual) - .then(|| info.columns.iter().find(|c| c.name == *name)) - .flatten(); - mapped.push(col.map(|c| (c, alias.clone().unwrap_or_else(|| c.name.clone())))); - } - SelItem::Expr => mapped.push(None), - } - } - if mapped.len() != result_names.len() { - return Err(mismatch()); - } - let mut columns = Vec::with_capacity(mapped.len()); - for (m, result_name) in mapped.iter().zip(result_names) { - columns.push(match m { - Some((c, expected)) => { - if result_name != expected { - return Err(mismatch()); - } - (!c.generated && col_type(&c.type_name).is_some()).then(|| EditColumn { - name: c.name.clone(), - type_name: c.type_name.clone(), - }) - } - None => None, - }); - } - - let mut key = Vec::with_capacity(info.key.len()); - for k in &info.key { - let found = columns - .iter() - .position(|c| c.as_ref().is_some_and(|c| c.name == *k)); - match found { - Some(i) => key.push(i), - None if mapped.iter().flatten().any(|(c, _)| c.name == *k) => { - return Err(format!( - "Read-only: key column {k} has a type that cannot be edited here." - )) - } - None => { - let kind = if info.primary { "primary key" } else { "key" }; - return Err(format!( - "Read-only: add the {kind} columns ({}) to the query to edit rows.", - info.key.join(", ") - )); - } - } - } - Ok(EditTarget { - schema: Some(info.owner.clone()), - table: info.name.clone(), - columns, - key, - }) -} - -/// Resolves a table name the way Oracle does (current schema, then public -/// synonyms; one level of synonym) and reads its columns and keys, in one -/// round trip. -const LOOKUP_SQL: &str = " -with named as ( - select o.owner, o.object_name, o.object_type - from all_objects o - where o.owner = nvl(:1, sys_context('USERENV', 'CURRENT_SCHEMA')) - and o.object_name = :2 - and o.subobject_name is null - and o.object_type in ('TABLE', 'VIEW', 'SYNONYM', 'MATERIALIZED VIEW') - union all - select s.owner, s.synonym_name, 'SYNONYM' - from all_synonyms s - where :3 is null and s.owner = 'PUBLIC' and s.synonym_name = :4 - and not exists ( - select 1 from all_objects o - where o.owner = sys_context('USERENV', 'CURRENT_SCHEMA') - and o.object_name = :5 - and o.subobject_name is null - and o.object_type in ('TABLE', 'VIEW', 'SYNONYM', 'MATERIALIZED VIEW')) -), -resolved as ( - select n.object_type kind, n.owner, n.object_name name - from named n - where n.object_type <> 'SYNONYM' - union all - select case when s.db_link is not null then 'REMOTE' - else nvl(o.object_type, 'MISSING') end, - s.table_owner, s.table_name - from named n - join all_synonyms s on s.owner = n.owner and s.synonym_name = n.object_name - left join all_objects o on o.owner = s.table_owner and o.object_name = s.table_name - and o.subobject_name is null - and o.object_type in ('TABLE', 'VIEW', 'SYNONYM', 'MATERIALIZED VIEW') - where n.object_type = 'SYNONYM' -) -select 'O', r.kind, r.owner, r.name, cast(null as varchar2(3)), cast(null as varchar2(40)) - from resolved r -union all -select 'C', c.column_name, - case - when c.data_type in ('VARCHAR2', 'NVARCHAR2', 'CHAR', 'NCHAR', 'RAW') - then c.data_type || '(' || - case when c.char_length > 0 then c.char_length else c.data_length end || ')' - when c.data_type = 'NUMBER' and c.data_precision is not null - then 'NUMBER(' || c.data_precision || - case when c.data_scale <> 0 then ',' || c.data_scale end || ')' - when c.data_type = 'FLOAT' and c.data_precision is not null - then 'FLOAT(' || c.data_precision || ')' - else c.data_type end, - c.nullable, c.virtual_column, to_char(c.column_id) - from resolved r - join all_tab_cols c on c.owner = r.owner and c.table_name = r.name - where r.kind = 'TABLE' and c.hidden_column = 'NO' and c.column_id is not null -union all -select 'K', k.constraint_type, k.constraint_name, kc.column_name, - cast(null as varchar2(3)), to_char(kc.position) - from resolved r - join all_constraints k on k.owner = r.owner and k.table_name = r.name - join all_cons_columns kc on kc.owner = k.owner - and kc.constraint_name = k.constraint_name and kc.table_name = k.table_name - where r.kind = 'TABLE' and k.constraint_type in ('P', 'U') and k.status = 'ENABLED'"; - -fn lookup_table( - conn: &Connection, - schema: Option<&str>, - name: &str, -) -> Result { - let schema = schema.map(str::to_string); - let name = name.to_string(); - let schema_bind: &dyn oracledb::ToDbValue = match &schema { - Some(s) => s, - None => &oracledb::DB_TYPE_VARCHAR, - }; - let cursor = conn.query(LOOKUP_SQL, &[schema_bind, &name, schema_bind, &name, &name])?; - let mut rows = Vec::new(); - for row in cursor { - let row = row?; - let mut cells = Vec::with_capacity(6); - for i in 0..6 { - cells.push(row.get::>(i)?.unwrap_or_default()); - } - rows.push(cells); - } - Ok(table_info(&name, rows)) -} - -/// Builds the table description from the rows of [`LOOKUP_SQL`]. -fn table_info(written: &str, rows: Vec>) -> Lookup { - let mut kinds = Vec::new(); - let mut target = None; - let mut columns: Vec<(u32, TableColumn)> = Vec::new(); - // (type, name) -> [(position, column)], ordered by constraint name. - let mut constraints: std::collections::BTreeMap<(String, String), Vec<(u32, String)>> = - Default::default(); - for r in rows { - match r[0].as_str() { - "O" => { - if r[1] == "TABLE" { - target = Some((r[2].clone(), r[3].clone())); - } - kinds.push(r[1].clone()); - } - "C" => columns.push(( - r[5].parse().unwrap_or(u32::MAX), - TableColumn { - name: r[1].clone(), - type_name: r[2].clone(), - nullable: r[3] != "N", - generated: r[4] == "YES", - }, - )), - "K" => constraints - .entry((r[1].clone(), r[2].clone())) - .or_default() - .push((r[5].parse().unwrap_or(u32::MAX), r[3].clone())), - _ => {} - } - } - let has = |k: &str| kinds.iter().any(|x| x == k); - if has("MATERIALIZED VIEW") { - return Lookup::ReadOnly(format!("Read-only: {written} is a materialized view.")); - } - if has("REMOTE") { - return Lookup::ReadOnly(RO_REMOTE.into()); - } - if has("VIEW") { - return Lookup::ReadOnly(format!( - "Read-only: {written} is a view; only tables can be edited." - )); - } - let Some((owner, name)) = target else { - return Lookup::ReadOnly(RO_TABLE.into()); - }; - columns.sort_by_key(|(id, _)| *id); - let columns: Vec = columns.into_iter().map(|(_, c)| c).collect(); - - // The primary key, else the narrowest unique key on NOT NULL columns. - let mut keys: Vec<(bool, Vec)> = constraints - .into_iter() - .map(|((kind, _), mut cols)| { - cols.sort_by_key(|(pos, _)| *pos); - (kind == "P", cols.into_iter().map(|(_, c)| c).collect()) - }) - .filter(|(primary, cols): &(bool, Vec)| { - *primary - || cols - .iter() - .all(|k| columns.iter().any(|c| c.name == *k && !c.nullable)) - }) - .collect(); - keys.sort_by_key(|(primary, cols)| (!*primary, cols.len())); - let Some((primary, key)) = keys.into_iter().next() else { - return Lookup::ReadOnly(format!("Read-only: table {name} has no primary key.")); - }; - Lookup::Table(TableInfo { - owner, - name, - columns, - key, - primary, - }) -} - -// --------------------------------------------------------------------------- -// Applying grid changes -// --------------------------------------------------------------------------- - -/// Largest string or RAW value bound as one value (the PL/SQL limit). -const MAX_BIND_BYTES: usize = 32767; -/// Digits an Oracle NUMBER mantissa can hold. -const NUMBER_DIGITS: usize = 40; - -/// How a column's text is converted and bound. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ColType { - Number, - BinaryFloat, - BinaryDouble, - Date, - Timestamp, - TimestampTz, - Text, - Binary, - Bool, -} - -/// Types the grid can write. TIMESTAMP WITH LOCAL TIME ZONE, intervals, -/// LONG, JSON, objects and the like stay read-only. -fn col_type(type_name: &str) -> Option { - let t = type_name.trim().to_ascii_uppercase(); - if t.starts_with("TIMESTAMP") { - return if t.contains("LOCAL") { - None - } else if t.contains("TIME ZONE") { - Some(ColType::TimestampTz) - } else { - Some(ColType::Timestamp) - }; - } - let base = t.split(['(', ' ']).next().unwrap_or_default(); - Some(match base { - "NUMBER" | "FLOAT" | "INTEGER" | "DECIMAL" => ColType::Number, - "BINARY_FLOAT" => ColType::BinaryFloat, - "BINARY_DOUBLE" => ColType::BinaryDouble, - "DATE" => ColType::Date, - "VARCHAR2" | "NVARCHAR2" | "VARCHAR" | "CHAR" | "NCHAR" | "CLOB" | "NCLOB" => ColType::Text, - "RAW" | "BLOB" => ColType::Binary, - "BOOLEAN" => ColType::Bool, - _ => return None, - }) -} - -enum Bind { - Text(String), - Number(OracleNumber), - Float(f32), - Double(f64), - Time(OracleTimestamp), - Raw(Vec), - Bool(bool), -} - -impl Bind { - fn value(&self) -> &dyn oracledb::ToDbValue { - match self { - Bind::Text(v) => v, - Bind::Number(v) => v, - Bind::Float(v) => v, - Bind::Double(v) => v, - Bind::Time(v) => v, - Bind::Raw(v) => v, - Bind::Bool(v) => v, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Op { - Update, - Delete, - Insert, -} - -struct Planned { - /// 1-based index of the change. - row: usize, - op: Op, - sql: String, - binds: Vec, -} - -/// A number from its text: exact digits for an `OracleNumber` bind, or -/// `E` for `to_number`, which has no decimal or group -/// character and so does not depend on NLS settings. -enum NumberText { - Exact(OracleNumber), - Scientific(String), -} - -/// Parses `[-+]digits[.digits]`. Integers ending in zeros go through -/// `to_number`: the driver encodes their trailing zero digits instead of -/// dropping them, which is not Oracle's canonical NUMBER form. -fn parse_number(text: &str) -> Option { - let s = text.trim(); - let (negative, body) = match s.strip_prefix('-') { - Some(b) => (true, b), - None => (false, s.strip_prefix('+').unwrap_or(s)), - }; - let (int, frac) = body.split_once('.').unwrap_or((body, "")); - if (int.is_empty() && frac.is_empty()) - || !int.bytes().all(|b| b.is_ascii_digit()) - || !frac.bytes().all(|b| b.is_ascii_digit()) - { - return None; - } - let int = int.trim_start_matches('0'); - let frac = frac.trim_end_matches('0'); - let sign = if negative { "-" } else { "" }; - if frac.is_empty() && int.is_empty() { - return "0".parse().ok().map(NumberText::Exact); - } - if frac.is_empty() && int.ends_with('0') { - let mantissa = int.trim_end_matches('0'); - if mantissa.len() > NUMBER_DIGITS { - return None; - } - let exponent = int.len() - mantissa.len(); - return Some(NumberText::Scientific(format!( - "{sign}{mantissa}E{exponent}" - ))); - } - if int.len() + frac.len() > NUMBER_DIGITS { - // Leading zeros of the fraction do not count as digits. - let digits = if int.is_empty() { - frac.trim_start_matches('0').len() - } else { - int.len() + frac.len() - }; - if digits > NUMBER_DIGITS { - return None; - } - } - let int = if int.is_empty() { "0" } else { int }; - let text = if frac.is_empty() { - format!("{sign}{int}") - } else { - format!("{sign}{int}.{frac}") - }; - text.parse().ok().map(NumberText::Exact) -} - -/// Parses the format [`timestamp`] prints: -/// `YYYY-MM-DD[ HH:MI:SS[.fffffffff]][ +HH:MM]` (`T` may separate date and -/// time). Returns the offset as `+HH:MM`. -fn parse_timestamp(text: &str) -> Option<(OracleTimestamp, Option)> { - fn num(s: &str) -> Option { - if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) { - return None; - } - s.parse().ok() - } - let s = text.trim(); - let date = s.get(..10)?; - if date.as_bytes()[4] != b'-' || date.as_bytes()[7] != b'-' { - return None; - } - let year = num(&date[..4])?; - let month = num(&date[5..7])?; - let day = num(&date[8..10])?; - if year == 0 { - return None; - } - chrono::NaiveDate::from_ymd_opt(year as i32, month, day)?; - - let mut rest = &s[10..]; - let (mut hour, mut minute, mut second, mut nanos) = (0, 0, 0, 0); - let b = rest.as_bytes(); - if b.len() >= 9 && matches!(b[0], b' ' | b'T') && b[3] == b':' && b[6] == b':' { - hour = num(rest.get(1..3)?)?; - minute = num(rest.get(4..6)?)?; - second = num(rest.get(7..9)?)?; - if hour > 23 || minute > 59 || second > 59 { - return None; - } - rest = rest.get(9..)?; - if let Some(f) = rest.strip_prefix('.') { - let digits = f.bytes().take_while(u8::is_ascii_digit).count(); - if digits == 0 || digits > 9 { - return None; - } - nanos = num(&f[..digits])? * 10u32.pow((9 - digits) as u32); - rest = &f[digits..]; - } - } - let rest = rest.trim_start(); - let tz = if rest.is_empty() { - None - } else { - let b = rest.as_bytes(); - if b.len() != 6 || !matches!(b[0], b'+' | b'-') || b[3] != b':' { - return None; - } - let hh = num(rest.get(1..3)?)?; - let mm = num(rest.get(4..6)?)?; - if hh > 14 || mm > 59 { - return None; - } - Some(rest.to_string()) - }; - let t = OracleTimestamp::new_timestamp( - year as i16, - month as u8, - day as u8, - hour as u8, - minute as u8, - second as u8, - nanos, - ); - Some((t, tz)) -} - -fn parse_hex(text: &str) -> Option> { - let s = text.trim(); - if !s.len().is_multiple_of(2) { - return None; - } - (0..s.len()) - .step_by(2) - .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()) - .collect() -} - -fn parse_bool(text: &str) -> Option { - match text.trim().to_ascii_uppercase().as_str() { - "TRUE" | "1" => Some(true), - "FALSE" | "0" => Some(false), - _ => None, - } -} - -/// Quoted identifier. Oracle names cannot contain double quotes. -fn quote_ident(name: &str) -> AppResult { - if name.is_empty() || name.contains(['"', '\0']) { - return Err(AppError::invalid(format!("Invalid name: {name}"))); - } - Ok(format!("\"{name}\"")) -} - -fn too_long(name: &str) -> AppError { - AppError::invalid(format!( - "Column {name}: values longer than {MAX_BIND_BYTES} bytes cannot be saved from the grid." - )) -} - -/// Binds of one statement, numbered in order of appearance. -#[derive(Default)] -struct SqlBuilder { - binds: Vec, -} - -impl SqlBuilder { - fn bind(&mut self, b: Bind) -> String { - self.binds.push(b); - format!(":{}", self.binds.len()) - } - - /// SQL expression for a value of `col`: a typed bind, wrapped where the - /// bind type alone does not say enough. - fn value(&mut self, col: &EditColumn, text: &str) -> AppResult { - let name = &col.name; - let ty = col_type(&col.type_name) - .ok_or_else(|| AppError::invalid(format!("Column {name} cannot be edited here.")))?; - let bad = |what: &str| { - AppError::invalid(format!("Column {name}: '{text}' is not a valid {what}.")) - }; - Ok(match ty { - ColType::Number => match parse_number(text).ok_or_else(|| bad("number"))? { - NumberText::Exact(n) => self.bind(Bind::Number(n)), - NumberText::Scientific(s) => format!("to_number({})", self.bind(Bind::Text(s))), - }, - ColType::BinaryFloat => { - let v = text.trim().parse::().map_err(|_| bad("number"))?; - self.bind(Bind::Float(v)) - } - ColType::BinaryDouble => { - let v = text.trim().parse::().map_err(|_| bad("number"))?; - self.bind(Bind::Double(v)) - } - ColType::Date => match parse_timestamp(text) { - Some((t, None)) if t.nanoseconds() == 0 => { - format!("cast({} as date)", self.bind(Bind::Time(t))) - } - _ => return Err(bad("date (YYYY-MM-DD HH:MI:SS)")), - }, - ColType::Timestamp => match parse_timestamp(text) { - Some((t, None)) => self.bind(Bind::Time(t)), - _ => return Err(bad("timestamp (YYYY-MM-DD HH:MI:SS.FF)")), - }, - ColType::TimestampTz => match parse_timestamp(text) { - Some((t, Some(tz))) => { - let ts = self.bind(Bind::Time(t)); - let tz = self.bind(Bind::Text(tz)); - format!("from_tz({ts}, {tz})") - } - _ => { - return Err(bad( - "timestamp with time zone (YYYY-MM-DD HH:MI:SS.FF +HH:MM)", - )) - } - }, - ColType::Text => { - if text.len() > MAX_BIND_BYTES { - return Err(too_long(name)); - } - self.bind(Bind::Text(text.to_string())) - } - ColType::Binary => { - if text.contains("… (") { - return Err(AppError::invalid( - "This value is only a preview and cannot be saved.", - )); - } - let bytes = parse_hex(text).ok_or_else(|| bad("hexadecimal value"))?; - if bytes.len() > MAX_BIND_BYTES { - return Err(too_long(name)); - } - self.bind(Bind::Raw(bytes)) - } - ColType::Bool => { - let v = parse_bool(text).ok_or_else(|| bad("boolean (TRUE or FALSE)"))?; - self.bind(Bind::Bool(v)) - } - }) - } - - fn value_or_null(&mut self, col: &EditColumn, value: &Option) -> AppResult { - match value { - Some(text) => self.value(col, text), - None => Ok("null".into()), - } - } - - /// `k1 = :n and k2 is null ...` - fn key_filter( - &mut self, - key_cols: &[&EditColumn], - key: &[Option], - ) -> AppResult { - if key.len() != key_cols.len() { - return Err(AppError::invalid("The row key does not match the result.")); - } - let mut parts = Vec::with_capacity(key.len()); - for (col, value) in key_cols.iter().zip(key) { - let ident = quote_ident(&col.name)?; - parts.push(match value { - Some(text) => format!("{ident} = {}", self.value(col, text)?), - None => format!("{ident} is null"), - }); - } - Ok(parts.join(" and ")) - } -} - -fn edit_column(target: &EditTarget, index: usize) -> AppResult<&EditColumn> { - target - .columns - .get(index) - .and_then(Option::as_ref) - .ok_or_else(|| AppError::invalid(format!("Result column {} cannot be edited.", index + 1))) -} - -/// Values by table column; a column given twice keeps the last value. -fn change_values<'a>( - target: &'a EditTarget, - values: &'a [CellValue], -) -> AppResult)>> { - let mut out: Vec<(&EditColumn, &Option)> = Vec::with_capacity(values.len()); - for v in values { - let col = edit_column(target, v.column)?; - match out.iter_mut().find(|(c, _)| c.name == col.name) { - Some(slot) => slot.1 = &v.value, - None => out.push((col, &v.value)), - } - } - Ok(out) -} - -/// Builds every statement before anything runs, so bad input changes nothing. -fn plan_changes(req: &ApplyRequest) -> AppResult> { - let target = &req.target; - let table = match &target.schema { - Some(schema) => format!("{}.{}", quote_ident(schema)?, quote_ident(&target.table)?), - None => quote_ident(&target.table)?, - }; - let key_cols = target - .key - .iter() - .map(|&i| edit_column(target, i)) - .collect::>>()?; - let mut planned = Vec::with_capacity(req.changes.len()); - for (n, change) in req.changes.iter().enumerate() { - let mut b = SqlBuilder::default(); - let (op, sql) = match change { - RowChange::Update { key, values } => { - let values = change_values(target, values)?; - if values.is_empty() { - continue; - } - let mut sets = Vec::with_capacity(values.len()); - for (col, value) in values { - let expr = b.value_or_null(col, value)?; - sets.push(format!("{} = {expr}", quote_ident(&col.name)?)); - } - let filter = b.key_filter(&key_cols, key)?; - let sql = format!("update {table} set {} where {filter}", sets.join(", ")); - (Op::Update, sql) - } - RowChange::Delete { key } => { - let filter = b.key_filter(&key_cols, key)?; - (Op::Delete, format!("delete from {table} where {filter}")) - } - RowChange::Insert { values } => { - let values = change_values(target, values)?; - let sql = if values.is_empty() { - // Oracle has no DEFAULT VALUES: name one column as DEFAULT. - let col = - target.columns.iter().flatten().next().ok_or_else(|| { - AppError::invalid("This result has no editable columns.") - })?; - let ident = quote_ident(&col.name)?; - format!("insert into {table} ({ident}) values (default)") - } else { - let mut names = Vec::with_capacity(values.len()); - let mut exprs = Vec::with_capacity(values.len()); - for (col, value) in values { - names.push(quote_ident(&col.name)?); - exprs.push(b.value_or_null(col, value)?); - } - format!( - "insert into {table} ({}) values ({})", - names.join(", "), - exprs.join(", ") - ) - }; - (Op::Insert, sql) - } - }; - planned.push(Planned { - row: n + 1, - op, - sql, - binds: b.binds, - }); - } - Ok(planned) -} - -fn not_saved(row: usize, matched: u64) -> AppError { - let message = if matched == 0 { - format!( - "Row {row} was not saved: 0 rows matched its key (changed or removed by someone else)." - ) - } else { - format!("Row {row} was not saved: {matched} rows matched its key.") - }; - AppError::new(ErrorKind::Database, message) -} - -fn run_changes(conn: &Connection, planned: &[Planned], out: &mut ApplyResult) -> AppResult<()> { - for p in planned { - let binds: Vec<&dyn oracledb::ToDbValue> = p.binds.iter().map(Bind::value).collect(); - let affected = conn - .execute(&p.sql, &binds) - .map_err(map_error)? - .rows_affected(); - if affected != 1 { - return Err(not_saved(p.row, affected)); - } - match p.op { - Op::Update => out.updated += 1, - Op::Delete => out.deleted += 1, - Op::Insert => out.inserted += 1, - } - } - Ok(()) -} - -fn apply_blocking( - conn: &Connection, - req: &ApplyRequest, - state: &Mutex, -) -> AppResult { - let started = Instant::now(); - let planned = plan_changes(req)?; - let autocommit = state.lock().autocommit; - if !autocommit { - // On failure only these changes are undone; earlier work of the open - // transaction stays. - conn.execute("savepoint lq_grid_apply", &[]) - .map_err(map_error)?; - } - let mut out = ApplyResult::default(); - if let Err(e) = run_changes(conn, &planned, &mut out) { - if autocommit { - let _ = conn.rollback(); - } else { - let _ = conn.execute("rollback to savepoint lq_grid_apply", &[]); - } - return Err(e); - } - if autocommit { - if let Err(e) = conn.commit() { - let _ = conn.rollback(); - return Err(map_error(e)); - } - state.lock().in_transaction = false; - } else if !planned.is_empty() { - state.lock().in_transaction = true; - } - out.elapsed_ms = started.elapsed().as_millis() as u64; - out.in_transaction = state.lock().in_transaction; - Ok(out) -} - -fn connection_error(e: oracledb::Error) -> AppError { - let mut err = map_error(e); - err.kind = ErrorKind::Connection; - err -} - -pub fn map_error(e: oracledb::Error) -> AppError { - use oracledb::ErrorKind as K; - match e.kind() { - K::DbError(db) => { - let code = format!("ORA-{:05}", db.code()); - let message = db.message(); - let message = message - .strip_prefix(&format!("{code}: ")) - .unwrap_or(message) - .trim_end() - .to_string(); - let mut err = AppError::new(ErrorKind::Database, message); - // 1013: "user requested cancel of current operation". - if db.code() == 1013 { - err.kind = ErrorKind::Cancelled; - } - if db.offset() > 0 { - err.position = Some(db.offset()); - } - err.code = Some(code); - err - } - K::DeadConnection | K::NotConnected => { - AppError::connection("The connection to the server was closed.") - } - K::CallTimeoutExceeded => AppError::new(ErrorKind::Cancelled, "Call timeout exceeded."), - // The driver lost its place in the server's reply; the session - // replaces the connection (see `OraSession::reopen`). - K::UnknownTtcMessageType(..) - | K::UnknownServerSidePiggyback(_) - | K::OutOfData - | K::UnexpectedResult - | K::UnexpectedError - | K::UnableToRecover => AppError::new(ErrorKind::Internal, e.to_string()), - _ => AppError::new(ErrorKind::Database, e.to_string()), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn strips_terminators_only_for_sql() { - assert_eq!(prepare_sql("select 1 from dual;"), "select 1 from dual"); - assert_eq!(prepare_sql("select 1 from dual\n/"), "select 1 from dual"); - assert_eq!(prepare_sql("begin null; end;\n/"), "begin null; end;"); - assert_eq!( - prepare_sql("create or replace procedure p as begin null; end;"), - "create or replace procedure p as begin null; end;" - ); - assert_eq!( - prepare_sql("select 10/2 from dual"), - "select 10/2 from dual" - ); - } - - #[test] - fn detects_plsql_units() { - assert!(is_plsql("DECLARE x number; BEGIN null; END;")); - assert!(is_plsql( - "create or replace editionable package body pkg as end;" - )); - assert!(is_plsql( - "CREATE TRIGGER t BEFORE INSERT ON x BEGIN NULL; END;" - )); - assert!(!is_plsql("create table t (id number)")); - assert!(!is_plsql( - "create or replace view v as select 1 x from dual" - )); - } - - // --- Editable results: pure helpers --- - - fn col(name: &str, type_name: &str) -> TableColumn { - TableColumn { - name: name.into(), - type_name: type_name.into(), - nullable: true, - generated: false, - } - } - - fn edit_col(name: &str, type_name: &str) -> Option { - Some(EditColumn { - name: name.into(), - type_name: type_name.into(), - }) - } - - #[test] - fn parses_single_table_selects() { - let s = parse_select( - "select /*+ first_rows */ id, t.name, qty * 2 as dbl, q'[it's, from]' lit -- x\n from lq t where x = 'a, from' order by 1", - ) - .unwrap(); - assert_eq!(s.schema, None); - assert_eq!(s.table, "LQ"); - assert_eq!(s.alias.as_deref(), Some("T")); - assert_eq!( - s.items, - [ - SelItem::Column { - qual: vec![], - name: "ID".into(), - alias: None - }, - SelItem::Column { - qual: vec!["T".into()], - name: "NAME".into(), - alias: None - }, - SelItem::Expr, - SelItem::Expr, - ] - ); - - let s = parse_select(r#"select m.*, "Some Col" as "x" from app."My Tab" m for update"#) - .unwrap(); - assert_eq!(s.schema.as_deref(), Some("APP")); - assert_eq!(s.table, "My Tab"); - assert_eq!( - s.items, - [ - SelItem::Star(vec!["M".into()]), - SelItem::Column { - qual: vec![], - name: "Some Col".into(), - alias: Some("x".into()) - }, - ] - ); - - // A subquery in WHERE does not change where the rows come from. - assert!(parse_select( - "select * from t where id in (select id from u group by id) fetch first 5 rows only" - ) - .is_ok()); - } - - #[test] - fn rejects_other_query_shapes() { - let cases = [ - ("select a.id from a join b on a.id = b.id", RO_JOIN), - ("select * from a, b", RO_JOIN), - ("select * from a left outer join b using (id)", RO_JOIN), - ("select * from (select 1 x from dual)", RO_TABLE), - ("select * from table(f())", RO_TABLE), - ("with q as (select 1 from dual) select * from q", RO_TABLE), - ("select distinct x from t", RO_GROUPED), - ("select x, count(*) from t group by x", RO_GROUPED), - ("select x from t having count(*) > 1", RO_GROUPED), - ("select x from t union all select x from u", RO_SET), - ("select x from t where a = 1 minus select x from u", RO_SET), - ("select level from t connect by level < 3", RO_COMPLEX), - ("select * from t as of scn 1", RO_COMPLEX), - ("select * from t sample (10)", RO_COMPLEX), - ("select * from t pivot (sum(v) for k in (1))", RO_COMPLEX), - ("select * from t@remote", RO_REMOTE), - ("update t set x = 1", RO_TABLE), - ("select 'unclosed from t", RO_COMPLEX), - ]; - for (sql, reason) in cases { - assert_eq!(parse_select(sql), Err(reason), "{sql}"); - } - } - - fn sample_table() -> TableInfo { - let mut gen = col("TOTAL", "NUMBER"); - gen.generated = true; - TableInfo { - owner: "APP".into(), - name: "ORDERS".into(), - columns: vec![ - col("ID", "NUMBER(10)"), - col("NAME", "VARCHAR2(50)"), - gen, - col("SEEN", "TIMESTAMP(6) WITH LOCAL TIME ZONE"), - ], - key: vec!["ID".into()], - primary: true, - } - } - - #[test] - fn maps_result_columns_to_the_table() { - let info = sample_table(); - let shape = parse_select("select name, o.id, id + 1, total from orders o").unwrap(); - let t = map_columns(&shape, &info, &["NAME", "ID", "ID+1", "TOTAL"]).unwrap(); - assert_eq!(t.schema.as_deref(), Some("APP")); - assert_eq!(t.table, "ORDERS"); - assert_eq!(t.key, [1]); - assert_eq!(t.columns[0].as_ref().unwrap().name, "NAME"); - assert_eq!(t.columns[1].as_ref().unwrap().type_name, "NUMBER(10)"); - // Expression, virtual column. - assert!(t.columns[2].is_none()); - assert!(t.columns[3].is_none()); - - let shape = parse_select("select * from orders").unwrap(); - let t = map_columns(&shape, &info, &["ID", "NAME", "TOTAL", "SEEN"]).unwrap(); - assert_eq!(t.key, [0]); - // TIMESTAMP WITH LOCAL TIME ZONE stays read-only. - assert!(t.columns[3].is_none()); - - // The result must line up with what the text says. - assert!(map_columns(&shape, &info, &["ID", "NAME"]).is_err()); - let shape = parse_select("select id x from orders").unwrap(); - assert!(map_columns(&shape, &info, &["ID"]).is_err()); - assert!(map_columns(&shape, &info, &["X"]).is_ok()); - - let shape = parse_select("select name from orders").unwrap(); - let reason = map_columns(&shape, &info, &["NAME"]).unwrap_err(); - assert_eq!( - reason, - "Read-only: add the primary key columns (ID) to the query to edit rows." - ); - - // A qualifier that is not the table is not one of its columns. - let shape = parse_select("select s.id, id from orders").unwrap(); - let t = map_columns(&shape, &info, &["ID", "ID"]).unwrap(); - assert!(t.columns[0].is_none()); - assert_eq!(t.key, [1]); - } - - fn row(cells: &[&str]) -> Vec { - cells.iter().map(|c| c.to_string()).collect() - } - - #[test] - fn chooses_the_table_key() { - let rows = vec![ - row(&["O", "TABLE", "APP", "T", "", ""]), - row(&["C", "B", "VARCHAR2(10)", "N", "NO", "2"]), - row(&["C", "A", "NUMBER", "Y", "NO", "1"]), - row(&["C", "C", "NUMBER", "N", "NO", "3"]), - row(&["K", "U", "T_A", "A", "", "1"]), - row(&["K", "U", "T_BC", "C", "", "2"]), - row(&["K", "U", "T_BC", "B", "", "1"]), - ]; - let Lookup::Table(info) = table_info("T", rows.clone()) else { - panic!("not a table") - }; - assert_eq!( - info.columns - .iter() - .map(|c| c.name.as_str()) - .collect::>(), - ["A", "B", "C"] - ); - // T_A is on a nullable column. - assert_eq!(info.key, ["B", "C"]); - assert!(!info.primary); - - let mut with_pk = rows.clone(); - with_pk.push(row(&["K", "P", "T_PK", "A", "", "1"])); - let Lookup::Table(info) = table_info("T", with_pk) else { - panic!("not a table") - }; - assert_eq!(info.key, ["A"]); - assert!(info.primary); - - let Lookup::ReadOnly(reason) = table_info("T", rows[..4].to_vec()) else { - panic!("editable without a key") - }; - assert_eq!(reason, "Read-only: table T has no primary key."); - - let Lookup::ReadOnly(reason) = - table_info("V", vec![row(&["O", "VIEW", "APP", "V", "", ""])]) - else { - panic!("view") - }; - assert!(reason.contains("view"), "{reason}"); - assert!(matches!(table_info("X", vec![]), Lookup::ReadOnly(_))); - } - - fn number(text: &str) -> String { - match parse_number(text).unwrap_or_else(|| panic!("{text}")) { - NumberText::Exact(n) => n.to_string(), - NumberText::Scientific(s) => format!("sci {s}"), - } - } - - #[test] - fn converts_numbers_without_nls() { - assert_eq!(number("123.4500"), "123.45"); - assert_eq!(number("-0.001"), "-0.001"); - assert_eq!(number(".5"), "0.5"); - assert_eq!(number("+7"), "7"); - assert_eq!(number("0"), "0"); - assert_eq!(number("-0.0"), "0"); - assert_eq!(number("15"), "15"); - assert_eq!( - number("12345678901234567890.123456789"), - "12345678901234567890.123456789" - ); - assert_eq!(number("100"), "sci 1E2"); - assert_eq!(number("-1000"), "sci -1E3"); - assert_eq!(number(&format!("1{}", "0".repeat(125))), "sci 1E125"); - assert_eq!( - number(&format!("0.{}1", "0".repeat(120))), - format!("0.{}1", "0".repeat(120)) - ); - for bad in ["", "-", "abc", "1e5", "1,5", "1.2.3", " ", &"9".repeat(41)] { - assert!(parse_number(bad).is_none(), "{bad}"); - } - } - - #[test] - fn parses_displayed_timestamps() { - let (t, tz) = parse_timestamp("2024-05-01 13:45:07").unwrap(); - assert_eq!( - ( - t.year(), - t.month(), - t.day(), - t.hour(), - t.minute(), - t.second() - ), - (2024, 5, 1, 13, 45, 7) - ); - assert_eq!((t.nanoseconds(), tz), (0, None)); - let (t, _) = parse_timestamp("2024-05-01 13:45:07.123").unwrap(); - assert_eq!(t.nanoseconds(), 123_000_000); - let (t, tz) = parse_timestamp("2024-05-01 13:45:07.123456789 -06:00").unwrap(); - assert_eq!(t.nanoseconds(), 123_456_789); - assert_eq!(tz.as_deref(), Some("-06:00")); - let (t, _) = parse_timestamp("2024-05-01").unwrap(); - assert_eq!((t.hour(), t.second()), (0, 0)); - assert!(parse_timestamp("2024-05-01T13:45:07").is_some()); - for bad in [ - "2024-02-30 00:00:00", - "2024-05-01 24:00:00", - "2024-05-01 13:45", - "2024-05-01 13:45:07.", - "2024-05-01 13:45:07 +3", - "01/05/2024", - "", - ] { - assert!(parse_timestamp(bad).is_none(), "{bad}"); - } - - // What `timestamp` prints parses back to the same value. - let t = OracleTimestamp::new_timestamp(1999, 12, 31, 23, 59, 58, 120_000_000); - let shown = timestamp(&t, 6, false); - assert_eq!(shown, "1999-12-31 23:59:58.120000"); - assert_eq!(parse_timestamp(&shown).unwrap().0, t); - } - - #[test] - fn shows_time_zone_values_in_local_time() { - // The driver hands over UTC plus the offset. - let utc = OracleTimestamp::new_timestamp_tz(2025, 10, 31, 17, 52, 15, 456_000_000, -6, 0); - assert_eq!(timestamp(&utc, 3, true), "2025-10-31 11:52:15.456 -06:00"); - let utc = OracleTimestamp::new_timestamp_tz(2024, 1, 1, 2, 0, 0, 0, -3, -30); - assert_eq!(timestamp(&utc, 0, true), "2023-12-31 22:30:00 -03:30"); - let utc = OracleTimestamp::new_timestamp_tz(2024, 2, 28, 20, 0, 0, 0, 5, 30); - assert_eq!(timestamp(&utc, 0, true), "2024-02-29 01:30:00 +05:30"); - } - - #[test] - fn parses_binary_and_bool() { - assert_eq!(parse_hex("DEADbeef"), Some(vec![0xDE, 0xAD, 0xBE, 0xEF])); - assert_eq!(parse_hex(""), Some(vec![])); - assert_eq!(parse_hex("ABC"), None); - assert_eq!(parse_hex("ZZ"), None); - assert_eq!(parse_bool("true"), Some(true)); - assert_eq!(parse_bool("FALSE"), Some(false)); - assert_eq!(parse_bool("yes"), None); - } - - fn sample_target() -> EditTarget { - EditTarget { - schema: Some("APP".into()), - table: "My Tab".into(), - columns: vec![ - edit_col("ID", "NUMBER(10)"), - edit_col("Some Value", "VARCHAR2(20)"), - None, - edit_col("D", "DATE"), - edit_col("TZ", "TIMESTAMP(6) WITH TIME ZONE"), - edit_col("BIN", "BLOB"), - edit_col("F", "BINARY_DOUBLE"), - ], - key: vec![0], - } - } - - fn cv(column: usize, value: Option<&str>) -> CellValue { - CellValue { - column, - value: value.map(str::to_string), - } - } - - fn plan(changes: Vec) -> AppResult> { - plan_changes(&ApplyRequest { - target: sample_target(), - changes, - }) - } - - #[test] - fn builds_statements_with_binds() { - let p = plan(vec![ - RowChange::Update { - key: vec![Some("10".into())], - values: vec![cv(1, Some("x")), cv(3, None), cv(1, Some("it's"))], - }, - RowChange::Delete { key: vec![None] }, - RowChange::Insert { values: vec![] }, - RowChange::Insert { - values: vec![ - cv(3, Some("2024-02-29 13:00:00")), - cv(4, Some("2024-02-29 13:00:00.5 +03:00")), - cv(6, Some("Inf")), - ], - }, - RowChange::Update { - key: vec![Some("7".into())], - values: vec![], - }, - ]) - .unwrap(); - assert_eq!(p.len(), 4); - assert_eq!( - p[0].sql, - r#"update "APP"."My Tab" set "Some Value" = :1, "D" = null where "ID" = to_number(:2)"# - ); - assert!(matches!(&p[0].binds[0], Bind::Text(s) if s == "it's")); - assert!(matches!(&p[0].binds[1], Bind::Text(s) if s == "1E1")); - assert_eq!(p[1].sql, r#"delete from "APP"."My Tab" where "ID" is null"#); - assert_eq!(p[1].op, Op::Delete); - assert_eq!( - p[2].sql, - r#"insert into "APP"."My Tab" ("ID") values (default)"# - ); - assert_eq!( - p[3].sql, - r#"insert into "APP"."My Tab" ("D", "TZ", "F") values (cast(:1 as date), from_tz(:2, :3), :4)"# - ); - assert!(matches!(&p[3].binds[2], Bind::Text(s) if s == "+03:00")); - assert!(matches!(&p[3].binds[3], Bind::Double(f) if f.is_infinite())); - assert_eq!(p[3].row, 4); - } - - #[test] - fn rejects_bad_changes() { - let invalid = |changes: Vec| { - let err = plan(changes).err().expect("should fail"); - assert_eq!(err.kind, ErrorKind::Invalid, "{err}"); - err.message - }; - // Expression column. - invalid(vec![RowChange::Insert { - values: vec![cv(2, Some("1"))], - }]); - invalid(vec![RowChange::Delete { - key: vec![Some("abc".into())], - }]); - invalid(vec![RowChange::Delete { key: vec![] }]); - invalid(vec![RowChange::Insert { - values: vec![cv(3, Some("2024-01-01 10:00:00.5"))], - }]); - invalid(vec![RowChange::Insert { - values: vec![cv(4, Some("2024-01-01 10:00:00"))], - }]); - let msg = invalid(vec![RowChange::Insert { - values: vec![cv(5, Some("DEADBEEF… (40000 bytes)"))], - }]); - assert_eq!(msg, "This value is only a preview and cannot be saved."); - let mut target = sample_target(); - target.table = "bad\"name".into(); - assert!(plan_changes(&ApplyRequest { - target, - changes: vec![RowChange::Delete { - key: vec![Some("1".into())] - }], - }) - .is_err()); - } - - // --- Editable results against a real server (see integration_tests.rs) --- - - fn ora_profile() -> Option<(ConnectionProfile, Option)> { - let env = |n: &str| std::env::var(n).ok().filter(|v| !v.is_empty()); - Some(( - ConnectionProfile { - name: "test".into(), - engine: crate::model::Engine::Oracle, - host: env("LQ_ORA_HOST")?, - port: env("LQ_ORA_PORT") - .and_then(|p| p.parse().ok()) - .unwrap_or(1521), - user: env("LQ_ORA_USER")?, - database: env("LQ_ORA_SERVICE").unwrap_or_else(|| "FREEPDB1".into()), - oracle_connect_type: OracleConnectType::Service, - ..Default::default() - }, - env("LQ_ORA_PASSWORD"), - )) - } - - async fn open() -> Option { - let (profile, pw) = ora_profile()?; - Some(connect(&profile, pw.as_deref()).await.expect("connection")) - } - - async fn run(s: &OraSession, sql: &str) -> ExecResult { - s.execute(&ExecRequest { - sql: sql.into(), - max_rows: 100, - }) - .await - .unwrap_or_else(|e| panic!("{sql}: {e}")) - } - - async fn try_run(s: &OraSession, sql: &str) -> bool { - s.execute(&ExecRequest { - sql: sql.into(), - max_rows: 0, - }) - .await - .is_ok() - } - - fn target_of(r: &ExecResult) -> EditTarget { - r.editable - .clone() - .unwrap_or_else(|| panic!("read-only: {:?}", r.read_only_reason)) - } - - fn reason_of(r: &ExecResult) -> String { - assert!(r.editable.is_none(), "editable: {:?}", r.editable); - r.read_only_reason.clone().expect("a reason") - } - - async fn apply( - s: &OraSession, - target: &EditTarget, - changes: Vec, - ) -> AppResult { - s.apply_changes(&ApplyRequest { - target: target.clone(), - changes, - }) - .await - } - - #[tokio::test] - #[ignore] - async fn oracle_edit_detection() { - let Some(s) = open().await else { return }; - for t in ["lq_edit_t", "lq_edit_nokey", "lq_edit_uk"] { - try_run(&s, &format!("drop table {t} purge")).await; - } - run(&s, "create table lq_edit_t (id number(10) primary key, name varchar2(50), qty number(10,2))").await; - run(&s, "create table lq_edit_nokey (a number, b varchar2(10))").await; - run(&s, "create table lq_edit_uk (code varchar2(10) not null, v number, constraint lq_edit_uk_u unique (code))").await; - - let r = run(&s, "select id, name, qty * 2 as dbl from lq_edit_t").await; - let t = target_of(&r); - assert_eq!(t.table, "LQ_EDIT_T"); - assert_eq!(t.schema, s.current_schema); - assert_eq!(t.key, [0]); - assert_eq!(t.columns[1].as_ref().unwrap().name, "NAME"); - assert!(t.columns[2].is_none()); - - let r = run( - &s, - "select name, e.id from lq_edit_t e where id > 0 order by id", - ) - .await; - assert_eq!(target_of(&r).key, [1]); - let r = run(&s, "select * from lq_edit_t").await; - let t = target_of(&r); - assert_eq!(t.key, [0]); - assert_eq!(t.columns[2].as_ref().unwrap().type_name, "NUMBER(10,2)"); - - let r = run( - &s, - "select a.id, b.name from lq_edit_t a join lq_edit_t b on a.id = b.id", - ) - .await; - assert!(reason_of(&r).contains("several tables")); - let r = run(&s, "select * from lq_edit_nokey").await; - assert!( - reason_of(&r).contains("no primary key"), - "{:?}", - r.read_only_reason - ); - let r = run(&s, "select name from lq_edit_t").await; - assert!(reason_of(&r).contains("(ID)"), "{:?}", r.read_only_reason); - let r = run(&s, "select v, code from lq_edit_uk").await; - assert_eq!(target_of(&r).key, [1]); - let r = run(&s, "select name, count(*) from lq_edit_t group by name").await; - reason_of(&r); - let r = run(&s, "select sysdate from dual").await; - reason_of(&r); - let r = run(&s, "insert into lq_edit_t (id) values (1)").await; - assert!(r.editable.is_none() && r.read_only_reason.is_none()); - - // Synonyms and views, when the test user may create them. - if try_run(&s, "create or replace synonym lq_edit_syn for lq_edit_t").await { - let r = run(&s, "select * from lq_edit_syn").await; - assert_eq!(target_of(&r).table, "LQ_EDIT_T"); - try_run(&s, "drop synonym lq_edit_syn").await; - } - if try_run( - &s, - "create or replace view lq_edit_v as select * from lq_edit_t", - ) - .await - { - let r = run(&s, "select * from lq_edit_v").await; - assert!(reason_of(&r).contains("view")); - try_run(&s, "drop view lq_edit_v").await; - } - - for t in ["lq_edit_t", "lq_edit_nokey", "lq_edit_uk"] { - run(&s, &format!("drop table {t} purge")).await; - } - } - - #[tokio::test] - #[ignore] - async fn oracle_edit_round_trip_types() { - let Some(s) = open().await else { return }; - try_run(&s, "drop table lq_edit_types purge").await; - run( - &s, - "create table lq_edit_types ( - id number(10) primary key, n number(20,5), big number, i number(10), - f binary_float, d binary_double, dt date, ts timestamp(6), ts9 timestamp(9), - tz timestamp(3) with time zone, c varchar2(100), ch char(5), nc nvarchar2(20), - cl clob, r raw(16), bl blob)", - ) - .await; - run( - &s, - "insert into lq_edit_types (id, n, big, i, f, d, dt, ts, ts9, tz, c, ch, nc, cl, r, bl) - values (10, 12345.678, 1e30, 1000, 1.5, 0.1, timestamp '2024-02-29 13:45:10', - timestamp '2024-02-29 13:45:10.123456', timestamp '2024-02-29 13:45:10.123456789', - timestamp '2024-02-29 13:45:10.250 -03:00', 'it''s' || chr(10) || 'two \"lines\"', - 'ab', 'olá', to_clob('long text' || chr(10) || 'x'), hextoraw('DEADBEEF'), - hextoraw('00FF10'))", - ) - .await; - run(&s, "insert into lq_edit_types (id) values (20)").await; - run( - &s, - "insert into lq_edit_types (id, n, f) values (7, -0.5, -2.25)", - ) - .await; - - let sql = "select * from lq_edit_types order by id"; - let before = run(&s, sql).await; - let t = target_of(&before); - assert_eq!(t.key, [0]); - assert!(t.columns.iter().all(Option::is_some), "{:?}", t.columns); - let row10 = &before.rows[1]; - assert_eq!(row10[0].as_deref(), Some("10")); - assert_eq!( - row10[2].as_deref(), - Some(format!("1{}", "0".repeat(30)).as_str()) - ); - assert_eq!(row10[6].as_deref(), Some("2024-02-29 13:45:10")); - assert_eq!(row10[9].as_deref(), Some("2024-02-29 13:45:10.250 -03:00")); - assert_eq!(row10[11].as_deref(), Some("ab ")); - - // Every column written back with its own displayed text. - let changes = before - .rows - .iter() - .map(|row| RowChange::Update { - key: vec![row[0].clone()], - values: (1..row.len()).map(|i| cv(i, row[i].as_deref())).collect(), - }) - .collect(); - let res = apply(&s, &t, changes).await.unwrap(); - assert_eq!(res.updated, 3); - assert!(!res.in_transaction); - let after = run(&s, sql).await; - assert_eq!(after.rows, before.rows); - - // New values in the display format. - let res = apply( - &s, - &t, - vec![RowChange::Update { - key: vec![Some("10".into())], - values: vec![ - cv(1, Some("-0.00001")), - cv(4, Some("Inf")), - cv(5, Some("-1.25")), - cv(6, Some("2023-01-02 03:04:05")), - cv(7, Some("2023-01-02 03:04:05.000001")), - cv(9, Some("2023-01-02 03:04:05.5 +05:30")), - cv(10, Some("x'y\"z")), - cv(12, None), - cv(14, Some("0a0b")), - ], - }], - ) - .await - .unwrap(); - assert_eq!(res.updated, 1); - let row = run(&s, "select * from lq_edit_types where id = 10") - .await - .rows - .remove(0); - assert_eq!(row[1].as_deref(), Some("-0.00001")); - assert_eq!(row[4].as_deref(), Some("Inf")); - assert_eq!(row[5].as_deref(), Some("-1.25")); - assert_eq!(row[6].as_deref(), Some("2023-01-02 03:04:05")); - assert_eq!(row[7].as_deref(), Some("2023-01-02 03:04:05.000001")); - assert_eq!(row[9].as_deref(), Some("2023-01-02 03:04:05.500 +05:30")); - assert_eq!(row[10].as_deref(), Some("x'y\"z")); - assert_eq!(row[12], None); - assert_eq!(row[14].as_deref(), Some("0A0B")); - - // Insert a copy of a row under a new key, then delete it. - let source = &after.rows[1]; - let mut values: Vec = (1..source.len()) - .map(|i| cv(i, source[i].as_deref())) - .collect(); - values.push(cv(0, Some("30"))); - let res = apply(&s, &t, vec![RowChange::Insert { values }]) - .await - .unwrap(); - assert_eq!(res.inserted, 1); - let copy = run(&s, "select * from lq_edit_types where id = 30") - .await - .rows - .remove(0); - assert_eq!(copy[1..], source[1..]); - let res = apply( - &s, - &t, - vec![RowChange::Delete { - key: vec![Some("30".into())], - }], - ) - .await - .unwrap(); - assert_eq!(res.deleted, 1); - assert!(run(&s, "select * from lq_edit_types where id = 30") - .await - .rows - .is_empty()); - - run(&s, "drop table lq_edit_types purge").await; - } - - #[tokio::test] - #[ignore] - async fn oracle_edit_date_keys_and_booleans() { - let Some(s) = open().await else { return }; - try_run(&s, "drop table lq_edit_dk purge").await; - run(&s, "create table lq_edit_dk (d date, ts timestamp(6), v varchar2(10), primary key (d, ts))").await; - run(&s, "insert into lq_edit_dk values (timestamp '2024-01-02 03:04:05', timestamp '2024-01-02 03:04:05.000007', 'a')").await; - let r = run(&s, "select v, d, ts from lq_edit_dk").await; - let t = target_of(&r); - assert_eq!(t.key, [1, 2]); - let row = &r.rows[0]; - let res = apply( - &s, - &t, - vec![RowChange::Update { - key: vec![row[1].clone(), row[2].clone()], - values: vec![cv(0, Some("b"))], - }], - ) - .await - .unwrap(); - assert_eq!(res.updated, 1); - run(&s, "drop table lq_edit_dk purge").await; - - // BOOLEAN columns exist from 23ai on. - try_run(&s, "drop table lq_edit_bool purge").await; - if try_run( - &s, - "create table lq_edit_bool (id number primary key, b boolean)", - ) - .await - { - run(&s, "insert into lq_edit_bool values (1, true)").await; - let r = run(&s, "select * from lq_edit_bool").await; - let t = target_of(&r); - assert_eq!(r.rows[0][1].as_deref(), Some("TRUE")); - apply( - &s, - &t, - vec![RowChange::Update { - key: vec![Some("1".into())], - values: vec![cv(1, Some("FALSE"))], - }], - ) - .await - .unwrap(); - let r = run(&s, "select b from lq_edit_bool").await; - assert_eq!(r.rows[0][0].as_deref(), Some("FALSE")); - run(&s, "drop table lq_edit_bool purge").await; - } - } - - #[tokio::test] - #[ignore] - async fn oracle_edit_transactions() { - let Some(s) = open().await else { return }; - let other = open().await.unwrap(); - try_run(&s, "drop table lq_edit_tx purge").await; - run( - &s, - "create table lq_edit_tx (id number primary key, v varchar2(10))", - ) - .await; - run(&s, "insert into lq_edit_tx values (1, 'a')").await; - run(&s, "insert into lq_edit_tx values (2, 'b')").await; - let t = target_of(&run(&s, "select id, v from lq_edit_tx").await); - let set = |id: &str, v: &str| RowChange::Update { - key: vec![Some(id.into())], - values: vec![cv(1, Some(v))], - }; - let values = |rows: Vec>>| -> Vec { - rows.into_iter() - .map(|r| r[0].clone().unwrap_or_default()) - .collect() - }; - let sql = "select v from lq_edit_tx order by id"; - - // A key that matches nothing undoes the whole batch. - let err = apply(&s, &t, vec![set("1", "x"), set("99", "y")]) - .await - .unwrap_err(); - assert_eq!(err.kind, ErrorKind::Database); - assert!( - err.message.starts_with("Row 2 was not saved: 0 rows"), - "{err}" - ); - assert_eq!(values(run(&s, sql).await.rows), ["a", "b"]); - assert!(!s.tx_state().in_transaction); - - // Autocommit: other sessions see the change at once. - let res = apply(&s, &t, vec![set("1", "x")]).await.unwrap(); - assert!(!res.in_transaction); - assert_eq!(values(run(&other, sql).await.rows), ["x", "b"]); - - // Manual mode: the change joins the open transaction. - s.set_autocommit(false).await.unwrap(); - let res = apply(&s, &t, vec![set("2", "z")]).await.unwrap(); - assert!(res.in_transaction); - assert!(s.tx_state().in_transaction); - assert_eq!(values(run(&s, sql).await.rows), ["x", "z"]); - assert_eq!(values(run(&other, sql).await.rows), ["x", "b"]); - s.end_transaction(false).await.unwrap(); - assert_eq!(values(run(&s, sql).await.rows), ["x", "b"]); - - // A failure in manual mode keeps the earlier work of the transaction. - run(&s, "update lq_edit_tx set v = 'm' where id = 1").await; - let err = apply( - &s, - &t, - vec![ - set("2", "q"), - RowChange::Delete { - key: vec![Some("99".into())], - }, - ], - ) - .await - .unwrap_err(); - assert!(err.message.starts_with("Row 2"), "{err}"); - assert!(s.tx_state().in_transaction); - assert_eq!(values(run(&s, sql).await.rows), ["m", "b"]); - s.end_transaction(false).await.unwrap(); - s.set_autocommit(true).await.unwrap(); - - // Bad input is refused before anything runs. - let err = apply( - &s, - &t, - vec![RowChange::Delete { - key: vec![Some("abc".into())], - }], - ) - .await - .unwrap_err(); - assert_eq!(err.kind, ErrorKind::Invalid); - assert_eq!(values(run(&s, sql).await.rows), ["x", "b"]); - - run(&s, "drop table lq_edit_tx purge").await; - } - - #[tokio::test] - #[ignore] - async fn oracle_edit_quoted_names() { - let Some(s) = open().await else { return }; - try_run(&s, r#"drop table "lq_edit Mixed" purge"#).await; - run(&s, r#"create table "lq_edit Mixed" ("Id Key" number primary key, "Some Value" varchar2(20), "lower" date)"#).await; - run( - &s, - r#"insert into "lq_edit Mixed" values (1, 'one', date '2024-01-01')"#, - ) - .await; - - let r = run( - &s, - r#"select m."Some Value" sv, m."Id Key", "lower" from "lq_edit Mixed" m"#, - ) - .await; - let t = target_of(&r); - assert_eq!(t.table, "lq_edit Mixed"); - assert_eq!(t.key, [1]); - assert_eq!(t.columns[0].as_ref().unwrap().name, "Some Value"); - - let res = apply( - &s, - &t, - vec![ - RowChange::Update { - key: vec![Some("1".into())], - values: vec![cv(0, Some("uno")), cv(2, Some("2024-12-31 23:59:59"))], - }, - RowChange::Insert { - values: vec![cv(1, Some("2")), cv(0, Some("two"))], - }, - ], - ) - .await - .unwrap(); - assert_eq!((res.updated, res.inserted), (1, 1)); - let r = run( - &s, - r#"select "Id Key", "Some Value", "lower" from "lq_edit Mixed" order by 1"#, - ) - .await; - assert_eq!(r.rows[0][1].as_deref(), Some("uno")); - assert_eq!(r.rows[0][2].as_deref(), Some("2024-12-31 23:59:59")); - assert_eq!(r.rows[1][1].as_deref(), Some("two")); - let t2 = target_of(&r); - let res = apply( - &s, - &t2, - vec![RowChange::Delete { - key: vec![Some("2".into())], - }], - ) - .await - .unwrap(); - assert_eq!(res.deleted, 1); - - run(&s, r#"drop table "lq_edit Mixed" purge"#).await; - } -} diff --git a/src-tauri/src/drivers/pg_value.rs b/src-tauri/src/drivers/pg_value.rs deleted file mode 100644 index 02e0fdf..0000000 --- a/src-tauri/src/drivers/pg_value.rs +++ /dev/null @@ -1,895 +0,0 @@ -//! Decoding of the PostgreSQL binary format to text. -//! -//! tokio-postgres always requests results in binary format. Instead of -//! relying on the generic conversions (which fail on NUMERIC NaN/Infinity, -//! infinite dates, extension types, etc.), each type is decoded here and -//! formatted the way the server itself would in text output. - -use std::fmt::Write as _; - -use tokio_postgres::types::{FromSql, Kind, Type}; - -use crate::model::ValueKind; - -type BoxError = Box; - -/// Maximum bytes shown for very large binary values. -const BINARY_PREVIEW_BYTES: usize = 32 * 1024; - -/// An already formatted cell value. Accepts any type. -pub struct PgCell(pub Option); - -impl<'a> FromSql<'a> for PgCell { - fn from_sql(ty: &Type, raw: &'a [u8]) -> Result { - Ok(PgCell(Some(decode(ty, raw)?))) - } - - fn from_sql_null(_: &Type) -> Result { - Ok(PgCell(None)) - } - - fn accepts(_: &Type) -> bool { - true - } -} - -mod oid { - pub const BOOL: u32 = 16; - pub const BYTEA: u32 = 17; - pub const CHAR: u32 = 18; - pub const NAME: u32 = 19; - pub const INT8: u32 = 20; - pub const INT2: u32 = 21; - pub const INT4: u32 = 23; - pub const REGPROC: u32 = 24; - pub const TEXT: u32 = 25; - pub const OID: u32 = 26; - pub const TID: u32 = 27; - pub const XID: u32 = 28; - pub const CID: u32 = 29; - pub const JSON: u32 = 114; - pub const XML: u32 = 142; - pub const POINT: u32 = 600; - pub const LSEG: u32 = 601; - pub const BOX: u32 = 603; - pub const LINE: u32 = 628; - pub const CIDR: u32 = 650; - pub const FLOAT4: u32 = 700; - pub const FLOAT8: u32 = 701; - pub const UNKNOWN: u32 = 705; - pub const CIRCLE: u32 = 718; - pub const MACADDR8: u32 = 774; - pub const MONEY: u32 = 790; - pub const MACADDR: u32 = 829; - pub const INET: u32 = 869; - pub const BPCHAR: u32 = 1042; - pub const VARCHAR: u32 = 1043; - pub const DATE: u32 = 1082; - pub const TIME: u32 = 1083; - pub const TIMESTAMP: u32 = 1114; - pub const TIMESTAMPTZ: u32 = 1184; - pub const INTERVAL: u32 = 1186; - pub const TIMETZ: u32 = 1266; - pub const BIT: u32 = 1560; - pub const VARBIT: u32 = 1562; - pub const NUMERIC: u32 = 1700; - pub const REFCURSOR: u32 = 1790; - pub const REGPROCEDURE: u32 = 2202; - pub const REGOPER: u32 = 2203; - pub const REGOPERATOR: u32 = 2204; - pub const REGCLASS: u32 = 2205; - pub const REGTYPE: u32 = 2206; - pub const RECORD: u32 = 2249; - pub const CSTRING: u32 = 2275; - pub const VOID: u32 = 2278; - pub const UUID: u32 = 2950; - pub const PG_LSN: u32 = 3220; - pub const REGCONFIG: u32 = 3734; - pub const REGDICTIONARY: u32 = 3769; - pub const JSONB: u32 = 3802; - pub const JSONPATH: u32 = 4072; - pub const REGNAMESPACE: u32 = 4089; - pub const REGROLE: u32 = 4096; - pub const REGCOLLATION: u32 = 4191; - pub const XID8: u32 = 5069; -} - -pub fn value_kind(ty: &Type) -> ValueKind { - match ty.kind() { - Kind::Domain(inner) => return value_kind(inner), - Kind::Enum(_) => return ValueKind::Text, - Kind::Array(_) | Kind::Range(_) | Kind::Multirange(_) | Kind::Composite(_) => { - return ValueKind::Other - } - _ => {} - } - match ty.oid() { - oid::INT2 - | oid::INT4 - | oid::INT8 - | oid::FLOAT4 - | oid::FLOAT8 - | oid::NUMERIC - | oid::MONEY - | oid::OID - | oid::XID - | oid::XID8 - | oid::CID => ValueKind::Number, - oid::BOOL => ValueKind::Bool, - oid::DATE | oid::TIME | oid::TIMETZ | oid::TIMESTAMP | oid::TIMESTAMPTZ | oid::INTERVAL => { - ValueKind::Temporal - } - oid::BYTEA => ValueKind::Binary, - oid::JSON | oid::JSONB | oid::JSONPATH => ValueKind::Json, - oid::TEXT - | oid::VARCHAR - | oid::BPCHAR - | oid::NAME - | oid::CHAR - | oid::UUID - | oid::XML - | oid::UNKNOWN - | oid::CSTRING => ValueKind::Text, - _ => ValueKind::Other, - } -} - -/// Readable type name (`varchar`, `int4[]`, `schema.type`). -pub fn type_label(ty: &Type) -> String { - let base = match ty.kind() { - Kind::Array(member) => return format!("{}[]", type_label(member)), - _ => ty.name().to_string(), - }; - match ty.schema() { - "pg_catalog" | "public" | "" => base, - schema => format!("{schema}.{base}"), - } -} - -pub fn decode(ty: &Type, raw: &[u8]) -> Result { - match ty.kind() { - Kind::Domain(inner) => return decode(inner, raw), - Kind::Enum(_) => return utf8(raw), - Kind::Array(member) => return decode_array(member, raw), - Kind::Range(inner) => return decode_range(inner, raw), - Kind::Multirange(inner) => return decode_multirange(inner, raw), - Kind::Composite(fields) => { - let types: Vec = fields.iter().map(|f| f.type_().clone()).collect(); - return decode_record(Some(&types), raw); - } - _ => {} - } - let mut r = Reader::new(raw); - let text = match ty.oid() { - oid::BOOL => (if r.u8()? != 0 { "true" } else { "false" }).to_string(), - oid::INT2 => r.i16()?.to_string(), - oid::INT4 => r.i32()?.to_string(), - oid::INT8 => r.i64()?.to_string(), - oid::OID - | oid::XID - | oid::CID - | oid::REGPROC - | oid::REGPROCEDURE - | oid::REGOPER - | oid::REGOPERATOR - | oid::REGCLASS - | oid::REGTYPE - | oid::REGCONFIG - | oid::REGDICTIONARY - | oid::REGNAMESPACE - | oid::REGROLE - | oid::REGCOLLATION => r.u32()?.to_string(), - oid::XID8 => r.u64()?.to_string(), - oid::FLOAT4 => float(f64::from(r.f32()?), true), - oid::FLOAT8 => float(r.f64()?, false), - oid::NUMERIC => numeric(raw)?, - oid::MONEY => money(r.i64()?), - oid::TEXT - | oid::VARCHAR - | oid::BPCHAR - | oid::NAME - | oid::UNKNOWN - | oid::XML - | oid::REFCURSOR - | oid::CSTRING - | oid::JSON => utf8(raw)?, - oid::CHAR => char::from(r.u8()?).to_string(), - oid::JSONB | oid::JSONPATH => { - // The first byte is the format version (1). - utf8(raw.get(1..).unwrap_or_default())? - } - oid::UUID => uuid::Uuid::from_slice(raw)?.hyphenated().to_string(), - oid::BYTEA => hex_bytea(raw), - oid::DATE => date(r.i32()?), - oid::TIME => time_of_day(r.i64()?), - oid::TIMETZ => { - let micros = r.i64()?; - // The zone comes in seconds WEST of UTC. - let zone = r.i32()?; - format!("{}{}", time_of_day(micros), offset(-zone)) - } - oid::TIMESTAMP => timestamp(r.i64()?, false), - oid::TIMESTAMPTZ => timestamp(r.i64()?, true), - oid::INTERVAL => { - let micros = r.i64()?; - let days = r.i32()?; - let months = r.i32()?; - interval(micros, days, months) - } - oid::INET | oid::CIDR => inet(raw, ty.oid() == oid::CIDR)?, - oid::MACADDR | oid::MACADDR8 => raw - .iter() - .map(|b| format!("{b:02x}")) - .collect::>() - .join(":"), - oid::POINT => format!("({},{})", float(r.f64()?, false), float(r.f64()?, false)), - oid::LSEG | oid::BOX => { - let (x1, y1, x2, y2) = (r.f64()?, r.f64()?, r.f64()?, r.f64()?); - let (open, close) = if ty.oid() == oid::LSEG { - ("[", "]") - } else { - ("", "") - }; - format!( - "{open}({},{}),({},{}){close}", - float(x1, false), - float(y1, false), - float(x2, false), - float(y2, false) - ) - } - oid::LINE => format!( - "{{{},{},{}}}", - float(r.f64()?, false), - float(r.f64()?, false), - float(r.f64()?, false) - ), - oid::CIRCLE => format!( - "<({},{}),{}>", - float(r.f64()?, false), - float(r.f64()?, false), - float(r.f64()?, false) - ), - oid::BIT | oid::VARBIT => { - let len = r.i32()?.max(0) as usize; - let mut s = String::with_capacity(len); - for i in 0..len { - let byte = raw.get(4 + i / 8).copied().unwrap_or(0); - s.push(if byte & (0x80 >> (i % 8)) != 0 { - '1' - } else { - '0' - }); - } - s - } - oid::PG_LSN => { - let v = r.u64()?; - format!("{:X}/{:X}", v >> 32, v & 0xFFFF_FFFF) - } - oid::TID => { - let block = r.u32()?; - let offset = r.u16()?; - format!("({block},{offset})") - } - oid::RECORD => decode_record(None, raw)?, - oid::VOID => String::new(), - _ => match ty.name() { - "hstore" => hstore(raw)?, - // citext and other textual extension types use plain UTF-8. - _ => fallback(raw), - }, - }; - Ok(text) -} - -struct Reader<'a> { - buf: &'a [u8], - pos: usize, -} - -impl<'a> Reader<'a> { - fn new(buf: &'a [u8]) -> Self { - Self { buf, pos: 0 } - } - - fn take(&mut self, n: usize) -> Result<&'a [u8], BoxError> { - let end = self.pos.checked_add(n).filter(|&e| e <= self.buf.len()); - match end { - Some(end) => { - let slice = &self.buf[self.pos..end]; - self.pos = end; - Ok(slice) - } - None => Err("truncated binary value".into()), - } - } - - fn u8(&mut self) -> Result { - Ok(self.take(1)?[0]) - } - fn u16(&mut self) -> Result { - Ok(u16::from_be_bytes(self.take(2)?.try_into()?)) - } - fn i16(&mut self) -> Result { - Ok(i16::from_be_bytes(self.take(2)?.try_into()?)) - } - fn i32(&mut self) -> Result { - Ok(i32::from_be_bytes(self.take(4)?.try_into()?)) - } - fn u32(&mut self) -> Result { - Ok(u32::from_be_bytes(self.take(4)?.try_into()?)) - } - fn i64(&mut self) -> Result { - Ok(i64::from_be_bytes(self.take(8)?.try_into()?)) - } - fn u64(&mut self) -> Result { - Ok(u64::from_be_bytes(self.take(8)?.try_into()?)) - } - fn f32(&mut self) -> Result { - Ok(f32::from_be_bytes(self.take(4)?.try_into()?)) - } - fn f64(&mut self) -> Result { - Ok(f64::from_be_bytes(self.take(8)?.try_into()?)) - } - - /// Length-prefixed value (-1 = NULL). - fn sized(&mut self) -> Result, BoxError> { - let len = self.i32()?; - if len < 0 { - Ok(None) - } else { - Ok(Some(self.take(len as usize)?)) - } - } -} - -fn utf8(raw: &[u8]) -> Result { - Ok(String::from_utf8_lossy(raw).into_owned()) -} - -/// Text when it looks like text; otherwise hexadecimal, like bytea. -fn fallback(raw: &[u8]) -> String { - match std::str::from_utf8(raw) { - Ok(s) - if !s - .chars() - .any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t')) => - { - s.to_string() - } - _ => hex_bytea(raw), - } -} - -fn hex_bytea(raw: &[u8]) -> String { - let shown = &raw[..raw.len().min(super::binary_limit(BINARY_PREVIEW_BYTES))]; - let mut s = String::with_capacity(2 + shown.len() * 2); - s.push_str("\\x"); - for b in shown { - let _ = write!(s, "{b:02x}"); - } - if raw.len() > shown.len() { - let _ = write!(s, "… ({} bytes)", raw.len()); - } - s -} - -fn float(v: f64, single: bool) -> String { - if v.is_nan() { - "NaN".into() - } else if v.is_infinite() { - if v > 0.0 { - "Infinity".into() - } else { - "-Infinity".into() - } - } else if single { - // Shortest representation that preserves the 32-bit value. - (v as f32).to_string() - } else { - v.to_string() - } -} - -fn money(cents: i64) -> String { - let sign = if cents < 0 { "-" } else { "" }; - let abs = cents.unsigned_abs(); - format!("{sign}{}.{:02}", abs / 100, abs % 100) -} - -/// NUMERIC: base-10000 digits with weight and display scale. -pub fn numeric(raw: &[u8]) -> Result { - let mut r = Reader::new(raw); - let ndigits = r.i16()?.max(0) as usize; - let weight = r.i16()? as i32; - let sign = r.u16()?; - let dscale = r.u16()? as usize; - match sign { - 0xC000 => return Ok("NaN".into()), - 0xD000 => return Ok("Infinity".into()), - 0xF000 => return Ok("-Infinity".into()), - _ => {} - } - let mut digits = Vec::with_capacity(ndigits); - for _ in 0..ndigits { - digits.push(r.i16()?); - } - let digit = |i: i32| -> i16 { - if i < 0 { - 0 - } else { - digits.get(i as usize).copied().unwrap_or(0) - } - }; - - let mut s = String::new(); - if sign == 0x4000 { - s.push('-'); - } - if weight < 0 { - s.push('0'); - } else { - for i in 0..=weight { - if i == 0 { - let _ = write!(s, "{}", digit(i)); - } else { - let _ = write!(s, "{:04}", digit(i)); - } - } - } - if dscale > 0 { - s.push('.'); - let mut frac = String::with_capacity(dscale + 4); - let mut i = weight + 1; - while frac.len() < dscale { - let _ = write!(frac, "{:04}", digit(i)); - i += 1; - } - frac.truncate(dscale); - s.push_str(&frac); - } - Ok(s) -} - -/// `num_days_from_ce()` of 2000-01-01, the PostgreSQL epoch. -const DAYS_2000_FROM_CE: i32 = 730_120; - -fn ymd_from_days(days_since_2000: i64) -> Option<(i32, u32, u32)> { - use chrono::Datelike; - let ce = i64::from(DAYS_2000_FROM_CE) + days_since_2000; - let date = chrono::NaiveDate::from_num_days_from_ce_opt(i32::try_from(ce).ok()?)?; - Some((date.year(), date.month(), date.day())) -} - -fn format_ymd(year: i32, month: u32, day: u32) -> (String, bool) { - // Proleptic calendar: year 0 is 1 BC. - if year <= 0 { - (format!("{:04}-{month:02}-{day:02}", 1 - year), true) - } else { - (format!("{year:04}-{month:02}-{day:02}"), false) - } -} - -fn date(days: i32) -> String { - match days { - i32::MAX => "infinity".into(), - i32::MIN => "-infinity".into(), - _ => match ymd_from_days(i64::from(days)) { - Some((y, m, d)) => { - let (s, bc) = format_ymd(y, m, d); - if bc { - format!("{s} BC") - } else { - s - } - } - None => days.to_string(), - }, - } -} - -fn fraction(micros: i64) -> String { - if micros == 0 { - return String::new(); - } - let s = format!(".{micros:06}"); - s.trim_end_matches('0').to_string() -} - -fn time_of_day(micros: i64) -> String { - let secs = micros.div_euclid(1_000_000); - let frac = micros.rem_euclid(1_000_000); - format!( - "{:02}:{:02}:{:02}{}", - secs / 3600, - (secs / 60) % 60, - secs % 60, - fraction(frac) - ) -} - -/// Offset in seconds east of UTC → `+03`, `-03:30`. -fn offset(east_secs: i32) -> String { - let sign = if east_secs < 0 { '-' } else { '+' }; - let abs = east_secs.unsigned_abs(); - let (h, m, s) = (abs / 3600, (abs / 60) % 60, abs % 60); - match (m, s) { - (0, 0) => format!("{sign}{h:02}"), - (_, 0) => format!("{sign}{h:02}:{m:02}"), - _ => format!("{sign}{h:02}:{m:02}:{s:02}"), - } -} - -/// TIMESTAMP(TZ): microseconds since 2000-01-01. With a time zone, shows the -/// machine's local zone, as a client with a local `TimeZone` would. -fn timestamp(micros: i64, with_tz: bool) -> String { - match micros { - i64::MAX => return "infinity".into(), - i64::MIN => return "-infinity".into(), - _ => {} - } - let (micros, tz) = if with_tz { - let utc_secs = micros.div_euclid(1_000_000) + 946_684_800; - let east = chrono::DateTime::from_timestamp(utc_secs, 0) - .map(|dt| { - use chrono::Offset; - dt.with_timezone(&chrono::Local) - .offset() - .fix() - .local_minus_utc() - }) - .unwrap_or(0); - (micros + i64::from(east) * 1_000_000, Some(offset(east))) - } else { - (micros, None) - }; - let days = micros.div_euclid(86_400_000_000); - let in_day = micros.rem_euclid(86_400_000_000); - let Some((y, m, d)) = ymd_from_days(days) else { - return micros.to_string(); - }; - let (ymd, bc) = format_ymd(y, m, d); - let mut s = format!("{ymd} {}", time_of_day(in_day)); - if let Some(tz) = tz { - s.push_str(&tz); - } - if bc { - s.push_str(" BC"); - } - s -} - -/// `postgres` style (the server default): `1 year 2 mons 3 days 04:05:06`. -fn interval(micros: i64, days: i32, months: i32) -> String { - let mut parts: Vec = Vec::new(); - let years = months / 12; - let mons = months % 12; - let plural = - |n: i64, one: &str, many: &str| format!("{n} {}", if n.abs() == 1 { one } else { many }); - if years != 0 { - parts.push(plural(i64::from(years), "year", "years")); - } - if mons != 0 { - parts.push(plural(i64::from(mons), "mon", "mons")); - } - if days != 0 { - parts.push(plural(i64::from(days), "day", "days")); - } - if micros != 0 || parts.is_empty() { - let sign = if micros < 0 { "-" } else { "" }; - let abs = micros.unsigned_abs(); - let secs = abs / 1_000_000; - let frac = (abs % 1_000_000) as i64; - parts.push(format!( - "{sign}{:02}:{:02}:{:02}{}", - secs / 3600, - (secs / 60) % 60, - secs % 60, - fraction(frac) - )); - } - parts.join(" ") -} - -fn inet(raw: &[u8], is_cidr_type: bool) -> Result { - let mut r = Reader::new(raw); - let family = r.u8()?; - let bits = r.u8()?; - let _is_cidr = r.u8()?; - let len = r.u8()? as usize; - let addr = r.take(len)?; - let (text, max_bits) = match family { - 2 if len == 4 => ( - std::net::Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3]).to_string(), - 32, - ), - 3 if len == 16 => { - let octets: [u8; 16] = addr.try_into()?; - (std::net::Ipv6Addr::from(octets).to_string(), 128) - } - _ => return Ok(hex_bytea(raw)), - }; - if is_cidr_type || bits != max_bits { - Ok(format!("{text}/{bits}")) - } else { - Ok(text) - } -} - -fn hstore(raw: &[u8]) -> Result { - let mut r = Reader::new(raw); - let count = r.i32()?.max(0); - let mut pairs = Vec::with_capacity(count as usize); - for _ in 0..count { - let key = r.sized()?.map(String::from_utf8_lossy).unwrap_or_default(); - let value = match r.sized()? { - Some(v) => format!("\"{}\"", escape_quoted(&String::from_utf8_lossy(v))), - None => "NULL".into(), - }; - pairs.push(format!("\"{}\"=>{value}", escape_quoted(&key))); - } - Ok(pairs.join(", ")) -} - -fn escape_quoted(s: &str) -> String { - s.replace('\\', "\\\\").replace('"', "\\\"") -} - -/// Quoting in array output style: empty strings, a literal NULL, whitespace -/// or special characters require quotes. -fn array_element(s: &str) -> String { - let needs_quotes = s.is_empty() - || s.eq_ignore_ascii_case("null") - || s.chars() - .any(|c| matches!(c, '{' | '}' | ',' | '"' | '\\') || c.is_whitespace()); - if needs_quotes { - format!("\"{}\"", escape_quoted(s)) - } else { - s.to_string() - } -} - -fn decode_array(member: &Type, raw: &[u8]) -> Result { - let mut r = Reader::new(raw); - let ndim = r.i32()?.max(0) as usize; - let _has_nulls = r.i32()?; - let _elem_oid = r.u32()?; - if ndim == 0 { - return Ok("{}".into()); - } - let mut dims = Vec::with_capacity(ndim); - for _ in 0..ndim { - let len = r.i32()?.max(0) as usize; - let lower = r.i32()?; - dims.push((len, lower)); - } - let mut prefix = String::new(); - if dims.iter().any(|&(_, lower)| lower != 1) { - for &(len, lower) in &dims { - let _ = write!(prefix, "[{}:{}]", lower, lower + len as i32 - 1); - } - prefix.push('='); - } - let total: usize = dims.iter().map(|d| d.0).product(); - let mut elems = Vec::with_capacity(total); - for _ in 0..total { - elems.push(match r.sized()? { - Some(bytes) => array_element(&decode(member, bytes)?), - None => "NULL".into(), - }); - } - let mut out = prefix; - let mut idx = 0; - write_dims(&mut out, &dims, &elems, &mut idx); - Ok(out) -} - -fn write_dims(out: &mut String, dims: &[(usize, i32)], elems: &[String], idx: &mut usize) { - out.push('{'); - let (len, _) = dims[0]; - for i in 0..len { - if i > 0 { - out.push(','); - } - if dims.len() > 1 { - write_dims(out, &dims[1..], elems, idx); - } else if let Some(e) = elems.get(*idx) { - out.push_str(e); - *idx += 1; - } - } - out.push('}'); -} - -fn decode_range(inner: &Type, raw: &[u8]) -> Result { - const EMPTY: u8 = 0x01; - const LB_INC: u8 = 0x02; - const UB_INC: u8 = 0x04; - const LB_INF: u8 = 0x08; - const UB_INF: u8 = 0x10; - let mut r = Reader::new(raw); - let flags = r.u8()?; - if flags & EMPTY != 0 { - return Ok("empty".into()); - } - let mut bound = |inf: bool| -> Result { - if inf { - return Ok(String::new()); - } - match r.sized()? { - Some(b) => { - let v = decode(inner, b)?; - let quote = v - .chars() - .any(|c| matches!(c, ',' | '(' | ')' | '[' | ']' | '"') || c.is_whitespace()); - Ok(if quote { - format!("\"{}\"", escape_quoted(&v)) - } else { - v - }) - } - None => Ok(String::new()), - } - }; - let lower = bound(flags & LB_INF != 0)?; - let upper = bound(flags & UB_INF != 0)?; - Ok(format!( - "{}{lower},{upper}{}", - if flags & LB_INC != 0 { '[' } else { '(' }, - if flags & UB_INC != 0 { ']' } else { ')' } - )) -} - -fn decode_multirange(inner: &Type, raw: &[u8]) -> Result { - let mut r = Reader::new(raw); - let count = r.i32()?.max(0); - let mut parts = Vec::with_capacity(count as usize); - for _ in 0..count { - if let Some(b) = r.sized()? { - parts.push(decode_range(inner, b)?); - } - } - Ok(format!("{{{}}}", parts.join(","))) -} - -/// Composite type or `record`. Without the field types (anonymous record), -/// uses the OID carried in the value itself. -fn decode_record(types: Option<&[Type]>, raw: &[u8]) -> Result { - let mut r = Reader::new(raw); - let count = r.i32()?.max(0) as usize; - let mut parts = Vec::with_capacity(count); - for i in 0..count { - let field_oid = r.u32()?; - let ty = types - .and_then(|t| t.get(i).cloned()) - .or_else(|| Type::from_oid(field_oid)); - let text = match r.sized()? { - None => String::new(), - Some(bytes) => { - let v = match &ty { - Some(ty) => decode(ty, bytes)?, - None => fallback(bytes), - }; - let quote = v.is_empty() - || v.chars() - .any(|c| matches!(c, ',' | '(' | ')' | '"' | '\\') || c.is_whitespace()); - if quote { - format!("\"{}\"", escape_quoted(&v)) - } else { - v - } - } - }; - parts.push(text); - } - Ok(format!("({})", parts.join(","))) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn numeric_bytes(ndigits: i16, weight: i16, sign: u16, dscale: u16, digits: &[i16]) -> Vec { - let mut v = Vec::new(); - v.extend_from_slice(&ndigits.to_be_bytes()); - v.extend_from_slice(&weight.to_be_bytes()); - v.extend_from_slice(&sign.to_be_bytes()); - v.extend_from_slice(&dscale.to_be_bytes()); - for d in digits { - v.extend_from_slice(&d.to_be_bytes()); - } - v - } - - #[test] - fn numeric_formats_like_server() { - // 12345.678 → digits [1, 2345, 6780], weight 1, scale 3 - assert_eq!( - numeric(&numeric_bytes(3, 1, 0, 3, &[1, 2345, 6780])).unwrap(), - "12345.678" - ); - // -0.0012 → [12], weight -1, scale 4 - assert_eq!( - numeric(&numeric_bytes(1, -1, 0x4000, 4, &[12])).unwrap(), - "-0.0012" - ); - // 0.00000001 → groups 0000 0001: digit [1], weight -2, scale 8 - assert_eq!( - numeric(&numeric_bytes(1, -2, 0, 8, &[1])).unwrap(), - "0.00000001" - ); - // 10000 → [1], weight 1, scale 0 (trailing zeros omitted from the digits) - assert_eq!(numeric(&numeric_bytes(1, 1, 0, 0, &[1])).unwrap(), "10000"); - // 1.50 → scale 2 keeps the zero - assert_eq!( - numeric(&numeric_bytes(2, 0, 0, 2, &[1, 5000])).unwrap(), - "1.50" - ); - assert_eq!(numeric(&numeric_bytes(0, 0, 0, 0, &[])).unwrap(), "0"); - assert_eq!( - numeric(&numeric_bytes(0, 0, 0xC000, 0, &[])).unwrap(), - "NaN" - ); - assert_eq!( - numeric(&numeric_bytes(0, 0, 0xF000, 0, &[])).unwrap(), - "-Infinity" - ); - } - - #[test] - fn dates_and_times() { - assert_eq!(date(0), "2000-01-01"); - assert_eq!(date(-1), "1999-12-31"); - assert_eq!(date(i32::MAX), "infinity"); - assert_eq!( - timestamp(86_400_000_000 + 3_723_500_000, false), - "2000-01-02 01:02:03.5" - ); - assert_eq!(time_of_day(45_296_000_001), "12:34:56.000001"); - assert_eq!(offset(-3 * 3600), "-03"); - assert_eq!(offset(5 * 3600 + 1800), "+05:30"); - } - - #[test] - fn intervals() { - assert_eq!(interval(0, 0, 0), "00:00:00"); - assert_eq!( - interval(14_706_000_000, 3, 14), - "1 year 2 mons 3 days 04:05:06" - ); - assert_eq!(interval(-1_500_000, 1, 0), "1 day -00:00:01.5"); - } - - #[test] - fn arrays() { - let mut raw = Vec::new(); - raw.extend_from_slice(&1i32.to_be_bytes()); // ndim - raw.extend_from_slice(&1i32.to_be_bytes()); // has nulls - raw.extend_from_slice(&25u32.to_be_bytes()); // text - raw.extend_from_slice(&3i32.to_be_bytes()); // len - raw.extend_from_slice(&1i32.to_be_bytes()); // lower - for item in [Some("a b"), None, Some("x")] { - match item { - Some(s) => { - raw.extend_from_slice(&(s.len() as i32).to_be_bytes()); - raw.extend_from_slice(s.as_bytes()); - } - None => raw.extend_from_slice(&(-1i32).to_be_bytes()), - } - } - assert_eq!(decode_array(&Type::TEXT, &raw).unwrap(), "{\"a b\",NULL,x}"); - } - - #[test] - fn inet_values() { - assert_eq!( - inet(&[2, 32, 0, 4, 10, 0, 0, 1], false).unwrap(), - "10.0.0.1" - ); - assert_eq!( - inet(&[2, 24, 1, 4, 10, 0, 0, 0], true).unwrap(), - "10.0.0.0/24" - ); - } -} diff --git a/src-tauri/src/drivers/postgres.rs b/src-tauri/src/drivers/postgres.rs deleted file mode 100644 index bcc3b35..0000000 --- a/src-tauri/src/drivers/postgres.rs +++ /dev/null @@ -1,2295 +0,0 @@ -//! PostgreSQL session over the tokio-postgres extended protocol. -//! -//! - Queries that return rows run in a portal with a row limit -//! (`Execute` with `max_rows`), so a `SELECT` on a huge table does not -//! pull everything over the network. -//! - Values are decoded from the binary format by [`super::pg_value`]. -//! - Server NOTICE/WARNING messages (`RAISE NOTICE`) are collected and -//! returned along with the result. -//! - Cancellation uses the server's cancel protocol, on a separate -//! connection, without waiting for the running query. -//! - A SELECT is editable in the grid when the row description (table OID -//! and attribute number of each column) points to one table whose key is -//! in the result. Edits are sent as text-format parameters, so the server -//! parses them with each column's own input function. - -use std::collections::HashMap; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use futures_util::StreamExt; -use parking_lot::Mutex; -use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; -use rustls::crypto::CryptoProvider; -use rustls::pki_types::{CertificateDer, ServerName, UnixTime}; -use rustls::{DigitallySignedStruct, SignatureScheme}; -use tokio_postgres::error::ErrorPosition; -use tokio_postgres::types::{private::BytesMut, Format, IsNull, ToSql, Type}; -use tokio_postgres::{AsyncMessage, CancelToken, Client, SimpleQueryMessage, Statement}; -use tokio_postgres_rustls::MakeRustlsConnect; - -use super::pg_value::{type_label, value_kind, PgCell}; -use super::{first_keywords, RowSink, StreamEvent, TxState, STREAM_BATCH}; -use crate::error::{AppError, AppResult, ErrorKind}; -use crate::model::{ - ApplyRequest, ApplyResult, ColumnInfo, ConnectionProfile, DbColumn, DbObject, EditColumn, - EditTarget, ExecRequest, ExecResult, RowChange, SslMode, -}; - -pub struct PgSession { - client: tokio::sync::Mutex, - cancel: CancelToken, - tls: MakeRustlsConnect, - notices: Arc>>, - closed: Arc, - state: Mutex, - /// Catalog data of tables seen in results, by table OID. - tables: Mutex>>, - pub server_version: String, - pub current_user: Option, - pub current_schema: Option, -} - -pub async fn connect(profile: &ConnectionProfile, password: Option<&str>) -> AppResult { - let mut cfg = tokio_postgres::Config::new(); - cfg.host(profile.host.trim()) - .port(if profile.port == 0 { - 5432 - } else { - profile.port - }) - .user(profile.user.trim()) - .application_name("LowQuery") - .connect_timeout(Duration::from_secs(15)) - .keepalives_idle(Duration::from_secs(60)); - if !profile.database.trim().is_empty() { - cfg.dbname(profile.database.trim()); - } - if let Some(pw) = password { - cfg.password(pw); - } - cfg.ssl_mode(match profile.ssl_mode { - SslMode::Disable => tokio_postgres::config::SslMode::Disable, - SslMode::Prefer => tokio_postgres::config::SslMode::Prefer, - SslMode::Require | SslMode::VerifyFull => tokio_postgres::config::SslMode::Require, - }); - - let tls = MakeRustlsConnect::new(tls_config(profile.ssl_mode)?); - let (client, mut connection) = cfg.connect(tls.clone()).await.map_err(map_error)?; - - let notices = Arc::new(Mutex::new(Vec::new())); - let closed = Arc::new(AtomicBool::new(false)); - { - let notices = notices.clone(); - let closed = closed.clone(); - tauri::async_runtime::spawn(async move { - let mut messages = futures_util::stream::poll_fn(move |cx| connection.poll_message(cx)); - while let Some(message) = messages.next().await { - match message { - Ok(AsyncMessage::Notice(n)) => { - // 25001/25P01: redundant BEGIN/ROLLBACK warnings, - // produced by the internal transaction handling. - if !matches!(n.code().code(), "25001" | "25P01") { - notices - .lock() - .push(format!("{}: {}", n.severity(), n.message())); - } - } - Ok(_) => {} - Err(_) => break, - } - } - closed.store(true, Ordering::SeqCst); - }); - } - - let row = client - .query_one( - "SELECT current_setting('server_version'), current_user::text, current_schema()::text", - &[], - ) - .await - .map_err(map_error)?; - - Ok(PgSession { - cancel: client.cancel_token(), - client: tokio::sync::Mutex::new(client), - tls, - notices, - closed, - state: Mutex::new(TxState { - autocommit: true, - in_transaction: false, - }), - tables: Mutex::new(HashMap::new()), - server_version: format!("PostgreSQL {}", row.get::<_, String>(0)), - current_user: row.get(1), - current_schema: row.get(2), - }) -} - -/// Statements the server rejects inside a transaction block. -fn must_run_outside_transaction(sql: &str) -> bool { - let kw = first_keywords(sql, 2); - let first = kw.first().map(String::as_str).unwrap_or(""); - let second = kw.get(1).map(String::as_str).unwrap_or(""); - match (first, second) { - ("VACUUM", _) => true, - ("CREATE" | "DROP", "DATABASE" | "TABLESPACE") => true, - ("ALTER", "SYSTEM") => true, - ("CREATE" | "DROP" | "REINDEX", _) => sql.to_ascii_uppercase().contains("CONCURRENTLY"), - _ => false, - } -} - -impl PgSession { - /// Runs the grid edits as one unit. With autocommit they commit together - /// or not at all. Inside an open transaction they run under a savepoint, - /// so a failure undoes only this batch and the transaction stays usable. - /// In manual mode without a transaction, one is opened and left open. - pub async fn apply_changes(&self, req: &ApplyRequest) -> AppResult { - if self.is_closed() { - return Err(AppError::connection( - "The connection to the server was closed.", - )); - } - let changes = req - .changes - .iter() - .map(|c| build_change(&req.target, c)) - .collect::>>()?; - - let client = self.client.lock().await; - let started = Instant::now(); - let state = *self.state.lock(); - let manual = !state.autocommit || state.in_transaction; - let opened = !state.in_transaction; - - client - .batch_execute(if opened { - "BEGIN" - } else { - "SAVEPOINT lq_apply" - }) - .await - .map_err(map_error)?; - if manual && opened { - self.state.lock().in_transaction = true; - } - - let mut outcome = run_changes(&client, &changes).await; - if outcome.is_ok() { - let end = if !opened { - Some("RELEASE SAVEPOINT lq_apply") - } else if !manual { - Some("COMMIT") - } else { - None - }; - if let Some(end) = end { - if let Err(e) = client.batch_execute(end).await { - if end == "COMMIT" { - // A failed COMMIT ends the transaction anyway. - return Err(map_error(e)); - } - outcome = Err(map_error(e)); - } - } - } - let mut result = match outcome { - Ok(result) => result, - Err(e) => { - // Undo only this batch inside an existing transaction; if - // that fails too, end the transaction. - let kept = !opened - && client - .batch_execute("ROLLBACK TO SAVEPOINT lq_apply; RELEASE SAVEPOINT lq_apply") - .await - .is_ok(); - if !kept { - let _ = client.batch_execute("ROLLBACK").await; - self.state.lock().in_transaction = false; - self.tables.lock().clear(); - } - return Err(e); - } - }; - drop(client); - result.elapsed_ms = started.elapsed().as_millis() as u64; - result.in_transaction = self.state.lock().in_transaction; - Ok(result) - } - - /// Whether the rows of a result can be edited, from the table OID and - /// attribute number the server reports for each column. - async fn edit_target( - &self, - client: &Client, - sql: &str, - origins: &[(Option, Option)], - ) -> Result { - let first = first_keywords(sql, 1); - if !matches!( - first.first().map(String::as_str), - Some("SELECT" | "WITH" | "TABLE") - ) { - return Err(NOT_A_TABLE.into()); - } - let oid = single_table(origins)?; - let tokens = sql_tokens(sql); - // The row description of a UNION names the first branch's table, - // but the rows may come from any branch. - if has_union(&tokens) { - return Err("Read-only: the result combines rows from several queries.".into()); - } - if joins_tables(&tokens) { - return Err(JOINS_TABLES.into()); - } - let meta = self - .table_meta(client, oid) - .await - .ok_or_else(|| "Read-only: the table's key could not be read.".to_string())?; - target_for(&meta, oid, origins) - } - - /// Catalog data of one table, cached. One round trip on a miss; inside a - /// transaction it runs under a savepoint so a failure cannot abort it. - async fn table_meta(&self, client: &Client, oid: u32) -> Option> { - if let Some(meta) = self.tables.lock().get(&oid) { - return Some(meta.clone()); - } - let query = table_meta_sql(oid); - let in_tx = self.state.lock().in_transaction; - let sql = if in_tx { - format!("SAVEPOINT lq_edit_meta; {query}; RELEASE SAVEPOINT lq_edit_meta") - } else { - query - }; - let messages = match client.simple_query(&sql).await { - Ok(m) => m, - Err(_) => { - if in_tx { - let _ = client - .batch_execute( - "ROLLBACK TO SAVEPOINT lq_edit_meta; RELEASE SAVEPOINT lq_edit_meta", - ) - .await; - } - return None; - } - }; - let rows: Vec>> = messages - .iter() - .filter_map(|m| match m { - SimpleQueryMessage::Row(r) => { - Some((0..r.len()).map(|i| r.get(i).map(str::to_string)).collect()) - } - _ => None, - }) - .collect(); - let meta = Arc::new(parse_table_meta(&rows)?); - let mut tables = self.tables.lock(); - if tables.len() >= 256 { - tables.clear(); - } - tables.insert(oid, meta.clone()); - Some(meta) - } - - pub fn is_closed(&self) -> bool { - self.closed.load(Ordering::SeqCst) - } - - pub fn tx_state(&self) -> TxState { - *self.state.lock() - } - - pub async fn execute(&self, req: &ExecRequest) -> AppResult { - if self.is_closed() { - return Err(AppError::connection( - "The connection to the server was closed.", - )); - } - let mut client = self.client.lock().await; - self.notices.lock().clear(); - let started = Instant::now(); - let state = *self.state.lock(); - let keywords = first_keywords(&req.sql, 2); - let first = keywords.first().map(String::as_str).unwrap_or(""); - - let outcome = self.run(&mut client, req, state).await; - - // Updates the transaction state based on what was executed. - let in_transaction = self.state.lock().in_transaction; - match (&outcome, first) { - (Ok(_), "BEGIN" | "START") => self.state.lock().in_transaction = true, - (Ok(_), "COMMIT" | "ROLLBACK" | "END" | "ABORT") => { - // ROLLBACK TO SAVEPOINT keeps the transaction open. - if keywords.get(1).map(String::as_str) != Some("TO") { - self.state.lock().in_transaction = false; - } - } - (Err(_), _) if in_transaction => { - // An error inside the block invalidates the whole transaction: the - // only option is to roll it back. Doing it here keeps the next - // statement from failing with "current transaction is aborted". - let _ = client.batch_execute("ROLLBACK").await; - self.state.lock().in_transaction = false; - self.notices - .lock() - .push("The transaction was rolled back because of the error.".into()); - } - _ => {} - } - // DDL (or undoing it) may change keys and column types. - if matches!( - first, - "CREATE" | "ALTER" | "DROP" | "ROLLBACK" | "ABORT" | "DO" | "CALL" | "IMPORT" - ) || (outcome.is_err() && in_transaction) - { - self.tables.lock().clear(); - } - drop(client); - - let mut result = outcome?; - result.elapsed_ms = started.elapsed().as_millis() as u64; - result.notices = std::mem::take(&mut *self.notices.lock()); - result.in_transaction = self.state.lock().in_transaction; - Ok(result) - } - - async fn run( - &self, - client: &mut Client, - req: &ExecRequest, - state: TxState, - ) -> AppResult { - let stmt = client.prepare(&req.sql).await.map_err(map_error)?; - let manual = !state.autocommit || state.in_transaction; - - if stmt.columns().is_empty() { - if !state.autocommit && !state.in_transaction && !must_run_outside_transaction(&req.sql) - { - let kw = first_keywords(&req.sql, 1); - let is_tx_control = matches!( - kw.first().map(String::as_str), - Some( - "BEGIN" - | "START" - | "COMMIT" - | "ROLLBACK" - | "END" - | "ABORT" - | "SAVEPOINT" - | "RELEASE" - ) - ); - if !is_tx_control { - client.batch_execute("BEGIN").await.map_err(map_error)?; - self.state.lock().in_transaction = true; - } - } - let affected = client.execute(&stmt, &[]).await.map_err(map_error)?; - return Ok(ExecResult { - rows_affected: Some(affected), - ..Default::default() - }); - } - - let columns = stmt - .columns() - .iter() - .map(|c| ColumnInfo { - name: c.name().to_string(), - type_name: type_label(c.type_()), - kind: value_kind(c.type_()), - }) - .collect(); - - if manual && !state.in_transaction { - client.batch_execute("BEGIN").await.map_err(map_error)?; - self.state.lock().in_transaction = true; - } - - // Inside an already open transaction, the BEGIN from `transaction()` - // becomes a (filtered) warning and the object is forgotten so it does - // not end the user's transaction. In autocommit, it is a short - // transaction just for the portal, committed right after. - let tx = client.transaction().await.map_err(map_error)?; - let rows = fetch_rows(&tx, &stmt, req.max_rows).await; - let rows = match rows { - Ok(rows) => rows, - Err(e) => return Err(e), // drop → ROLLBACK - }; - if manual { - std::mem::forget(tx); - } else { - tx.commit().await.map_err(map_error)?; - } - - let mut out = Vec::with_capacity(rows.len()); - for row in &rows { - let mut cells = Vec::with_capacity(row.len()); - for i in 0..row.len() { - let cell: PgCell = row - .try_get(i) - .map_err(|e| AppError::internal(format!("Column {}: {e}", i + 1)))?; - cells.push(cell.0); - } - out.push(cells); - } - let truncated = req.max_rows > 0 && out.len() > req.max_rows; - if truncated { - out.truncate(req.max_rows); - } - let origins: Vec<_> = stmt - .columns() - .iter() - .map(|c| (c.table_oid(), c.column_id())) - .collect(); - let (editable, read_only_reason) = match self.edit_target(client, &req.sql, &origins).await - { - Ok(target) => (Some(target), None), - Err(reason) => (None, Some(reason)), - }; - Ok(ExecResult { - columns: Some(columns), - rows: out, - truncated, - editable, - read_only_reason, - ..Default::default() - }) - } - - pub async fn cancel(&self) -> AppResult<()> { - self.cancel - .cancel_query(self.tls.clone()) - .await - .map_err(map_error) - } - - pub async fn set_autocommit(&self, on: bool) -> AppResult { - if on && self.state.lock().in_transaction { - // Switching back to autocommit commits pending work, - // as JDBC clients do. - self.end_transaction(true).await?; - } - let mut st = self.state.lock(); - st.autocommit = on; - Ok(*st) - } - - pub async fn end_transaction(&self, commit: bool) -> AppResult { - let client = self.client.lock().await; - client - .batch_execute(if commit { "COMMIT" } else { "ROLLBACK" }) - .await - .map_err(map_error)?; - if !commit { - self.tables.lock().clear(); - } - let mut st = self.state.lock(); - st.in_transaction = false; - Ok(*st) - } - - pub async fn list_schemas(&self) -> AppResult> { - let client = self.client.lock().await; - let rows = client - .query( - "SELECT nspname::text FROM pg_namespace - WHERE nspname NOT LIKE 'pg\\_toast%' AND nspname NOT LIKE 'pg\\_temp\\_%' - ORDER BY nspname IN ('pg_catalog', 'information_schema'), nspname", - &[], - ) - .await - .map_err(map_error)?; - Ok(rows.iter().map(|r| r.get(0)).collect()) - } - - pub async fn list_objects(&self, schema: &str) -> AppResult> { - let client = self.client.lock().await; - let rows = client - .query( - "SELECT c.relname::text, - CASE c.relkind WHEN 'r' THEN 'table' WHEN 'p' THEN 'table' - WHEN 'v' THEN 'view' WHEN 'm' THEN 'matview' - WHEN 'f' THEN 'foreign' ELSE 'sequence' END - FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = $1 AND c.relkind IN ('r','p','v','m','f','S') - AND NOT c.relispartition - UNION ALL - SELECT p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')', - CASE p.prokind WHEN 'p' THEN 'procedure' ELSE 'function' END - FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace - WHERE n.nspname = $1 AND p.prokind IN ('f','p') - ORDER BY 2, 1", - &[&schema], - ) - .await - .map_err(map_error)?; - Ok(rows - .iter() - .map(|r| DbObject { - name: r.get(0), - kind: r.get(1), - }) - .collect()) - } - - pub async fn list_columns(&self, schema: &str, table: &str) -> AppResult> { - let client = self.client.lock().await; - let rows = client - .query( - "SELECT a.attname::text, format_type(a.atttypid, a.atttypmod), - NOT a.attnotnull, - COALESCE(a.attnum = ANY(i.indkey::int2[]), false), - pg_get_expr(d.adbin, d.adrelid) - FROM pg_attribute a - JOIN pg_class c ON c.oid = a.attrelid - JOIN pg_namespace n ON n.oid = c.relnamespace - LEFT JOIN pg_index i ON i.indrelid = c.oid AND i.indisprimary - LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum - WHERE n.nspname = $1 AND c.relname = $2 AND a.attnum > 0 AND NOT a.attisdropped - ORDER BY a.attnum", - &[&schema, &table], - ) - .await - .map_err(map_error)?; - Ok(rows - .iter() - .map(|r| DbColumn { - name: r.get(0), - type_name: r.get(1), - nullable: r.get(2), - primary_key: r.get(3), - default_value: r.get(4), - key_role: None, - }) - .collect()) - } - - /// Reads the rows through a portal in a read-only snapshot, one batch - /// at a time. - pub async fn stream(&self, sql: &str, sink: RowSink) -> AppResult { - let mut client = self.client.lock().await; - let stmt = client.prepare(sql).await.map_err(map_error)?; - let columns = stmt - .columns() - .iter() - .map(|c| ColumnInfo { - name: c.name().to_string(), - type_name: type_label(c.type_()), - kind: value_kind(c.type_()), - }) - .collect(); - sink.send(StreamEvent::Columns(columns)) - .await - .map_err(|_| super::stream_stopped())?; - let tx = client - .build_transaction() - .read_only(true) - .isolation_level(tokio_postgres::IsolationLevel::RepeatableRead) - .start() - .await - .map_err(map_error)?; - let portal = tx.bind(&stmt, &[]).await.map_err(map_error)?; - let mut total = 0u64; - loop { - let rows = tx - .query_portal(&portal, STREAM_BATCH as i32) - .await - .map_err(map_error)?; - let n = rows.len(); - let batch = super::full_values(|| { - rows.iter() - .map(|row| { - (0..row.len()) - .map(|i| { - row.try_get::<_, PgCell>(i).map(|c| c.0).map_err(|e| { - AppError::internal(format!("Column {}: {e}", i + 1)) - }) - }) - .collect::>>() - }) - .collect::>>() - })?; - total += n as u64; - if !batch.is_empty() { - sink.send(StreamEvent::Rows(batch)) - .await - .map_err(|_| super::stream_stopped())?; - } - if n < STREAM_BATCH { - break; - } - } - tx.commit().await.map_err(map_error)?; - Ok(total) - } - - pub async fn object_ddl(&self, schema: &str, name: &str, kind: &str) -> AppResult { - let client = self.client.lock().await; - let client = &*client; - - if matches!(kind, "function" | "procedure") { - let rows = text_rows( - client, - "SELECT pg_get_functiondef(p.oid) - FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace - WHERE n.nspname = $1 - AND p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' = $2", - &[schema, name], - ) - .await?; - let def = rows.first().map(|r| cell_text(r, 0)).unwrap_or_default(); - return Ok(if def.trim().is_empty() { - def - } else { - format!("{};\n", def.trim_end()) - }); - } - - let rel = text_rows( - client, - "SELECT c.oid::text, c.relkind::text, c.relpersistence::text, - quote_ident(n.nspname) || '.' || quote_ident(c.relname) - FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = $1 AND c.relname = $2", - &[schema, name], - ) - .await?; - let Some(rel) = rel.first() else { - return Err(AppError::not_found(format!( - "{schema}.{name} was not found." - ))); - }; - let oid = cell_text(rel, 0); - let relkind = cell_text(rel, 1); - let target = cell_text(rel, 3); - let mut out = match relkind.as_str() { - "v" | "m" => { - let def = text_rows( - client, - "SELECT pg_get_viewdef($1::text::oid, true)", - &[&oid], - ) - .await?; - let body = def.first().map(|r| cell_text(r, 0)).unwrap_or_default(); - let body = body.trim().trim_end_matches(';'); - if relkind == "v" { - format!("CREATE OR REPLACE VIEW {target} AS\n{body};\n") - } else { - format!("CREATE MATERIALIZED VIEW {target} AS\n{body}\nWITH DATA;\n") - } - } - "S" => pg_sequence_ddl(client, &oid, &target).await?, - "r" | "p" | "f" => { - pg_table_ddl(client, &oid, &relkind, &cell_text(rel, 2), &target).await? - } - other => { - return Err(AppError::invalid(format!( - "LowQuery cannot script this kind of relation ({other})." - ))); - } - }; - - // Indexes not behind a constraint, triggers and comments. - let extra = text_rows( - client, - "SELECT * FROM ( - SELECT pg_get_indexdef(i.indexrelid) || ';' FROM pg_index i - WHERE i.indrelid = $1::text::oid - AND NOT EXISTS (SELECT 1 FROM pg_constraint c - WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid) - ORDER BY 1) ix - UNION ALL - SELECT * FROM ( - SELECT pg_get_triggerdef(t.oid, true) || ';' FROM pg_trigger t - WHERE t.tgrelid = $1::text::oid AND NOT t.tgisinternal ORDER BY t.tgname) tr - UNION ALL - SELECT 'COMMENT ON ' || CASE c.relkind WHEN 'v' THEN 'VIEW' - WHEN 'm' THEN 'MATERIALIZED VIEW' WHEN 'S' THEN 'SEQUENCE' - WHEN 'f' THEN 'FOREIGN TABLE' ELSE 'TABLE' END - || ' ' || $2::text || ' IS ' || quote_literal(d.description) || ';' - FROM pg_description d JOIN pg_class c ON c.oid = d.objoid - WHERE d.objoid = $1::text::oid AND d.classoid = 'pg_class'::regclass - AND d.objsubid = 0 - UNION ALL - SELECT * FROM ( - SELECT 'COMMENT ON COLUMN ' || $2::text || '.' || quote_ident(a.attname) - || ' IS ' || quote_literal(d.description) || ';' - FROM pg_description d - JOIN pg_attribute a ON a.attrelid = d.objoid AND a.attnum = d.objsubid - WHERE d.objoid = $1::text::oid AND d.classoid = 'pg_class'::regclass - AND d.objsubid > 0 - ORDER BY d.objsubid) cm", - &[&oid, &target], - ) - .await?; - for row in extra { - out.push_str(&format!("\n{}\n", cell_text(&row, 0))); - } - Ok(out) - } -} - -/// Catalog query whose columns are all text. -async fn text_rows( - client: &Client, - sql: &str, - params: &[&str], -) -> AppResult>>> { - let params: Vec<&(dyn ToSql + Sync)> = - params.iter().map(|p| p as &(dyn ToSql + Sync)).collect(); - let rows = client.query(sql, ¶ms).await.map_err(map_error)?; - Ok(rows - .iter() - .map(|r| (0..r.len()).map(|i| r.get(i)).collect()) - .collect()) -} - -fn cell_text(row: &[Option], i: usize) -> String { - row.get(i).cloned().flatten().unwrap_or_default() -} - -async fn pg_sequence_ddl(client: &Client, oid: &str, target: &str) -> AppResult { - let rows = text_rows( - client, - "SELECT format_type(s.seqtypid, NULL), s.seqincrement::text, s.seqmin::text, - s.seqmax::text, s.seqstart::text, s.seqcache::text, s.seqcycle::text - FROM pg_sequence s WHERE s.seqrelid = $1::text::oid", - &[oid], - ) - .await?; - let Some(q) = rows.first() else { - return Ok(String::new()); - }; - Ok(format!( - "CREATE SEQUENCE {target}\n AS {}\n INCREMENT BY {}\n MINVALUE {}\n MAXVALUE {}\n START WITH {}\n CACHE {}\n {}CYCLE;\n", - cell_text(q, 0), - cell_text(q, 1), - cell_text(q, 2), - cell_text(q, 3), - cell_text(q, 4), - cell_text(q, 5), - if cell_text(q, 6) == "true" { "" } else { "NO " } - )) -} - -/// CREATE TABLE with columns, defaults, identity and generated columns, and -/// the primary key, unique, check and exclusion constraints; foreign keys -/// follow as ALTER TABLE so tables can be created in any order. -async fn pg_table_ddl( - client: &Client, - oid: &str, - relkind: &str, - persistence: &str, - target: &str, -) -> AppResult { - // attidentity (10+) and attgenerated (12+) are read through to_jsonb so - // older servers leave them empty instead of failing. - let columns = text_rows( - client, - "SELECT quote_ident(a.attname), format_type(a.atttypid, a.atttypmod), - a.attnotnull::text, pg_get_expr(d.adbin, d.adrelid), - to_jsonb(a) ->> 'attidentity', to_jsonb(a) ->> 'attgenerated' - FROM pg_attribute a - LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum - WHERE a.attrelid = $1::text::oid AND a.attnum > 0 AND NOT a.attisdropped - ORDER BY a.attnum", - &[oid], - ) - .await?; - let constraints = text_rows( - client, - "SELECT quote_ident(conname), pg_get_constraintdef(oid, true), contype::text - FROM pg_constraint - WHERE conrelid = $1::text::oid AND contype IN ('p', 'u', 'c', 'x', 'f') AND conislocal - ORDER BY CASE contype WHEN 'p' THEN 0 WHEN 'u' THEN 1 WHEN 'c' THEN 2 - WHEN 'x' THEN 3 ELSE 4 END, conname", - &[oid], - ) - .await?; - let mut lines: Vec = columns - .iter() - .map(|c| { - let mut line = format!(" {} {}", cell_text(c, 0), cell_text(c, 1)); - let default = cell_text(c, 3); - match (cell_text(c, 4).as_str(), cell_text(c, 5).as_str()) { - ("a", _) => line.push_str(" GENERATED ALWAYS AS IDENTITY"), - ("d", _) => line.push_str(" GENERATED BY DEFAULT AS IDENTITY"), - (_, "s") => line.push_str(&format!(" GENERATED ALWAYS AS ({default}) STORED")), - (_, "v") => line.push_str(&format!(" GENERATED ALWAYS AS ({default}) VIRTUAL")), - _ if !default.is_empty() => line.push_str(&format!(" DEFAULT {default}")), - _ => {} - } - if cell_text(c, 2) == "true" { - line.push_str(" NOT NULL"); - } - line - }) - .collect(); - let mut foreign_keys = Vec::new(); - for c in &constraints { - let def = format!("CONSTRAINT {} {}", cell_text(c, 0), cell_text(c, 1)); - if cell_text(c, 2) == "f" { - foreign_keys.push(format!("ALTER TABLE {target} ADD {def};")); - } else { - lines.push(format!(" {def}")); - } - } - let head = match (relkind, persistence) { - ("f", _) => "CREATE FOREIGN TABLE", - (_, "u") => "CREATE UNLOGGED TABLE", - _ => "CREATE TABLE", - }; - let mut out = format!("{head} {target} (\n{}\n)", lines.join(",\n")); - if relkind == "p" { - let key = text_rows(client, "SELECT pg_get_partkeydef($1::text::oid)", &[oid]).await?; - let key = key.first().map(|r| cell_text(r, 0)).unwrap_or_default(); - out.push_str(&format!("\nPARTITION BY {key}")); - } - if relkind == "f" { - let server = text_rows( - client, - "SELECT quote_ident(s.srvname), - (SELECT string_agg(quote_ident(split_part(o, '=', 1)) || ' ' - || quote_literal(substr(o, strpos(o, '=') + 1)), ', ') - FROM unnest(ft.ftoptions) o) - FROM pg_foreign_table ft JOIN pg_foreign_server s ON s.oid = ft.ftserver - WHERE ft.ftrelid = $1::text::oid", - &[oid], - ) - .await?; - if let Some(sv) = server.first() { - out.push_str(&format!("\nSERVER {}", cell_text(sv, 0))); - let options = cell_text(sv, 1); - if !options.is_empty() { - out.push_str(&format!("\nOPTIONS ({options})")); - } - } - } - out.push_str(";\n"); - for fk in foreign_keys { - out.push_str(&format!("\n{fk}\n")); - } - Ok(out) -} - -async fn fetch_rows( - tx: &tokio_postgres::Transaction<'_>, - stmt: &Statement, - max_rows: usize, -) -> AppResult> { - if max_rows == 0 { - return tx.query(stmt, &[]).await.map_err(map_error); - } - let portal = tx.bind(stmt, &[]).await.map_err(map_error)?; - let limit = i32::try_from(max_rows.saturating_add(1)).unwrap_or(i32::MAX); - tx.query_portal(&portal, limit).await.map_err(map_error) -} - -const NOT_A_TABLE: &str = "Read-only: only rows from a table can be edited."; -const JOINS_TABLES: &str = - "Read-only: the query joins tables; select from one table to edit its rows."; - -/// Catalog data of a table behind a result. -#[derive(Debug)] -struct TableMeta { - schema: String, - name: String, - /// `pg_class.relkind`: `r` table, `p` partitioned table, `v` view... - kind: String, - /// attnum, name, type as in DDL. - columns: Vec<(i16, String, String)>, - /// Attribute numbers of the primary key, or of a unique key whose - /// columns are all NOT NULL, in key order. - key: Option>, - primary: bool, -} - -/// One row per column, all values as text (simple protocol). The chosen key -/// is the primary key, else the narrowest valid unique index without -/// expressions or predicate whose key columns are all NOT NULL. -fn table_meta_sql(oid: u32) -> String { - format!( - "SELECT n.nspname, c.relname, c.relkind, a.attnum, a.attname, - pg_catalog.format_type(a.atttypid, a.atttypmod), k.cols, k.indisprimary - FROM pg_catalog.pg_class c - JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace - LEFT JOIN pg_catalog.pg_attribute a - ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped - LEFT JOIN LATERAL ( - SELECT (SELECT string_agg(u.k::text, ',' ORDER BY u.o) - FROM unnest(i.indkey::int2[]) WITH ORDINALITY u(k, o) - WHERE u.o <= i.indnkeyatts) AS cols, - i.indisprimary - FROM pg_catalog.pg_index i - WHERE i.indrelid = c.oid AND i.indisunique AND i.indisvalid - AND (i.indisprimary OR ( - i.indpred IS NULL AND i.indexprs IS NULL - AND NOT EXISTS ( - SELECT 1 - FROM unnest(i.indkey::int2[]) WITH ORDINALITY u(k, o) - JOIN pg_catalog.pg_attribute x - ON x.attrelid = c.oid AND x.attnum = u.k - WHERE u.o <= i.indnkeyatts AND NOT x.attnotnull))) - ORDER BY i.indisprimary DESC, i.indnkeyatts, i.indexrelid - LIMIT 1) k ON true - WHERE c.oid = {oid} - ORDER BY a.attnum" - ) -} - -fn parse_table_meta(rows: &[Vec>]) -> Option { - let first = rows.first()?; - let text = |row: &Vec>, i: usize| row.get(i).cloned().flatten(); - let key = text(first, 6).map(|cols| { - cols.split(',') - .filter_map(|k| k.trim().parse::().ok()) - .collect::>() - }); - let mut columns = Vec::with_capacity(rows.len()); - for row in rows { - if let (Some(attnum), Some(name), Some(ty)) = (text(row, 3), text(row, 4), text(row, 5)) { - columns.push((attnum.parse().ok()?, name, ty)); - } - } - Some(TableMeta { - schema: text(first, 0)?, - name: text(first, 1)?, - kind: text(first, 2)?, - columns, - key: key.filter(|k| !k.is_empty()), - primary: text(first, 7).as_deref() == Some("t"), - }) -} - -/// The one table all base columns come from. -fn single_table(origins: &[(Option, Option)]) -> Result { - let mut table = None; - for &(oid, _) in origins { - match (table, oid) { - (_, None) => {} - (None, Some(oid)) => table = Some(oid), - (Some(t), Some(oid)) if t != oid => { - return Err("Read-only: the result combines columns from several tables.".into()) - } - _ => {} - } - } - table.ok_or_else(|| NOT_A_TABLE.to_string()) -} - -fn target_for( - meta: &TableMeta, - oid: u32, - origins: &[(Option, Option)], -) -> Result { - if !matches!(meta.kind.as_str(), "r" | "p") { - return Err(NOT_A_TABLE.into()); - } - let Some(key) = &meta.key else { - return Err(format!( - "Read-only: table {} has no primary key.", - meta.name - )); - }; - let column = |attnum: i16| meta.columns.iter().find(|c| c.0 == attnum); - let columns: Vec> = origins - .iter() - .map(|&(t, attnum)| match (t, attnum) { - (Some(t), Some(attnum)) if t == oid => column(attnum).map(|c| EditColumn { - name: c.1.clone(), - type_name: c.2.clone(), - }), - _ => None, - }) - .collect(); - let positions: Vec> = key - .iter() - .map(|&k| { - origins - .iter() - .position(|&(t, attnum)| t == Some(oid) && attnum == Some(k)) - .filter(|&i| columns[i].is_some()) - }) - .collect(); - if positions.iter().any(Option::is_none) { - let names: Vec<&str> = key - .iter() - .map(|&k| column(k).map(|c| c.1.as_str()).unwrap_or("?")) - .collect(); - return Err(format!( - "Read-only: add the {} columns ({}) to the query to edit rows.", - if meta.primary { "primary key" } else { "key" }, - names.join(", ") - )); - } - Ok(EditTarget { - schema: Some(meta.schema.clone()), - table: meta.name.clone(), - columns, - key: positions.into_iter().flatten().collect(), - }) -} - -/// Keywords and the punctuation that shapes clauses, outside strings, -/// quoted identifiers, comments and dollar quotes. -#[derive(Debug, PartialEq, Eq)] -enum SqlToken { - /// Uppercased. - Word(String), - Open, - Close, - Comma, -} - -fn sql_tokens(sql: &str) -> Vec { - let mut tokens = Vec::new(); - let b = sql.as_bytes(); - let is_word = |c: u8| c.is_ascii_alphanumeric() || c == b'_' || c == b'$' || c >= 0x80; - let mut i = 0; - while i < b.len() { - let c = b[i]; - let prev_word = i > 0 && is_word(b[i - 1]); - if c == b'-' && b.get(i + 1) == Some(&b'-') { - while i < b.len() && b[i] != b'\n' { - i += 1; - } - } else if c == b'/' && b.get(i + 1) == Some(&b'*') { - // Block comments nest. - let mut depth = 0; - while i < b.len() { - if b[i] == b'/' && b.get(i + 1) == Some(&b'*') { - depth += 1; - i += 2; - } else if b[i] == b'*' && b.get(i + 1) == Some(&b'/') { - depth -= 1; - i += 2; - if depth == 0 { - break; - } - } else { - i += 1; - } - } - } else if c == b'\'' || c == b'"' { - // E'...' strings accept backslash escapes. - let escapes = c == b'\'' - && i > 0 - && matches!(b[i - 1], b'e' | b'E') - && !(i > 1 && is_word(b[i - 2])); - i += 1; - while i < b.len() { - if escapes && b[i] == b'\\' { - i += 2; - } else if b[i] == c { - if b.get(i + 1) == Some(&c) { - i += 2; - } else { - break; - } - } else { - i += 1; - } - } - i += 1; - } else if c == b'$' && !prev_word { - // Dollar quote: $$...$$ or $tag$...$tag$. - let mut j = i + 1; - while j < b.len() && (b[j].is_ascii_alphanumeric() || b[j] == b'_' || b[j] >= 0x80) { - j += 1; - } - let tag_ok = - j < b.len() && b[j] == b'$' && !b.get(i + 1).is_some_and(|d| d.is_ascii_digit()); - if tag_ok { - let tag = &sql[i..=j]; - i = match sql[j + 1..].find(tag) { - Some(end) => j + 1 + end + tag.len(), - None => b.len(), - }; - } else { - i += 1; - } - } else if is_word(c) && !prev_word { - let start = i; - while i < b.len() && is_word(b[i]) { - i += 1; - } - tokens.push(SqlToken::Word(sql[start..i].to_ascii_uppercase())); - } else { - match c { - b'(' => tokens.push(SqlToken::Open), - b')' => tokens.push(SqlToken::Close), - b',' => tokens.push(SqlToken::Comma), - _ => {} - } - i += 1; - } - } - tokens -} - -/// Whether `UNION` appears as a keyword. -fn has_union(tokens: &[SqlToken]) -> bool { - tokens - .iter() - .any(|t| matches!(t, SqlToken::Word(w) if w == "UNION")) -} - -/// Whether the query joins tables at any depth: a `JOIN` keyword, or a -/// comma in a `FROM` list. Both sides of a self-join report the same table -/// OID, so the row description alone cannot tell them apart. -fn joins_tables(tokens: &[SqlToken]) -> bool { - // One entry per paren depth: inside a FROM list at that depth. - let mut in_from = vec![false]; - for t in tokens { - match t { - SqlToken::Open => in_from.push(false), - SqlToken::Close => { - if in_from.len() > 1 { - in_from.pop(); - } - } - SqlToken::Comma => { - if in_from.last() == Some(&true) { - return true; - } - } - SqlToken::Word(w) => { - let state = in_from.last_mut().expect("depth 0 is never popped"); - match w.as_str() { - "JOIN" => return true, - "FROM" => *state = true, - "WHERE" | "GROUP" | "HAVING" | "WINDOW" | "ORDER" | "LIMIT" | "OFFSET" - | "FETCH" | "FOR" | "UNION" | "INTERSECT" | "EXCEPT" => *state = false, - _ => {} - } - } - } - } - false -} - -/// A value sent in text format: the server parses it with the input -/// function of the type it infers for the parameter (the column's type). -#[derive(Debug)] -struct TextParam<'a>(Option<&'a str>); - -impl ToSql for TextParam<'_> { - fn to_sql( - &self, - _ty: &Type, - out: &mut BytesMut, - ) -> Result> { - match self.0 { - Some(s) => { - out.extend_from_slice(s.as_bytes()); - Ok(IsNull::No) - } - None => Ok(IsNull::Yes), - } - } - - fn accepts(_: &Type) -> bool { - true - } - - fn encode_format(&self, _ty: &Type) -> Format { - Format::Text - } - - tokio_postgres::types::to_sql_checked!(); -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ChangeKind { - Update, - Delete, - Insert, -} - -/// One statement ready to run, with its parameters in order. -#[derive(Debug)] -struct BuiltChange { - kind: ChangeKind, - sql: String, - params: Vec>, -} - -fn quote_ident(name: &str) -> String { - format!("\"{}\"", name.replace('"', "\"\"")) -} - -fn qualified_table(target: &EditTarget) -> String { - match &target.schema { - Some(schema) => format!("{}.{}", quote_ident(schema), quote_ident(&target.table)), - None => quote_ident(&target.table), - } -} - -fn edit_column(target: &EditTarget, index: usize) -> AppResult<&EditColumn> { - target - .columns - .get(index) - .and_then(Option::as_ref) - .ok_or_else(|| AppError::invalid(format!("Column {} cannot be edited.", index + 1))) -} - -/// `$n`, routed through numeric for `money`, whose own input depends on -/// `lc_monetary`. -fn placeholder(n: usize, column: &EditColumn) -> String { - if column.type_name == "money" { - format!("${n}::numeric::money") - } else { - format!("${n}") - } -} - -fn check_value(value: &Option) -> AppResult> { - match value { - Some(v) if v.contains("… (") => Err(AppError::invalid( - "This value is only a preview and cannot be saved.", - )), - _ => Ok(value.clone()), - } -} - -/// Table columns and values of a change; a column given twice keeps the -/// last value. -fn assignments<'a>( - target: &'a EditTarget, - values: &[crate::model::CellValue], -) -> AppResult)>> { - let mut out: Vec<(&EditColumn, Option)> = Vec::with_capacity(values.len()); - for v in values { - let column = edit_column(target, v.column)?; - let value = check_value(&v.value)?; - match out.iter_mut().find(|(c, _)| c.name == column.name) { - Some(slot) => slot.1 = value, - None => out.push((column, value)), - } - } - Ok(out) -} - -fn where_key( - target: &EditTarget, - key: &[Option], - params: &mut Vec>, -) -> AppResult { - if key.len() != target.key.len() { - return Err(AppError::invalid( - "The row key does not match the result's key columns.", - )); - } - let mut parts = Vec::with_capacity(key.len()); - for (&index, value) in target.key.iter().zip(key) { - let column = edit_column(target, index)?; - match check_value(value)? { - None => parts.push(format!("{} IS NULL", quote_ident(&column.name))), - Some(v) => { - params.push(Some(v)); - parts.push(format!( - "{} = {}", - quote_ident(&column.name), - placeholder(params.len(), column) - )); - } - } - } - Ok(parts.join(" AND ")) -} - -/// The statement for one change; `None` for an update without values. -fn build_change(target: &EditTarget, change: &RowChange) -> AppResult> { - let table = qualified_table(target); - let mut params = Vec::new(); - let built = match change { - RowChange::Update { key, values } => { - let sets = assignments(target, values)?; - if sets.is_empty() { - return Ok(None); - } - let mut set_sql = Vec::with_capacity(sets.len()); - for (column, value) in sets { - params.push(value); - set_sql.push(format!( - "{} = {}", - quote_ident(&column.name), - placeholder(params.len(), column) - )); - } - let filter = where_key(target, key, &mut params)?; - BuiltChange { - kind: ChangeKind::Update, - sql: format!("UPDATE {table} SET {} WHERE {filter}", set_sql.join(", ")), - params, - } - } - RowChange::Delete { key } => { - let filter = where_key(target, key, &mut params)?; - BuiltChange { - kind: ChangeKind::Delete, - sql: format!("DELETE FROM {table} WHERE {filter}"), - params, - } - } - RowChange::Insert { values } => { - let sets = assignments(target, values)?; - if sets.is_empty() { - BuiltChange { - kind: ChangeKind::Insert, - sql: format!("INSERT INTO {table} DEFAULT VALUES"), - params, - } - } else { - let mut names = Vec::with_capacity(sets.len()); - let mut slots = Vec::with_capacity(sets.len()); - for (column, value) in sets { - params.push(value); - names.push(quote_ident(&column.name)); - slots.push(placeholder(params.len(), column)); - } - BuiltChange { - kind: ChangeKind::Insert, - sql: format!( - "INSERT INTO {table} ({}) VALUES ({})", - names.join(", "), - slots.join(", ") - ), - params, - } - } - } - }; - Ok(Some(built)) -} - -/// Runs the statements in order, inside the caller's transaction. -async fn run_changes(client: &Client, changes: &[Option]) -> AppResult { - let mut prepared: HashMap<&str, Statement> = HashMap::new(); - let mut result = ApplyResult::default(); - for (i, change) in changes.iter().enumerate() { - let Some(change) = change else { continue }; - let row = i + 1; - let row_error = |e: tokio_postgres::Error| { - let mut err = map_error(e); - if err.kind == ErrorKind::Database { - err.message = format!("Row {row} was not saved: {}", err.message); - err.position = None; - } - err - }; - let stmt = match prepared.get(change.sql.as_str()) { - Some(stmt) => stmt.clone(), - None => { - let stmt = client.prepare(&change.sql).await.map_err(row_error)?; - prepared.insert(&change.sql, stmt.clone()); - stmt - } - }; - let params: Vec = change - .params - .iter() - .map(|p| TextParam(p.as_deref())) - .collect(); - let refs: Vec<&(dyn ToSql + Sync)> = - params.iter().map(|p| p as &(dyn ToSql + Sync)).collect(); - let affected = client.execute(&stmt, &refs).await.map_err(row_error)?; - match change.kind { - ChangeKind::Insert => result.inserted += affected, - kind => { - if affected != 1 { - let mut msg = - format!("Row {row} was not saved: {affected} rows matched its key"); - msg.push_str(if affected == 0 { - " (changed or removed by someone else)." - } else { - "." - }); - return Err(AppError::new(ErrorKind::Database, msg)); - } - if kind == ChangeKind::Update { - result.updated += 1; - } else { - result.deleted += 1; - } - } - } - } - Ok(result) -} - -pub fn map_error(e: tokio_postgres::Error) -> AppError { - if let Some(db) = e.as_db_error() { - let code = db.code().code().to_string(); - let kind = if code == "57014" { - ErrorKind::Cancelled - } else { - ErrorKind::Database - }; - let mut err = AppError::new(kind, db.message()); - err.position = match db.position() { - Some(ErrorPosition::Original(p)) => Some((*p as usize).saturating_sub(1)), - _ => None, - }; - err.detail = db.detail().map(str::to_string); - err.hint = db.hint().map(str::to_string); - // Authentication (class 28) and connection (08) errors are not SQL errors. - if code.starts_with("28") || code.starts_with("08") { - err.kind = ErrorKind::Connection; - } - err.code = Some(code); - return err; - } - let mut message = e.to_string(); - let mut source = std::error::Error::source(&e); - while let Some(s) = source { - let text = s.to_string(); - if !message.contains(&text) { - message.push_str(": "); - message.push_str(&text); - } - source = s.source(); - } - if e.is_closed() { - return AppError::connection("The connection to the server was closed."); - } - AppError::connection(message) -} - -pub(super) fn tls_config(mode: SslMode) -> AppResult { - let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); - let builder = rustls::ClientConfig::builder_with_provider(provider.clone()) - .with_safe_default_protocol_versions() - .map_err(|e| AppError::internal(e.to_string()))?; - let config = if mode == SslMode::VerifyFull { - let mut roots = rustls::RootCertStore::empty(); - roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); - for cert in rustls_native_certs::load_native_certs().certs { - let _ = roots.add(cert); - } - builder.with_root_certificates(roots).with_no_client_auth() - } else { - // libpq's `prefer`/`require` encrypt without validating the certificate. - builder - .dangerous() - .with_custom_certificate_verifier(Arc::new(AcceptAnyCert(provider))) - .with_no_client_auth() - }; - Ok(config) -} - -#[derive(Debug)] -struct AcceptAnyCert(Arc); - -impl ServerCertVerifier for AcceptAnyCert { - fn verify_server_cert( - &self, - _end_entity: &CertificateDer<'_>, - _intermediates: &[CertificateDer<'_>], - _server_name: &ServerName<'_>, - _ocsp_response: &[u8], - _now: UnixTime, - ) -> Result { - Ok(ServerCertVerified::assertion()) - } - - fn verify_tls12_signature( - &self, - message: &[u8], - cert: &CertificateDer<'_>, - dss: &DigitallySignedStruct, - ) -> Result { - rustls::crypto::verify_tls12_signature( - message, - cert, - dss, - &self.0.signature_verification_algorithms, - ) - } - - fn verify_tls13_signature( - &self, - message: &[u8], - cert: &CertificateDer<'_>, - dss: &DigitallySignedStruct, - ) -> Result { - rustls::crypto::verify_tls13_signature( - message, - cert, - dss, - &self.0.signature_verification_algorithms, - ) - } - - fn supported_verify_schemes(&self) -> Vec { - self.0.signature_verification_algorithms.supported_schemes() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::model::CellValue; - - fn target() -> EditTarget { - EditTarget { - schema: Some("My Schema".into()), - table: "Order \"Lines\"".into(), - columns: vec![ - Some(EditColumn { - name: "Id".into(), - type_name: "integer".into(), - }), - Some(EditColumn { - name: "price".into(), - type_name: "money".into(), - }), - None, - Some(EditColumn { - name: "code".into(), - type_name: "text".into(), - }), - ], - key: vec![0, 3], - } - } - - fn cell(column: usize, value: Option<&str>) -> CellValue { - CellValue { - column, - value: value.map(str::to_string), - } - } - - fn some(v: &str) -> Option { - Some(v.to_string()) - } - - #[test] - fn quotes_identifiers() { - assert_eq!(quote_ident("a"), "\"a\""); - assert_eq!(quote_ident("Mixed Case"), "\"Mixed Case\""); - assert_eq!(quote_ident("say \"hi\""), "\"say \"\"hi\"\"\""); - assert_eq!( - qualified_table(&target()), - "\"My Schema\".\"Order \"\"Lines\"\"\"" - ); - } - - #[test] - fn builds_update_with_null_key_and_money() { - let change = RowChange::Update { - key: vec![some("7"), None], - values: vec![cell(1, Some("12.34")), cell(3, None)], - }; - let built = build_change(&target(), &change).unwrap().unwrap(); - assert_eq!(built.kind, ChangeKind::Update); - assert_eq!( - built.sql, - "UPDATE \"My Schema\".\"Order \"\"Lines\"\"\" SET \"price\" = $1::numeric::money, \ - \"code\" = $2 WHERE \"Id\" = $3 AND \"code\" IS NULL" - ); - assert_eq!(built.params, vec![some("12.34"), None, some("7")]); - } - - #[test] - fn update_keeps_last_value_of_a_column_and_skips_empty() { - let change = RowChange::Update { - key: vec![some("1"), some("a")], - values: vec![cell(3, Some("x")), cell(3, Some("y"))], - }; - let built = build_change(&target(), &change).unwrap().unwrap(); - assert!(built.sql.contains("SET \"code\" = $1 WHERE")); - assert_eq!(built.params, vec![some("y"), some("1"), some("a")]); - let empty = RowChange::Update { - key: vec![some("1"), some("a")], - values: vec![], - }; - assert!(build_change(&target(), &empty).unwrap().is_none()); - } - - #[test] - fn builds_delete_and_insert() { - let delete = RowChange::Delete { - key: vec![some("1"), some("a'b")], - }; - let built = build_change(&target(), &delete).unwrap().unwrap(); - assert_eq!( - built.sql, - "DELETE FROM \"My Schema\".\"Order \"\"Lines\"\"\" WHERE \"Id\" = $1 AND \"code\" = $2" - ); - assert_eq!(built.params, vec![some("1"), some("a'b")]); - - let insert = RowChange::Insert { - values: vec![cell(0, Some("5")), cell(1, Some("1.00")), cell(3, None)], - }; - let built = build_change(&target(), &insert).unwrap().unwrap(); - assert_eq!( - built.sql, - "INSERT INTO \"My Schema\".\"Order \"\"Lines\"\"\" (\"Id\", \"price\", \"code\") \ - VALUES ($1, $2::numeric::money, $3)" - ); - assert_eq!(built.params, vec![some("5"), some("1.00"), None]); - - let defaults = RowChange::Insert { values: vec![] }; - let built = build_change(&target(), &defaults).unwrap().unwrap(); - assert_eq!( - built.sql, - "INSERT INTO \"My Schema\".\"Order \"\"Lines\"\"\" DEFAULT VALUES" - ); - assert!(built.params.is_empty()); - } - - #[test] - fn rejects_invalid_changes() { - let preview = RowChange::Update { - key: vec![some("1"), some("a")], - values: vec![cell(3, Some("\\x0102… (40000 bytes)"))], - }; - let err = build_change(&target(), &preview).unwrap_err(); - assert_eq!(err.kind, ErrorKind::Invalid); - assert_eq!( - err.message, - "This value is only a preview and cannot be saved." - ); - - let expression = RowChange::Insert { - values: vec![cell(2, Some("x"))], - }; - assert_eq!( - build_change(&target(), &expression).unwrap_err().kind, - ErrorKind::Invalid - ); - let out_of_range = RowChange::Insert { - values: vec![cell(9, Some("x"))], - }; - assert_eq!( - build_change(&target(), &out_of_range).unwrap_err().kind, - ErrorKind::Invalid - ); - let short_key = RowChange::Delete { - key: vec![some("1")], - }; - assert_eq!( - build_change(&target(), &short_key).unwrap_err().kind, - ErrorKind::Invalid - ); - } - - fn meta(kind: &str, key: Option>, primary: bool) -> TableMeta { - TableMeta { - schema: "public".into(), - name: "orders".into(), - kind: kind.into(), - columns: vec![ - (1, "id".into(), "integer".into()), - (2, "name".into(), "character varying(20)".into()), - (3, "total".into(), "numeric(10,2)".into()), - ], - key, - primary, - } - } - - #[test] - fn detects_editable_results() { - let origins = [ - (Some(10), Some(2)), - (None, None), - (Some(10), Some(1)), - (Some(10), Some(3)), - ]; - let t = target_for(&meta("r", Some(vec![1]), true), 10, &origins).unwrap(); - assert_eq!(t.schema.as_deref(), Some("public")); - assert_eq!(t.table, "orders"); - assert_eq!(t.key, vec![2]); - assert!(t.columns[1].is_none()); - let name = t.columns[0].as_ref().unwrap(); - assert_eq!( - (name.name.as_str(), name.type_name.as_str()), - ("name", "character varying(20)") - ); - - // Key in key order, not result order. - let t = target_for(&meta("p", Some(vec![3, 1]), false), 10, &origins).unwrap(); - assert_eq!(t.key, vec![3, 2]); - } - - #[test] - fn explains_read_only_results() { - let origins = [(Some(10), Some(2)), (Some(10), Some(3))]; - assert_eq!( - target_for(&meta("r", Some(vec![1]), true), 10, &origins).unwrap_err(), - "Read-only: add the primary key columns (id) to the query to edit rows." - ); - assert_eq!( - target_for(&meta("r", Some(vec![1, 2]), false), 10, &origins).unwrap_err(), - "Read-only: add the key columns (id, name) to the query to edit rows." - ); - assert_eq!( - target_for(&meta("r", None, false), 10, &origins).unwrap_err(), - "Read-only: table orders has no primary key." - ); - assert_eq!( - target_for(&meta("v", Some(vec![2]), true), 10, &origins).unwrap_err(), - NOT_A_TABLE - ); - assert_eq!(single_table(&[(None, None)]).unwrap_err(), NOT_A_TABLE); - assert_eq!( - single_table(&[(Some(1), Some(1)), (None, None), (Some(2), Some(1))]).unwrap_err(), - "Read-only: the result combines columns from several tables." - ); - assert_eq!( - single_table(&[(None, None), (Some(5), Some(1)), (Some(5), Some(2))]), - Ok(5) - ); - } - - #[test] - fn parses_catalog_rows() { - let row = |attnum: &str, name: &str, ty: &str| { - vec![ - some("public"), - some("orders"), - some("r"), - some(attnum), - some(name), - some(ty), - some("2,1"), - some("t"), - ] - }; - let m = parse_table_meta(&[row("1", "id", "integer"), row("2", "Name", "text")]).unwrap(); - assert_eq!(m.key, Some(vec![2, 1])); - assert!(m.primary); - assert_eq!(m.columns[1], (2, "Name".to_string(), "text".to_string())); - - let no_key = vec![ - some("s"), - some("t"), - some("r"), - some("1"), - some("a"), - some("integer"), - None, - None, - ]; - let m = parse_table_meta(&[no_key]).unwrap(); - assert_eq!(m.key, None); - assert!(!m.primary); - assert!(parse_table_meta(&[]).is_none()); - } - - fn union(sql: &str) -> bool { - has_union(&sql_tokens(sql)) - } - - fn joins(sql: &str) -> bool { - joins_tables(&sql_tokens(sql)) - } - - #[test] - fn finds_joins_at_any_depth() { - assert!(joins( - "SELECT a.id, a.x FROM t a JOIN t b ON b.id = a.parent" - )); - assert!(joins("select a.id from t a cross join t b")); - assert!(joins("SELECT a.id FROM t a NATURAL JOIN t b")); - assert!(joins("SELECT a.id, b.x FROM t a, t b WHERE a.id = b.id")); - assert!(joins( - "SELECT * FROM (SELECT a.id, b.x FROM t a, t b) s ORDER BY 1" - )); - assert!(joins( - "SELECT * FROM (SELECT a.id FROM t a JOIN t b USING (id)) s" - )); - assert!(joins("SELECT a.id FROM t a, LATERAL (SELECT 1) l")); - assert!(!joins("select a, b from t")); - assert!(!joins("select f(a, b) from t where x in (1,2)")); - assert!(!joins("select * from t order by a, b")); - assert!(!joins("SELECT a, b FROM t GROUP BY a, b LIMIT 5")); - assert!(!joins("SELECT extract(year FROM d), b FROM t")); - assert!(!joins( - "SELECT a FROM t WHERE b IN (SELECT x FROM u) AND c = 'x, y'" - )); - assert!(!joins("SELECT a FROM t FOR UPDATE OF t, u")); - assert!(!joins( - "SELECT a FROM \"join, x\" -- join - WHERE b = 'join'" - )); - assert!(!joins("WITH c AS (SELECT 1) SELECT a FROM t")); - assert!(!joins( - "SELECT a, (SELECT max(b) FROM u WHERE u.a = t.a) FROM t" - )); - } - - #[test] - fn finds_union_outside_literals() { - assert!(union("SELECT 1 UNION SELECT 2")); - assert!(union("select a from t\nunion all select a from u")); - assert!(!union("SELECT 'union' FROM t")); - assert!(!union("SELECT \"union\" FROM t")); - assert!(!union("SELECT 1 -- union\nFROM t")); - assert!(!union("SELECT 1 /* a /* union */ b */ FROM t")); - assert!(!union("SELECT $$ union $$, $q$ union $q$ FROM t")); - assert!(!union("SELECT E'it\\'s union' FROM t")); - assert!(!union( - "SELECT reunion, union_id, x$union FROM t WHERE a = $1" - )); - assert!(union("SELECT 'a''b' union SELECT 'c'")); - } -} - -/// Need `LQ_PG_HOST` (and optionally `LQ_PG_PORT`, `LQ_PG_USER`, -/// `LQ_PG_PASSWORD`, `LQ_PG_DB`), like `integration_tests`. -#[cfg(test)] -mod edit_integration_tests { - use super::*; - use crate::model::CellValue; - - fn env(name: &str) -> Option { - std::env::var(name).ok().filter(|v| !v.is_empty()) - } - - async fn session() -> Option { - let profile = ConnectionProfile { - name: "test".into(), - host: env("LQ_PG_HOST")?, - port: env("LQ_PG_PORT") - .and_then(|p| p.parse().ok()) - .unwrap_or(5432), - user: env("LQ_PG_USER").unwrap_or_else(|| "postgres".into()), - database: env("LQ_PG_DB").unwrap_or_else(|| "postgres".into()), - ssl_mode: SslMode::Prefer, - ..Default::default() - }; - Some( - connect(&profile, env("LQ_PG_PASSWORD").as_deref()) - .await - .expect("connection"), - ) - } - - async fn exec(s: &PgSession, sql: &str) -> ExecResult { - s.execute(&ExecRequest { - sql: sql.into(), - max_rows: 1000, - }) - .await - .unwrap_or_else(|e| panic!("{sql}: {e}")) - } - - async fn rows(s: &PgSession, sql: &str) -> Vec>> { - exec(s, sql).await.rows - } - - async fn reason(s: &PgSession, sql: &str) -> String { - let r = exec(s, sql).await; - assert!(r.editable.is_none(), "{sql} should be read-only"); - r.read_only_reason - .unwrap_or_else(|| panic!("{sql}: no reason")) - } - - fn cell(column: usize, value: Option<&str>) -> CellValue { - CellValue { - column, - value: value.map(str::to_string), - } - } - - fn update(key: &str, values: Vec) -> RowChange { - RowChange::Update { - key: vec![Some(key.into())], - values, - } - } - - fn insert(key: &str, value: Option<&str>) -> RowChange { - let mut values = vec![cell(0, Some(key))]; - if let Some(v) = value { - values.push(cell(1, Some(v))); - } - RowChange::Insert { values } - } - - async fn apply( - s: &PgSession, - target: &EditTarget, - changes: Vec, - ) -> AppResult { - s.apply_changes(&ApplyRequest { - target: target.clone(), - changes, - }) - .await - } - - #[tokio::test] - #[ignore] - async fn postgres_edit_detection() { - let Some(s) = session().await else { return }; - for sql in [ - "DROP VIEW IF EXISTS lq_edit_view", - "DROP TABLE IF EXISTS lq_edit_det, lq_edit_det2, lq_edit_nokey, lq_edit_uniq", - "CREATE TABLE lq_edit_det (id int PRIMARY KEY, name text, qty numeric(10,2))", - "CREATE TABLE lq_edit_det2 (id int PRIMARY KEY, det_id int)", - "CREATE TABLE lq_edit_nokey (a int, b text)", - "CREATE TABLE lq_edit_uniq (a int NOT NULL, b int NOT NULL, c text, UNIQUE (a, b))", - "CREATE VIEW lq_edit_view AS SELECT * FROM lq_edit_det", - "INSERT INTO lq_edit_det VALUES (1, 'x', 1.5)", - ] { - exec(&s, sql).await; - } - - let r = exec( - &s, - "SELECT name, upper(name) AS u, id, qty FROM lq_edit_det", - ) - .await; - assert!(r.read_only_reason.is_none()); - let t = r.editable.expect("editable"); - assert_eq!(t.table, "lq_edit_det"); - assert_eq!(t.schema, s.current_schema.clone()); - assert_eq!(t.key, vec![2]); - assert!(t.columns[1].is_none()); - assert_eq!(t.columns[0].as_ref().unwrap().name, "name"); - assert_eq!(t.columns[3].as_ref().unwrap().type_name, "numeric(10,2)"); - - let t = exec(&s, "SELECT c, b, a FROM lq_edit_uniq") - .await - .editable - .expect("unique key"); - assert_eq!(t.key, vec![2, 1]); - - assert!(reason( - &s, - "SELECT d.id, d.name, e.id FROM lq_edit_det d JOIN lq_edit_det2 e ON e.det_id = d.id" - ) - .await - .contains("several tables")); - // Self-joins report one table OID for both aliases. - assert_eq!( - reason( - &s, - "SELECT a.id, a.name, b.qty FROM lq_edit_det a JOIN lq_edit_det b ON b.id = a.id" - ) - .await, - JOINS_TABLES - ); - assert_eq!( - reason(&s, "SELECT a.id, b.name FROM lq_edit_det a, lq_edit_det b").await, - JOINS_TABLES - ); - assert_eq!( - reason(&s, "SELECT * FROM lq_edit_nokey").await, - "Read-only: table lq_edit_nokey has no primary key." - ); - assert_eq!( - reason(&s, "SELECT name FROM lq_edit_det").await, - "Read-only: add the primary key columns (id) to the query to edit rows." - ); - assert_eq!(reason(&s, "SELECT * FROM lq_edit_view").await, NOT_A_TABLE); - assert_eq!(reason(&s, "SELECT 1").await, NOT_A_TABLE); - // The server reports no source table for UNION columns; the scan - // covers servers that report the first branch's table. - let union = reason( - &s, - "SELECT id, name FROM lq_edit_det UNION ALL SELECT id, name FROM lq_edit_det", - ) - .await; - assert!( - union == NOT_A_TABLE || union.contains("several queries"), - "{union}" - ); - - // Detection inside a manual transaction (cache miss) keeps it usable. - s.set_autocommit(false).await.unwrap(); - let r = exec(&s, "SELECT id, det_id FROM lq_edit_det2").await; - assert!(r.in_transaction); - assert_eq!(r.editable.expect("editable").key, vec![0]); - assert_eq!(rows(&s, "SELECT 1").await, vec![vec![Some("1".into())]]); - assert!(s.tx_state().in_transaction); - s.end_transaction(false).await.unwrap(); - s.set_autocommit(true).await.unwrap(); - - // DDL clears the cache: a key added later is seen. - exec(&s, "ALTER TABLE lq_edit_nokey ADD PRIMARY KEY (a)").await; - let t = exec(&s, "SELECT b, a FROM lq_edit_nokey") - .await - .editable - .expect("editable"); - assert_eq!(t.key, vec![1]); - - exec(&s, "DROP VIEW lq_edit_view").await; - exec( - &s, - "DROP TABLE lq_edit_det, lq_edit_det2, lq_edit_nokey, lq_edit_uniq", - ) - .await; - } - - #[tokio::test] - #[ignore] - async fn postgres_edit_round_trips_types() { - let Some(s) = session().await else { return }; - exec(&s, "DROP TABLE IF EXISTS lq_edit_types").await; - exec( - &s, - "CREATE TABLE lq_edit_types (id serial PRIMARY KEY, n numeric(12,3), nn numeric, - i2 smallint, i4 integer, i8 bigint, f4 real, f8 double precision, b boolean, - d date, ts timestamp(6), tstz timestamptz, tm time, ttz timetz, iv interval, - t text, vc varchar(20), ch char(5), by bytea, arr int[], tarr text[], j jsonb, - u uuid, m money, ip inet, tsarr timestamptz[])", - ) - .await; - exec( - &s, - r#"INSERT INTO lq_edit_types (n, nn, i2, i4, i8, f4, f8, b, d, ts, tstz, tm, ttz, iv, - t, vc, ch, by, arr, tarr, j, u, m, ip, tsarr) - VALUES (12345.678, 'NaN', -32768, 2147483647, -9223372036854775808, 1.1, 0.1, true, - '2024-02-29', '2024-02-29 13:45:10.123456', '2024-02-29 13:45:10.25+00', - '23:59:59.999999', '13:00:01+05:30', '1 year 2 mons -3 days 04:05:06.5', - E'it''s\n"quoted" \\ end', 'abc', 'ab', '\xdeadbeef00', '{1,NULL,3}', - '{"a b","c,d","","NULL",NULL}', '{"a": [1, 2]}', - 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 12.34::numeric::money, - '192.168.0.1/24', '{"2024-01-01 00:00:00+00","1999-12-31 23:59:59.5-03"}')"#, - ) - .await; - exec(&s, "INSERT INTO lq_edit_types DEFAULT VALUES").await; - - let sql = "SELECT * FROM lq_edit_types ORDER BY id"; - let before = exec(&s, sql).await; - let target = before.editable.clone().expect("editable"); - assert_eq!(target.key, vec![0]); - let changes = before - .rows - .iter() - .map(|row| { - update( - row[0].as_deref().unwrap(), - (1..row.len()).map(|i| cell(i, row[i].as_deref())).collect(), - ) - }) - .collect(); - let r = apply(&s, &target, changes).await.expect("apply"); - assert_eq!(r.updated, 2); - assert!(!r.in_transaction); - assert_eq!(exec(&s, sql).await.rows, before.rows); - - // The stored values themselves did not move. - let check = rows( - &s, - r#"SELECT count(*) FROM lq_edit_types WHERE n = 12345.678 AND nn = 'NaN' - AND f4 = 1.1::real AND f8 = 0.1::float8 - AND tstz = '2024-02-29 13:45:10.25+00' AND ttz = '13:00:01+05:30' - AND iv = '1 year 2 mons -3 days 04:05:06.5'::interval - AND t = E'it''s\n"quoted" \\ end' AND by = '\xdeadbeef00'::bytea - AND m = 12.34::numeric::money AND ch = 'ab' - AND tarr = '{"a b","c,d","","NULL",NULL}'::text[] - AND tsarr[2] = '1999-12-31 23:59:59.5-03'"#, - ) - .await; - assert_eq!(check, vec![vec![Some("1".into())]]); - - // NULL in one row, a value in the row of NULLs. - let id = before.rows[0][0].clone().unwrap(); - apply( - &s, - &target, - vec![update(&id, vec![cell(15, None), cell(8, Some("false"))])], - ) - .await - .expect("apply"); - let row = rows( - &s, - &format!("SELECT t, b FROM lq_edit_types WHERE id = {id}"), - ) - .await; - assert_eq!(row, vec![vec![None, Some("false".into())]]); - let id2 = before.rows[1][0].clone().unwrap(); - apply( - &s, - &target, - vec![update(&id2, vec![cell(18, Some("\\x00ff"))])], - ) - .await - .expect("apply"); - let row = rows( - &s, - &format!("SELECT by FROM lq_edit_types WHERE id = {id2}"), - ) - .await; - assert_eq!(row, vec![vec![Some("\\x00ff".into())]]); - - // Too long for varchar(20) fails instead of being cut. - let long = "x".repeat(21); - let err = apply(&s, &target, vec![update(&id, vec![cell(16, Some(&long))])]) - .await - .unwrap_err(); - assert_eq!(err.code.as_deref(), Some("22001")); - - exec(&s, "DROP TABLE lq_edit_types").await; - } - - #[tokio::test] - #[ignore] - async fn postgres_edit_changes_and_transactions() { - let Some(s) = session().await else { return }; - exec( - &s, - r#"DROP TABLE IF EXISTS "lq_edit_Mixed Case", lq_edit_defaults"#, - ) - .await; - exec( - &s, - r#"CREATE TABLE "lq_edit_Mixed Case" ("Key Col" int PRIMARY KEY, - "Value ""Q""" text, created int DEFAULT 7)"#, - ) - .await; - exec( - &s, - "CREATE TABLE lq_edit_defaults (id serial PRIMARY KEY, v int DEFAULT 5)", - ) - .await; - - let select = r#"SELECT "Key Col", "Value ""Q""" FROM "lq_edit_Mixed Case" ORDER BY 1"#; - let target = exec(&s, select).await.editable.expect("editable"); - assert_eq!(target.table, "lq_edit_Mixed Case"); - assert_eq!(target.columns[1].as_ref().unwrap().name, "Value \"Q\""); - - let r = apply( - &s, - &target, - vec![ - insert("1", Some("one")), - insert("2", Some("two")), - insert("3", None), - ], - ) - .await - .expect("insert"); - assert_eq!(r.inserted, 3); - assert_eq!( - rows( - &s, - r#"SELECT created FROM "lq_edit_Mixed Case" WHERE "Key Col" = 3"# - ) - .await, - vec![vec![Some("7".into())]] - ); - - let r = apply( - &s, - &target, - vec![ - update("1", vec![cell(1, Some("uno"))]), - RowChange::Delete { - key: vec![Some("2".into())], - }, - ], - ) - .await - .expect("update and delete"); - assert_eq!((r.updated, r.deleted), (1, 1)); - let expected = vec![ - vec![Some("1".to_string()), Some("uno".to_string())], - vec![Some("3".to_string()), None], - ]; - assert_eq!(rows(&s, select).await, expected); - - // A key that matches nothing undoes the whole batch. - let err = apply( - &s, - &target, - vec![ - update("1", vec![cell(1, Some("changed"))]), - update("99", vec![cell(1, Some("x"))]), - ], - ) - .await - .unwrap_err(); - assert_eq!(err.kind, ErrorKind::Database); - assert!( - err.message - .starts_with("Row 2 was not saved: 0 rows matched"), - "{err}" - ); - assert_eq!(rows(&s, select).await, expected); - - // Server errors keep their code. - let err = apply(&s, &target, vec![insert("1", Some("dup"))]) - .await - .unwrap_err(); - assert_eq!(err.code.as_deref(), Some("23505")); - assert!(err.message.starts_with("Row 1 was not saved"), "{err}"); - assert_eq!(rows(&s, select).await, expected); - - // Manual commit: the edits open a transaction and stay in it. - s.set_autocommit(false).await.unwrap(); - let r = apply( - &s, - &target, - vec![update("1", vec![cell(1, Some("manual"))])], - ) - .await - .expect("manual"); - assert!(r.in_transaction); - assert!(s.tx_state().in_transaction); - s.end_transaction(false).await.unwrap(); - assert_eq!(rows(&s, select).await, expected); - s.end_transaction(false).await.unwrap(); - - // A failed batch inside an open transaction keeps the transaction - // and its earlier work. - exec( - &s, - r#"UPDATE "lq_edit_Mixed Case" SET created = 8 WHERE "Key Col" = 3"#, - ) - .await; - assert!(s.tx_state().in_transaction); - let err = apply( - &s, - &target, - vec![ - update("3", vec![cell(1, Some("three"))]), - update("99", vec![cell(1, Some("x"))]), - ], - ) - .await - .unwrap_err(); - assert_eq!(err.kind, ErrorKind::Database); - assert!(s.tx_state().in_transaction); - s.end_transaction(true).await.unwrap(); - s.set_autocommit(true).await.unwrap(); - assert_eq!( - rows( - &s, - r#"SELECT created, "Value ""Q""" FROM "lq_edit_Mixed Case" WHERE "Key Col" = 3"# - ) - .await, - vec![vec![Some("8".into()), None]] - ); - - // No values: all defaults. - let target = exec(&s, "SELECT id, v FROM lq_edit_defaults") - .await - .editable - .expect("editable"); - let r = apply(&s, &target, vec![RowChange::Insert { values: vec![] }]) - .await - .expect("defaults"); - assert_eq!(r.inserted, 1); - assert_eq!( - rows(&s, "SELECT v FROM lq_edit_defaults").await, - vec![vec![Some("5".into())]] - ); - - exec(&s, r#"DROP TABLE "lq_edit_Mixed Case", lq_edit_defaults"#).await; - } -} diff --git a/src-tauri/src/drivers/redis_db.rs b/src-tauri/src/drivers/redis_db.rs deleted file mode 100644 index 3c605e8..0000000 --- a/src-tauri/src/drivers/redis_db.rs +++ /dev/null @@ -1,1887 +0,0 @@ -//! Redis (and Valkey) session over the `redis` crate (RESP protocol). -//! -//! - Each `execute` call is one command written like redis-cli input, split -//! with redis-cli's rules (`sdssplitargs`) and sent as raw arguments. -//! - The connection speaks RESP3 so maps, sets, doubles and booleans keep -//! their types; servers without HELLO (Redis < 6) fall back to RESP2. -//! - Replies become a table: scalars one `value` cell, maps `field`/`value`, -//! arrays `#`/`value` (or one column per element of uniform tuples), INFO -//! `section`/`key`/`value`. Nested values are compact JSON-like text and -//! binary strings use redis-cli escapes (`"\xff"`), so nothing is lossy. -//! - Redis has no autocommit mode: the transaction state is MULTI, tracked -//! by command name. -//! - Cancel runs `CLIENT UNBLOCK ERROR` over a short-lived second -//! connection, which only interrupts blocking commands. - -use std::fmt::Write as _; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::{Duration, Instant}; - -use parking_lot::Mutex; -use redis::aio::MultiplexedConnection; -use redis::{ - AsyncConnectionConfig, Client, Cmd, ConnectionAddr, IntoConnectionInfo, ProtocolVersion, - RedisConnectionInfo, RedisError, ServerError, TlsCertificates, Value, -}; - -use super::TxState; -use crate::error::{AppError, AppResult, ErrorKind}; -use crate::model::{ - ColumnInfo, ConnectionProfile, DbColumn, DbObject, ExecRequest, ExecResult, SslMode, ValueKind, -}; - -const DEFAULT_PORT: u16 = 6379; -const CONNECT_TIMEOUT: Duration = Duration::from_secs(15); -/// TLS attempt of `prefer`: a plain server may wait for a line that never -/// comes, so the attempt gives up early and falls back to plain TCP. -const PREFER_TLS_TIMEOUT: Duration = Duration::from_secs(5); -/// Keys listed per database in the tree. -pub const MAX_KEYS: usize = 1000; -const SCAN_COUNT: usize = 500; -const NOT_BLOCKING: &str = "Redis can only interrupt blocking commands such as BLPOP or XREAD."; -/// Commands that would leave the connection in a mode where replies no -/// longer match requests. -const UNSUPPORTED: &[&str] = &[ - "SUBSCRIBE", - "PSUBSCRIBE", - "SSUBSCRIBE", - "MONITOR", - "SYNC", - "PSYNC", -]; - -#[derive(Default)] -struct State { - /// Between MULTI and EXEC/DISCARD. - in_multi: bool, - /// Logical database selected on the connection. - db: i64, - /// SELECT queued inside MULTI, applied when EXEC runs. - queued_select: Option, -} - -pub struct RedisSession { - conn: tokio::sync::Mutex, - /// Client that opened the session, reused by `cancel`. - client: Client, - client_id: Option, - busy: AtomicBool, - state: Mutex, - pub server_version: String, - pub current_user: Option, - pub current_schema: Option, -} - -pub async fn connect( - profile: &ConnectionProfile, - password: Option<&str>, -) -> AppResult { - // rustls has more than one crypto provider compiled in; the redis crate - // builds its TLS config with the process default. - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - - let db = parse_db(&profile.database) - .ok_or_else(|| AppError::invalid("The database must be a number (0, 1, 2...)."))?; - let mut auth = RedisConnectionInfo::default().set_protocol(ProtocolVersion::RESP3); - let user = profile.user.trim(); - if !user.is_empty() { - auth = auth.set_username(user); - } - if let Some(p) = password.filter(|p| !p.is_empty()) { - auth = auth.set_password(p); - } - let target = Target { - host: profile.host.trim().to_string(), - port: if profile.port == 0 { - DEFAULT_PORT - } else { - profile.port - }, - auth, - }; - - let (client, mut conn) = match profile.ssl_mode { - SslMode::Disable => target.open(&Tls::Off, CONNECT_TIMEOUT).await, - SslMode::Prefer => match target.open(&Tls::Lenient, PREFER_TLS_TIMEOUT).await { - Err(e) if !is_server_reply(&e) => target.open(&Tls::Off, CONNECT_TIMEOUT).await, - other => other, - }, - SslMode::Require => target.open(&Tls::Lenient, CONNECT_TIMEOUT).await, - SslMode::VerifyFull => target.open_verified().await, - } - .map_err(connect_error)?; - - let _ = call(&mut conn, &command(&["CLIENT", "SETNAME", "LowQuery"])).await; - if db != 0 { - call(&mut conn, &command(&["SELECT", &db.to_string()])) - .await - .map_err(as_connection)?; - } - let info = match call(&mut conn, &command(&["INFO", "server"])).await { - Ok(v) => text_of(&v), - Err(e) if e.kind == ErrorKind::Connection || is_auth_code(&e) => { - return Err(as_connection(e)) - } - Err(_) => None, - }; - let client_id = match call(&mut conn, &command(&["CLIENT", "ID"])).await { - Ok(Value::Int(id)) => Some(id), - _ => None, - }; - let current_user = call(&mut conn, &command(&["ACL", "WHOAMI"])) - .await - .ok() - .and_then(|v| text_of(&v)); - - Ok(RedisSession { - conn: tokio::sync::Mutex::new(conn), - client, - client_id, - busy: AtomicBool::new(false), - state: Mutex::new(State { - db, - ..State::default() - }), - server_version: product_version(info.as_deref().unwrap_or_default()), - current_user, - current_schema: Some(format!("db{db}")), - }) -} - -enum Tls { - Off, - /// Encrypted without validating the certificate (`prefer`/`require`). - Lenient, - /// Validated against these PEM roots, or the bundled ones when `None`. - Verified(Option>), -} - -struct Target { - host: String, - port: u16, - auth: RedisConnectionInfo, -} - -impl Target { - fn client(&self, tls: &Tls, auth: RedisConnectionInfo) -> Result { - let addr = match tls { - Tls::Off => ConnectionAddr::Tcp(self.host.clone(), self.port), - Tls::Lenient | Tls::Verified(_) => ConnectionAddr::TcpTls { - host: self.host.clone(), - port: self.port, - insecure: matches!(tls, Tls::Lenient), - tls_params: None, - }, - }; - let info = addr.into_connection_info()?.set_redis_settings(auth); - match tls { - Tls::Verified(Some(pem)) => Client::build_with_tls( - info, - TlsCertificates { - client_tls: None, - root_cert: Some(pem.clone()), - }, - ), - _ => Client::open(info), - } - } - - /// Opens with RESP3, or RESP2 when the server has no HELLO. - async fn open( - &self, - tls: &Tls, - timeout: Duration, - ) -> Result<(Client, MultiplexedConnection), RedisError> { - let client = self.client(tls, self.auth.clone())?; - match open_connection(&client, timeout).await { - Ok(conn) => Ok((client, conn)), - Err(e) if resp3_unsupported(&e) => { - let auth = self.auth.clone().set_protocol(ProtocolVersion::RESP2); - let client = self.client(tls, auth)?; - let conn = open_connection(&client, timeout).await?; - Ok((client, conn)) - } - Err(e) => Err(e), - } - } - - /// Validates against the OS store first, then the bundled roots (the - /// OS store may lack a public root it would only fetch on demand). - async fn open_verified(&self) -> Result<(Client, MultiplexedConnection), RedisError> { - if let Some(pem) = native_roots_pem() { - match self.open(&Tls::Verified(Some(pem)), CONNECT_TIMEOUT).await { - Err(e) if describe(&e).to_lowercase().contains("certificate") => {} - other => return other, - } - } - self.open(&Tls::Verified(None), CONNECT_TIMEOUT).await - } -} - -async fn open_connection( - client: &Client, - timeout: Duration, -) -> Result { - // No response timeout: blocking commands may wait as long as they ask. - let config = AsyncConnectionConfig::new() - .set_connection_timeout(Some(timeout)) - .set_response_timeout(None); - client - .get_multiplexed_async_connection_with_config(&config) - .await -} - -fn resp3_unsupported(e: &RedisError) -> bool { - if e.kind() == redis::ErrorKind::RESP3NotSupported { - return true; - } - let detail = e.detail().unwrap_or_default().to_ascii_lowercase(); - e.code() == Some("ERR") && detail.contains("unknown command") && detail.contains("hello") -} - -/// The server answered (an auth failure, for example): TLS itself worked. -fn is_server_reply(e: &RedisError) -> bool { - matches!( - e.kind(), - redis::ErrorKind::Server(_) - | redis::ErrorKind::Extension - | redis::ErrorKind::AuthenticationFailed - ) -} - -/// Certificates of the OS store as PEM, skipping those rustls cannot parse. -fn native_roots_pem() -> Option> { - let mut store = rustls::RootCertStore::empty(); - let mut pem = String::new(); - for cert in rustls_native_certs::load_native_certs().certs { - if store.add(cert.clone()).is_ok() { - pem.push_str(&pem_certificate(&cert)); - } - } - (!pem.is_empty()).then(|| pem.into_bytes()) -} - -fn pem_certificate(der: &[u8]) -> String { - let encoded = base64(der); - let mut out = String::from("-----BEGIN CERTIFICATE-----\n"); - for line in encoded.as_bytes().chunks(64) { - out.push_str(std::str::from_utf8(line).unwrap_or_default()); - out.push('\n'); - } - out.push_str("-----END CERTIFICATE-----\n"); - out -} - -fn base64(bytes: &[u8]) -> String { - const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); - for chunk in bytes.chunks(3) { - let n = (u32::from(chunk[0]) << 16) - | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) - | u32::from(*chunk.get(2).unwrap_or(&0)); - for i in 0..4 { - if i <= chunk.len() { - out.push(TABLE[(n >> (18 - 6 * i) & 63) as usize] as char); - } else { - out.push('='); - } - } - } - out -} - -/// `""` → 0, `"3"` or `"db3"` → 3. -fn parse_db(text: &str) -> Option { - let t = text.trim(); - if t.is_empty() { - return Some(0); - } - let digits = if t.len() > 2 && t[..2].eq_ignore_ascii_case("db") { - &t[2..] - } else { - t - }; - digits.parse().ok().filter(|n| *n >= 0) -} - -/// `Redis 7.4.1`, `Valkey 8.1.0` or `Dragonfly 1.27.1`, from `INFO server`. -pub fn product_version(info: &str) -> String { - let field = |name: &str| { - info.lines() - .filter_map(|l| l.trim().split_once(':')) - .find(|(k, _)| *k == name) - .map(|(_, v)| v.trim().to_string()) - }; - let redis = field("redis_version"); - let valkey = field("valkey_version"); - if valkey.is_some() || field("server_name").as_deref() == Some("valkey") { - return format!("Valkey {}", valkey.or(redis).unwrap_or_default()) - .trim_end() - .to_string(); - } - if let Some(v) = field("dragonfly_version") { - return format!("Dragonfly {}", v.trim_start_matches("df-v")); - } - format!("Redis {}", redis.unwrap_or_default()) - .trim_end() - .to_string() -} - -fn command(parts: &[&str]) -> Cmd { - let mut cmd = Cmd::new(); - for p in parts { - cmd.arg(*p); - } - cmd -} - -/// Sends one command; an error reply becomes an `AppError`. -async fn call(conn: &mut MultiplexedConnection, cmd: &Cmd) -> AppResult { - match conn.send_packed_command(cmd).await.map_err(map_error)? { - Value::ServerError(e) => Err(server_error(&e)), - v => Ok(v), - } -} - -impl RedisSession { - pub fn tx_state(&self) -> TxState { - TxState { - autocommit: true, - in_transaction: self.state.lock().in_multi, - } - } - - pub async fn execute(&self, req: &ExecRequest) -> AppResult { - let text = req.sql.trim(); - let args = if text.starts_with('#') || text.starts_with("//") { - Vec::new() - } else { - split_args(&req.sql)? - }; - if args.is_empty() { - return Ok(ExecResult { - in_transaction: self.tx_state().in_transaction, - ..ExecResult::default() - }); - } - let name = String::from_utf8_lossy(&args[0]).to_ascii_uppercase(); - let reply_off = name == "CLIENT" && arg_is(&args, 1, "REPLY"); - if UNSUPPORTED.contains(&name.as_str()) || reply_off { - return Err(AppError::invalid(format!( - "{} is not supported in the query editor.", - if reply_off { "CLIENT REPLY" } else { &name } - ))); - } - let mut cmd = Cmd::new(); - for a in &args { - cmd.arg(a.as_slice()); - } - - let mut conn = self.conn.lock().await; - self.busy.store(true, Ordering::SeqCst); - let started = Instant::now(); - let reply = conn.send_packed_command(&cmd).await; - let elapsed_ms = started.elapsed().as_millis() as u64; - self.busy.store(false, Ordering::SeqCst); - track(&mut self.state.lock(), &name, &args, &reply); - drop(conn); - - let value = reply.map_err(map_error)?; - if let Value::ServerError(e) = &value { - return Err(server_error(e)); - } - let grid = tabulate(&name, &args, value, req.max_rows); - let (columns, rows) = grid.finish(); - Ok(ExecResult { - columns: Some(columns), - rows, - truncated: grid.truncated, - rows_affected: None, - elapsed_ms, - notices: grid.notices, - in_transaction: self.tx_state().in_transaction, - ..Default::default() - }) - } - - pub async fn cancel(&self) -> AppResult<()> { - if !self.busy.load(Ordering::SeqCst) { - return Ok(()); - } - let Some(id) = self.client_id else { - return Err(AppError::invalid(NOT_BLOCKING)); - }; - let mut conn = open_connection(&self.client, CONNECT_TIMEOUT) - .await - .map_err(connect_error)?; - let reply = call( - &mut conn, - &command(&["CLIENT", "UNBLOCK", &id.to_string(), "ERROR"]), - ) - .await?; - match reply { - Value::Int(0) => Err(AppError::invalid(NOT_BLOCKING)), - _ => Ok(()), - } - } - - pub async fn set_autocommit(&self, on: bool) -> AppResult { - if on { - Ok(self.tx_state()) - } else { - Err(AppError::invalid( - "Redis has no autocommit mode; use MULTI and EXEC.", - )) - } - } - - pub async fn end_transaction(&self, commit: bool) -> AppResult { - if !self.tx_state().in_transaction { - return Ok(self.tx_state()); - } - let name = if commit { "EXEC" } else { "DISCARD" }; - let mut conn = self.conn.lock().await; - let reply = conn.send_packed_command(&command(&[name])).await; - track(&mut self.state.lock(), name, &[], &reply); - drop(conn); - if let Value::ServerError(e) = reply.map_err(map_error)? { - return Err(server_error(&e)); - } - Ok(self.tx_state()) - } - - fn check_not_in_multi(&self) -> AppResult<()> { - if self.tx_state().in_transaction { - return Err(AppError::invalid( - "Finish the transaction with EXEC or DISCARD first.", - )); - } - Ok(()) - } - - /// The current database first, then those with keys, then the empty - /// ones (when CONFIG GET databases is allowed). - pub async fn list_schemas(&self) -> AppResult> { - self.check_not_in_multi()?; - let mut conn = self.conn.lock().await; - // A user without INFO or CONFIG rights still sees its database. - let keyspace = match call(&mut conn, &command(&["INFO", "keyspace"])).await { - Ok(v) => text_of(&v).unwrap_or_default(), - Err(e) if e.kind == ErrorKind::Connection => return Err(e), - Err(_) => String::new(), - }; - let mut used: Vec = info_rows(&keyspace) - .into_iter() - .filter_map(|[_, key, _]| key.strip_prefix("db").and_then(|n| n.parse().ok())) - .collect(); - let count = match call(&mut conn, &command(&["CONFIG", "GET", "databases"])).await { - Ok(v) => config_value(v).and_then(|n| n.parse::().ok()), - Err(_) => None, - }; - drop(conn); - - let current = self.state.lock().db; - used.sort_unstable(); - let mut dbs = vec![current]; - dbs.extend(used.iter().filter(|n| **n != current)); - dbs.extend((0..count.unwrap_or(0)).filter(|n| *n != current && !used.contains(n))); - Ok(dbs.into_iter().map(|n| format!("db{n}")).collect()) - } - - /// Up to [`MAX_KEYS`] keys of the database with their types, sorted by - /// type then name. - pub async fn list_objects(&self, schema: &str) -> AppResult> { - let db = parse_db(schema) - .ok_or_else(|| AppError::invalid(format!("Unknown database: {schema}")))?; - self.check_not_in_multi()?; - let mut conn = self.conn.lock().await; - let current = self.state.lock().db; - if db != current { - call(&mut conn, &command(&["SELECT", &db.to_string()])).await?; - } - let outcome = key_types(&mut conn).await; - if db != current { - let back = call(&mut conn, &command(&["SELECT", ¤t.to_string()])).await; - if back.is_err() { - self.state.lock().db = db; - } - } - let mut objects: Vec = outcome? - .into_iter() - .filter_map(|(key, kind)| { - kind.map(|kind| DbObject { - name: text(&key), - kind, - }) - }) - .collect(); - objects.sort_by(|a, b| (&a.kind, &a.name).cmp(&(&b.kind, &b.name))); - Ok(objects) - } - - pub async fn list_columns(&self, _schema: &str, _table: &str) -> AppResult> { - Ok(Vec::new()) - } -} - -/// SCAN until [`MAX_KEYS`] keys or the end, then TYPE for each key in one -/// pipeline. Keys removed meanwhile have no type. -async fn key_types(conn: &mut MultiplexedConnection) -> AppResult, Option)>> { - let mut cursor = b"0".to_vec(); - let mut keys: Vec> = Vec::new(); - loop { - let mut cmd = Cmd::new(); - cmd.arg("SCAN") - .arg(cursor.as_slice()) - .arg("COUNT") - .arg(SCAN_COUNT); - let reply = call(conn, &cmd).await?; - let Value::Array(mut parts) = reply else { - return Err(AppError::internal("Unexpected SCAN reply.")); - }; - if parts.len() != 2 { - return Err(AppError::internal("Unexpected SCAN reply.")); - } - if let Value::Array(found) = parts.pop().unwrap_or_default() { - keys.extend(found.into_iter().filter_map(|k| bytes_of(&k))); - } - cursor = bytes_of(&parts[0]).unwrap_or_default(); - if cursor == b"0" || keys.len() >= MAX_KEYS { - break; - } - } - keys.sort_unstable(); - keys.dedup(); - keys.truncate(MAX_KEYS); - if keys.is_empty() { - return Ok(Vec::new()); - } - - let mut pipe = redis::pipe(); - for k in &keys { - pipe.cmd("TYPE").arg(k.as_slice()); - } - let types = conn - .send_packed_commands(&pipe, 0, keys.len()) - .await - .map_err(map_error)?; - Ok(keys - .into_iter() - .zip(types.iter().map(|t| text_of(t).and_then(|t| key_kind(&t)))) - .collect()) -} - -/// Tree kind of a TYPE reply: core types as they are, module types -/// lowercased (`ReJSON-RL` → `json`). -fn key_kind(type_name: &str) -> Option { - let lower = type_name.trim().to_ascii_lowercase(); - match lower.as_str() { - "" | "none" => None, - "rejson-rl" => Some("json".into()), - _ => Some(lower), - } -} - -/// Updates the MULTI state and the selected database after a command. -fn track(state: &mut State, name: &str, args: &[Vec], reply: &Result) { - let value = match reply { - Ok(v) => v, - // The connection is gone, and the transaction with it. - Err(_) => { - state.in_multi = false; - state.queued_select = None; - return; - } - }; - let failed = matches!(value, Value::ServerError(_)); - match name { - // EXEC and DISCARD end the transaction even when they fail - // (EXECABORT, or no MULTI at all). - "EXEC" => { - let select = state.queued_select.take(); - if let (Some(db), Value::Array(_)) = (select, value) { - state.db = db; - } - state.in_multi = false; - } - "DISCARD" => { - state.in_multi = false; - state.queued_select = None; - } - "MULTI" if !failed => state.in_multi = true, - "RESET" if !failed => *state = State::default(), - "SELECT" if !failed => { - if let Some(db) = args - .get(1) - .and_then(|a| std::str::from_utf8(a).ok()?.parse().ok()) - { - if state.in_multi { - state.queued_select = Some(db); - } else { - state.db = db; - } - } - } - _ => {} - } -} - -fn arg_is(args: &[Vec], i: usize, word: &str) -> bool { - args.get(i) - .is_some_and(|a| a.eq_ignore_ascii_case(word.as_bytes())) -} - -fn has_arg(args: &[Vec], word: &str) -> bool { - args.iter() - .skip(1) - .any(|a| a.eq_ignore_ascii_case(word.as_bytes())) -} - -// --------------------------------------------------------------------------- -// Argument parsing (redis-cli's sdssplitargs) - -fn is_space(c: u8) -> bool { - matches!(c, b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c) -} - -fn hex_value(c: u8) -> Option { - (c as char).to_digit(16).map(|d| d as u8) -} - -/// Splits a command line into arguments the way redis-cli does: double -/// quotes take `\n \r \t \b \a \\ \"` and `\xHH`, single quotes only `\'`, -/// and a closing quote must be followed by a space or the end. -pub fn split_args(line: &str) -> AppResult>> { - let b = line.as_bytes(); - let invalid_at = |message: &str, byte: usize| { - let mut err = AppError::invalid(message); - err.position = Some(line[..byte].chars().count()); - err - }; - let mut args = Vec::new(); - let mut p = 0; - loop { - while p < b.len() && is_space(b[p]) { - p += 1; - } - if p >= b.len() { - return Ok(args); - } - let mut current = Vec::new(); - let mut in_double = false; - let mut in_single = false; - let mut quote_start = 0; - loop { - if in_double { - if p >= b.len() { - return Err(invalid_at("Unbalanced quotes in the command.", quote_start)); - } - let next = b.get(p + 1).copied(); - if b[p] == b'\\' && next == Some(b'x') { - let hi = b.get(p + 2).copied().and_then(hex_value); - let lo = b.get(p + 3).copied().and_then(hex_value); - if let (Some(hi), Some(lo)) = (hi, lo) { - current.push(hi * 16 + lo); - p += 3; - } else { - p += 1; - current.push(b'x'); - } - } else if b[p] == b'\\' && next.is_some() { - p += 1; - current.push(match b[p] { - b'n' => b'\n', - b'r' => b'\r', - b't' => b'\t', - b'b' => 0x08, - b'a' => 0x07, - c => c, - }); - } else if b[p] == b'"' { - if b.get(p + 1).is_some_and(|c| !is_space(*c)) { - return Err(invalid_at( - "A closing quote must be followed by a space.", - p, - )); - } - p += 1; - break; - } else { - current.push(b[p]); - } - } else if in_single { - if p >= b.len() { - return Err(invalid_at("Unbalanced quotes in the command.", quote_start)); - } - if b[p] == b'\\' && b.get(p + 1) == Some(&b'\'') { - p += 1; - current.push(b'\''); - } else if b[p] == b'\'' { - if b.get(p + 1).is_some_and(|c| !is_space(*c)) { - return Err(invalid_at( - "A closing quote must be followed by a space.", - p, - )); - } - p += 1; - break; - } else { - current.push(b[p]); - } - } else if p >= b.len() || is_space(b[p]) { - break; - } else if b[p] == b'"' { - in_double = true; - quote_start = p; - } else if b[p] == b'\'' { - in_single = true; - quote_start = p; - } else { - current.push(b[p]); - } - p += 1; - } - args.push(current); - } -} - -// --------------------------------------------------------------------------- -// Replies as tables - -/// Rows of reply values before formatting. -#[derive(Default)] -struct Grid { - names: Vec, - rows: Vec>, - truncated: bool, - notices: Vec, -} - -impl Grid { - fn new(names: &[&str]) -> Self { - Grid { - names: names.iter().map(|n| n.to_string()).collect(), - ..Grid::default() - } - } - - fn finish(&self) -> (Vec, Vec>>) { - let columns = self - .names - .iter() - .enumerate() - .map(|(i, name)| { - let values: Vec<&Value> = self - .rows - .iter() - .filter_map(|r| r.get(i)) - .filter(|v| !matches!(v, Value::Nil)) - .collect(); - ColumnInfo { - name: name.clone(), - type_name: column_type(&values), - kind: if name == "#" || name == "score" { - ValueKind::Number - } else { - column_kind(&values) - }, - } - }) - .collect(); - let rows = self - .rows - .iter() - .map(|r| r.iter().map(cell).collect()) - .collect(); - (columns, rows) - } -} - -/// Keeps at most `max_rows` items (0 = all); true when some were dropped. -fn limit(items: &mut Vec, max_rows: usize) -> bool { - if max_rows > 0 && items.len() > max_rows { - items.truncate(max_rows); - true - } else { - false - } -} - -fn is_aggregate(v: &Value) -> bool { - matches!( - v, - Value::Array(_) - | Value::Set(_) - | Value::Map(_) - | Value::Push { .. } - | Value::Attribute { .. } - ) -} - -fn unwrap_attribute(v: Value) -> Value { - match v { - Value::Attribute { data, .. } => unwrap_attribute(*data), - other => other, - } -} - -/// Sorted-set replies whose pairs are member and score. -fn has_scores(name: &str, args: &[Vec]) -> bool { - name.starts_with('Z') && (has_arg(args, "WITHSCORES") || matches!(name, "ZPOPMIN" | "ZPOPMAX")) -} - -/// Commands whose RESP2 reply is a flat field/value list. -fn has_field_pairs(name: &str, args: &[Vec]) -> bool { - match name { - "HGETALL" => true, - "CONFIG" => arg_is(args, 1, "GET"), - "HRANDFIELD" => has_arg(args, "WITHVALUES"), - _ => false, - } -} - -fn tabulate(name: &str, args: &[Vec], value: Value, max_rows: usize) -> Grid { - let value = unwrap_attribute(value); - if name == "INFO" { - if let Some(text) = text_of(&value) { - let mut rows = info_rows(&text); - let mut grid = Grid::new(&["section", "key", "value"]); - grid.truncated = limit(&mut rows, max_rows); - grid.rows = rows - .into_iter() - .map(|r| r.into_iter().map(Value::SimpleString).collect()) - .collect(); - return grid; - } - } - match value { - Value::Array(mut parts) - if matches!(name, "SCAN" | "SSCAN" | "HSCAN" | "ZSCAN") - && parts.len() == 2 - && matches!(parts[1], Value::Array(_)) => - { - let Value::Array(items) = parts.pop().unwrap_or_default() else { - unreachable!() - }; - let cursor = cell(&parts[0]).unwrap_or_default(); - let mut grid = match name { - "HSCAN" if !has_arg(args, "NOVALUES") => pairs(items, "field", "value", max_rows), - "ZSCAN" => pairs(items, "member", "score", max_rows), - _ => list(items, max_rows), - }; - grid.notices.push(if cursor == "0" { - "Next cursor: 0 (the scan is complete).".into() - } else { - format!("Next cursor: {cursor}") - }); - grid - } - Value::Map(mut entries) => { - let mut grid = Grid::new(&["field", "value"]); - grid.truncated = limit(&mut entries, max_rows); - grid.rows = entries.into_iter().map(|(k, v)| vec![k, v]).collect(); - grid - } - Value::Array(items) | Value::Set(items) | Value::Push { data: items, .. } => { - if let Some(width) = tuple_width(&items) { - let names: Vec = if width == 2 && has_scores(name, args) { - vec!["member".into(), "score".into()] - } else if width == 2 && matches!(name, "XRANGE" | "XREVRANGE") { - vec!["id".into(), "fields".into()] - } else { - (1..=width).map(|i| i.to_string()).collect() - }; - let mut items = items; - let mut grid = Grid { - names, - ..Grid::default() - }; - grid.truncated = limit(&mut items, max_rows); - grid.rows = items - .into_iter() - .map(|t| match t { - Value::Array(cells) => cells, - other => vec![other], - }) - .collect(); - return grid; - } - let flat = items.len().is_multiple_of(2) && !items.iter().any(is_aggregate); - if flat && has_scores(name, args) { - pairs(items, "member", "score", max_rows) - } else if flat && has_field_pairs(name, args) { - pairs(items, "field", "value", max_rows) - } else { - list(items, max_rows) - } - } - scalar => { - let mut grid = Grid::new(&["value"]); - grid.rows = vec![vec![scalar]]; - grid - } - } -} - -/// Width of a non-empty list whose items are all arrays of the same length -/// (at least 2). -fn tuple_width(items: &[Value]) -> Option { - let mut width = None; - for item in items { - let Value::Array(cells) = item else { - return None; - }; - if cells.len() < 2 || width.is_some_and(|w| w != cells.len()) { - return None; - } - width = Some(cells.len()); - } - width -} - -fn list(mut items: Vec, max_rows: usize) -> Grid { - let mut grid = Grid::new(&["#", "value"]); - grid.truncated = limit(&mut items, max_rows); - grid.rows = items - .into_iter() - .enumerate() - .map(|(i, v)| vec![Value::Int(i as i64 + 1), v]) - .collect(); - grid -} - -/// A flat `[a1, b1, a2, b2...]` list as two columns. -fn pairs(items: Vec, a: &str, b: &str, max_rows: usize) -> Grid { - if !items.len().is_multiple_of(2) { - return list(items, max_rows); - } - let mut grid = Grid::new(&[a, b]); - let mut it = items.into_iter(); - let mut rows = Vec::new(); - while let (Some(x), Some(y)) = (it.next(), it.next()) { - rows.push(vec![x, y]); - } - grid.truncated = limit(&mut rows, max_rows); - grid.rows = rows; - grid -} - -/// `[section, key, value]` rows from INFO text (`# Section` and -/// `key:value` lines). -fn info_rows(text: &str) -> Vec<[String; 3]> { - let mut section = String::new(); - let mut rows = Vec::new(); - for line in text.lines() { - let line = line.trim(); - if line.is_empty() { - continue; - } - if let Some(name) = line.strip_prefix('#') { - section = name.trim().to_string(); - continue; - } - let (key, value) = line.split_once(':').unwrap_or((line, "")); - rows.push([section.clone(), key.to_string(), value.to_string()]); - } - rows -} - -/// Value of `CONFIG GET ` (a map in RESP3, a pair in RESP2). -fn config_value(v: Value) -> Option { - match v { - Value::Map(mut entries) => entries.pop().and_then(|(_, v)| text_of(&v)), - Value::Array(items) if items.len() == 2 => text_of(&items[1]), - _ => None, - } -} - -fn type_name(v: &Value) -> &'static str { - match v { - Value::Nil => "nil", - Value::Int(_) => "integer", - Value::Double(_) => "double", - Value::Boolean(_) => "boolean", - Value::BigNumber(_) => "big number", - Value::BulkString(_) | Value::SimpleString(_) | Value::Okay => "string", - Value::VerbatimString { .. } => "verbatim string", - Value::Array(_) | Value::Push { .. } => "array", - Value::Set(_) => "set", - Value::Map(_) | Value::Attribute { .. } => "map", - Value::ServerError(_) => "error", - _ => "other", - } -} - -fn column_type(values: &[&Value]) -> String { - let mut names = values.iter().map(|v| type_name(v)); - match names.next() { - None => "nil".into(), - Some(first) if names.all(|n| n == first) => first.into(), - Some(_) => "mixed".into(), - } -} - -fn column_kind(values: &[&Value]) -> ValueKind { - if values.is_empty() { - ValueKind::Text - } else if values - .iter() - .all(|v| matches!(v, Value::Int(_) | Value::Double(_) | Value::BigNumber(_))) - { - ValueKind::Number - } else if values.iter().all(|v| matches!(v, Value::Boolean(_))) { - ValueKind::Bool - } else if values.iter().all(|v| is_aggregate(v)) { - ValueKind::Json - } else { - ValueKind::Text - } -} - -/// Text of a cell: scalars as they are, nested values as compact JSON-like -/// text, errors inside a reply (EXEC) as `(error) CODE message`. -fn cell(v: &Value) -> Option { - match v { - Value::Nil => None, - Value::ServerError(e) => Some(error_text(e)), - v if is_aggregate(v) => { - let mut out = String::new(); - write_nested(&mut out, v); - Some(out) - } - v => Some(scalar_text(v)), - } -} - -fn scalar_text(v: &Value) -> String { - match v { - Value::Int(i) => i.to_string(), - Value::Double(d) => double_text(*d), - Value::Boolean(b) => b.to_string(), - Value::BigNumber(n) => String::from_utf8_lossy(n).into_owned(), - Value::BulkString(b) => text(b), - Value::SimpleString(s) => s.clone(), - Value::Okay => "OK".into(), - Value::VerbatimString { text, .. } => text.clone(), - Value::Nil => String::new(), - other => cell(other).unwrap_or_default(), - } -} - -fn double_text(d: f64) -> String { - if d.is_nan() { - "nan".into() - } else if d.is_infinite() { - if d > 0.0 { "inf" } else { "-inf" }.into() - } else { - let plain = d.to_string(); - if plain.len() > 24 { - format!("{d:e}") - } else { - plain - } - } -} - -fn error_text(e: &ServerError) -> String { - match e.details() { - Some(d) => format!("(error) {} {d}", e.code()), - None => format!("(error) {}", e.code()), - } -} - -/// Bytes as text when they are readable UTF-8, otherwise redis-cli's -/// quoted form with escapes (`"\xff"`), which never loses data. -fn text(bytes: &[u8]) -> String { - match std::str::from_utf8(bytes) { - Ok(s) - if !s - .chars() - .any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t')) => - { - s.to_string() - } - _ => repr(bytes), - } -} - -/// redis-cli's `sdscatrepr`. -pub fn repr(bytes: &[u8]) -> String { - let mut out = String::with_capacity(bytes.len() + 2); - out.push('"'); - for &b in bytes { - match b { - b'\\' => out.push_str("\\\\"), - b'"' => out.push_str("\\\""), - b'\n' => out.push_str("\\n"), - b'\r' => out.push_str("\\r"), - b'\t' => out.push_str("\\t"), - 0x07 => out.push_str("\\a"), - 0x08 => out.push_str("\\b"), - 0x20..=0x7e => out.push(b as char), - _ => { - let _ = write!(out, "\\x{b:02x}"); - } - } - } - out.push('"'); - out -} - -fn json_string(out: &mut String, s: &str) { - out.push_str(&serde_json::to_string(s).unwrap_or_default()); -} - -/// Compact JSON-like text. Binary strings keep redis-cli escapes. -fn write_nested(out: &mut String, v: &Value) { - match v { - Value::Nil => out.push_str("null"), - Value::Int(i) => { - let _ = write!(out, "{i}"); - } - Value::Double(d) if d.is_finite() => out.push_str(&double_text(*d)), - Value::Double(d) => json_string(out, &double_text(*d)), - Value::Boolean(b) => { - let _ = write!(out, "{b}"); - } - Value::BigNumber(n) => out.push_str(&String::from_utf8_lossy(n)), - Value::BulkString(b) => match std::str::from_utf8(b) { - Ok(s) => json_string(out, s), - Err(_) => out.push_str(&repr(b)), - }, - Value::SimpleString(s) => json_string(out, s), - Value::Okay => json_string(out, "OK"), - Value::VerbatimString { text, .. } => json_string(out, text), - Value::Array(items) | Value::Set(items) | Value::Push { data: items, .. } => { - out.push('['); - for (i, item) in items.iter().enumerate() { - if i > 0 { - out.push(','); - } - write_nested(out, item); - } - out.push(']'); - } - Value::Map(entries) => { - out.push('{'); - for (i, (k, v)) in entries.iter().enumerate() { - if i > 0 { - out.push(','); - } - match k { - Value::BulkString(_) - | Value::SimpleString(_) - | Value::VerbatimString { .. } => write_nested(out, k), - other => { - let mut key = String::new(); - write_nested(&mut key, other); - json_string(out, &key); - } - } - out.push(':'); - write_nested(out, v); - } - out.push('}'); - } - Value::Attribute { data, .. } => write_nested(out, data), - Value::ServerError(e) => json_string(out, &error_text(e)), - _ => out.push_str("null"), - } -} - -/// Text of a string-like reply. -fn text_of(v: &Value) -> Option { - match v { - Value::BulkString(b) => Some(String::from_utf8_lossy(b).into_owned()), - Value::SimpleString(s) => Some(s.clone()), - Value::VerbatimString { text, .. } => Some(text.clone()), - Value::Okay => Some("OK".into()), - _ => None, - } -} - -fn bytes_of(v: &Value) -> Option> { - match v { - Value::BulkString(b) => Some(b.clone()), - Value::SimpleString(s) => Some(s.as_bytes().to_vec()), - _ => None, - } -} - -// --------------------------------------------------------------------------- -// Errors - -/// Error reply: `code` is its first word (ERR, WRONGTYPE, NOAUTH...), -/// `message` the rest. -fn reply_error(code: &str, detail: &str) -> AppError { - let detail = detail.trim(); - let (kind, message) = match code { - "MOVED" | "ASK" => ( - ErrorKind::Database, - format!( - "The key is served by another node ({detail}). Redis Cluster is not supported yet." - ), - ), - // A blocking command interrupted by `cancel`. - "UNBLOCKED" => (ErrorKind::Cancelled, "The command was interrupted.".into()), - _ if detail.is_empty() => (ErrorKind::Database, code.to_string()), - _ => (ErrorKind::Database, detail.to_string()), - }; - let mut err = AppError::new(kind, message); - err.code = Some(code.to_string()); - err -} - -fn server_error(e: &ServerError) -> AppError { - reply_error(e.code(), e.details().unwrap_or_default()) -} - -fn describe(e: &RedisError) -> String { - let mut message = e.to_string(); - let mut source = std::error::Error::source(e); - while let Some(s) = source { - let text = s.to_string(); - if !message.contains(&text) { - message.push_str(": "); - message.push_str(&text); - } - source = s.source(); - } - message -} - -pub fn map_error(e: RedisError) -> AppError { - use redis::ErrorKind as K; - match e.kind() { - // RESP2 AUTH failure; the library drops the server's code. - K::AuthenticationFailed => { - let mut err = AppError::connection("Invalid username or password."); - err.code = Some("WRONGPASS".into()); - err - } - K::Server(_) | K::Extension => { - reply_error(e.code().unwrap_or("ERR"), e.detail().unwrap_or_default()) - } - K::Io | K::Parse => AppError::connection(describe(&e)), - K::InvalidClientConfig => AppError::invalid(describe(&e)), - _ => AppError::new(ErrorKind::Database, describe(&e)), - } -} - -fn is_auth_code(e: &AppError) -> bool { - matches!(e.code.as_deref(), Some("NOAUTH" | "WRONGPASS")) -} - -/// Errors while opening a session are connection errors; NOAUTH and -/// WRONGPASS keep their code. -fn as_connection(mut e: AppError) -> AppError { - e.kind = ErrorKind::Connection; - e -} - -fn connect_error(e: RedisError) -> AppError { - if e.is_timeout() { - return AppError::connection("Timed out connecting to the server."); - } - as_connection(map_error(e)) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Arc; - - fn args(line: &str) -> Vec { - split_args(line) - .unwrap() - .into_iter() - .map(|a| String::from_utf8(a).unwrap()) - .collect() - } - - #[test] - fn splits_like_redis_cli() { - assert_eq!(args(" HGETALL user:1 "), ["HGETALL", "user:1"]); - assert_eq!(args(r#"SET k "a b\n""#), ["SET", "k", "a b\n"]); - assert_eq!( - args(r#"SET "q\"x\\" 'it\'s' "\t\r\a\b""#), - ["SET", "q\"x\\", "it's", "\t\r\x07\x08"] - ); - // Single quotes keep backslashes except before a quote. - assert_eq!(args(r"ECHO 'a\nb'"), ["ECHO", r"a\nb"]); - // Quotes inside a bare word join it. - assert_eq!(args(r#"ECHO ab"c d""#), ["ECHO", "abc d"]); - assert_eq!(args(r#"ECHO """#), ["ECHO", ""]); - assert_eq!(args("ECHO ação"), ["ECHO", "ação"]); - assert!(split_args(" \n ").unwrap().is_empty()); - - let raw = split_args(r#"SET k "\xff\x41\xZZ""#).unwrap(); - assert_eq!(raw[2], b"\xffAxZZ"); - - let e = split_args(r#"GET "abc"#).unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - assert_eq!(e.position, Some(4)); - assert_eq!(split_args("GET 'abc").unwrap_err().kind, ErrorKind::Invalid); - assert_eq!( - split_args(r#"GET "a\"#).unwrap_err().kind, - ErrorKind::Invalid - ); - let e = split_args(r#"GET "a"b"#).unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - assert_eq!(e.position, Some(6)); - } - - #[test] - fn sends_raw_bytes() { - let mut cmd = Cmd::new(); - for a in split_args(r#"SET k "\xff""#).unwrap() { - cmd.arg(a.as_slice()); - } - assert_eq!( - cmd.get_packed_command(), - b"*3\r\n$3\r\nSET\r\n$1\r\nk\r\n$1\r\n\xff\r\n" - ); - } - - fn resp(bytes: &[u8]) -> Value { - redis::parse_redis_value(bytes).unwrap() - } - - fn table( - name: &str, - line: &str, - value: Value, - max_rows: usize, - ) -> (Vec, Vec>>, Grid) { - let a = split_args(line).unwrap(); - let grid = tabulate(name, &a, value, max_rows); - let (c, r) = grid.finish(); - (c, r, grid) - } - - fn names(cols: &[ColumnInfo]) -> Vec<&str> { - cols.iter().map(|c| c.name.as_str()).collect() - } - - fn row(r: &[Option]) -> Vec> { - r.iter().map(|c| c.as_deref()).collect() - } - - #[test] - fn formats_scalars() { - let (c, r, _) = table("GET", "GET k", Value::BulkString(b"a b\n".to_vec()), 0); - assert_eq!(names(&c), ["value"]); - assert_eq!(c[0].kind, ValueKind::Text); - assert_eq!(row(&r[0]), [Some("a b\n")]); - - let (c, r, _) = table("INCR", "INCR k", Value::Int(42), 0); - assert_eq!( - (c[0].kind, c[0].type_name.as_str()), - (ValueKind::Number, "integer") - ); - assert_eq!(row(&r[0]), [Some("42")]); - - let (c, r, _) = table("ZSCORE", "ZSCORE z m", resp(b",1.5\r\n"), 0); - assert_eq!(c[0].kind, ValueKind::Number); - assert_eq!(row(&r[0]), [Some("1.5")]); - assert_eq!(double_text(3.0), "3"); - assert_eq!(double_text(f64::INFINITY), "inf"); - assert_eq!(double_text(1e300), "1e300"); - - let (c, r, _) = table("X", "X", resp(b"#t\r\n"), 0); - assert_eq!(c[0].kind, ValueKind::Bool); - assert_eq!(row(&r[0]), [Some("true")]); - - let (_, r, _) = table("GET", "GET k", Value::Nil, 0); - assert_eq!(row(&r[0]), [None]); - let (_, r, _) = table("SET", "SET k v", Value::Okay, 0); - assert_eq!(row(&r[0]), [Some("OK")]); - let (_, r, _) = table( - "X", - "X", - resp(b"(3492890328409238509324850943850943825024385\r\n"), - 0, - ); - assert_eq!( - row(&r[0]), - [Some("3492890328409238509324850943850943825024385")] - ); - let (_, r, _) = table("X", "X", resp(b"=15\r\ntxt:Some string\r\n"), 0); - assert_eq!(row(&r[0]), [Some("Some string")]); - } - - #[test] - fn escapes_binary_strings() { - assert_eq!(text(b"\xff\x00a\"\\"), r#""\xff\x00a\"\\""#); - assert_eq!(text("ação\n".as_bytes()), "ação\n"); - assert_eq!(text(b"a\x00b"), r#""a\x00b""#); - assert_eq!(repr(b"\x07\x08\t\r\n "), r#""\a\b\t\r\n ""#); - let (_, r, _) = table("GET", "GET k", Value::BulkString(vec![0xff, b'a']), 0); - assert_eq!(row(&r[0]), [Some(r#""\xffa""#)]); - } - - #[test] - fn formats_maps_and_arrays() { - // RESP3 HGETALL. - let map = resp(b"%2\r\n$2\r\nf1\r\n$2\r\nv1\r\n$2\r\nf2\r\n:7\r\n"); - let (c, r, _) = table("HGETALL", "HGETALL h", map.clone(), 0); - assert_eq!(names(&c), ["field", "value"]); - assert_eq!(c[1].type_name, "mixed"); - assert_eq!(row(&r[1]), [Some("f2"), Some("7")]); - let (_, r, g) = table("HGETALL", "HGETALL h", map, 1); - assert_eq!((r.len(), g.truncated), (1, true)); - - // RESP2 HGETALL: a flat list. - let flat = resp(b"*4\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n"); - let (c, r, _) = table("HGETALL", "HGETALL h", flat.clone(), 0); - assert_eq!(names(&c), ["field", "value"]); - assert_eq!(row(&r[0]), [Some("a"), Some("1")]); - // Other commands: index and value. - let (c, r, g) = table("LRANGE", "LRANGE l 0 -1", flat, 3); - assert_eq!(names(&c), ["#", "value"]); - assert_eq!(c[0].kind, ValueKind::Number); - assert_eq!(row(&r[2]), [Some("3"), Some("b")]); - assert!(g.truncated); - - // RESP3 ZRANGE WITHSCORES: [member, score] pairs. - let z = resp(b"*2\r\n*2\r\n$1\r\na\r\n,1\r\n*2\r\n$1\r\nb\r\n,2.5\r\n"); - let (c, r, _) = table("ZRANGE", "ZRANGE z 0 -1 WITHSCORES", z.clone(), 0); - assert_eq!(names(&c), ["member", "score"]); - assert_eq!(c[1].kind, ValueKind::Number); - assert_eq!(row(&r[1]), [Some("b"), Some("2.5")]); - let (c, _, _) = table("LMPOP", "X", z, 0); - assert_eq!(names(&c), ["1", "2"]); - // RESP2 ZRANGE WITHSCORES: flat, scores as strings. - let flat = resp(b"*2\r\n$1\r\na\r\n$1\r\n1\r\n"); - let (c, r, _) = table("ZRANGE", "ZRANGE z 0 -1 withscores", flat, 0); - assert_eq!(names(&c), ["member", "score"]); - assert_eq!(c[1].kind, ValueKind::Number); - assert_eq!(row(&r[0]), [Some("a"), Some("1")]); - - // Nested values: compact JSON-like text. - let nested = resp(b"*2\r\n*2\r\n$3\r\n1-0\r\n*2\r\n$1\r\nf\r\n$3\r\na\"b\r\n$1\r\nx\r\n"); - let (c, r, _) = table("XRANGE", "XRANGE s - +", nested, 0); - assert_eq!(names(&c), ["#", "value"]); - assert_eq!(c[1].kind, ValueKind::Text); - assert_eq!(row(&r[0]), [Some("1"), Some(r#"["1-0",["f","a\"b"]]"#)]); - let deep = resp(b"*1\r\n%1\r\n$1\r\nk\r\n~2\r\n_\r\n$1\r\n\xff\r\n"); - let (c, r, _) = table("X", "X", deep, 0); - assert_eq!(c[1].kind, ValueKind::Json); - assert_eq!(row(&r[0])[1], Some(r#"{"k":[null,"\xff"]}"#)); - - // EXEC with an error inside. - let exec = resp(b"*2\r\n+OK\r\n-WRONGTYPE Operation against a key\r\n"); - let (_, r, _) = table("EXEC", "EXEC", exec, 0); - assert_eq!( - row(&r[1]), - [Some("2"), Some("(error) WRONGTYPE Operation against a key")] - ); - - // Empty list. - let (c, r, _) = table("KEYS", "KEYS x*", Value::Array(vec![]), 0); - assert_eq!(names(&c), ["#", "value"]); - assert!(r.is_empty()); - } - - #[test] - fn scan_replies_show_the_cursor() { - let v = resp(b"*2\r\n$2\r\n17\r\n*4\r\n$1\r\nf\r\n$1\r\nv\r\n$1\r\ng\r\n$1\r\nw\r\n"); - let (c, r, g) = table("HSCAN", "HSCAN h 0", v.clone(), 0); - assert_eq!(names(&c), ["field", "value"]); - assert_eq!(r.len(), 2); - assert_eq!(g.notices, ["Next cursor: 17"]); - let (c, r, _) = table("SSCAN", "SSCAN s 0", v, 0); - assert_eq!(names(&c), ["#", "value"]); - assert_eq!(r.len(), 4); - } - - #[test] - fn parses_info() { - let info = "# Server\r\nredis_version:7.4.1\r\nredis_mode:standalone\r\n\r\n# Keyspace\r\ndb0:keys=3,expires=0,avg_ttl=0\r\n"; - let (c, r, _) = table( - "INFO", - "INFO", - Value::BulkString(info.as_bytes().to_vec()), - 0, - ); - assert_eq!(names(&c), ["section", "key", "value"]); - assert_eq!(r.len(), 3); - assert_eq!( - row(&r[0]), - [Some("Server"), Some("redis_version"), Some("7.4.1")] - ); - assert_eq!( - row(&r[2]), - [ - Some("Keyspace"), - Some("db0"), - Some("keys=3,expires=0,avg_ttl=0") - ] - ); - let (_, r, g) = table( - "INFO", - "INFO", - Value::BulkString(info.as_bytes().to_vec()), - 2, - ); - assert_eq!((r.len(), g.truncated), (2, true)); - - assert_eq!(product_version(info), "Redis 7.4.1"); - assert_eq!( - product_version( - "redis_version:7.2.4\r\nserver_name:valkey\r\nvalkey_version:8.1.0\r\n" - ), - "Valkey 8.1.0" - ); - assert_eq!( - product_version("dragonfly_version:df-v1.27.1\r\n"), - "Dragonfly 1.27.1" - ); - assert_eq!(product_version(""), "Redis"); - } - - #[test] - fn maps_errors_and_kinds() { - let Value::ServerError(e) = resp(b"-WRONGTYPE Operation against a key\r\n") else { - panic!() - }; - let err = server_error(&e); - assert_eq!(err.kind, ErrorKind::Database); - assert_eq!(err.code.as_deref(), Some("WRONGTYPE")); - assert_eq!(err.message, "Operation against a key"); - let Value::ServerError(e) = resp(b"-MOVED 3999 127.0.0.1:6381\r\n") else { - panic!() - }; - let err = server_error(&e); - assert_eq!(err.code.as_deref(), Some("MOVED")); - assert!(err.message.contains("Redis Cluster is not supported yet")); - let Value::ServerError(e) = resp(b"-UNBLOCKED client unblocked via CLIENT UNBLOCK\r\n") - else { - panic!() - }; - assert_eq!(server_error(&e).kind, ErrorKind::Cancelled); - - assert_eq!(key_kind("ReJSON-RL").as_deref(), Some("json")); - assert_eq!(key_kind("zset").as_deref(), Some("zset")); - assert_eq!(key_kind("TSDB-TYPE").as_deref(), Some("tsdb-type")); - assert_eq!(key_kind("none"), None); - - assert_eq!(parse_db(""), Some(0)); - assert_eq!(parse_db(" 3 "), Some(3)); - assert_eq!(parse_db("db12"), Some(12)); - assert_eq!(parse_db("x"), None); - assert_eq!(parse_db("-1"), None); - - assert_eq!(base64(b"Man"), "TWFu"); - assert_eq!(base64(b"Ma"), "TWE="); - assert_eq!(base64(b"M"), "TQ=="); - } - - #[test] - fn tracks_multi() { - let mut st = State::default(); - let ok = |s: &str| Ok(Value::SimpleString(s.into())); - let a = |l: &str| split_args(l).unwrap(); - track(&mut st, "MULTI", &a("MULTI"), &Ok(Value::Okay)); - assert!(st.in_multi); - track(&mut st, "SELECT", &a("SELECT 4"), &ok("QUEUED")); - assert_eq!((st.db, st.queued_select), (0, Some(4))); - let err = resp(b"-ERR unknown command\r\n"); - track(&mut st, "NOPE", &a("NOPE"), &Ok(err.clone())); - assert!(st.in_multi); - track( - &mut st, - "EXEC", - &a("EXEC"), - &Ok(Value::Array(vec![Value::Okay])), - ); - assert!(!st.in_multi); - assert_eq!(st.db, 4); - track(&mut st, "MULTI", &a("MULTI"), &Ok(Value::Okay)); - track( - &mut st, - "EXEC", - &a("EXEC"), - &Ok(resp(b"-EXECABORT Transaction discarded\r\n")), - ); - assert!(!st.in_multi); - track(&mut st, "SELECT", &a("SELECT 2"), &Ok(Value::Okay)); - assert_eq!(st.db, 2); - track(&mut st, "SELECT", &a("SELECT 99"), &Ok(err)); - assert_eq!(st.db, 2); - } - - // Integration tests: need a server. Variables: LQ_REDIS_HOST, - // LQ_REDIS_PORT (6379) and LQ_REDIS_PASSWORD (optional). - - fn env(name: &str) -> Option { - std::env::var(name).ok().filter(|v| !v.is_empty()) - } - - fn profile() -> Option<(ConnectionProfile, Option)> { - let host = env("LQ_REDIS_HOST")?; - Some(( - ConnectionProfile { - name: "test".into(), - engine: crate::model::Engine::Redis, - host, - port: env("LQ_REDIS_PORT") - .and_then(|p| p.parse().ok()) - .unwrap_or(DEFAULT_PORT), - ssl_mode: SslMode::Disable, - ..Default::default() - }, - env("LQ_REDIS_PASSWORD"), - )) - } - - async fn session() -> Option { - let (profile, password) = profile()?; - Some( - connect(&profile, password.as_deref()) - .await - .expect("connect"), - ) - } - - fn req(line: &str, max_rows: usize) -> ExecRequest { - ExecRequest { - sql: line.into(), - max_rows, - } - } - - async fn run(s: &RedisSession, line: &str) -> ExecResult { - s.execute(&req(line, 100)) - .await - .unwrap_or_else(|e| panic!("{line}: {e}")) - } - - fn first(r: &ExecResult) -> Option<&str> { - r.rows[0][0].as_deref() - } - - #[tokio::test] - #[ignore] - async fn connects_and_reports_version() { - let Some(s) = session().await else { return }; - assert!( - s.server_version.starts_with("Redis ") || s.server_version.starts_with("Valkey "), - "{}", - s.server_version - ); - assert_eq!(s.current_schema.as_deref(), Some("db0")); - assert!(s.current_user.is_some()); - let st = s.tx_state(); - assert!(st.autocommit && !st.in_transaction); - assert!(run(&s, "# comment").await.columns.is_none()); - assert!(run(&s, "// comment").await.columns.is_none()); - assert_eq!(first(&run(&s, "PING").await), Some("PONG")); - - // `prefer` falls back to plain TCP on a server without TLS. - let (mut profile, password) = profile().unwrap(); - profile.ssl_mode = SslMode::Prefer; - profile.database = "2".into(); - let started = Instant::now(); - let p = connect(&profile, password.as_deref()) - .await - .expect("prefer"); - assert!(started.elapsed() < Duration::from_secs(10)); - assert_eq!(p.current_schema.as_deref(), Some("db2")); - - // ACL user: right and wrong password. - run(&s, "ACL SETUSER lq_test on >lq-secret ~* &* +@all").await; - profile.ssl_mode = SslMode::Disable; - profile.user = "lq_test".into(); - let u = connect(&profile, Some("lq-secret")) - .await - .expect("acl user"); - assert_eq!(u.current_user.as_deref(), Some("lq_test")); - let e = match connect(&profile, Some("wrong")).await { - Ok(_) => panic!("connected with a wrong password"), - Err(e) => e, - }; - assert_eq!(e.kind, ErrorKind::Connection); - assert_eq!(e.code.as_deref(), Some("WRONGPASS")); - run(&s, "ACL DELUSER lq_test").await; - } - - #[tokio::test] - #[ignore] - async fn sets_and_gets_strings() { - let Some(s) = session().await else { return }; - assert_eq!( - first(&run(&s, r#"SET "lq:t:str key" "a b\n""#).await), - Some("OK") - ); - let r = run(&s, r#"GET "lq:t:str key""#).await; - assert_eq!(first(&r), Some("a b\n")); - assert_eq!(r.columns.as_ref().unwrap()[0].name, "value"); - run(&s, r#"SET lq:t:bin "\xff\x00ok""#).await; - assert_eq!( - first(&run(&s, "GET lq:t:bin").await), - Some(r#""\xff\x00ok""#) - ); - assert_eq!(first(&run(&s, "GET lq:t:missing").await), None); - let r = run(&s, "INCRBY lq:t:n 5").await; - assert_eq!(r.columns.unwrap()[0].kind, ValueKind::Number); - run(&s, "DEL lq:t:n").await; - - let e = s.execute(&req(r#"GET "abc"#, 10)).await.unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - } - - #[tokio::test] - #[ignore] - async fn hashes_and_sorted_sets_have_columns() { - let Some(s) = session().await else { return }; - run(&s, "DEL lq:t:h lq:t:z").await; - run(&s, r#"HSET lq:t:h f1 v1 f2 "v 2""#).await; - let r = run(&s, "HGETALL lq:t:h").await; - let cols: Vec = r.columns.unwrap().into_iter().map(|c| c.name).collect(); - assert_eq!(cols, ["field", "value"]); - let mut rows: Vec>> = r.rows; - rows.sort(); - assert_eq!(rows[1], [Some("f2".to_string()), Some("v 2".to_string())]); - - run(&s, "ZADD lq:t:z 1 a 2.5 b").await; - let r = run(&s, "ZRANGE lq:t:z 0 -1 WITHSCORES").await; - let cols = r.columns.unwrap(); - assert_eq!(cols[0].name, "member"); - assert_eq!(cols[1].name, "score"); - assert_eq!(cols[1].kind, ValueKind::Number); - assert_eq!(r.rows[1], [Some("b".to_string()), Some("2.5".to_string())]); - - let e = s.execute(&req("LPUSH lq:t:h x", 10)).await.unwrap_err(); - assert_eq!(e.kind, ErrorKind::Database); - assert_eq!(e.code.as_deref(), Some("WRONGTYPE")); - run(&s, "DEL lq:t:h lq:t:z").await; - } - - #[tokio::test] - #[ignore] - async fn limits_rows_and_parses_info() { - let Some(s) = session().await else { return }; - run(&s, "DEL lq:t:list").await; - let values: Vec = (1..=50).map(|i| i.to_string()).collect(); - run(&s, &format!("RPUSH lq:t:list {}", values.join(" "))).await; - let r = s.execute(&req("LRANGE lq:t:list 0 -1", 10)).await.unwrap(); - assert_eq!(r.rows.len(), 10); - assert!(r.truncated); - assert_eq!(r.rows[9], [Some("10".to_string()), Some("10".to_string())]); - let r = s.execute(&req("LRANGE lq:t:list 0 -1", 0)).await.unwrap(); - assert_eq!(r.rows.len(), 50); - assert!(!r.truncated); - run(&s, "DEL lq:t:list").await; - - let r = run(&s, "INFO server").await; - let cols: Vec = r.columns.unwrap().into_iter().map(|c| c.name).collect(); - assert_eq!(cols, ["section", "key", "value"]); - assert!(r - .rows - .iter() - .any(|row| row[0].as_deref() == Some("Server") - && row[1].as_deref() == Some("redis_version"))); - } - - #[tokio::test] - #[ignore] - async fn lists_databases_and_keys() { - let Some(s) = session().await else { return }; - run(&s, "SET lq:t:home here").await; - run(&s, "SELECT 9").await; - for line in [ - "DEL lq:obj:str lq:obj:hash lq:obj:list lq:obj:set lq:obj:zset lq:obj:stream", - "SET lq:obj:str v", - "HSET lq:obj:hash f v", - "RPUSH lq:obj:list a", - "SADD lq:obj:set a", - "ZADD lq:obj:zset 1 a", - "XADD lq:obj:stream * f v", - ] { - run(&s, line).await; - } - let schemas = s.list_schemas().await.unwrap(); - assert_eq!(schemas[0], "db9"); - run(&s, "SELECT 0").await; - assert_eq!(s.list_schemas().await.unwrap()[0], "db0"); - - let objects = s.list_objects("db9").await.unwrap(); - let kind = |name: &str| { - objects - .iter() - .find(|o| o.name == name) - .map(|o| o.kind.as_str()) - }; - assert_eq!(kind("lq:obj:str"), Some("string")); - assert_eq!(kind("lq:obj:hash"), Some("hash")); - assert_eq!(kind("lq:obj:list"), Some("list")); - assert_eq!(kind("lq:obj:set"), Some("set")); - assert_eq!(kind("lq:obj:zset"), Some("zset")); - assert_eq!(kind("lq:obj:stream"), Some("stream")); - let sorted = objects - .windows(2) - .all(|w| (&w[0].kind, &w[0].name) <= (&w[1].kind, &w[1].name)); - assert!(sorted); - // The session is back on its own database. - assert_eq!(first(&run(&s, "GET lq:t:home").await), Some("here")); - assert!(s - .list_columns("db9", "lq:obj:str") - .await - .unwrap() - .is_empty()); - } - - #[tokio::test] - #[ignore] - async fn tracks_transactions() { - let Some(s) = session().await else { return }; - let e = s.set_autocommit(false).await.unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - assert!(s.set_autocommit(true).await.unwrap().autocommit); - - assert!(run(&s, "MULTI").await.in_transaction); - let r = run(&s, "SET lq:t:tx 1").await; - assert_eq!(first(&r), Some("QUEUED")); - assert!(r.in_transaction && s.tx_state().in_transaction); - let r = run(&s, "EXEC").await; - assert!(!r.in_transaction && !s.tx_state().in_transaction); - assert_eq!(r.rows[0][1].as_deref(), Some("OK")); - - run(&s, "MULTI").await; - run(&s, "SET lq:t:tx 2").await; - let st = s.end_transaction(false).await.unwrap(); - assert!(!st.in_transaction); - assert_eq!(first(&run(&s, "GET lq:t:tx").await), Some("1")); - - run(&s, "MULTI").await; - let e = s.execute(&req("NOSUCHCOMMAND", 10)).await.unwrap_err(); - assert_eq!(e.code.as_deref(), Some("ERR")); - assert!(s.tx_state().in_transaction); - let e = s.end_transaction(true).await.unwrap_err(); - assert_eq!(e.code.as_deref(), Some("EXECABORT")); - assert!(!s.tx_state().in_transaction); - run(&s, "DEL lq:t:tx").await; - } - - #[tokio::test] - #[ignore] - async fn cancels_a_blocking_command() { - let Some(s) = session().await else { return }; - let s = Arc::new(s); - let started = Instant::now(); - let running = { - let s = s.clone(); - tokio::spawn(async move { s.execute(&req("BLPOP lq:never 30", 10)).await }) - }; - tokio::time::sleep(Duration::from_secs(1)).await; - s.cancel().await.unwrap(); - let e = running.await.unwrap().unwrap_err(); - assert_eq!(e.kind, ErrorKind::Cancelled); - assert_eq!(e.code.as_deref(), Some("UNBLOCKED")); - assert!(started.elapsed() < Duration::from_secs(15)); - assert_eq!(first(&run(&s, "PING").await), Some("PONG")); - // Nothing running: nothing to do. - s.cancel().await.unwrap(); - } -} diff --git a/src-tauri/src/drivers/sqlite.rs b/src-tauri/src/drivers/sqlite.rs deleted file mode 100644 index bf4a9a1..0000000 --- a/src-tauri/src/drivers/sqlite.rs +++ /dev/null @@ -1,2761 +0,0 @@ -//! SQLite session on an embedded database file, through `rusqlite` with the -//! bundled SQLite library. -//! -//! The connection is synchronous and not `Sync`: it lives behind a mutex and -//! every call runs in `spawn_blocking`. The row limit stops stepping the -//! statement at `max_rows + 1`. Cancel uses `sqlite3_interrupt`, which is safe -//! to call from another thread while a statement runs. -//! -//! Grid editing: the column origins come from `sqlite3_column_table_name` -//! and friends, which resolve views and subqueries to their base table. An -//! `EXPLAIN QUERY PLAN` then checks that the rows come from one table -//! instance (no joins, self-joins or compound selects, whose origins SQLite -//! reports from one arm only). Keys come from `pragma_table_xinfo`, cached per -//! session. - -use std::collections::HashMap; -use std::fmt::Write as _; -use std::panic::AssertUnwindSafe; -use std::path::Path; -use std::sync::Arc; -use std::time::Instant; - -use parking_lot::Mutex; -use rusqlite::types::{Type, Value, ValueRef}; -use rusqlite::{ffi, Connection, InterruptHandle, OpenFlags, Statement}; - -use super::{first_keywords, RowSink, StreamEvent, TxState, STREAM_BATCH}; -use crate::error::{AppError, AppResult, ErrorKind}; -use crate::model::{ - ApplyRequest, ApplyResult, ColumnInfo, ConnectionProfile, DbColumn, DbObject, EditColumn, - EditTarget, ExecRequest, ExecResult, RowChange, ValueKind, -}; - -const BINARY_PREVIEW_BYTES: usize = 32 * 1024; -const BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); - -pub struct LiteSession { - conn: Arc>, - interrupt: InterruptHandle, - state: Arc>, - catalog: Arc>, - pub server_version: String, - pub current_user: Option, - pub current_schema: Option, -} - -pub async fn connect(profile: &ConnectionProfile) -> AppResult { - let path = profile.database.trim().to_string(); - let create = profile.create_file; - blocking(move || { - if path.is_empty() { - return Err(AppError::invalid("Choose the database file.")); - } - let special = path == ":memory:" || path.starts_with("file:"); - if !special && !Path::new(&path).exists() && !create { - return Err(AppError::connection(format!( - "Database file not found: {path}" - ))); - } - let mut flags = OpenFlags::SQLITE_OPEN_READ_WRITE - | OpenFlags::SQLITE_OPEN_NO_MUTEX - | OpenFlags::SQLITE_OPEN_URI; - if create { - flags |= OpenFlags::SQLITE_OPEN_CREATE; - } - let conn = Connection::open_with_flags(&path, flags).map_err(connection_error)?; - conn.busy_timeout(BUSY_TIMEOUT).map_err(connection_error)?; - conn.execute_batch("PRAGMA foreign_keys = ON") - .map_err(connection_error)?; - // Opening is lazy: reading the schema catches files that are not - // databases now instead of on the first statement. - conn.query_row("SELECT count(*) FROM sqlite_schema", [], |r| { - r.get::<_, i64>(0) - }) - .map_err(connection_error)?; - - Ok(LiteSession { - interrupt: conn.get_interrupt_handle(), - conn: Arc::new(Mutex::new(conn)), - state: Arc::new(Mutex::new(TxState { - autocommit: true, - in_transaction: false, - })), - catalog: Arc::default(), - server_version: format!("SQLite {}", rusqlite::version()), - current_user: None, - current_schema: Some("main".into()), - }) - }) - .await -} - -async fn blocking(f: F) -> AppResult -where - T: Send + 'static, - F: FnOnce() -> AppResult + Send + 'static, -{ - tauri::async_runtime::spawn_blocking(f) - .await - .map_err(|e| AppError::internal(e.to_string()))? -} - -impl LiteSession { - pub async fn apply_changes(&self, req: &ApplyRequest) -> AppResult { - // Every value is converted before anything runs. - let steps = plan_changes(&req.target, &req.changes)?; - let conn = self.conn.clone(); - let state = self.state.clone(); - blocking(move || { - let conn = conn.lock(); - let autocommit = state.lock().autocommit; - let started = Instant::now(); - let outcome = apply_steps(&conn, &steps, autocommit); - let in_transaction = !conn.is_autocommit(); - state.lock().in_transaction = in_transaction; - let mut result = outcome?; - result.elapsed_ms = started.elapsed().as_millis() as u64; - result.in_transaction = in_transaction; - Ok(result) - }) - .await - } - - pub fn tx_state(&self) -> TxState { - *self.state.lock() - } - - pub async fn execute(&self, req: &ExecRequest) -> AppResult { - let conn = self.conn.clone(); - let state = self.state.clone(); - let catalog = self.catalog.clone(); - let sql = req.sql.clone(); - let max_rows = req.max_rows; - blocking(move || { - let conn = conn.lock(); - let autocommit = state.lock().autocommit; - let started = Instant::now(); - let outcome = run(&conn, &catalog, &sql, max_rows, autocommit); - // SQLite knows whether a transaction is open, including one - // started or ended by the user's own BEGIN/COMMIT/ROLLBACK. - let in_transaction = !conn.is_autocommit(); - state.lock().in_transaction = in_transaction; - let mut result = outcome?; - result.elapsed_ms = started.elapsed().as_millis() as u64; - result.in_transaction = in_transaction; - Ok(result) - }) - .await - } - - pub async fn cancel(&self) -> AppResult<()> { - self.interrupt.interrupt(); - Ok(()) - } - - pub async fn set_autocommit(&self, on: bool) -> AppResult { - let conn = self.conn.clone(); - let state = self.state.clone(); - blocking(move || { - let conn = conn.lock(); - // Switching back to autocommit commits pending work, as JDBC - // clients do. - let outcome = if on && !conn.is_autocommit() { - conn.execute_batch("COMMIT").map_err(map_error) - } else { - Ok(()) - }; - let mut st = state.lock(); - st.in_transaction = !conn.is_autocommit(); - outcome?; - st.autocommit = on; - Ok(*st) - }) - .await - } - - pub async fn end_transaction(&self, commit: bool) -> AppResult { - let conn = self.conn.clone(); - let state = self.state.clone(); - blocking(move || { - let conn = conn.lock(); - let outcome = if conn.is_autocommit() { - Ok(()) - } else { - conn.execute_batch(if commit { "COMMIT" } else { "ROLLBACK" }) - .map_err(map_error) - }; - let mut st = state.lock(); - st.in_transaction = !conn.is_autocommit(); - outcome?; - Ok(*st) - }) - .await - } - - pub async fn list_schemas(&self) -> AppResult> { - let rows = self - .query_rows( - "SELECT name FROM pragma_database_list - ORDER BY CASE name WHEN 'main' THEN 0 WHEN 'temp' THEN 2 ELSE 1 END, name" - .into(), - Vec::new(), - ) - .await?; - Ok(rows.into_iter().map(|mut r| r.swap_remove(0)).collect()) - } - - pub async fn list_objects(&self, schema: &str) -> AppResult> { - let sql = format!( - "SELECT name, type FROM {}.sqlite_schema - WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' - ORDER BY type, name", - quote_ident(schema) - ); - let rows = self.query_rows(sql, Vec::new()).await?; - Ok(rows - .into_iter() - .map(|mut r| DbObject { - kind: r.pop().unwrap_or_default(), - name: r.pop().unwrap_or_default(), - }) - .collect()) - } - - pub async fn list_columns(&self, schema: &str, table: &str) -> AppResult> { - // table_xinfo also lists generated columns; hidden = 1 are the - // hidden columns of virtual tables. - let rows = self - .query_rows( - "SELECT name, type, \"notnull\", pk, dflt_value FROM pragma_table_xinfo(?1, ?2) - WHERE hidden <> 1 ORDER BY cid" - .into(), - vec![table.to_string(), schema.to_string()], - ) - .await?; - Ok(rows - .into_iter() - .map(|r| DbColumn { - name: r[0].clone(), - type_name: r[1].clone(), - nullable: r[2] == "0", - primary_key: r[3] != "0", - default_value: Some(r[4].clone()).filter(|d| !d.is_empty()), - key_role: None, - }) - .collect()) - } - - /// Steps through the rows of a query, sending them in batches. - pub async fn stream(&self, sql: &str, sink: RowSink) -> AppResult { - let conn = self.conn.clone(); - let sql = sql.to_string(); - blocking(move || { - let conn = conn.lock(); - let mut stmt = conn.prepare(&sql).map_err(map_error)?; - let n = stmt.column_count(); - if n == 0 { - return Err(AppError::invalid("The statement returns no rows.")); - } - let info = stmt - .columns() - .map(|c| { - let decl = c - .decl_type() - .map(|t| t.trim().to_string()) - .unwrap_or_default(); - ColumnInfo { - name: c.name().to_string(), - kind: if decl.is_empty() { - class_kind(None) - } else { - declared_kind(&decl) - }, - type_name: decl, - } - }) - .collect(); - sink.blocking_send(StreamEvent::Columns(info)) - .map_err(|_| super::stream_stopped())?; - let mut rows = stmt.raw_query(); - let mut total = 0u64; - let mut batch = Vec::with_capacity(STREAM_BATCH); - while let Some(row) = rows.next().map_err(map_error)? { - let cells = super::full_values(|| { - (0..n) - .map(|i| row.get_ref(i).map(cell)) - .collect::, _>>() - }) - .map_err(map_error)?; - batch.push(cells); - total += 1; - if batch.len() == STREAM_BATCH { - let full = std::mem::replace(&mut batch, Vec::with_capacity(STREAM_BATCH)); - sink.blocking_send(StreamEvent::Rows(full)) - .map_err(|_| super::stream_stopped())?; - } - } - if !batch.is_empty() { - sink.blocking_send(StreamEvent::Rows(batch)) - .map_err(|_| super::stream_stopped())?; - } - Ok(total) - }) - .await - } - - /// The statements SQLite keeps for the table or view, then its indexes - /// and triggers. - pub async fn object_ddl(&self, schema: &str, name: &str, kind: &str) -> AppResult { - if !matches!(kind, "table" | "view") { - return Err(AppError::invalid(format!( - "LowQuery cannot script a {kind} on SQLite." - ))); - } - let sql = format!( - "SELECT sql FROM {}.sqlite_schema - WHERE sql IS NOT NULL - AND ((type IN ('table', 'view') AND name = ?1) - OR (type IN ('index', 'trigger') AND tbl_name = ?1)) - ORDER BY CASE type WHEN 'table' THEN 0 WHEN 'view' THEN 0 WHEN 'index' THEN 1 ELSE 2 END, - name", - quote_ident(schema) - ); - let rows = self.query_rows(sql, vec![name.to_string()]).await?; - Ok(rows - .into_iter() - .map(|r| format!("{};\n", r[0].trim_end().trim_end_matches(';'))) - .collect::>() - .join("\n")) - } - - async fn query_rows(&self, sql: String, params: Vec) -> AppResult>> { - let conn = self.conn.clone(); - blocking(move || { - let conn = conn.lock(); - let mut stmt = conn.prepare(&sql).map_err(map_error)?; - let n = stmt.column_count(); - let mut rows = stmt - .query(rusqlite::params_from_iter(params.iter())) - .map_err(map_error)?; - let mut out = Vec::new(); - while let Some(row) = rows.next().map_err(map_error)? { - let mut cells = Vec::with_capacity(n); - for i in 0..n { - cells.push(cell(row.get_ref(i).map_err(map_error)?).unwrap_or_default()); - } - out.push(cells); - } - Ok(out) - }) - .await - } -} - -/// Runs one statement. In manual-commit mode a transaction is opened first -/// and stays open until the user ends it. -fn run( - conn: &Connection, - catalog: &Mutex, - sql: &str, - max_rows: usize, - autocommit: bool, -) -> AppResult { - if is_blank(sql) { - return Ok(ExecResult::default()); - } - let kw = first_keywords(sql, 1); - let first = kw.first().map(String::as_str).unwrap_or(""); - // Transaction control is the user's own; VACUUM, ATTACH and DETACH - // cannot run inside a transaction, and several PRAGMAs are ignored or - // fail there. - let skip_begin = matches!( - first, - "BEGIN" - | "COMMIT" - | "END" - | "ROLLBACK" - | "SAVEPOINT" - | "RELEASE" - | "VACUUM" - | "ATTACH" - | "DETACH" - | "PRAGMA" - ); - let opened = !autocommit && conn.is_autocommit() && !skip_begin; - if opened { - conn.execute_batch("BEGIN").map_err(map_error)?; - } - let outcome = statement(conn, catalog, sql, max_rows, first); - if outcome.is_err() && opened && !conn.is_autocommit() { - // The failed statement was the only one in the transaction opened - // for it: do not leave an empty transaction behind. - let _ = conn.execute_batch("ROLLBACK"); - } - outcome -} - -fn statement( - conn: &Connection, - catalog: &Mutex, - sql: &str, - max_rows: usize, - first: &str, -) -> AppResult { - let mut stmt = conn.prepare(sql).map_err(map_error)?; - let readonly = stmt.readonly(); - if !readonly || matches!(first, "ATTACH" | "DETACH") { - // DDL may change keys: reload them on the next query. - catalog.lock().tables.clear(); - } - if stmt.column_count() == 0 { - stmt.raw_execute().map_err(map_error)?; - // changes() keeps the count of the last DML, so it only means - // something right after one. WITH without result columns is DML. - let dml = matches!(first, "INSERT" | "UPDATE" | "DELETE" | "REPLACE" | "WITH"); - return Ok(ExecResult { - rows_affected: dml.then(|| conn.changes()), - ..Default::default() - }); - } - - let declared: Vec<(String, Option)> = stmt - .columns() - .map(|c| { - ( - c.name().to_string(), - c.decl_type() - .map(|t| t.trim().to_string()) - .filter(|t| !t.is_empty()), - ) - }) - .collect(); - let n = declared.len(); - let editable = readonly && matches!(first, "SELECT" | "WITH"); - let origins = if editable { - column_origins(&stmt) - } else { - None - }; - let decls: Vec> = declared.iter().map(|(_, d)| d.clone()).collect(); - // Storage class of the first non-null value, for columns without a - // declared type (expressions). - let mut classes: Vec> = vec![None; n]; - let mut out = Vec::new(); - let mut truncated = false; - let mut rows = stmt.raw_query(); - while let Some(row) = rows.next().map_err(map_error)? { - if max_rows > 0 && out.len() == max_rows { - truncated = true; - break; - } - let mut cells = Vec::with_capacity(n); - for (i, class) in classes.iter_mut().enumerate() { - let value = row.get_ref(i).map_err(map_error)?; - if class.is_none() && value.data_type() != Type::Null { - *class = Some(value.data_type()); - } - cells.push(cell(value)); - } - out.push(cells); - } - drop(rows); - - let columns = declared - .into_iter() - .zip(classes) - .map(|((name, decl), class)| match decl { - Some(t) => ColumnInfo { - name, - kind: declared_kind(&t), - type_name: t, - }, - None => ColumnInfo { - name, - type_name: class_name(class).into(), - kind: class_kind(class), - }, - }) - .collect(); - let mut result = ExecResult { - columns: Some(columns), - rows: out, - truncated, - ..Default::default() - }; - if editable { - let target = match origins { - Some(origins) => edit_target(conn, catalog, sql, &origins, &decls), - None => Err(UNKNOWN_TABLE.into()), - }; - match target { - Ok(target) => result.editable = Some(target), - Err(reason) => result.read_only_reason = Some(reason), - } - } - Ok(result) -} - -/// Only whitespace, comments and semicolons: SQLite prepares nothing. -fn is_blank(sql: &str) -> bool { - let bytes = sql.as_bytes(); - let mut i = 0; - while i < bytes.len() { - let c = bytes[i]; - if c.is_ascii_whitespace() || c == b';' { - i += 1; - } else if c == b'-' && bytes.get(i + 1) == Some(&b'-') { - while i < bytes.len() && bytes[i] != b'\n' { - i += 1; - } - } else if c == b'/' && bytes.get(i + 1) == Some(&b'*') { - i += 2; - while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') { - i += 1; - } - i += 2; - } else { - return false; - } - } - true -} - -fn quote_ident(name: &str) -> String { - format!("\"{}\"", name.replace('"', "\"\"")) -} - -/// Kind from the declared type, following SQLite's affinity rules plus the -/// common names for booleans, dates and JSON. -fn declared_kind(decl: &str) -> ValueKind { - let t = decl.to_ascii_uppercase(); - let has = |s: &str| t.contains(s); - if has("BOOL") { - ValueKind::Bool - } else if has("JSON") { - ValueKind::Json - } else if has("DATE") || has("TIME") { - ValueKind::Temporal - } else if has("INT") { - ValueKind::Number - } else if has("CHAR") || has("CLOB") || has("TEXT") || has("STRING") || has("UUID") { - ValueKind::Text - } else if has("BLOB") || has("BINARY") { - ValueKind::Binary - } else if has("REAL") || has("FLOA") || has("DOUB") || has("NUM") || has("DEC") || has("MONEY") - { - ValueKind::Number - } else { - ValueKind::Other - } -} - -fn class_name(class: Option) -> &'static str { - match class { - Some(Type::Integer) => "INTEGER", - Some(Type::Real) => "REAL", - Some(Type::Text) => "TEXT", - Some(Type::Blob) => "BLOB", - Some(Type::Null) | None => "NULL", - } -} - -fn class_kind(class: Option) -> ValueKind { - match class { - Some(Type::Integer | Type::Real) => ValueKind::Number, - Some(Type::Text) => ValueKind::Text, - Some(Type::Blob) => ValueKind::Binary, - Some(Type::Null) | None => ValueKind::Other, - } -} - -fn cell(value: ValueRef<'_>) -> Option { - match value { - ValueRef::Null => None, - ValueRef::Integer(i) => Some(i.to_string()), - ValueRef::Real(f) => Some(real(f)), - ValueRef::Text(t) => Some(String::from_utf8_lossy(t).into_owned()), - ValueRef::Blob(b) => Some(blob(b)), - } -} - -/// Shortest text that reads back as the same double. Always shows it is a -/// REAL (`3.0`, `1.0e+300`), like the sqlite3 shell. -fn real(v: f64) -> String { - if v.is_nan() { - return "NaN".into(); - } - if v.is_infinite() { - return if v > 0.0 { "Inf" } else { "-Inf" }.into(); - } - let abs = v.abs(); - if abs != 0.0 && !(1e-5..1e16).contains(&abs) { - let s = format!("{v:e}"); - let (mantissa, exp) = s.split_once('e').unwrap_or((&s, "0")); - let mantissa = if mantissa.contains('.') { - mantissa.to_string() - } else { - format!("{mantissa}.0") - }; - let exp = if exp.starts_with('-') { - exp.to_string() - } else { - format!("+{exp}") - }; - return format!("{mantissa}e{exp}"); - } - let s = v.to_string(); - if s.contains('.') { - s - } else { - s + ".0" - } -} - -/// `X'00FF'` like a blob literal; large blobs show the first 32 KiB. -fn blob(bytes: &[u8]) -> String { - let shown = &bytes[..bytes.len().min(super::binary_limit(BINARY_PREVIEW_BYTES))]; - let mut s = String::with_capacity(shown.len() * 2 + 3); - s.push_str("X'"); - for b in shown { - let _ = write!(s, "{b:02X}"); - } - s.push('\''); - if bytes.len() > shown.len() { - let _ = write!(s, "… ({} bytes)", bytes.len()); - } - s -} - -const UNKNOWN_TABLE: &str = "Read-only: the table behind this result could not be identified."; - -/// Keys and columns of the tables behind editable results, per session. -#[derive(Default)] -struct Catalog { - tables: HashMap<(String, String), Arc>, -} - -#[derive(Debug, Default)] -struct TableMeta { - /// Column names, with whether each one can be written (generated and - /// hidden columns cannot). - columns: Vec<(String, bool)>, - /// Primary key columns in key order. - pk: Vec, - /// UNIQUE keys whose columns are all NOT NULL. - unique: Vec>, -} - -/// (database, table, column) behind each result column, `None` for -/// expressions. `None` overall if SQLite returns a name that is not UTF-8. -fn column_origins(stmt: &Statement<'_>) -> Option>> { - // rusqlite panics on names that are not UTF-8. - std::panic::catch_unwind(AssertUnwindSafe(|| { - stmt.columns_with_metadata() - .map(|m| { - Some(( - m.database_name()?.to_string(), - m.table_name()?.to_string(), - m.origin_name()?.to_string(), - )) - }) - .collect() - })) - .ok() -} - -/// The table an editable result comes from, or why it is read-only. -fn edit_target( - conn: &Connection, - catalog: &Mutex, - sql: &str, - origins: &[Option<(String, String, String)>], - decls: &[Option], -) -> Result { - let mut tables = origins.iter().flatten().map(|(db, t, _)| (db, t)); - let Some((db, table)) = tables.next() else { - return Err("Read-only: only rows from a table can be edited.".into()); - }; - if tables.any(|(d, t)| d != db || t != table) { - return Err("Read-only: the result combines columns from several tables.".into()); - } - let shape = query_plan(conn, sql).map_err(|_| UNKNOWN_TABLE.to_string())?; - if shape.compound { - return Err("Read-only: the result combines rows from several queries.".into()); - } - if shape.sources != 1 { - return Err("Read-only: the result combines rows from several tables.".into()); - } - let meta = table_meta(conn, catalog, db, table).map_err(|_| UNKNOWN_TABLE.to_string())?; - build_target(db, table, &meta, origins, decls) -} - -fn build_target( - db: &str, - table: &str, - meta: &TableMeta, - origins: &[Option<(String, String, String)>], - decls: &[Option], -) -> Result { - let has_rowid = meta.pk.is_empty() - && !meta - .columns - .iter() - .any(|(n, _)| n.eq_ignore_ascii_case("rowid")); - let columns: Vec> = origins - .iter() - .enumerate() - .map(|(i, origin)| { - let (_, _, origin) = origin.as_ref()?; - if let Some((name, writable)) = meta - .columns - .iter() - .find(|(n, _)| n.eq_ignore_ascii_case(origin)) - { - return writable.then(|| EditColumn { - name: name.clone(), - type_name: decls.get(i).cloned().flatten().unwrap_or_default(), - }); - } - // rowid, oid and _rowid_ all report "rowid". - (has_rowid && origin.eq_ignore_ascii_case("rowid")).then(|| EditColumn { - name: "rowid".into(), - type_name: "INTEGER".into(), - }) - }) - .collect(); - let find = |name: &str| { - columns.iter().position(|c| { - c.as_ref() - .is_some_and(|c| c.name.eq_ignore_ascii_case(name)) - }) - }; - let key: Option> = if !meta.pk.is_empty() { - let key: Option> = meta.pk.iter().map(|k| find(k)).collect(); - if key.is_none() { - return Err(format!( - "Read-only: add the primary key columns ({}) to the query to edit rows.", - meta.pk.join(", ") - )); - } - key - } else { - meta.unique - .iter() - .find_map(|u| u.iter().map(|k| find(k)).collect()) - .or_else(|| has_rowid.then(|| find("rowid").map(|i| vec![i])).flatten()) - }; - match key { - Some(key) => Ok(EditTarget { - schema: Some(db.to_string()), - table: table.to_string(), - columns, - key, - }), - None if has_rowid => Err(format!( - "Read-only: table {table} has no primary key; add rowid to the query to edit rows." - )), - None => Err(format!("Read-only: table {table} has no primary key.")), - } -} - -fn table_meta( - conn: &Connection, - catalog: &Mutex, - db: &str, - table: &str, -) -> rusqlite::Result> { - let key = (db.to_string(), table.to_string()); - if let Some(meta) = catalog.lock().tables.get(&key) { - return Ok(meta.clone()); - } - let meta = Arc::new(load_table_meta(conn, db, table)?); - catalog.lock().tables.insert(key, meta.clone()); - Ok(meta) -} - -fn load_table_meta(conn: &Connection, db: &str, table: &str) -> rusqlite::Result { - let mut meta = TableMeta::default(); - let mut pk = Vec::new(); - let mut not_null = Vec::new(); - let mut stmt = conn.prepare_cached( - "SELECT name, \"notnull\", pk, hidden FROM pragma_table_xinfo(?1, ?2) ORDER BY cid", - )?; - let mut rows = stmt.query([table, db])?; - while let Some(row) = rows.next()? { - let name: String = row.get(0)?; - if row.get::<_, i64>(1)? != 0 { - not_null.push(name.to_ascii_lowercase()); - } - let position: i64 = row.get(2)?; - if position > 0 { - pk.push((position, name.clone())); - } - // hidden: 1 virtual table hidden column, 2 and 3 generated. - meta.columns.push((name, row.get::<_, i64>(3)? == 0)); - } - pk.sort(); - meta.pk = pk.into_iter().map(|(_, n)| n).collect(); - - let mut stmt = conn.prepare_cached( - "SELECT il.name, ii.name FROM pragma_index_list(?1, ?2) AS il, \ - pragma_index_info(il.name, ?2) AS ii \ - WHERE il.\"unique\" AND NOT il.partial AND il.origin <> 'pk' \ - ORDER BY il.seq, ii.seqno", - )?; - let mut rows = stmt.query([table, db])?; - // (index, columns, usable): expression columns have no name. - let mut indexes: Vec<(String, Vec, bool)> = Vec::new(); - while let Some(row) = rows.next()? { - let index: String = row.get(0)?; - let column: Option = row.get(1)?; - if indexes.last().is_none_or(|(i, _, _)| *i != index) { - indexes.push((index, Vec::new(), true)); - } - let entry = indexes.last_mut().expect("pushed above"); - match column { - Some(c) if not_null.contains(&c.to_ascii_lowercase()) => entry.1.push(c), - _ => entry.2 = false, - } - } - meta.unique = indexes - .into_iter() - .filter(|(_, cols, usable)| *usable && !cols.is_empty()) - .map(|(_, cols, _)| cols) - .collect(); - Ok(meta) -} - -/// What `EXPLAIN QUERY PLAN` says about where the rows come from. -#[derive(Debug, PartialEq, Eq)] -struct PlanShape { - /// UNION, INTERSECT, EXCEPT or a recursive CTE produces rows. - compound: bool, - /// Table scans that produce rows (joins count each table). - sources: usize, -} - -fn query_plan(conn: &Connection, sql: &str) -> rusqlite::Result { - let mut stmt = conn.prepare(&format!("EXPLAIN QUERY PLAN {sql}"))?; - // raw_query: parameters stay unbound (NULL), as in execute. - let mut rows = stmt.raw_query(); - let mut lines = Vec::new(); - while let Some(row) = rows.next()? { - lines.push((row.get(0)?, row.get(1)?, row.get(3)?)); - } - Ok(plan_shape(&lines)) -} - -/// Reads plan rows (id, parent, detail). Subqueries in expressions (WHERE, -/// select list) do not add rows; scans of a co-routine or materialized -/// subquery read rows already counted inside it; an OR over several indexes -/// is one scan. -fn plan_shape(lines: &[(i64, i64, String)]) -> PlanShape { - let ancestors = |i: usize| { - let mut out = Vec::new(); - let mut parent = lines[i].1; - while parent != 0 && out.len() < lines.len() { - match lines.iter().position(|l| l.0 == parent) { - Some(p) => { - out.push(p); - parent = lines[p].1; - } - None => break, - } - } - out - }; - let in_expression = |d: &str| { - [ - "SCALAR SUBQUERY", - "CORRELATED SCALAR SUBQUERY", - "LIST SUBQUERY", - "CORRELATED LIST SUBQUERY", - ] - .iter() - .any(|p| d.starts_with(p)) - }; - let subquery_name = |d: &str| { - d.strip_prefix("CO-ROUTINE ") - .or_else(|| d.strip_prefix("MATERIALIZE ")) - .map(str::to_string) - }; - let names = |rest: &str, name: &str| { - rest.strip_prefix(name) - .is_some_and(|r| r.is_empty() || r.starts_with(' ')) - }; - let mut shape = PlanShape { - compound: false, - sources: 0, - }; - for (i, (_, _, detail)) in lines.iter().enumerate() { - let up = ancestors(i); - if up.iter().any(|&a| in_expression(&lines[a].2)) || in_expression(detail) { - continue; - } - if [ - "COMPOUND", - "MERGE (", - "SETUP", - "RECURSIVE STEP", - "LEFT-MOST SUBQUERY", - ] - .iter() - .any(|p| detail.starts_with(p)) - { - shape.compound = true; - } - if detail.starts_with("MULTI-INDEX OR") { - shape.sources += 1; - continue; - } - if up.iter().any(|&a| lines[a].2.starts_with("MULTI-INDEX OR")) { - continue; - } - let Some(rest) = detail - .strip_prefix("SCAN ") - .or_else(|| detail.strip_prefix("SEARCH ")) - else { - continue; - }; - // A constant row, or an EXISTS turned into a semi-join: no rows. - if rest.starts_with("CONSTANT ROW") || rest.contains(" EXISTS") { - continue; - } - let reads_subquery = lines - .iter() - .enumerate() - .any(|(j, l)| subquery_name(&l.2).is_some_and(|n| names(rest, &n)) && !up.contains(&j)); - if !reads_subquery { - shape.sources += 1; - } - } - shape -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Op { - Update, - Delete, - Insert, -} - -/// One statement of an apply, with its bound values. -#[derive(Debug, PartialEq)] -struct Step { - /// 1-based index of the change, for messages. - row: usize, - op: Op, - sql: String, - params: Vec, -} - -fn plan_changes(target: &EditTarget, changes: &[RowChange]) -> AppResult> { - let table = match &target.schema { - Some(schema) => format!("{}.{}", quote_ident(schema), quote_ident(&target.table)), - None => quote_ident(&target.table), - }; - let mut steps = Vec::with_capacity(changes.len()); - for (i, change) in changes.iter().enumerate() { - let mut params = Vec::new(); - let (op, sql) = match change { - // Nothing to save for this row. - RowChange::Update { values, .. } if values.is_empty() => continue, - RowChange::Update { key, values } => { - let mut sets = Vec::with_capacity(values.len()); - for v in values { - let column = target_column(target, v.column)?; - sets.push(format!("{} = ?", quote_ident(&column.name))); - params.push(to_value(v.value.as_deref(), &column.type_name)?); - } - let cond = key_condition(target, key, &mut params)?; - let sql = format!("UPDATE {table} SET {} WHERE {cond}", sets.join(", ")); - (Op::Update, sql) - } - RowChange::Delete { key } => { - let cond = key_condition(target, key, &mut params)?; - (Op::Delete, format!("DELETE FROM {table} WHERE {cond}")) - } - RowChange::Insert { values } if values.is_empty() => { - (Op::Insert, format!("INSERT INTO {table} DEFAULT VALUES")) - } - RowChange::Insert { values } => { - let mut names = Vec::with_capacity(values.len()); - for v in values { - let column = target_column(target, v.column)?; - names.push(quote_ident(&column.name)); - params.push(to_value(v.value.as_deref(), &column.type_name)?); - } - let marks = vec!["?"; names.len()].join(", "); - let sql = format!( - "INSERT INTO {table} ({}) VALUES ({marks})", - names.join(", ") - ); - (Op::Insert, sql) - } - }; - steps.push(Step { - row: i + 1, - op, - sql, - params, - }); - } - Ok(steps) -} - -fn target_column(target: &EditTarget, index: usize) -> AppResult<&EditColumn> { - target - .columns - .get(index) - .and_then(Option::as_ref) - .ok_or_else(|| { - AppError::invalid(format!( - "Result column {} is not a table column and cannot be edited.", - index + 1 - )) - }) -} - -fn key_condition( - target: &EditTarget, - key: &[Option], - params: &mut Vec, -) -> AppResult { - if key.len() != target.key.len() { - return Err(AppError::invalid( - "The row key does not match the key columns of the result.", - )); - } - let mut parts = Vec::with_capacity(key.len()); - for (&index, value) in target.key.iter().zip(key) { - let column = target_column(target, index)?; - let name = quote_ident(&column.name); - match value { - None => parts.push(format!("{name} IS NULL")), - Some(v) => { - parts.push(format!("{name} = ?")); - params.push(to_value(Some(v), &column.type_name)?); - } - } - } - Ok(parts.join(" AND ")) -} - -/// Runs the steps as one unit. Outside a transaction it opens one: with -/// autocommit it commits, in manual mode it stays open, as for user -/// statements. Inside an open transaction a savepoint undoes a failed batch -/// and keeps earlier work. -fn apply_steps(conn: &Connection, steps: &[Step], autocommit: bool) -> AppResult { - let mut result = ApplyResult::default(); - if conn.is_autocommit() { - conn.execute_batch(if autocommit { - "BEGIN IMMEDIATE" - } else { - "BEGIN" - }) - .map_err(map_error)?; - let mut outcome = run_steps(conn, steps, &mut result); - if outcome.is_ok() && autocommit { - outcome = conn.execute_batch("COMMIT").map_err(map_error); - } - if outcome.is_err() && !conn.is_autocommit() { - let _ = conn.execute_batch("ROLLBACK"); - } - outcome.map(|()| result) - } else { - conn.execute_batch("SAVEPOINT lq_apply") - .map_err(map_error)?; - let outcome = run_steps(conn, steps, &mut result); - if outcome.is_err() { - let _ = conn.execute_batch("ROLLBACK TO lq_apply"); - } - let released = conn.execute_batch("RELEASE lq_apply").map_err(map_error); - outcome.and(released).map(|()| result) - } -} - -fn run_steps(conn: &Connection, steps: &[Step], result: &mut ApplyResult) -> AppResult<()> { - for step in steps { - let changed = conn - .prepare_cached(&step.sql) - .and_then(|mut s| s.execute(rusqlite::params_from_iter(&step.params))) - .map_err(|e| { - let mut err = map_error(e); - // The position would point into SQL the user never saw. - err.position = None; - if err.kind == ErrorKind::Database { - err.message = format!("Row {} was not saved: {}", step.row, err.message); - } - err - })?; - match step.op { - Op::Insert => result.inserted += changed as u64, - Op::Update | Op::Delete if changed != 1 => { - let why = if changed == 0 { - " (changed or removed by someone else)" - } else { - "" - }; - return Err(AppError::new( - ErrorKind::Database, - format!( - "Row {} was not saved: {changed} rows matched its key{why}.", - step.row - ), - )); - } - Op::Update => result.updated += 1, - Op::Delete => result.deleted += 1, - } - } - Ok(()) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Affinity { - Integer, - Text, - Blob, - Real, - Numeric, -} - -/// Column affinity from the declared type (SQLite "Datatypes", 3.1). -fn affinity(decl: &str) -> Affinity { - let t = decl.to_ascii_uppercase(); - let has = |s: &str| t.contains(s); - if has("INT") { - Affinity::Integer - } else if has("CHAR") || has("CLOB") || has("TEXT") { - Affinity::Text - } else if has("BLOB") || t.trim().is_empty() { - Affinity::Blob - } else if has("REAL") || has("FLOA") || has("DOUB") { - Affinity::Real - } else { - Affinity::Numeric - } -} - -/// Converts grid text back to a value for a column with the declared type. -/// Numeric affinities bind numbers; columns without affinity (BLOB or no -/// type) keep their storage class through the display format: `X'..'` is a -/// blob, and text that the formatter would print for an integer or real is -/// that number. -fn to_value(text: Option<&str>, decl: &str) -> AppResult { - let Some(text) = text else { - return Ok(Value::Null); - }; - if text.starts_with("X'") && text.contains("'… (") { - return Err(AppError::invalid( - "This value is only a preview and cannot be saved.", - )); - } - let value = match affinity(decl) { - Affinity::Text => None, - Affinity::Integer | Affinity::Real | Affinity::Numeric => { - let t = text.trim(); - let boolean = decl.to_ascii_uppercase().contains("BOOL"); - if boolean && t.eq_ignore_ascii_case("true") { - Some(Value::Integer(1)) - } else if boolean && t.eq_ignore_ascii_case("false") { - Some(Value::Integer(0)) - } else if let Ok(i) = t.parse::() { - Some(Value::Integer(i)) - } else { - parse_real(t).map(Value::Real) - } - } - Affinity::Blob => hex_blob(text) - .map(Value::Blob) - .or_else(|| match text.parse::() { - Ok(i) if i.to_string() == text => Some(Value::Integer(i)), - _ => parse_real(text) - .filter(|&f| real(f) == text) - .map(Value::Real), - }), - }; - Ok(value.unwrap_or_else(|| Value::Text(text.to_string()))) -} - -/// A decimal or exponent literal, or the `Inf` the formatter prints. -fn parse_real(t: &str) -> Option { - match t { - "Inf" | "+Inf" => return Some(f64::INFINITY), - "-Inf" => return Some(f64::NEG_INFINITY), - _ => {} - } - let literal = t.bytes().any(|b| b.is_ascii_digit()) - && t.bytes() - .all(|b| b.is_ascii_digit() || b"+-.eE".contains(&b)); - literal.then(|| t.parse().ok()).flatten() -} - -/// Bytes of an `X'00FF'` literal. -fn hex_blob(t: &str) -> Option> { - let hex = t - .strip_prefix("X'") - .or_else(|| t.strip_prefix("x'"))? - .strip_suffix('\'')?; - if hex.len() % 2 != 0 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { - return None; - } - (0..hex.len()) - .step_by(2) - .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).ok()) - .collect() -} - -macro_rules! code_names { - ($code:expr; $($name:ident),* $(,)?) => { - match $code { - $(ffi::$name => Some(stringify!($name)),)* - _ => None, - } - }; -} - -/// Name of an (extended) result code, as in the SQLite documentation. -fn code_name(code: i32) -> String { - fn lookup(code: i32) -> Option<&'static str> { - code_names!(code; - SQLITE_ERROR, SQLITE_INTERNAL, SQLITE_PERM, SQLITE_ABORT, SQLITE_BUSY, - SQLITE_LOCKED, SQLITE_NOMEM, SQLITE_READONLY, SQLITE_INTERRUPT, SQLITE_IOERR, - SQLITE_CORRUPT, SQLITE_NOTFOUND, SQLITE_FULL, SQLITE_CANTOPEN, SQLITE_PROTOCOL, - SQLITE_EMPTY, SQLITE_SCHEMA, SQLITE_TOOBIG, SQLITE_CONSTRAINT, SQLITE_MISMATCH, - SQLITE_MISUSE, SQLITE_NOLFS, SQLITE_AUTH, SQLITE_FORMAT, SQLITE_RANGE, - SQLITE_NOTADB, - SQLITE_ERROR_MISSING_COLLSEQ, SQLITE_ERROR_RETRY, SQLITE_ERROR_SNAPSHOT, - SQLITE_IOERR_READ, SQLITE_IOERR_SHORT_READ, SQLITE_IOERR_WRITE, SQLITE_IOERR_FSYNC, - SQLITE_IOERR_DIR_FSYNC, SQLITE_IOERR_TRUNCATE, SQLITE_IOERR_FSTAT, - SQLITE_IOERR_UNLOCK, SQLITE_IOERR_RDLOCK, SQLITE_IOERR_DELETE, SQLITE_IOERR_BLOCKED, - SQLITE_IOERR_NOMEM, SQLITE_IOERR_ACCESS, SQLITE_IOERR_CHECKRESERVEDLOCK, - SQLITE_IOERR_LOCK, SQLITE_IOERR_CLOSE, SQLITE_IOERR_DIR_CLOSE, SQLITE_IOERR_SHMOPEN, - SQLITE_IOERR_SHMSIZE, SQLITE_IOERR_SHMLOCK, SQLITE_IOERR_SHMMAP, SQLITE_IOERR_SEEK, - SQLITE_IOERR_DELETE_NOENT, SQLITE_IOERR_MMAP, SQLITE_IOERR_GETTEMPPATH, - SQLITE_IOERR_CONVPATH, SQLITE_IOERR_VNODE, SQLITE_IOERR_AUTH, - SQLITE_IOERR_BEGIN_ATOMIC, SQLITE_IOERR_COMMIT_ATOMIC, SQLITE_IOERR_ROLLBACK_ATOMIC, - SQLITE_IOERR_DATA, SQLITE_IOERR_CORRUPTFS, - SQLITE_LOCKED_SHAREDCACHE, SQLITE_LOCKED_VTAB, - SQLITE_BUSY_RECOVERY, SQLITE_BUSY_SNAPSHOT, SQLITE_BUSY_TIMEOUT, - SQLITE_CANTOPEN_NOTEMPDIR, SQLITE_CANTOPEN_ISDIR, SQLITE_CANTOPEN_FULLPATH, - SQLITE_CANTOPEN_CONVPATH, SQLITE_CANTOPEN_DIRTYWAL, SQLITE_CANTOPEN_SYMLINK, - SQLITE_CORRUPT_VTAB, SQLITE_CORRUPT_SEQUENCE, SQLITE_CORRUPT_INDEX, - SQLITE_READONLY_RECOVERY, SQLITE_READONLY_CANTLOCK, SQLITE_READONLY_ROLLBACK, - SQLITE_READONLY_DBMOVED, SQLITE_READONLY_CANTINIT, SQLITE_READONLY_DIRECTORY, - SQLITE_ABORT_ROLLBACK, - SQLITE_CONSTRAINT_CHECK, SQLITE_CONSTRAINT_COMMITHOOK, SQLITE_CONSTRAINT_FOREIGNKEY, - SQLITE_CONSTRAINT_FUNCTION, SQLITE_CONSTRAINT_NOTNULL, SQLITE_CONSTRAINT_PRIMARYKEY, - SQLITE_CONSTRAINT_TRIGGER, SQLITE_CONSTRAINT_UNIQUE, SQLITE_CONSTRAINT_VTAB, - SQLITE_CONSTRAINT_ROWID, SQLITE_CONSTRAINT_PINNED, SQLITE_CONSTRAINT_DATATYPE, - SQLITE_AUTH_USER, - ) - } - lookup(code) - .or_else(|| lookup(code & 0xff)) - .map(str::to_string) - .unwrap_or_else(|| format!("SQLITE_{code}")) -} - -fn sqlite_error(error: ffi::Error, msg: Option) -> AppError { - let message = msg.unwrap_or_else(|| ffi::code_to_str(error.extended_code).to_string()); - let mut err = AppError::new(ErrorKind::Database, message); - if error.code == ffi::ErrorCode::OperationInterrupted { - err.kind = ErrorKind::Cancelled; - err.message = "The statement was cancelled.".into(); - } - err.code = Some(code_name(error.extended_code)); - err -} - -fn connection_error(e: rusqlite::Error) -> AppError { - let mut err = map_error(e); - err.kind = ErrorKind::Connection; - err -} - -pub fn map_error(e: rusqlite::Error) -> AppError { - match e { - rusqlite::Error::SqliteFailure(error, msg) => sqlite_error(error, msg), - rusqlite::Error::SqlInputError { - error, - msg, - sql, - offset, - } => { - let mut err = sqlite_error(error, Some(msg)); - // SQLite reports a byte offset; the UI wants characters. - err.position = usize::try_from(offset) - .ok() - .and_then(|o| sql.get(..o)) - .map(|s| s.chars().count()); - err - } - rusqlite::Error::MultipleStatement => { - AppError::invalid("Only one statement can run at a time.") - } - other => AppError::new(ErrorKind::Database, other.to_string()), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::model::Engine; - use std::path::PathBuf; - use std::sync::atomic::{AtomicUsize, Ordering}; - - static COUNTER: AtomicUsize = AtomicUsize::new(0); - - fn temp_path(name: &str) -> PathBuf { - let n = COUNTER.fetch_add(1, Ordering::SeqCst); - let path = std::env::temp_dir().join(format!( - "lowquery-test-{name}-{}-{n}.db", - std::process::id() - )); - let _ = std::fs::remove_file(&path); - path - } - - fn profile(path: &Path, create: bool) -> ConnectionProfile { - ConnectionProfile { - engine: Engine::Sqlite, - database: path.display().to_string(), - create_file: create, - ..Default::default() - } - } - - struct TempDb { - path: PathBuf, - session: Option, - } - - impl TempDb { - async fn new(name: &str) -> Self { - let path = temp_path(name); - let session = connect(&profile(&path, true)).await.unwrap(); - Self { - path, - session: Some(session), - } - } - - fn s(&self) -> &LiteSession { - self.session.as_ref().unwrap() - } - - async fn run(&self, sql: &str) -> ExecResult { - self.run_limit(sql, 0).await - } - - async fn run_limit(&self, sql: &str, max_rows: usize) -> ExecResult { - self.try_run(sql, max_rows) - .await - .unwrap_or_else(|e| panic!("{sql}: {e}")) - } - - async fn try_run(&self, sql: &str, max_rows: usize) -> AppResult { - self.s() - .execute(&ExecRequest { - sql: sql.into(), - max_rows, - }) - .await - } - - async fn scalar(&self, sql: &str) -> Option { - self.run(sql).await.rows[0][0].clone() - } - } - - impl Drop for TempDb { - fn drop(&mut self) { - self.session.take(); - for suffix in ["", "-journal", "-wal", "-shm"] { - let _ = std::fs::remove_file(format!("{}{suffix}", self.path.display())); - } - } - } - - #[test] - fn formats_reals_shortest() { - assert_eq!(real(3.0), "3.0"); - assert_eq!(real(-0.5), "-0.5"); - assert_eq!(real(0.1 + 0.2), "0.30000000000000004"); - assert_eq!(real(1e300), "1.0e+300"); - assert_eq!(real(-1.5e-7), "-1.5e-7"); - assert_eq!(real(123456789.125), "123456789.125"); - assert_eq!(real(f64::INFINITY), "Inf"); - assert_eq!(real(0.0), "0.0"); - } - - #[test] - fn kinds_follow_affinity() { - assert_eq!(declared_kind("INTEGER"), ValueKind::Number); - assert_eq!(declared_kind("bigint"), ValueKind::Number); - assert_eq!(declared_kind("NUMERIC(10,2)"), ValueKind::Number); - assert_eq!(declared_kind("DOUBLE PRECISION"), ValueKind::Number); - assert_eq!(declared_kind("VARCHAR(20)"), ValueKind::Text); - assert_eq!(declared_kind("DATETIME"), ValueKind::Temporal); - assert_eq!(declared_kind("BOOLEAN"), ValueKind::Bool); - assert_eq!(declared_kind("JSON"), ValueKind::Json); - assert_eq!(declared_kind("BLOB"), ValueKind::Binary); - assert_eq!(declared_kind("GEOMETRY"), ValueKind::Other); - } - - #[test] - fn names_result_codes() { - assert_eq!(code_name(ffi::SQLITE_ERROR), "SQLITE_ERROR"); - assert_eq!( - code_name(ffi::SQLITE_CONSTRAINT_UNIQUE), - "SQLITE_CONSTRAINT_UNIQUE" - ); - assert_eq!(code_name(ffi::SQLITE_IOERR | (99 << 8)), "SQLITE_IOERR"); - } - - #[test] - fn blank_statements() { - assert!(is_blank(" ; -- x\n /* y */ ;")); - assert!(!is_blank("-- x\nselect 1")); - } - - #[tokio::test] - async fn formats_every_storage_class() { - let db = TempDb::new("values").await; - assert!(db.s().server_version.starts_with("SQLite 3.")); - assert_eq!(db.s().current_schema.as_deref(), Some("main")); - db.run("CREATE TABLE v (i INTEGER, r REAL, t TEXT, b BLOB, n NUMERIC, d DATETIME, j JSON, f BOOLEAN)") - .await; - db.run( - "INSERT INTO v VALUES (-42, 2.5, 'olá', x'00ff10', 12.50, '2024-05-01 13:45:00', '{\"a\":1}', 1)", - ) - .await; - db.run("INSERT INTO v VALUES (NULL, 3, NULL, NULL, NULL, NULL, NULL, NULL)") - .await; - let r = db.run("SELECT * FROM v").await; - let cols = r.columns.unwrap(); - let types: Vec<_> = cols.iter().map(|c| c.type_name.as_str()).collect(); - assert_eq!( - types, - ["INTEGER", "REAL", "TEXT", "BLOB", "NUMERIC", "DATETIME", "JSON", "BOOLEAN"] - ); - let kinds: Vec<_> = cols.iter().map(|c| c.kind).collect(); - assert_eq!( - kinds, - [ - ValueKind::Number, - ValueKind::Number, - ValueKind::Text, - ValueKind::Binary, - ValueKind::Number, - ValueKind::Temporal, - ValueKind::Json, - ValueKind::Bool - ] - ); - let row = - |i: usize| -> Vec> { r.rows[i].iter().map(|c| c.as_deref()).collect() }; - assert_eq!( - row(0), - [ - Some("-42"), - Some("2.5"), - Some("olá"), - Some("X'00FF10'"), - Some("12.5"), - Some("2024-05-01 13:45:00"), - Some("{\"a\":1}"), - Some("1") - ] - ); - // REAL affinity stores 3 as 3.0. - assert_eq!(row(1)[1], Some("3.0")); - assert_eq!(row(1)[0], None); - - let r = db - .run("SELECT 1 + 1 AS a, 0.1 + 0.2, 'x', x'0A', NULL, 1e300, typeof(1)") - .await; - let cols = r.columns.unwrap(); - let types: Vec<_> = cols.iter().map(|c| c.type_name.as_str()).collect(); - assert_eq!( - types, - ["INTEGER", "REAL", "TEXT", "BLOB", "NULL", "REAL", "TEXT"] - ); - assert_eq!(cols[0].name, "a"); - assert_eq!(cols[4].kind, ValueKind::Other); - let cells: Vec<_> = r.rows[0].iter().map(|c| c.as_deref()).collect(); - assert_eq!( - cells, - [ - Some("2"), - Some("0.30000000000000004"), - Some("x"), - Some("X'0A'"), - None, - Some("1.0e+300"), - Some("integer") - ] - ); - - let big = db.scalar("SELECT zeroblob(40000)").await.unwrap(); - assert!(big.starts_with("X'0000")); - assert!(big.ends_with("'… (40000 bytes)")); - assert_eq!( - big.len(), - 2 + BINARY_PREVIEW_BYTES * 2 + "'… (40000 bytes)".len() - ); - } - - #[tokio::test] - async fn applies_row_limit() { - let db = TempDb::new("limit").await; - let sql = "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 10) SELECT x FROM c"; - let r = db.run_limit(sql, 5).await; - assert_eq!(r.rows.len(), 5); - assert!(r.truncated); - assert_eq!(r.rows[4][0].as_deref(), Some("5")); - let r = db.run_limit(sql, 10).await; - assert_eq!(r.rows.len(), 10); - assert!(!r.truncated); - let r = db.run_limit(sql, 0).await; - assert_eq!(r.rows.len(), 10); - assert!(!r.truncated); - } - - #[tokio::test] - async fn reports_rows_affected() { - let db = TempDb::new("affected").await; - let r = db - .run("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)") - .await; - assert_eq!(r.rows_affected, None); - assert!(r.columns.is_none()); - let r = db - .run("INSERT INTO t (v) VALUES ('a'), ('b'), ('c');") - .await; - assert_eq!(r.rows_affected, Some(3)); - let r = db.run("UPDATE t SET v = 'z' WHERE id > 1").await; - assert_eq!(r.rows_affected, Some(2)); - // A DDL right after keeps no stale count. - let r = db.run("CREATE INDEX t_v ON t (v)").await; - assert_eq!(r.rows_affected, None); - let r = db.run("DELETE FROM t").await; - assert_eq!(r.rows_affected, Some(3)); - // INSERT ... RETURNING returns rows. - let r = db - .run("INSERT INTO t (v) VALUES ('r') RETURNING id, v") - .await; - assert_eq!(r.rows.len(), 1); - // Comments only: nothing to do. - let r = db.run("-- nothing\n;").await; - assert!(r.columns.is_none()); - // Trigger bodies arrive as one statement. - db.run("CREATE TABLE log (msg TEXT)").await; - db.run( - "CREATE TRIGGER t_ins AFTER INSERT ON t BEGIN\n INSERT INTO log VALUES (new.v);\n INSERT INTO log VALUES ('again');\nEND;", - ) - .await; - db.run("INSERT INTO t (v) VALUES ('x')").await; - assert_eq!( - db.scalar("SELECT count(*) FROM log").await.as_deref(), - Some("2") - ); - } - - #[tokio::test] - async fn maps_errors() { - let db = TempDb::new("errors").await; - let e = db.try_run("SELEC 1", 0).await.unwrap_err(); - assert_eq!(e.kind, ErrorKind::Database); - assert_eq!(e.code.as_deref(), Some("SQLITE_ERROR")); - assert_eq!(e.position, Some(0)); - assert!(e.message.contains("syntax error"), "{}", e.message); - - // Character offset, not bytes: 'ção' has multibyte characters. - let e = db.try_run("SELECT 'ção', FROM t", 0).await.unwrap_err(); - assert_eq!(e.position, Some(14)); - - let e = db.try_run("SELECT * FROM missing", 0).await.unwrap_err(); - assert_eq!(e.code.as_deref(), Some("SQLITE_ERROR")); - assert!(e.message.contains("no such table"), "{}", e.message); - - db.run("CREATE TABLE u (k TEXT UNIQUE)").await; - db.run("INSERT INTO u VALUES ('a')").await; - let e = db - .try_run("INSERT INTO u VALUES ('a')", 0) - .await - .unwrap_err(); - assert_eq!(e.code.as_deref(), Some("SQLITE_CONSTRAINT_UNIQUE")); - assert_eq!(e.kind, ErrorKind::Database); - - // Foreign keys are enforced. - db.run("CREATE TABLE p (id INTEGER PRIMARY KEY)").await; - db.run("CREATE TABLE c (p INTEGER REFERENCES p (id))").await; - let e = db.try_run("INSERT INTO c VALUES (7)", 0).await.unwrap_err(); - assert_eq!(e.code.as_deref(), Some("SQLITE_CONSTRAINT_FOREIGNKEY")); - - let e = db.try_run("SELECT 1; SELECT 2", 0).await.unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - } - - #[tokio::test] - async fn manual_transactions() { - let db = TempDb::new("manual").await; - db.run("CREATE TABLE t (v INTEGER)").await; - let st = db.s().set_autocommit(false).await.unwrap(); - assert!(!st.autocommit && !st.in_transaction); - - let r = db.run("INSERT INTO t VALUES (1)").await; - assert!(r.in_transaction); - assert!(db.s().tx_state().in_transaction); - let st = db.s().end_transaction(false).await.unwrap(); - assert!(!st.in_transaction); - let r = db.run("SELECT count(*) FROM t").await; - assert_eq!(r.rows[0][0].as_deref(), Some("0")); - // Reads also open the transaction in manual mode. - assert!(r.in_transaction); - - db.run("INSERT INTO t VALUES (2)").await; - let st = db.s().end_transaction(true).await.unwrap(); - assert!(!st.in_transaction); - assert_eq!( - db.scalar("SELECT count(*) FROM t").await.as_deref(), - Some("1") - ); - db.s().end_transaction(true).await.unwrap(); - - // A failing first statement does not leave an empty transaction. - let e = db.try_run("SELEC 1", 0).await.unwrap_err(); - assert_eq!(e.code.as_deref(), Some("SQLITE_ERROR")); - assert!(!db.s().tx_state().in_transaction); - - // A failing statement inside a transaction keeps earlier work. - db.run("INSERT INTO t VALUES (3)").await; - db.try_run("INSERT INTO nope VALUES (1)", 0) - .await - .unwrap_err(); - assert!(db.s().tx_state().in_transaction); - - // COMMIT typed by the user ends it. - let r = db.run("COMMIT").await; - assert!(!r.in_transaction); - assert!(!db.s().tx_state().in_transaction); - assert_eq!( - db.scalar("SELECT count(*) FROM t").await.as_deref(), - Some("2") - ); - - // Back to autocommit commits pending work. - db.run("INSERT INTO t VALUES (4)").await; - let st = db.s().set_autocommit(true).await.unwrap(); - assert!(st.autocommit && !st.in_transaction); - assert_eq!( - db.scalar("SELECT count(*) FROM t").await.as_deref(), - Some("3") - ); - assert!(!db.s().tx_state().in_transaction); - } - - #[tokio::test] - async fn user_typed_transaction_control() { - let db = TempDb::new("typed").await; - db.run("CREATE TABLE t (v INTEGER)").await; - let r = db.run("BEGIN").await; - assert!(r.in_transaction); - db.run("INSERT INTO t VALUES (1)").await; - db.run("SAVEPOINT sp").await; - db.run("INSERT INTO t VALUES (2)").await; - let r = db.run("ROLLBACK TO sp").await; - assert!(r.in_transaction); - let r = db.run("COMMIT").await; - assert!(!r.in_transaction); - assert_eq!( - db.scalar("SELECT count(*) FROM t").await.as_deref(), - Some("1") - ); - - db.run("BEGIN").await; - db.run("DELETE FROM t").await; - let r = db.run("ROLLBACK").await; - assert!(!r.in_transaction); - assert_eq!( - db.scalar("SELECT count(*) FROM t").await.as_deref(), - Some("1") - ); - assert!(db.s().tx_state().autocommit); - } - - #[tokio::test] - async fn interrupts_long_query() { - let mut db = TempDb::new("cancel").await; - let session = Arc::new(db.session.take().unwrap()); - let runner = session.clone(); - let task = tokio::spawn(async move { - runner - .execute(&ExecRequest { - sql: "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 1000000000) SELECT count(*) FROM c".into(), - max_rows: 0, - }) - .await - }); - tokio::time::sleep(std::time::Duration::from_millis(200)).await; - let started = Instant::now(); - session.cancel().await.unwrap(); - let e = task.await.unwrap().unwrap_err(); - assert_eq!(e.kind, ErrorKind::Cancelled); - assert_eq!(e.code.as_deref(), Some("SQLITE_INTERRUPT")); - assert!(started.elapsed() < std::time::Duration::from_secs(5)); - // The session is usable afterwards. - let r = session - .execute(&ExecRequest { - sql: "SELECT 1".into(), - max_rows: 0, - }) - .await - .unwrap(); - assert_eq!(r.rows[0][0].as_deref(), Some("1")); - drop(session); - } - - #[tokio::test] - async fn creates_file_only_when_asked() { - let path = temp_path("create"); - let e = connect(&profile(&path, false)).await.err().unwrap(); - assert_eq!(e.kind, ErrorKind::Connection); - assert_eq!( - e.message, - format!("Database file not found: {}", path.display()) - ); - assert!(!path.exists()); - - let session = connect(&profile(&path, true)).await.unwrap(); - assert!(path.exists()); - drop(session); - // Existing file opens without create_file. - let session = connect(&profile(&path, false)).await.unwrap(); - drop(session); - let _ = std::fs::remove_file(&path); - - // A file that is not a database fails at connect time. - let junk = temp_path("junk"); - std::fs::write(&junk, vec![b'x'; 4096]).unwrap(); - let e = connect(&profile(&junk, false)).await.err().unwrap(); - assert_eq!(e.kind, ErrorKind::Connection); - assert_eq!(e.code.as_deref(), Some("SQLITE_NOTADB")); - let _ = std::fs::remove_file(&junk); - } - - #[tokio::test] - async fn lists_metadata() { - let db = TempDb::new("meta").await; - let other = temp_path("meta-other"); - db.run( - "CREATE TABLE person (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, \ - score NUMERIC(10,2), full TEXT GENERATED ALWAYS AS (name || '!') VIRTUAL)", - ) - .await; - db.run("INSERT INTO person (name) VALUES ('a')").await; - db.run("CREATE VIEW people AS SELECT name FROM person") - .await; - db.run("CREATE TABLE another (x)").await; - db.run(&format!( - "ATTACH DATABASE '{}' AS extra", - other.display().to_string().replace('\'', "''") - )) - .await; - db.run("CREATE TABLE extra.ext (k TEXT, v BLOB, PRIMARY KEY (k, v))") - .await; - db.run("CREATE TEMP TABLE scratch (z)").await; - - let schemas = db.s().list_schemas().await.unwrap(); - assert_eq!(schemas, ["main", "extra", "temp"]); - - let objects = db.s().list_objects("main").await.unwrap(); - let names: Vec<_> = objects - .iter() - .map(|o| (o.kind.as_str(), o.name.as_str())) - .collect(); - // sqlite_sequence is internal and hidden. - assert_eq!( - names, - [ - ("table", "another"), - ("table", "person"), - ("view", "people") - ] - ); - let ext = db.s().list_objects("extra").await.unwrap(); - assert_eq!(ext.len(), 1); - assert_eq!(ext[0].name, "ext"); - let tmp = db.s().list_objects("temp").await.unwrap(); - assert_eq!(tmp[0].name, "scratch"); - - let cols = db.s().list_columns("main", "person").await.unwrap(); - let shape: Vec<_> = cols - .iter() - .map(|c| { - ( - c.name.as_str(), - c.type_name.as_str(), - c.nullable, - c.primary_key, - ) - }) - .collect(); - assert_eq!( - shape, - [ - ("id", "INTEGER", true, true), - ("name", "TEXT", false, false), - ("score", "NUMERIC(10,2)", true, false), - ("full", "TEXT", true, false), - ] - ); - let cols = db.s().list_columns("extra", "ext").await.unwrap(); - assert!(cols.iter().all(|c| c.primary_key)); - let cols = db.s().list_columns("main", "ext").await.unwrap(); - assert!(cols.is_empty()); - - db.run("DETACH DATABASE extra").await; - let _ = std::fs::remove_file(&other); - } - // Grid editing. - - use crate::model::CellValue; - - fn set(column: usize, value: Option<&str>) -> CellValue { - CellValue { - column, - value: value.map(str::to_string), - } - } - - fn key(values: &[Option<&str>]) -> Vec> { - values.iter().map(|v| v.map(str::to_string)).collect() - } - - fn ec(name: &str, type_name: &str) -> Option { - Some(EditColumn { - name: name.into(), - type_name: type_name.into(), - }) - } - - fn col(name: &str, type_name: &str) -> Option<(String, String)> { - Some((name.into(), type_name.into())) - } - - fn cols(columns: &[Option]) -> Vec> { - columns - .iter() - .map(|c| c.as_ref().map(|c| (c.name.clone(), c.type_name.clone()))) - .collect() - } - - impl TempDb { - async fn target(&self, sql: &str) -> EditTarget { - let r = self.run(sql).await; - assert_eq!(r.read_only_reason, None, "{sql}"); - r.editable.unwrap_or_else(|| panic!("{sql}: not editable")) - } - - async fn reason(&self, sql: &str) -> String { - let r = self.run(sql).await; - assert!(r.editable.is_none(), "{sql}: editable"); - r.read_only_reason - .unwrap_or_else(|| panic!("{sql}: no reason")) - } - - async fn apply( - &self, - target: &EditTarget, - changes: Vec, - ) -> AppResult { - self.s() - .apply_changes(&ApplyRequest { - target: target.clone(), - changes, - }) - .await - } - - async fn rows(&self, sql: &str) -> Vec>> { - self.run(sql).await.rows - } - } - - fn texts(rows: &[&[Option<&str>]]) -> Vec>> { - rows.iter() - .map(|r| r.iter().map(|c| c.map(str::to_string)).collect()) - .collect() - } - - #[test] - fn affinity_rules() { - assert_eq!(affinity("INTEGER"), Affinity::Integer); - assert_eq!(affinity("BIGINT"), Affinity::Integer); - // "POINT" contains INT, as in SQLite. - assert_eq!(affinity("POINT"), Affinity::Integer); - assert_eq!(affinity("VARCHAR(20)"), Affinity::Text); - assert_eq!(affinity("CLOB"), Affinity::Text); - assert_eq!(affinity("BLOB"), Affinity::Blob); - assert_eq!(affinity(""), Affinity::Blob); - assert_eq!(affinity("DOUBLE PRECISION"), Affinity::Real); - assert_eq!(affinity("FLOAT"), Affinity::Real); - assert_eq!(affinity("NUMERIC(10,2)"), Affinity::Numeric); - assert_eq!(affinity("DECIMAL"), Affinity::Numeric); - assert_eq!(affinity("BOOLEAN"), Affinity::Numeric); - assert_eq!(affinity("DATETIME"), Affinity::Numeric); - } - - #[test] - fn converts_text_by_affinity() { - let v = |t: &str, decl: &str| to_value(Some(t), decl).unwrap(); - assert_eq!(to_value(None, "INTEGER").unwrap(), Value::Null); - assert_eq!(v("-42", "INTEGER"), Value::Integer(-42)); - assert_eq!(v(" 7 ", "INT"), Value::Integer(7)); - assert_eq!(v("2.5", "INTEGER"), Value::Real(2.5)); - assert_eq!(v("abc", "INTEGER"), Value::Text("abc".into())); - assert_eq!(v("3.0", "REAL"), Value::Real(3.0)); - assert_eq!(v("1.0e+300", "REAL"), Value::Real(1e300)); - assert_eq!(v("-1.5e-7", "DOUBLE"), Value::Real(-1.5e-7)); - assert_eq!(v("Inf", "REAL"), Value::Real(f64::INFINITY)); - assert_eq!(v("-Inf", "REAL"), Value::Real(f64::NEG_INFINITY)); - assert_eq!(v("NaN", "REAL"), Value::Text("NaN".into())); - assert_eq!(v("12.5", "NUMERIC(10,2)"), Value::Real(12.5)); - assert_eq!(v("12", "DECIMAL"), Value::Integer(12)); - assert_eq!(v("0x10", "NUMERIC"), Value::Text("0x10".into())); - assert_eq!(v("true", "BOOLEAN"), Value::Integer(1)); - assert_eq!(v("FALSE", "BOOL"), Value::Integer(0)); - assert_eq!(v("true", "NUMERIC"), Value::Text("true".into())); - assert_eq!( - v("2024-05-01 13:45:00.123", "DATETIME"), - Value::Text("2024-05-01 13:45:00.123".into()) - ); - // TEXT affinity keeps everything as typed. - assert_eq!(v("42", "TEXT"), Value::Text("42".into())); - assert_eq!(v("X'00'", "VARCHAR"), Value::Text("X'00'".into())); - // No affinity: the display format tells the storage class. - assert_eq!(v("X'00FF10'", "BLOB"), Value::Blob(vec![0, 0xff, 0x10])); - assert_eq!(v("x''", ""), Value::Blob(vec![])); - assert_eq!(v("X'0'", "BLOB"), Value::Text("X'0'".into())); - assert_eq!(v("X'ZZ'", "BLOB"), Value::Text("X'ZZ'".into())); - assert_eq!(v("42", ""), Value::Integer(42)); - assert_eq!(v("007", ""), Value::Text("007".into())); - assert_eq!(v("3.0", "BLOB"), Value::Real(3.0)); - assert_eq!(v("3.50", ""), Value::Text("3.50".into())); - assert_eq!(v("hello", ""), Value::Text("hello".into())); - - let e = to_value(Some("X'0000'… (40000 bytes)"), "BLOB").unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - assert_eq!( - e.message, - "This value is only a preview and cannot be saved." - ); - // Ordinary text with an ellipsis is not a preview. - assert_eq!(v("wait… (2)", "TEXT"), Value::Text("wait… (2)".into())); - } - - #[test] - fn builds_statements() { - let target = EditTarget { - schema: Some("main".into()), - table: "lq_edit Odd \"T\"".into(), - columns: vec![ - ec("My Id", "INTEGER"), - ec("v", "TEXT"), - None, - ec("k2", "TEXT"), - ], - key: vec![0, 3], - }; - let steps = plan_changes( - &target, - &[ - RowChange::Update { - key: key(&[Some("1"), None]), - values: vec![set(1, Some("it's")), set(0, Some("2"))], - }, - RowChange::Update { - key: key(&[Some("9"), Some("x")]), - values: vec![], - }, - RowChange::Delete { - key: key(&[Some("3"), Some("b")]), - }, - RowChange::Insert { - values: vec![set(1, None), set(3, Some("k"))], - }, - RowChange::Insert { values: vec![] }, - ], - ) - .unwrap(); - let t = "\"main\".\"lq_edit Odd \"\"T\"\"\""; - assert_eq!( - steps, - [ - Step { - row: 1, - op: Op::Update, - sql: format!("UPDATE {t} SET \"v\" = ?, \"My Id\" = ? WHERE \"My Id\" = ? AND \"k2\" IS NULL"), - params: vec![Value::Text("it's".into()), Value::Integer(2), Value::Integer(1)], - }, - Step { - row: 3, - op: Op::Delete, - sql: format!("DELETE FROM {t} WHERE \"My Id\" = ? AND \"k2\" = ?"), - params: vec![Value::Integer(3), Value::Text("b".into())], - }, - Step { - row: 4, - op: Op::Insert, - sql: format!("INSERT INTO {t} (\"v\", \"k2\") VALUES (?, ?)"), - params: vec![Value::Null, Value::Text("k".into())], - }, - Step { - row: 5, - op: Op::Insert, - sql: format!("INSERT INTO {t} DEFAULT VALUES"), - params: vec![], - }, - ] - ); - - let e = plan_changes( - &target, - &[RowChange::Insert { - values: vec![set(2, Some("x"))], - }], - ) - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - let e = plan_changes( - &target, - &[RowChange::Delete { - key: key(&[Some("1")]), - }], - ) - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - let e = plan_changes( - &target, - &[RowChange::Update { - key: key(&[Some("1"), Some("a")]), - values: vec![set(1, Some("X'00'… (9 bytes)"))], - }], - ) - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - } - - #[test] - fn reads_query_plans() { - let shape = |lines: &[(i64, i64, &str)]| { - let lines: Vec<_> = lines - .iter() - .map(|&(a, b, d)| (a, b, d.to_string())) - .collect(); - let s = plan_shape(&lines); - (s.compound, s.sources) - }; - assert_eq!(shape(&[(2, 0, "SCAN t")]), (false, 1)); - // OR over two indexes is one scan. - assert_eq!( - shape(&[ - (4, 0, "MULTI-INDEX OR"), - (5, 4, "INDEX 1"), - (11, 5, "SEARCH t USING INDEX t_name (name=?)"), - (16, 4, "INDEX 2"), - (22, 16, "SEARCH t USING INDEX t_n (n=?)"), - ]), - (false, 1) - ); - // EXISTS as a semi-join, and subqueries in expressions. - assert_eq!( - shape(&[ - (4, 0, "SCAN t"), - (6, 0, "SEARCH u EXISTS USING PRIMARY KEY (a=?)") - ]), - (false, 1) - ); - assert_eq!( - shape(&[ - (2, 0, "SEARCH t USING INTEGER PRIMARY KEY (rowid=?)"), - (6, 0, "LIST SUBQUERY 2"), - (8, 6, "MERGE (UNION)"), - (10, 8, "LEFT"), - (13, 10, "SCAN u"), - (23, 0, "CORRELATED SCALAR SUBQUERY 1"), - (29, 23, "SCAN u"), - ]), - (false, 1) - ); - // Window functions read t through a co-routine. - assert_eq!( - shape(&[ - (3, 0, "CO-ROUTINE (subquery-2)"), - (6, 3, "SCAN t USING COVERING INDEX t_name"), - (18, 0, "SCAN (subquery-2)"), - ]), - (false, 1) - ); - // A subquery aliased with the name of its table. - assert_eq!( - shape(&[(2, 0, "CO-ROUTINE t"), (5, 2, "SCAN t"), (9, 0, "SCAN t")]), - (false, 1) - ); - // Joins, self-joins and compounds. - assert_eq!( - shape(&[ - (3, 0, "SCAN a"), - (5, 0, "SEARCH b USING INTEGER PRIMARY KEY (rowid=?)") - ]), - (false, 2) - ); - assert_eq!( - shape(&[ - (1, 0, "COMPOUND QUERY"), - (2, 1, "LEFT-MOST SUBQUERY"), - (4, 2, "SCAN t"), - (10, 1, "UNION ALL"), - (12, 10, "SCAN CONSTANT ROW"), - ]), - (true, 1) - ); - assert!( - shape(&[ - (2, 0, "CO-ROUTINE r"), - (5, 2, "SETUP"), - (7, 5, "SCAN t"), - (20, 2, "RECURSIVE STEP"), - (21, 20, "SCAN r"), - (31, 0, "SCAN r"), - ]) - .0 - ); - assert_eq!(shape(&[(2, 0, "SCAN CONSTANT ROW")]), (false, 0)); - } - - #[tokio::test] - async fn detects_editable_results() { - let db = TempDb::new("edit-detect").await; - db.run( - "CREATE TABLE lq_edit_t (id INTEGER PRIMARY KEY, name TEXT NOT NULL, n NUMERIC(10,2), \ - g TEXT GENERATED ALWAYS AS (name || '!') VIRTUAL)", - ) - .await; - db.run("CREATE INDEX lq_edit_t_name ON lq_edit_t (name)") - .await; - db.run("CREATE INDEX lq_edit_t_n ON lq_edit_t (n)").await; - db.run("INSERT INTO lq_edit_t (name, n) VALUES ('a', 1), ('b', 2)") - .await; - db.run("CREATE TABLE lq_edit_c (b TEXT, a INT, v TEXT, PRIMARY KEY (b, a)) WITHOUT ROWID") - .await; - db.run("CREATE TABLE lq_edit_nk (x INT, y TEXT)").await; - db.run("CREATE TABLE lq_edit_u (code TEXT NOT NULL UNIQUE, maybe TEXT UNIQUE, v TEXT)") - .await; - db.run("CREATE VIEW lq_edit_v AS SELECT id, name FROM lq_edit_t WHERE id > 0") - .await; - db.run("CREATE VIEW lq_edit_vu AS SELECT id, name FROM lq_edit_t UNION ALL SELECT x, y FROM lq_edit_nk") - .await; - - let t = db - .target("SELECT id, name, name || '?' AS e, n, g FROM lq_edit_t") - .await; - assert_eq!(t.schema.as_deref(), Some("main")); - assert_eq!(t.table, "lq_edit_t"); - assert_eq!(t.key, [0]); - assert_eq!( - cols(&t.columns), - [ - col("id", "INTEGER"), - col("name", "TEXT"), - None, - col("n", "NUMERIC(10,2)"), - // Generated columns cannot be written. - None, - ] - ); - assert_eq!( - db.target("SELECT name, id AS k FROM lq_edit_t").await.key, - [1] - ); - // rowid of a table with INTEGER PRIMARY KEY is the key column. - assert_eq!( - cols(&db.target("SELECT rowid, name FROM lq_edit_t").await.columns)[0], - col("id", "INTEGER") - ); - // Composite key in key order, whatever the result order. - assert_eq!(db.target("SELECT v, a, b FROM lq_edit_c").await.key, [2, 1]); - // Filters, sorting, OR over indexes, subqueries and window functions. - for sql in [ - "SELECT * FROM lq_edit_t WHERE name = 'a' OR n = 2 ORDER BY name", - "SELECT * FROM lq_edit_t WHERE id IN (SELECT a FROM lq_edit_c)", - "SELECT * FROM lq_edit_t t WHERE EXISTS (SELECT 1 FROM lq_edit_c c WHERE c.b = t.name)", - "SELECT id, (SELECT count(*) FROM lq_edit_c) AS c FROM lq_edit_t", - "SELECT id, name, row_number() OVER (ORDER BY name) FROM lq_edit_t", - "SELECT * FROM (SELECT id, name FROM lq_edit_t ORDER BY name LIMIT 5)", - "WITH c AS (SELECT * FROM lq_edit_t) SELECT * FROM c", - // SQLite resolves view columns to the base table. - "SELECT * FROM lq_edit_v", - ] { - let t = db.target(sql).await; - assert_eq!(t.table, "lq_edit_t", "{sql}"); - assert_eq!(t.key, [0], "{sql}"); - } - assert_eq!( - cols( - &db.target("SELECT id, (SELECT 1) FROM lq_edit_t") - .await - .columns - )[1], - None - ); - - assert_eq!( - db.reason("SELECT t.id, c.v FROM lq_edit_t t JOIN lq_edit_c c ON c.b = t.name") - .await, - "Read-only: the result combines columns from several tables." - ); - assert_eq!( - db.reason("SELECT a.id, b.name FROM lq_edit_t a JOIN lq_edit_t b ON b.id = a.id + 1") - .await, - "Read-only: the result combines rows from several tables." - ); - assert_eq!( - db.reason("SELECT id, name FROM lq_edit_t UNION ALL SELECT 9, 'z'") - .await, - "Read-only: the result combines rows from several queries." - ); - assert_eq!( - db.reason("SELECT * FROM lq_edit_vu").await, - "Read-only: the result combines rows from several queries." - ); - assert_eq!( - db.reason("SELECT 1, 'x'").await, - "Read-only: only rows from a table can be edited." - ); - assert_eq!( - db.reason("SELECT count(*) FROM lq_edit_t").await, - "Read-only: only rows from a table can be edited." - ); - assert_eq!( - db.reason("SELECT name, n FROM lq_edit_t").await, - "Read-only: add the primary key columns (id) to the query to edit rows." - ); - assert_eq!( - db.reason("SELECT v, a FROM lq_edit_c").await, - "Read-only: add the primary key columns (b, a) to the query to edit rows." - ); - assert_eq!( - db.reason("SELECT * FROM lq_edit_nk").await, - "Read-only: table lq_edit_nk has no primary key; add rowid to the query to edit rows." - ); - // Without a primary key: rowid, oid or _rowid_ in the result. - for sql in [ - "SELECT rowid, * FROM lq_edit_nk", - "SELECT x, oid FROM lq_edit_nk", - "SELECT _rowid_, y FROM lq_edit_nk", - ] { - let t = db.target(sql).await; - let i = t.key[0]; - assert_eq!(cols(&t.columns)[i], col("rowid", "INTEGER"), "{sql}"); - } - // A UNIQUE NOT NULL key; the nullable one does not count. - assert_eq!(db.target("SELECT v, code FROM lq_edit_u").await.key, [1]); - assert_eq!( - db.reason("SELECT v, maybe FROM lq_edit_u").await, - "Read-only: table lq_edit_u has no primary key; add rowid to the query to edit rows." - ); - - // Attached and temporary schemas. - let other = temp_path("edit-detect-other"); - db.run(&format!( - "ATTACH DATABASE '{}' AS extra", - other.display().to_string().replace('\'', "''") - )) - .await; - db.run("CREATE TABLE extra.lq_edit_t (k TEXT PRIMARY KEY, v)") - .await; - db.run("CREATE TEMP TABLE lq_edit_tmp (k INTEGER PRIMARY KEY, v)") - .await; - let t = db.target("SELECT v, k FROM extra.lq_edit_t").await; - assert_eq!( - (t.schema.as_deref(), t.key.as_slice()), - (Some("extra"), &[1][..]) - ); - assert_eq!(cols(&t.columns)[0], col("v", "")); - let t = db.target("SELECT * FROM lq_edit_tmp").await; - assert_eq!(t.schema.as_deref(), Some("temp")); - - // Statements that are not queries say nothing. - for sql in [ - "PRAGMA table_info(lq_edit_t)", - "INSERT INTO lq_edit_nk VALUES (1, 'r') RETURNING *", - "EXPLAIN QUERY PLAN SELECT * FROM lq_edit_t", - ] { - let r = db.run(sql).await; - assert!( - r.editable.is_none() && r.read_only_reason.is_none(), - "{sql}" - ); - } - - // Keys are reloaded after DDL. - db.run("DROP TABLE lq_edit_nk").await; - db.run("CREATE TABLE lq_edit_nk (x INT PRIMARY KEY, y TEXT)") - .await; - assert_eq!(db.target("SELECT y, x FROM lq_edit_nk").await.key, [1]); - - db.run("DETACH DATABASE extra").await; - let _ = std::fs::remove_file(&other); - } - - #[tokio::test] - async fn applies_updates_deletes_and_inserts() { - let db = TempDb::new("edit-apply").await; - db.run("CREATE TABLE lq_edit_t (id INTEGER PRIMARY KEY, name TEXT NOT NULL DEFAULT 'none', n INT DEFAULT 5)") - .await; - db.run("INSERT INTO lq_edit_t (name, n) VALUES ('a', 1), ('b', 2), ('c', 3)") - .await; - let t = db.target("SELECT id, name, n, n * 2 FROM lq_edit_t").await; - let r = db - .apply( - &t, - vec![ - RowChange::Update { - key: key(&[Some("1")]), - values: vec![set(1, Some("a'2\nline")), set(2, None)], - }, - RowChange::Delete { - key: key(&[Some("2")]), - }, - RowChange::Insert { - values: vec![set(1, Some("d"))], - }, - RowChange::Insert { values: vec![] }, - ], - ) - .await - .unwrap(); - assert_eq!((r.updated, r.deleted, r.inserted), (1, 1, 2)); - assert!(!r.in_transaction); - assert!(!db.s().tx_state().in_transaction); - assert_eq!( - db.rows("SELECT id, name, n FROM lq_edit_t ORDER BY id") - .await, - texts(&[ - &[Some("1"), Some("a'2\nline"), None], - &[Some("3"), Some("c"), Some("3")], - &[Some("4"), Some("d"), Some("5")], - &[Some("5"), Some("none"), Some("5")], - ]) - ); - // Changing the key itself. - db.apply( - &t, - vec![RowChange::Update { - key: key(&[Some("5")]), - values: vec![set(0, Some("50"))], - }], - ) - .await - .unwrap(); - assert_eq!( - db.scalar("SELECT name FROM lq_edit_t WHERE id = 50") - .await - .as_deref(), - Some("none") - ); - // A column that is not in the table. - let e = db - .apply( - &t, - vec![RowChange::Update { - key: key(&[Some("1")]), - values: vec![set(3, Some("1"))], - }], - ) - .await - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - - // A table without a key, edited through rowid. - db.run("CREATE TABLE lq_edit_nk (x INT, y TEXT)").await; - db.run("INSERT INTO lq_edit_nk VALUES (1, 'same'), (2, 'same')") - .await; - let t = db.target("SELECT rowid, x, y FROM lq_edit_nk").await; - db.apply( - &t, - vec![ - RowChange::Update { - key: key(&[Some("2")]), - values: vec![set(2, Some("other"))], - }, - RowChange::Delete { - key: key(&[Some("1")]), - }, - ], - ) - .await - .unwrap(); - assert_eq!( - db.rows("SELECT rowid, x, y FROM lq_edit_nk").await, - texts(&[&[Some("2"), Some("2"), Some("other")]]) - ); - } - - #[tokio::test] - async fn round_trips_displayed_values() { - let db = TempDb::new("edit-roundtrip").await; - db.run( - "CREATE TABLE lq_edit_types (id INTEGER PRIMARY KEY, i INTEGER, bi BIGINT, r REAL, \ - d DOUBLE, num NUMERIC(10,2), dec DECIMAL(20,6), b BOOLEAN, dt DATE, ts DATETIME, \ - tz TIMESTAMP WITH TIME ZONE, t TEXT, vc VARCHAR(40), bl BLOB, u, nu TEXT)", - ) - .await; - db.run( - "INSERT INTO lq_edit_types VALUES (1, -42, 9223372036854775807, 2.5, 0.30000000000000004, \ - 12.5, 1234567.125, 1, '2024-02-29', '2024-05-01 13:45:00.123456', \ - '2024-05-01T13:45:00.123+02:00', 'it''s \"q\"' || char(10) || 'line 2', 'olá', \ - x'00FF10', 7, NULL)", - ) - .await; - db.run( - "INSERT INTO lq_edit_types VALUES (2, 0, -9223372036854775808, 1e300, -1.5e-7, \ - 100, -0.5, 0, '1999-12-31', '2000-01-01 00:00:00', '2000-01-01T00:00:00Z', '', \ - '42', x'', 2.5, 'x')", - ) - .await; - db.run( - "INSERT INTO lq_edit_types VALUES (3, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, \ - NULL, NULL, NULL, NULL, NULL, 'text in untyped', NULL)", - ) - .await; - let typed = "SELECT * FROM lq_edit_types ORDER BY id"; - let classes = "SELECT id, typeof(i), typeof(bi), typeof(r), typeof(d), typeof(num), \ - typeof(dec), typeof(b), typeof(dt), typeof(ts), typeof(tz), typeof(t), \ - typeof(vc), typeof(bl), typeof(u), typeof(nu) FROM lq_edit_types ORDER BY id"; - let before = db.run(typed).await; - let classes_before = db.rows(classes).await; - let target = before.editable.clone().unwrap(); - assert_eq!(target.key, [0]); - - // Write every displayed value back, keys included. - let changes: Vec = before - .rows - .iter() - .map(|row| RowChange::Update { - key: vec![row[0].clone()], - values: row - .iter() - .enumerate() - .map(|(i, v)| CellValue { - column: i, - value: v.clone(), - }) - .collect(), - }) - .collect(); - let r = db.apply(&target, changes).await.unwrap(); - assert_eq!(r.updated, 3); - assert_eq!(db.rows(typed).await, before.rows); - assert_eq!(db.rows(classes).await, classes_before); - - // Values typed in the grid. - db.apply( - &target, - vec![RowChange::Update { - key: key(&[Some("3")]), - values: vec![ - set(1, Some("12")), - set(3, Some("3")), - set(5, Some("9.99")), - set(7, Some("true")), - set(13, Some("X'CAFE'")), - ], - }], - ) - .await - .unwrap(); - assert_eq!( - db.rows( - "SELECT typeof(i), r, typeof(r), num, b, hex(bl) FROM lq_edit_types WHERE id = 3" - ) - .await, - texts(&[&[ - Some("integer"), - Some("3.0"), - Some("real"), - Some("9.99"), - Some("1"), - Some("CAFE") - ]]) - ); - - // A preview of a large blob cannot be saved. - db.run("UPDATE lq_edit_types SET bl = zeroblob(40000) WHERE id = 1") - .await; - let preview = db.scalar("SELECT bl FROM lq_edit_types WHERE id = 1").await; - let e = db - .apply( - &target, - vec![RowChange::Update { - key: key(&[Some("1")]), - values: vec![set(13, preview.as_deref())], - }], - ) - .await - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Invalid); - assert_eq!( - e.message, - "This value is only a preview and cannot be saved." - ); - } - - #[tokio::test] - async fn failed_change_rolls_back_the_batch() { - let db = TempDb::new("edit-rollback").await; - db.run("CREATE TABLE lq_edit_t (id INTEGER PRIMARY KEY, name TEXT UNIQUE)") - .await; - db.run("INSERT INTO lq_edit_t VALUES (1, 'a'), (2, 'b')") - .await; - let t = db.target("SELECT id, name FROM lq_edit_t").await; - let before = db.rows("SELECT * FROM lq_edit_t ORDER BY id").await; - - let e = db - .apply( - &t, - vec![ - RowChange::Update { - key: key(&[Some("1")]), - values: vec![set(1, Some("changed"))], - }, - RowChange::Insert { - values: vec![set(1, Some("new"))], - }, - RowChange::Update { - key: key(&[Some("99")]), - values: vec![set(1, Some("gone"))], - }, - ], - ) - .await - .unwrap_err(); - assert_eq!(e.kind, ErrorKind::Database); - assert_eq!( - e.message, - "Row 3 was not saved: 0 rows matched its key (changed or removed by someone else)." - ); - assert_eq!(db.rows("SELECT * FROM lq_edit_t ORDER BY id").await, before); - assert!(!db.s().tx_state().in_transaction); - - // Server errors keep their code and name the row. - let e = db - .apply( - &t, - vec![ - RowChange::Delete { - key: key(&[Some("1")]), - }, - RowChange::Update { - key: key(&[Some("2")]), - values: vec![set(1, Some("x"))], - }, - RowChange::Insert { - values: vec![set(1, Some("x"))], - }, - ], - ) - .await - .unwrap_err(); - assert_eq!(e.code.as_deref(), Some("SQLITE_CONSTRAINT_UNIQUE")); - assert!( - e.message.starts_with("Row 3 was not saved: UNIQUE"), - "{}", - e.message - ); - assert_eq!(e.position, None); - assert_eq!(db.rows("SELECT * FROM lq_edit_t ORDER BY id").await, before); - - // The session is still usable. - db.apply( - &t, - vec![RowChange::Delete { - key: key(&[Some("2")]), - }], - ) - .await - .unwrap(); - assert_eq!( - db.scalar("SELECT count(*) FROM lq_edit_t").await.as_deref(), - Some("1") - ); - } - - #[tokio::test] - async fn manual_commit_keeps_the_transaction() { - let db = TempDb::new("edit-manual").await; - db.run("CREATE TABLE lq_edit_t (id INTEGER PRIMARY KEY, v TEXT)") - .await; - db.run("INSERT INTO lq_edit_t VALUES (1, 'a')").await; - let t = db.target("SELECT id, v FROM lq_edit_t").await; - db.s().set_autocommit(false).await.unwrap(); - db.s().end_transaction(false).await.unwrap(); - - let r = db - .apply( - &t, - vec![RowChange::Insert { - values: vec![set(1, Some("b"))], - }], - ) - .await - .unwrap(); - assert!(r.in_transaction); - assert!(db.s().tx_state().in_transaction); - db.s().end_transaction(false).await.unwrap(); - assert_eq!( - db.scalar("SELECT count(*) FROM lq_edit_t").await.as_deref(), - Some("1") - ); - - // Inside an open transaction a failed batch undoes only itself. - db.run("INSERT INTO lq_edit_t VALUES (2, 'mine')").await; - let e = db - .apply( - &t, - vec![ - RowChange::Update { - key: key(&[Some("1")]), - values: vec![set(1, Some("z"))], - }, - RowChange::Delete { - key: key(&[Some("7")]), - }, - ], - ) - .await - .unwrap_err(); - assert!( - e.message.starts_with("Row 2 was not saved"), - "{}", - e.message - ); - assert!(db.s().tx_state().in_transaction); - assert_eq!( - db.rows("SELECT id, v FROM lq_edit_t ORDER BY id").await, - texts(&[&[Some("1"), Some("a")], &[Some("2"), Some("mine")]]) - ); - let r = db - .apply( - &t, - vec![RowChange::Update { - key: key(&[Some("1")]), - values: vec![set(1, Some("z"))], - }], - ) - .await - .unwrap(); - assert!(r.in_transaction); - db.s().end_transaction(true).await.unwrap(); - assert_eq!( - db.rows("SELECT id, v FROM lq_edit_t ORDER BY id").await, - texts(&[&[Some("1"), Some("z")], &[Some("2"), Some("mine")]]) - ); - - // Autocommit with a transaction the user opened: it stays open. - db.s().set_autocommit(true).await.unwrap(); - db.run("BEGIN").await; - let r = db - .apply( - &t, - vec![RowChange::Delete { - key: key(&[Some("2")]), - }], - ) - .await - .unwrap(); - assert!(r.in_transaction); - db.run("ROLLBACK").await; - assert_eq!( - db.scalar("SELECT count(*) FROM lq_edit_t").await.as_deref(), - Some("2") - ); - } - - #[tokio::test] - async fn edits_names_that_need_quoting() { - let db = TempDb::new("edit-quoting").await; - db.run("CREATE TABLE \"lq_edit Mixed Case\" (\"My Id\" INTEGER PRIMARY KEY, \"Some \"\"Value\"\"\" TEXT)") - .await; - db.run("INSERT INTO \"lq_edit Mixed Case\" VALUES (1, 'a'), (2, 'b')") - .await; - let t = db - .target("SELECT \"Some \"\"Value\"\"\" AS v, \"My Id\" FROM \"lq_edit Mixed Case\" AS \"q r\"") - .await; - assert_eq!(t.table, "lq_edit Mixed Case"); - assert_eq!(t.key, [1]); - assert_eq!(cols(&t.columns)[0], col("Some \"Value\"", "TEXT")); - let r = db - .apply( - &t, - vec![ - RowChange::Update { - key: key(&[Some("1")]), - values: vec![set(0, Some("A"))], - }, - RowChange::Delete { - key: key(&[Some("2")]), - }, - RowChange::Insert { - values: vec![set(0, Some("c")), set(1, Some("10"))], - }, - ], - ) - .await - .unwrap(); - assert_eq!((r.updated, r.deleted, r.inserted), (1, 1, 1)); - assert_eq!( - db.rows("SELECT * FROM \"lq_edit Mixed Case\" ORDER BY 1") - .await, - texts(&[&[Some("1"), Some("A")], &[Some("10"), Some("c")]]) - ); - } - - #[tokio::test] - async fn result_view_sql() { - let path = temp_path("view"); - let s = crate::drivers::Session::open(&profile(&path, true), None) - .await - .unwrap(); - crate::drivers::view_fixtures::check(&s, "sqlite").await; - drop(s); - let _ = std::fs::remove_file(&path); - } - - #[tokio::test] - async fn ddl_sql() { - let path = temp_path("ddl"); - let s = crate::drivers::Session::open(&profile(&path, true), None) - .await - .unwrap(); - crate::drivers::ddl_fixtures::check(&s, "sqlite", "main").await; - drop(s); - let _ = std::fs::remove_file(&path); - } - - #[tokio::test] - async fn export_import_round_trip() { - let path = temp_path("xfer"); - let s = crate::drivers::Session::open(&profile(&path, true), None) - .await - .unwrap(); - crate::transfer::round_trip::check(&s, "main").await; - drop(s); - let _ = std::fs::remove_file(&path); - } -} diff --git a/src-tauri/src/drivers/sqlserver.rs b/src-tauri/src/drivers/sqlserver.rs deleted file mode 100644 index 1018ca5..0000000 --- a/src-tauri/src/drivers/sqlserver.rs +++ /dev/null @@ -1,3404 +0,0 @@ -//! SQL Server session over TDS, using `tiberius`. -//! -//! - Each call is sent as a SQL batch, so temporary tables, `USE` and `SET` -//! options persist across calls, as in SSMS. The UI splits scripts on `GO`. -//! - Plain `SELECT` statements are limited by the server with -//! `SET ROWCOUNT`; everything else stops keeping rows at the limit. -//! - Manual commit uses `SET IMPLICIT_TRANSACTIONS ON`; `@@TRANCOUNT` is read -//! after every call, so the transaction flag is what the server reports. -//! - Cancel sends a TDS attention to the running batch. -//! - tiberius does not expose INFO tokens (PRINT, low-severity RAISERROR) nor -//! per-statement DONE counts, so there are no notices from the server and -//! `rows_affected` is `ROWCOUNT_BIG()` of the batch's last statement. -//! - Grid editing: plain queries are described by the server -//! (`sys.dm_exec_describe_first_result_set` in browse mode) together with -//! the unique keys of the source table, in one extra call. Edits are -//! applied with `sp_executesql` and explicit, style-fixed conversions. - -use std::fmt::Write as _; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::{Duration, Instant}; - -use futures_util::TryStreamExt; -use parking_lot::Mutex; -use tiberius::numeric::Numeric; -use tiberius::time::{Date, DateTime, DateTime2, DateTimeOffset, SmallDateTime, Time}; -use tiberius::{ - AuthMethod, Client, Column, ColumnData, ColumnType, Config, EncryptionLevel, QueryItem, Row, - SqlBrowser, ToSql, -}; -use tokio::net::TcpStream; -use tokio_util::compat::{Compat, TokioAsyncWriteCompatExt}; - -use super::{first_keywords, RowSink, StreamEvent, TxState, STREAM_BATCH}; -use crate::error::{AppError, AppResult, ErrorKind}; -use crate::model::{ - ApplyRequest, ApplyResult, ColumnInfo, ConnectionProfile, DbColumn, DbObject, EditColumn, - EditTarget, ExecRequest, ExecResult, RowChange, SslMode, ValueKind, -}; - -type MsClient = Client>; - -const CONNECT_TIMEOUT: Duration = Duration::from_secs(15); -/// How long to wait for the server to acknowledge a cancel. -const CANCEL_TIMEOUT: Duration = Duration::from_secs(15); -const BINARY_PREVIEW_BYTES: usize = 32 * 1024; -/// Days from 0001-01-01 and from 1900-01-01 to 1970-01-01. -const DAYS_0001_TO_EPOCH: i64 = 719_162; -const DAYS_1900_TO_EPOCH: i64 = 25_567; -/// Login failed (bad user or password, or an account without access). -const LOGIN_FAILED: u32 = 18456; -/// Cannot open the database requested by the login. -const CANNOT_OPEN_DATABASE: u32 = 4060; -const ONLY_TABLE_ROWS: &str = "Read-only: only rows from a table can be edited."; -/// Marks a binary value cut by `hex`. -const PREVIEW_MARK: &str = "… ("; - -/// Describes the first result set of `@P1` in browse mode (base tables, hidden -/// key columns) and lists the unique keys of the tables it reads, in one -/// call. Describe errors come back as rows, not as raised errors. A -/// transaction opened only by this call (manual-commit mode) is ended here. -const DESCRIBE_SQL: &str = "DECLARE @lq_tc int = @@TRANCOUNT; -DECLARE @lq_d TABLE (ord int, hidden bit, other_db bit, sch nvarchar(128), tab nvarchar(128), - col nvarchar(128), type_name nvarchar(256), computed bit, err nvarchar(4000)); -INSERT INTO @lq_d -SELECT column_ordinal, is_hidden, - CASE WHEN source_server IS NOT NULL OR source_database <> DB_NAME() THEN 1 ELSE 0 END, - source_schema, source_table, source_column, - COALESCE(system_type_name, CASE WHEN user_type_schema = N'sys' THEN user_type_name END), - is_computed_column, error_message -FROM sys.dm_exec_describe_first_result_set(@P1, NULL, 1); -SELECT hidden, other_db, sch, tab, col, type_name, computed, err FROM @lq_d ORDER BY ord; -SELECT o.sch, o.tab, i.index_id, i.is_primary_key, c.name, c.is_nullable -FROM (SELECT DISTINCT sch, tab FROM @lq_d WHERE tab IS NOT NULL AND other_db = 0) o -JOIN sys.indexes i ON i.object_id = OBJECT_ID(QUOTENAME(o.sch) + N'.' + QUOTENAME(o.tab)) -JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id - AND ic.key_ordinal > 0 -JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id -WHERE i.is_unique = 1 AND i.has_filter = 0 AND i.is_disabled = 0 AND i.is_hypothetical = 0 -ORDER BY o.sch, o.tab, i.is_primary_key DESC, i.index_id, ic.key_ordinal; -IF @@TRANCOUNT > @lq_tc COMMIT TRAN;"; - -pub struct MsSession { - client: tokio::sync::Mutex, - /// Kept to reopen the connection when a cancel cannot be acknowledged. - profile: ConnectionProfile, - password: Option, - cancel: tokio::sync::Notify, - broken: AtomicBool, - state: Mutex, - pub server_version: String, - pub current_user: Option, - pub current_schema: Option, -} - -pub async fn connect(profile: &ConnectionProfile, password: Option<&str>) -> AppResult { - let mut client = dial(profile, password).await?; - let rows = fetch( - &mut client, - "SELECT CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(128)), - CAST(SERVERPROPERTY('EngineEdition') AS int), SUSER_SNAME(), SCHEMA_NAME()", - ) - .await - .map_err(connection_error)?; - let mut row = rows.into_iter().next().unwrap_or_default().into_iter(); - let version = row.next().flatten().unwrap_or_default(); - let edition = row - .next() - .flatten() - .and_then(|e| e.parse().ok()) - .unwrap_or(0); - - Ok(MsSession { - server_version: server_label(&version, edition), - current_user: row.next().flatten(), - current_schema: row.next().flatten(), - client: tokio::sync::Mutex::new(client), - profile: profile.clone(), - password: password.map(str::to_string), - cancel: tokio::sync::Notify::new(), - broken: AtomicBool::new(false), - state: Mutex::new(TxState { - autocommit: true, - in_transaction: false, - }), - }) -} - -/// Opens a connection with the session defaults applied. -async fn dial(profile: &ConnectionProfile, password: Option<&str>) -> AppResult { - let (config, browser) = build_config(profile, password, None)?; - let client = match open_client(config, browser).await { - // Azure gateways may redirect the login to another node. - Err(tiberius::error::Error::Routing { host, port }) => { - let (config, _) = build_config(profile, password, Some((host, port)))?; - open_client(config, false).await - } - other => other, - }; - let mut client = client.map_err(connection_error)?; - fetch( - &mut client, - "SET TEXTSIZE 2147483647; SET IMPLICIT_TRANSACTIONS OFF; SELECT 1", - ) - .await - .map_err(connection_error)?; - Ok(client) -} - -/// Builds the tiberius configuration. Returns whether the port must be -/// resolved through the SQL Browser service (named instance without an -/// explicit port). `target` overrides host and port after a routing redirect. -fn build_config( - profile: &ConnectionProfile, - password: Option<&str>, - target: Option<(String, u16)>, -) -> AppResult<(Config, bool)> { - let mut config = Config::new(); - let instance = profile.instance.trim(); - let mut browser = false; - match target { - Some((host, port)) => { - config.host(host); - config.port(port); - } - None => { - config.host(profile.host.trim()); - if !instance.is_empty() { - config.instance_name(instance); - } - // With a named instance, the default port means "ask SQL Browser". - if !instance.is_empty() && matches!(profile.port, 0 | 1433) { - browser = true; - } else { - config.port(if profile.port == 0 { - 1433 - } else { - profile.port - }); - } - } - } - if !profile.database.trim().is_empty() { - config.database(profile.database.trim()); - } - config.application_name("LowQuery"); - config.handshake_timeout(Some(CONNECT_TIMEOUT)); - // Long-running statements are interrupted by the user, not by a timer. - config.command_timeout(None); - config.lossy_utf16_decoding(true); - match profile.ssl_mode { - // Only the login packet is encrypted, as SSMS does with Encrypt=false. - SslMode::Disable => { - config.encryption(EncryptionLevel::Off); - config.trust_cert(); - } - SslMode::Prefer => { - config.encryption(EncryptionLevel::On); - config.trust_cert(); - } - SslMode::Require => { - config.encryption(EncryptionLevel::Required); - config.trust_cert(); - } - SslMode::VerifyFull => config.encryption(EncryptionLevel::Required), - } - config.authentication(if profile.windows_auth { - windows_auth()? - } else { - AuthMethod::sql_server(profile.user.trim(), password.unwrap_or_default()) - }); - Ok((config, browser)) -} - -#[cfg(windows)] -fn windows_auth() -> AppResult { - Ok(AuthMethod::Integrated) -} - -#[cfg(not(windows))] -fn windows_auth() -> AppResult { - Err(AppError::invalid( - "Windows authentication is only available when LowQuery runs on Windows.", - )) -} - -async fn open_client(config: Config, browser: bool) -> tiberius::Result { - let addr = config.get_addr(); - let tcp = tokio::time::timeout(CONNECT_TIMEOUT, async { - if browser { - TcpStream::connect_named(&config).await - } else { - Ok(TcpStream::connect(&addr).await?) - } - }) - .await - .map_err(|_| tiberius::error::Error::Io { - kind: std::io::ErrorKind::TimedOut, - message: format!("Timed out connecting to {addr}."), - })??; - tcp.set_nodelay(true)?; - Client::connect(config, tcp.compat_write()).await -} - -fn server_label(version: &str, engine_edition: i64) -> String { - match engine_edition { - // 5: Azure SQL Database, 8: Azure SQL Managed Instance. - 5 | 8 => format!("Azure SQL {version}"), - _ => format!("SQL Server {version}"), - } -} - -/// Rows read from the first result set of a batch. -#[derive(Default)] -struct Batch { - columns: Option>, - rows: Vec>>, - truncated: bool, -} - -/// What the server reports after a batch. -struct After { - rowcount: u64, - trancount: i64, - xact_state: i64, -} - -impl MsSession { - /// Applies grid edits as one unit. With no transaction open, they run in - /// one that commits (autocommit) or stays open (manual commit). Inside an - /// open transaction they run after a savepoint, so a failure undoes only - /// them. - pub async fn apply_changes(&self, req: &ApplyRequest) -> AppResult { - let target = &req.target; - let table = qualified(target.schema.as_deref(), &target.table); - let mut client = self.lock().await?; - let autocommit = self.state.lock().autocommit; - let started = Instant::now(); - - // State, identity columns, and the transaction or savepoint in one - // trip. Sent as a plain batch: BEGIN TRAN inside sp_executesql would - // change the transaction count of the call. - let start = format!( - "DECLARE @lq_tc int = @@TRANCOUNT, @lq_xs int = XACT_STATE(); - SELECT @lq_tc, @lq_xs; - SELECT name FROM sys.identity_columns WHERE object_id = OBJECT_ID({}); - IF @lq_xs = 1 SAVE TRAN lq_apply; - ELSE IF @lq_xs = 0 AND @@TRANCOUNT = 0 BEGIN TRAN;", - nstr(&table) - ); - let sets = fetch_all(&mut client, &start) - .await - .map_err(|e| self.fail(e, None))?; - let state_rows = sets.first().map(Vec::as_slice).unwrap_or_default(); - let (trancount, xact_state) = (int_at(state_rows, 0), int_at(state_rows, 1)); - if xact_state == -1 { - return Err(doomed()); - } - let identity: Vec = sets - .get(1) - .map(|rows| rows.iter().filter_map(|r| r.first().cloned().flatten())) - .into_iter() - .flatten() - .collect(); - // Whether this call opened the transaction (or the implicit one). - let fresh = trancount == 0; - - let outcome = self.run_changes(&mut client, req, &identity).await; - let end = match &outcome { - // A commit that cannot complete is rolled back and reported. - Ok(_) if fresh && autocommit => { - "DECLARE @lq_ok int = 1; - WHILE @@TRANCOUNT > 0 AND XACT_STATE() = 1 COMMIT TRAN; - IF @@TRANCOUNT > 0 BEGIN SET @lq_ok = 0; ROLLBACK TRAN; END; - SELECT @@TRANCOUNT, XACT_STATE(), @lq_ok" - } - Ok(_) => "SELECT @@TRANCOUNT, XACT_STATE(), 1", - // Everything since the start belongs to this call. - Err(_) if fresh => { - "IF @@TRANCOUNT > 0 ROLLBACK TRAN; SELECT @@TRANCOUNT, XACT_STATE(), 0" - } - Err(_) => { - "IF XACT_STATE() = 1 ROLLBACK TRAN lq_apply; - SELECT @@TRANCOUNT, XACT_STATE(), 0" - } - }; - // Transaction count, XACT_STATE() and whether the commit completed. - let after = if self.broken.load(Ordering::SeqCst) { - None - } else { - match fetch(&mut client, end).await { - Ok(rows) => Some((int_at(&rows, 0), int_at(&rows, 1), int_at(&rows, 2))), - Err(e) => { - let err = self.fail(e, None); - if outcome.is_ok() { - return Err(err); - } - None - } - } - }; - drop(client); - if let Some((trancount, _, _)) = after { - self.state.lock().in_transaction = trancount > 0; - } - - let (updated, deleted, inserted) = match outcome { - Ok(counts) => counts, - Err(mut err) => { - if after.is_some_and(|(_, xact_state, _)| xact_state == -1) { - err.hint = - Some("The transaction can no longer be committed; roll it back.".into()); - } - return Err(err); - } - }; - if after.is_some_and(|(_, _, committed)| committed == 0) { - return Err(AppError::new( - ErrorKind::Database, - "The changes could not be committed and were rolled back.", - )); - } - Ok(ApplyResult { - updated, - deleted, - inserted, - elapsed_ms: started.elapsed().as_millis() as u64, - in_transaction: self.state.lock().in_transaction, - }) - } - - /// Runs every change; stops at the first failure. Returns the updated, - /// deleted and inserted counts. - async fn run_changes( - &self, - client: &mut MsClient, - req: &ApplyRequest, - identity: &[String], - ) -> AppResult<(u64, u64, u64)> { - let statements = req - .changes - .iter() - .map(|c| change_sql(&req.target, c, identity)) - .collect::>>()?; - let (mut updated, mut deleted, mut inserted) = (0, 0, 0); - for (i, statement) in statements.iter().enumerate() { - let Some(statement) = statement else { continue }; - let row = i + 1; - let params: Vec<&dyn ToSql> = - statement.params.iter().map(|p| p as &dyn ToSql).collect(); - let sql = format!("{};\nSELECT ROWCOUNT_BIG();", statement.sql); - let results = match client.query(sql, ¶ms).await { - Ok(stream) => stream.into_results().await, - Err(e) => Err(e), - }; - let results = results.map_err(|e| { - let mut err = self.fail(e, None); - err.position = None; - err.detail = Some(format!("Row {row} was not saved.")); - err - })?; - let count = results - .last() - .and_then(|rows| rows.first()) - .and_then(|r| r.try_get::(0).ok().flatten()) - .unwrap_or(0); - match statement.op { - ChangeOp::Insert => inserted += 1, - op => { - if count != 1 { - let why = if count == 0 { - "0 rows matched its key (changed or removed by someone else)".into() - } else { - format!("{count} rows matched its key") - }; - return Err(AppError::new( - ErrorKind::Database, - format!("Row {row} was not saved: {why}."), - )); - } - if op == ChangeOp::Update { - updated += 1; - } else { - deleted += 1; - } - } - } - } - Ok((updated, deleted, inserted)) - } - - /// Decides whether the rows of a result can be edited: the server - /// describes the query and reports the source table's unique keys. - /// Any failure only makes the result read-only. - async fn detect_edit( - &self, - client: &mut MsClient, - sql: &str, - columns: usize, - after: &After, - ) -> Result { - if !row_limit_applies(sql) { - return Err(ONLY_TABLE_ROWS.into()); - } - if sql_words(sql) - .iter() - .any(|w| matches!(w.as_str(), "UNION" | "EXCEPT" | "INTERSECT")) - { - return Err("Read-only: the result combines several queries.".into()); - } - if after.xact_state == -1 { - return Err("Read-only: the transaction must be rolled back first.".into()); - } - let results = match client.query(DESCRIBE_SQL, &[&sql]).await { - Ok(stream) => stream.into_results().await, - Err(e) => Err(e), - }; - let sets = match results { - Ok(sets) => texts(&sets), - Err(e) => { - // Only marks the session broken when the stream failed. - self.fail(e, None); - return Err(ONLY_TABLE_ROWS.into()); - } - }; - let text = |r: &Vec>, i: usize| r.get(i).cloned().flatten(); - let flag = - |r: &Vec>, i: usize| matches!(text(r, i).as_deref(), Some("true" | "1")); - let described: Vec = sets - .first() - .map(Vec::as_slice) - .unwrap_or_default() - .iter() - .map(|r| Described { - hidden: flag(r, 0), - other_db: flag(r, 1), - schema: text(r, 2), - table: text(r, 3), - column: text(r, 4), - type_name: text(r, 5), - computed: flag(r, 6), - error: text(r, 7), - }) - .collect(); - let keys: Vec = sets - .get(1) - .map(Vec::as_slice) - .unwrap_or_default() - .iter() - .map(|r| KeyPart { - schema: text(r, 0).unwrap_or_default(), - table: text(r, 1).unwrap_or_default(), - index: text(r, 2).and_then(|v| v.parse().ok()).unwrap_or(0), - primary: flag(r, 3), - column: text(r, 4).unwrap_or_default(), - nullable: flag(r, 5), - }) - .collect(); - edit_target(&described, &keys, columns) - } - - pub fn tx_state(&self) -> TxState { - *self.state.lock() - } - - pub async fn execute(&self, req: &ExecRequest) -> AppResult { - let mut client = self.lock().await?; - let limited = req.max_rows > 0 && row_limit_applies(&req.sql); - let batch = if limited { - // Same line as the statement, so error line numbers do not shift. - format!( - "SET ROWCOUNT {}; {}", - req.max_rows.saturating_add(1), - req.sql - ) - } else { - req.sql.clone() - }; - - let started = Instant::now(); - let outcome = { - let run = read_batch(&mut client, batch, req.max_rows); - tokio::select! { - r = run => Some(r), - _ = self.cancel.notified() => None, - } - }; - let elapsed_ms = started.elapsed().as_millis() as u64; - - let outcome = match outcome { - Some(Ok(batch)) => Ok(batch), - Some(Err(e)) => Err(self.fail(e, Some(&req.sql))), - None => { - // The batch future was dropped; the attention tells the server - // to stop and drains the rest of the response. - let acked = tokio::time::timeout(CANCEL_TIMEOUT, client.cancel_query()).await; - if matches!(acked, Ok(Ok(()))) { - Err(AppError::new( - ErrorKind::Cancelled, - "The statement was cancelled.", - )) - } else { - // The server may send the attention acknowledgement in a - // separate message that the driver does not read, which - // would leave every later response one message behind. - // A fresh connection is the only safe state. - match self.reopen(&mut client).await { - Ok(()) => { - let mut err = - AppError::new(ErrorKind::Cancelled, "The statement was cancelled."); - err.detail = Some( - "LowQuery reopened the connection to finish the cancel: temporary tables, session settings and uncommitted work of this tab were discarded." - .into(), - ); - Err(err) - } - Err(e) => { - self.broken.store(true, Ordering::SeqCst); - let mut err = AppError::new( - ErrorKind::Cancelled, - "The statement was cancelled, but the connection could not be reopened. Reconnect to continue.", - ); - err.detail = Some(e.message); - Err(err) - } - } - } - } - }; - - // Row count, transaction state, and the ROWCOUNT reset in one trip. - let after = if self.broken.load(Ordering::SeqCst) { - None - } else { - let sql = format!( - "SELECT ROWCOUNT_BIG(), @@TRANCOUNT, XACT_STATE();{}", - if limited { " SET ROWCOUNT 0;" } else { "" } - ); - match fetch(&mut client, &sql).await { - Ok(rows) => Some(parse_after(&rows)), - Err(e) => { - let err = self.fail(e, None); - if outcome.is_ok() { - return Err(err); - } - // Keep the original error, but say why the session broke. - if let Err(original) = &outcome { - if self.broken.load(Ordering::SeqCst) && original.detail.is_none() { - return Err(AppError { - detail: Some(err.message), - ..original.clone() - }); - } - } - None - } - } - }; - // Whether the grid may edit the rows, while the connection is held. - let edit = match (&outcome, &after) { - ( - Ok(Batch { - columns: Some(cols), - .. - }), - Some(after), - ) => Some( - self.detect_edit(&mut client, &req.sql, cols.len(), after) - .await, - ), - _ => None, - }; - drop(client); - - if let Some(after) = &after { - self.state.lock().in_transaction = after.trancount > 0; - } - let batch = outcome?; - let after = after.unwrap_or(After { - rowcount: 0, - trancount: 0, - xact_state: 0, - }); - - let mut result = ExecResult { - elapsed_ms, - in_transaction: self.state.lock().in_transaction, - ..Default::default() - }; - let first = first_keywords(&req.sql, 1); - let counts_rows = match first.first().map(String::as_str) { - Some("INSERT" | "UPDATE" | "DELETE" | "MERGE" | "BULK") => true, - // SELECT ... INTO and WITH ... return no result set. - Some("SELECT" | "WITH") => batch.columns.is_none(), - _ => false, - }; - if counts_rows { - result.rows_affected = Some(after.rowcount); - } - if after.xact_state == -1 { - result - .notices - .push("The transaction can no longer be committed; roll it back.".into()); - } - result.columns = batch.columns; - result.rows = batch.rows; - result.truncated = batch.truncated; - match edit { - Some(Ok(target)) => result.editable = Some(target), - Some(Err(reason)) => result.read_only_reason = Some(reason), - None => {} - } - Ok(result) - } - - pub async fn cancel(&self) -> AppResult<()> { - self.cancel.notify_waiters(); - Ok(()) - } - - pub async fn set_autocommit(&self, on: bool) -> AppResult { - let mut client = self.lock().await?; - let sql = if on { - // Turning autocommit back on commits pending work, like JDBC. - "WHILE @@TRANCOUNT > 0 AND XACT_STATE() = 1 COMMIT TRAN; - IF @@TRANCOUNT = 0 SET IMPLICIT_TRANSACTIONS OFF; - SELECT @@TRANCOUNT" - } else { - "SET IMPLICIT_TRANSACTIONS ON; SELECT @@TRANCOUNT" - }; - let rows = fetch(&mut client, sql) - .await - .map_err(|e| self.fail(e, None))?; - drop(client); - let trancount = first_int(&rows); - let mut st = self.state.lock(); - st.in_transaction = trancount > 0; - if on && st.in_transaction { - return Err(doomed()); - } - st.autocommit = on; - Ok(*st) - } - - pub async fn end_transaction(&self, commit: bool) -> AppResult { - let mut client = self.lock().await?; - let sql = if commit { - // Nested BEGIN TRAN needs one COMMIT per level. A doomed - // transaction cannot commit, and COMMIT would fail in a loop. - "WHILE @@TRANCOUNT > 0 AND XACT_STATE() = 1 COMMIT TRAN; SELECT @@TRANCOUNT" - } else { - "IF @@TRANCOUNT > 0 ROLLBACK TRAN; SELECT @@TRANCOUNT" - }; - let rows = fetch(&mut client, sql) - .await - .map_err(|e| self.fail(e, None))?; - drop(client); - let trancount = first_int(&rows); - let mut st = self.state.lock(); - st.in_transaction = trancount > 0; - if st.in_transaction { - return Err(doomed()); - } - Ok(*st) - } - - pub async fn list_schemas(&self) -> AppResult> { - // Fixed database-role schemas (db_owner...) only show up when they - // hold objects; system schemas go last. - let rows = self - .metadata( - "SELECT s.name FROM sys.schemas s - WHERE s.schema_id NOT BETWEEN 16384 AND 16399 - OR EXISTS (SELECT 1 FROM sys.objects o WHERE o.schema_id = s.schema_id) - ORDER BY CASE WHEN s.name = SCHEMA_NAME() THEN 0 - WHEN s.name IN ('sys', 'INFORMATION_SCHEMA', 'guest') - OR s.schema_id BETWEEN 16384 AND 16399 THEN 2 - ELSE 1 END, s.name" - .to_string(), - ) - .await?; - Ok(rows - .into_iter() - .filter_map(|mut r| r.drain(..).next().flatten()) - .collect()) - } - - pub async fn list_objects(&self, schema: &str) -> AppResult> { - let schema = nstr(schema); - let rows = self - .metadata(format!( - "SELECT name, kind FROM ( - SELECT o.name, - CASE o.type WHEN 'U' THEN 'table' WHEN 'V' THEN 'view' - WHEN 'SO' THEN 'sequence' WHEN 'SN' THEN 'synonym' - WHEN 'P' THEN 'procedure' WHEN 'PC' THEN 'procedure' - WHEN 'X' THEN 'procedure' ELSE 'function' END AS kind - FROM sys.all_objects o - WHERE o.schema_id = SCHEMA_ID({schema}) - AND o.type IN ('U','V','SO','SN','P','PC','X','FN','IF','TF','FS','FT') - AND (o.is_ms_shipped = 0 OR {schema} IN (N'sys', N'INFORMATION_SCHEMA')) - UNION ALL - SELECT t.name, 'type' FROM sys.types t - WHERE t.is_user_defined = 1 AND t.schema_id = SCHEMA_ID({schema}) - ) x - ORDER BY kind, name" - )) - .await?; - Ok(rows - .into_iter() - .map(|mut r| { - let kind = r.pop().flatten().unwrap_or_default(); - DbObject { - name: r.pop().flatten().unwrap_or_default(), - kind, - } - }) - .collect()) - } - - pub async fn list_columns(&self, schema: &str, table: &str) -> AppResult> { - let object = object_id(schema, table); - let rows = self - .metadata(format!( - "SELECT c.name, {COLUMN_TYPE}, - c.is_nullable, - CAST(CASE WHEN EXISTS ( - SELECT 1 FROM sys.indexes i - JOIN sys.index_columns ic ON ic.object_id = i.object_id - AND ic.index_id = i.index_id - WHERE i.object_id = c.object_id AND i.is_primary_key = 1 - AND ic.column_id = c.column_id) THEN 1 ELSE 0 END AS bit), - OBJECT_DEFINITION(c.default_object_id) - FROM sys.all_columns c - JOIN sys.types t ON t.user_type_id = c.user_type_id - WHERE c.object_id = {object} - ORDER BY c.column_id" - )) - .await?; - Ok(rows - .into_iter() - .map(|r| { - let text = |i: usize| r.get(i).cloned().flatten().unwrap_or_default(); - DbColumn { - name: text(0), - type_name: text(1), - nullable: text(2) == "true", - primary_key: text(3) == "true", - default_value: r.get(4).cloned().flatten(), - key_role: None, - } - }) - .collect()) - } - - /// Reads the first result set of a batch as the server sends it. - pub async fn stream(&self, sql: &str, sink: RowSink) -> AppResult { - let mut client = self.lock().await?; - let mut stream = client - .simple_query(sql.to_string()) - .await - .map_err(|e| self.fail(e, Some(sql)))?; - let mut total = 0u64; - let mut batch = Vec::with_capacity(STREAM_BATCH); - while let Some(item) = stream - .try_next() - .await - .map_err(|e| self.fail(e, Some(sql)))? - { - match item { - QueryItem::Metadata(meta) if meta.result_index() == 0 => { - let columns = meta.columns().iter().map(column_info).collect(); - sink.send(StreamEvent::Columns(columns)) - .await - .map_err(|_| super::stream_stopped())?; - } - QueryItem::Row(row) if row.result_index() == 0 => { - batch.push(super::full_values(|| { - row.cells() - .map(|(c, d)| cell(c.column_type(), d)) - .collect::>() - })); - total += 1; - if batch.len() == STREAM_BATCH { - let full = std::mem::replace(&mut batch, Vec::with_capacity(STREAM_BATCH)); - sink.send(StreamEvent::Rows(full)) - .await - .map_err(|_| super::stream_stopped())?; - } - } - _ => {} - } - } - if !batch.is_empty() { - sink.send(StreamEvent::Rows(batch)) - .await - .map_err(|_| super::stream_stopped())?; - } - Ok(total) - } - - /// Views, routines and triggers come from `OBJECT_DEFINITION`; tables, - /// sequences, synonyms and alias types are scripted from the catalog. - /// Batches are separated by `GO`. - pub async fn object_ddl(&self, schema: &str, name: &str, kind: &str) -> AppResult { - let object = object_id(schema, name); - let target = format!("{}.{}", quote_ident(schema), quote_ident(name)); - let text = |r: &[Option], i: usize| r.get(i).cloned().flatten().unwrap_or_default(); - match kind { - "view" | "function" | "procedure" => { - let rows = self - .metadata(format!("SELECT OBJECT_DEFINITION({object})")) - .await?; - let def = rows.first().map(|r| text(r, 0)).unwrap_or_default(); - Ok(if def.trim().is_empty() { - def - } else { - format!("{}\nGO\n", def.trim()) - }) - } - "table" => self.table_ddl(&object, &target).await, - "sequence" => { - let rows = self - .metadata(format!( - "SELECT TYPE_NAME(s.user_type_id), CAST(s.start_value AS nvarchar(60)), - CAST(s.increment AS nvarchar(60)), CAST(s.minimum_value AS nvarchar(60)), - CAST(s.maximum_value AS nvarchar(60)), s.is_cycling, s.is_cached, - CAST(s.cache_size AS nvarchar(20)) - FROM sys.sequences s WHERE s.object_id = {object}" - )) - .await?; - let Some(q) = rows.first() else { - return Ok(String::new()); - }; - let cache = match (text(q, 6).as_str(), text(q, 7)) { - ("false", _) => "NO CACHE".to_string(), - (_, size) if !size.is_empty() => format!("CACHE {size}"), - _ => "CACHE".to_string(), - }; - Ok(format!( - "CREATE SEQUENCE {target}\n AS {}\n START WITH {}\n INCREMENT BY {}\n MINVALUE {}\n MAXVALUE {}\n {}CYCLE\n {cache};\n", - text(q, 0), - text(q, 1), - text(q, 2), - text(q, 3), - text(q, 4), - if text(q, 5) == "true" { "" } else { "NO " }, - )) - } - "synonym" => { - let rows = self - .metadata(format!( - "SELECT base_object_name FROM sys.synonyms WHERE object_id = {object}" - )) - .await?; - let base = rows.first().map(|r| text(r, 0)).unwrap_or_default(); - Ok(format!("CREATE SYNONYM {target} FOR {base};\n")) - } - "type" => { - let rows = self - .metadata(format!( - "SELECT b.name, CAST(t.max_length AS int), CAST(t.precision AS int), - CAST(t.scale AS int), t.is_nullable, t.is_table_type - FROM sys.types t - LEFT JOIN sys.types b ON b.user_type_id = t.system_type_id - WHERE t.schema_id = SCHEMA_ID({}) AND t.name = {}", - nstr(schema), - nstr(name) - )) - .await?; - let Some(q) = rows.first() else { - return Ok(String::new()); - }; - if text(q, 5) == "true" { - return Err(AppError::invalid("LowQuery cannot script table types yet.")); - } - let num = |i: usize| text(q, i).parse::().unwrap_or(0); - let base = text(q, 0); - let ty = match base.as_str() { - "varchar" | "char" | "varbinary" | "binary" if num(1) == -1 => { - format!("{base}(max)") - } - "varchar" | "char" | "varbinary" | "binary" => format!("{base}({})", num(1)), - "nvarchar" | "nchar" if num(1) == -1 => format!("{base}(max)"), - "nvarchar" | "nchar" => format!("{base}({})", num(1) / 2), - "decimal" | "numeric" => format!("{base}({},{})", num(2), num(3)), - "datetime2" | "time" | "datetimeoffset" => format!("{base}({})", num(3)), - _ => base, - }; - let null = if text(q, 4) == "true" { - "NULL" - } else { - "NOT NULL" - }; - Ok(format!("CREATE TYPE {target} FROM {ty} {null};\n")) - } - _ => Err(AppError::invalid(format!( - "LowQuery cannot script a {kind} on SQL Server." - ))), - } - } - - async fn table_ddl(&self, object: &str, target: &str) -> AppResult { - let text = |r: &[Option], i: usize| r.get(i).cloned().flatten().unwrap_or_default(); - let columns = self - .metadata(format!( - "SELECT c.name, {COLUMN_TYPE}, c.is_nullable, c.is_identity, - CAST(ic.seed_value AS nvarchar(60)), CAST(ic.increment_value AS nvarchar(60)), - cc.definition, cc.is_persisted, dc.name, dc.definition - FROM sys.columns c - JOIN sys.types t ON t.user_type_id = c.user_type_id - LEFT JOIN sys.identity_columns ic - ON ic.object_id = c.object_id AND ic.column_id = c.column_id - LEFT JOIN sys.computed_columns cc - ON cc.object_id = c.object_id AND cc.column_id = c.column_id - LEFT JOIN sys.default_constraints dc - ON dc.parent_object_id = c.object_id AND dc.parent_column_id = c.column_id - WHERE c.object_id = {object} - ORDER BY c.column_id" - )) - .await?; - if columns.is_empty() { - return Ok(String::new()); - } - let mut lines: Vec = columns - .iter() - .map(|c| { - let name = quote_ident(&text(c, 0)); - let computed = text(c, 6); - if !computed.is_empty() { - let persisted = if text(c, 7) == "true" { - " PERSISTED" - } else { - "" - }; - return format!(" {name} AS {computed}{persisted}"); - } - let mut line = format!(" {name} {}", text(c, 1)); - if text(c, 3) == "true" { - line.push_str(&format!(" IDENTITY({},{})", text(c, 4), text(c, 5))); - } - line.push_str(if text(c, 2) == "true" { - " NULL" - } else { - " NOT NULL" - }); - if !text(c, 9).is_empty() { - line.push_str(&format!( - " CONSTRAINT {} DEFAULT {}", - quote_ident(&text(c, 8)), - text(c, 9) - )); - } - line - }) - .collect(); - - // Primary key and unique constraints, one row per key column. - let keys = self - .metadata(format!( - "SELECT kc.name, kc.type, i.type_desc, col.name, ic.is_descending_key - FROM sys.key_constraints kc - JOIN sys.indexes i ON i.object_id = kc.parent_object_id AND i.index_id = kc.unique_index_id - JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id - JOIN sys.columns col ON col.object_id = ic.object_id AND col.column_id = ic.column_id - WHERE kc.parent_object_id = {object} - ORDER BY kc.type, kc.name, ic.key_ordinal" - )) - .await?; - for (name, rows) in group_by_first(&keys) { - let kind = if text(rows[0], 1) == "PK" { - "PRIMARY KEY" - } else { - "UNIQUE" - }; - let cols = rows - .iter() - .map(|r| format!("{}{}", quote_ident(&text(r, 3)), desc(&text(r, 4)))) - .collect::>() - .join(", "); - lines.push(format!( - " CONSTRAINT {} {kind} {} ({cols})", - quote_ident(&name), - text(rows[0], 2) - )); - } - let checks = self - .metadata(format!( - "SELECT name, definition FROM sys.check_constraints - WHERE parent_object_id = {object} ORDER BY name" - )) - .await?; - for c in &checks { - lines.push(format!( - " CONSTRAINT {} CHECK {}", - quote_ident(&text(c, 0)), - text(c, 1) - )); - } - let mut out = format!("CREATE TABLE {target} (\n{}\n);\n", lines.join(",\n")); - - let indexes = self - .metadata(format!( - "SELECT i.name, i.is_unique, i.type_desc, c.name, ic.is_descending_key, - ic.is_included_column, i.filter_definition - FROM sys.indexes i - JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id - JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id - WHERE i.object_id = {object} AND i.is_primary_key = 0 - AND i.is_unique_constraint = 0 AND i.type IN (1, 2) - ORDER BY i.name, ic.is_included_column, ic.key_ordinal, ic.index_column_id" - )) - .await?; - for (name, rows) in group_by_first(&indexes) { - let unique = if text(rows[0], 1) == "true" { - "UNIQUE " - } else { - "" - }; - let key = rows - .iter() - .filter(|r| text(r, 5) != "true") - .map(|r| format!("{}{}", quote_ident(&text(r, 3)), desc(&text(r, 4)))) - .collect::>() - .join(", "); - let include = rows - .iter() - .filter(|r| text(r, 5) == "true") - .map(|r| quote_ident(&text(r, 3))) - .collect::>(); - out.push_str(&format!( - "\nCREATE {unique}{} INDEX {} ON {target} ({key})", - text(rows[0], 2), - quote_ident(&name) - )); - if !include.is_empty() { - out.push_str(&format!(" INCLUDE ({})", include.join(", "))); - } - let filter = text(rows[0], 6); - if !filter.is_empty() { - out.push_str(&format!(" WHERE {filter}")); - } - out.push_str(";\n"); - } - - let foreign_keys = self - .metadata(format!( - "SELECT fk.name, SCHEMA_NAME(rt.schema_id), rt.name, pc.name, rc.name, - fk.delete_referential_action_desc, fk.update_referential_action_desc - FROM sys.foreign_keys fk - JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id - JOIN sys.objects rt ON rt.object_id = fk.referenced_object_id - JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id - AND pc.column_id = fkc.parent_column_id - JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id - AND rc.column_id = fkc.referenced_column_id - WHERE fk.parent_object_id = {object} - ORDER BY fk.name, fkc.constraint_column_id" - )) - .await?; - for (name, rows) in group_by_first(&foreign_keys) { - let cols = |i: usize| { - rows.iter() - .map(|r| quote_ident(&text(r, i))) - .collect::>() - .join(", ") - }; - out.push_str(&format!( - "\nALTER TABLE {target} ADD CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {}.{} ({})", - quote_ident(&name), - cols(3), - quote_ident(&text(rows[0], 1)), - quote_ident(&text(rows[0], 2)), - cols(4) - )); - for (event, action) in [("DELETE", text(rows[0], 5)), ("UPDATE", text(rows[0], 6))] { - if action != "NO_ACTION" && !action.is_empty() { - out.push_str(&format!(" ON {event} {}", action.replace('_', " "))); - } - } - out.push_str(";\n"); - } - - let triggers = self - .metadata(format!( - "SELECT OBJECT_DEFINITION(object_id) FROM sys.triggers - WHERE parent_id = {object} ORDER BY name" - )) - .await?; - let triggers: Vec = triggers - .iter() - .map(|r| text(r, 0)) - .filter(|d| !d.trim().is_empty()) - .collect(); - if !triggers.is_empty() { - out.push_str("GO\n"); - for t in triggers { - out.push_str(&format!("\n{}\nGO\n", t.trim())); - } - } - Ok(out) - } - - /// Runs a catalog query. In manual-commit mode a SELECT opens an implicit - /// transaction, so one opened only by this query is ended right away. - async fn metadata(&self, sql: String) -> AppResult>>> { - let mut client = self.lock().await?; - let state = *self.state.lock(); - let sql = if !state.autocommit && !state.in_transaction { - format!("{sql};\nIF @@TRANCOUNT > 0 COMMIT TRAN;") - } else { - sql - }; - fetch(&mut client, &sql) - .await - .map_err(|e| self.fail(e, None)) - } - - /// Replaces the connection with a new one, keeping the autocommit mode. - async fn reopen(&self, client: &mut MsClient) -> AppResult<()> { - let mut fresh = dial(&self.profile, self.password.as_deref()).await?; - if !self.state.lock().autocommit { - fetch(&mut fresh, "SET IMPLICIT_TRANSACTIONS ON; SELECT 1") - .await - .map_err(connection_error)?; - } - *client = fresh; - self.state.lock().in_transaction = false; - Ok(()) - } - - async fn lock(&self) -> AppResult> { - self.ensure_open()?; - let client = self.client.lock().await; - self.ensure_open()?; - Ok(client) - } - - fn ensure_open(&self) -> AppResult<()> { - if self.broken.load(Ordering::SeqCst) { - return Err(AppError::connection( - "The connection to the server was lost. Reconnect to continue.", - )); - } - Ok(()) - } - - /// Maps the error and marks the session unusable when the stream broke. - fn fail(&self, e: tiberius::error::Error, sql: Option<&str>) -> AppError { - use tiberius::error::Error as E; - if matches!(e, E::Io { .. } | E::Protocol(_) | E::Tls(_)) { - self.broken.store(true, Ordering::SeqCst); - } - map_error(e, sql) - } -} - -fn doomed() -> AppError { - AppError::new( - ErrorKind::Database, - "The transaction cannot be committed (an error doomed it). Roll it back.", - ) -} - -/// Runs the batch and keeps the first result set, up to `max_rows` rows. The -/// rest of the response is read and discarded so the connection stays in -/// sync. -async fn read_batch( - client: &mut MsClient, - sql: String, - max_rows: usize, -) -> tiberius::Result { - let mut stream = client.simple_query(sql).await?; - let mut out = Batch::default(); - while let Some(item) = stream.try_next().await? { - match item { - QueryItem::Metadata(meta) if meta.result_index() == 0 => { - out.columns = Some(meta.columns().iter().map(column_info).collect()); - } - QueryItem::Row(row) if row.result_index() == 0 => { - if max_rows > 0 && out.rows.len() >= max_rows { - out.truncated = true; - } else { - out.rows - .push(row.cells().map(|(c, d)| cell(c.column_type(), d)).collect()); - } - } - _ => {} - } - } - Ok(out) -} - -/// Rows of the first result set of a batch, formatted as text. -async fn fetch(client: &mut MsClient, sql: &str) -> tiberius::Result>>> { - let rows = client - .simple_query(sql.to_string()) - .await? - .into_first_result() - .await?; - Ok(rows - .iter() - .map(|r| r.cells().map(|(c, d)| cell(c.column_type(), d)).collect()) - .collect()) -} - -/// Every result set of a plain batch, formatted as text. -async fn fetch_all( - client: &mut MsClient, - sql: &str, -) -> tiberius::Result>>>> { - let sets = client - .simple_query(sql.to_string()) - .await? - .into_results() - .await?; - Ok(texts(&sets)) -} - -fn texts(sets: &[Vec]) -> Vec>>> { - sets.iter() - .map(|rows| { - rows.iter() - .map(|r| r.cells().map(|(c, d)| cell(c.column_type(), d)).collect()) - .collect() - }) - .collect() -} - -/// Integer in column `i` of the first row, 0 when missing. -fn int_at(rows: &[Vec>], i: usize) -> i64 { - rows.first() - .and_then(|r| r.get(i)) - .cloned() - .flatten() - .and_then(|v| v.parse().ok()) - .unwrap_or(0) -} - -fn first_int(rows: &[Vec>]) -> i64 { - int_at(rows, 0) -} - -fn parse_after(rows: &[Vec>]) -> After { - After { - rowcount: int_at(rows, 0).max(0) as u64, - trancount: int_at(rows, 1), - xact_state: int_at(rows, 2), - } -} - -/// `SET ROWCOUNT` also limits INSERT/UPDATE/DELETE and `SELECT ... INTO`, so -/// it is only used when the batch is made of plain queries: it starts with -/// SELECT (or a CTE) and no reserved word that writes or controls flow -/// appears outside literals and comments. -fn row_limit_applies(sql: &str) -> bool { - const BLOCKING: &[&str] = &[ - "INTO", - "INSERT", - "UPDATE", - "DELETE", - "MERGE", - "EXEC", - "EXECUTE", - "SET", - "DECLARE", - "CREATE", - "ALTER", - "DROP", - "TRUNCATE", - "BEGIN", - "COMMIT", - "ROLLBACK", - "SAVE", - "USE", - "IF", - "WHILE", - "BULK", - "DBCC", - "OPEN", - "CLOSE", - "DEALLOCATE", - "GRANT", - "REVOKE", - "DENY", - "BACKUP", - "RESTORE", - ]; - let first = first_keywords(sql, 1); - if !matches!(first.first().map(String::as_str), Some("SELECT" | "WITH")) { - return false; - } - !sql_words(sql) - .iter() - .any(|w| BLOCKING.contains(&w.as_str())) -} - -/// Uppercased words of a T-SQL text, skipping string literals, quoted -/// identifiers (`"x"`, `[x]`) and comments (`--`, nested `/* */`). -fn sql_words(sql: &str) -> Vec { - let chars: Vec = sql.chars().collect(); - let mut words = Vec::new(); - let mut i = 0; - let closing = |chars: &[char], mut i: usize, end: char| { - // Skips to after the closing char; a doubled closing char is an escape. - while i < chars.len() { - if chars[i] == end { - if chars.get(i + 1) == Some(&end) { - i += 2; - continue; - } - return i + 1; - } - i += 1; - } - i - }; - while i < chars.len() { - let c = chars[i]; - if c == '\'' { - i = closing(&chars, i + 1, '\''); - } else if c == '"' { - i = closing(&chars, i + 1, '"'); - } else if c == '[' { - i = closing(&chars, i + 1, ']'); - } else if c == '-' && chars.get(i + 1) == Some(&'-') { - while i < chars.len() && chars[i] != '\n' { - i += 1; - } - } else if c == '/' && chars.get(i + 1) == Some(&'*') { - let mut depth = 0; - while i < chars.len() { - if chars[i] == '/' && chars.get(i + 1) == Some(&'*') { - depth += 1; - i += 2; - } else if chars[i] == '*' && chars.get(i + 1) == Some(&'/') { - depth -= 1; - i += 2; - if depth == 0 { - break; - } - } else { - i += 1; - } - } - } else if c.is_alphabetic() || c == '_' || c == '@' || c == '#' { - let start = i; - while i < chars.len() - && (chars[i].is_alphanumeric() || matches!(chars[i], '_' | '@' | '#' | '$')) - { - i += 1; - } - let word: String = chars[start..i].iter().collect(); - // N'...' is a Unicode literal, not the word N. - if !(word.eq_ignore_ascii_case("N") && chars.get(i) == Some(&'\'')) { - words.push(word.to_uppercase()); - } - } else { - i += 1; - } - } - words -} - -/// A column's type as DDL writes it, for `sys.columns c JOIN sys.types t`. -const COLUMN_TYPE: &str = "CASE WHEN t.is_user_defined = 1 THEN t.name - WHEN t.name IN ('varchar', 'char', 'varbinary', 'binary') - THEN t.name + '(' + CASE WHEN c.max_length = -1 THEN 'max' - ELSE CAST(c.max_length AS varchar(10)) END + ')' - WHEN t.name IN ('nvarchar', 'nchar') - THEN t.name + '(' + CASE WHEN c.max_length = -1 THEN 'max' - ELSE CAST(c.max_length / 2 AS varchar(10)) END + ')' - WHEN t.name IN ('decimal', 'numeric') - THEN t.name + '(' + CAST(c.precision AS varchar(10)) + ',' - + CAST(c.scale AS varchar(10)) + ')' - WHEN t.name IN ('datetime2', 'time', 'datetimeoffset') - THEN t.name + '(' + CAST(c.scale AS varchar(10)) + ')' - ELSE t.name END"; - -/// `OBJECT_ID` of `schema.name`, as an expression. -fn object_id(schema: &str, name: &str) -> String { - format!( - "OBJECT_ID(QUOTENAME({}) + N'.' + QUOTENAME({}))", - nstr(schema), - nstr(name) - ) -} - -/// Consecutive rows sharing their first column (catalog rows ordered by name). -fn group_by_first(rows: &[Vec>]) -> Vec<(String, Vec<&[Option]>)> { - let mut groups: Vec<(String, Vec<&[Option]>)> = Vec::new(); - for row in rows { - let key = row.first().cloned().flatten().unwrap_or_default(); - match groups.last_mut() { - Some((k, members)) if *k == key => members.push(row), - _ => groups.push((key, vec![row])), - } - } - groups -} - -fn desc(is_descending: &str) -> &'static str { - if is_descending == "true" { - " DESC" - } else { - "" - } -} - -/// T-SQL Unicode string literal. -fn nstr(s: &str) -> String { - format!("N'{}'", s.replace('\'', "''")) -} - -/// Bracket-quoted identifier. -fn quote_ident(name: &str) -> String { - format!("[{}]", name.replace(']', "]]")) -} - -fn qualified(schema: Option<&str>, table: &str) -> String { - match schema { - Some(s) if !s.is_empty() => format!("{}.{}", quote_ident(s), quote_ident(table)), - _ => quote_ident(table), - } -} - -/// One result column as the server describes it. -#[derive(Debug, Clone, Default)] -struct Described { - /// Key column added by browse mode, not part of the result. - hidden: bool, - /// Comes from another database or a linked server. - other_db: bool, - schema: Option, - table: Option, - column: Option, - type_name: Option, - computed: bool, - error: Option, -} - -/// One column of a unique index of a source table. -#[derive(Debug, Clone, Default)] -struct KeyPart { - schema: String, - table: String, - index: i64, - primary: bool, - column: String, - nullable: bool, -} - -/// The table behind a result, or why its rows cannot be edited. -fn edit_target( - described: &[Described], - keys: &[KeyPart], - result_columns: usize, -) -> Result { - let generic = || ONLY_TABLE_ROWS.to_string(); - if described.iter().any(|c| c.error.is_some()) { - return Err(generic()); - } - let visible: Vec<&Described> = described.iter().filter(|c| !c.hidden).collect(); - if visible.is_empty() || visible.len() != result_columns { - return Err(generic()); - } - let mut source: Option<(&str, &str)> = None; - for c in &visible { - let (Some(schema), Some(table), Some(_)) = - (c.schema.as_deref(), c.table.as_deref(), c.column.as_deref()) - else { - continue; - }; - if c.other_db { - return Err("Read-only: the table is in another database.".into()); - } - match source { - None => source = Some((schema, table)), - Some(s) if s != (schema, table) => { - return Err("Read-only: the result combines columns from several tables.".into()) - } - _ => {} - } - } - let (schema, table) = source.ok_or_else(generic)?; - let of_table = - |c: &Described| c.schema.as_deref() == Some(schema) && c.table.as_deref() == Some(table); - - // Plain, writable columns of the table; a repeated column is edited - // through its first occurrence only. - let mut columns: Vec> = Vec::with_capacity(visible.len()); - let mut seen: Vec<&str> = Vec::new(); - for c in &visible { - let editable = match (c.column.as_deref(), c.type_name.as_deref()) { - (Some(name), Some(ty)) - if of_table(c) - && !c.computed - && !seen.contains(&name) - && value_expr(ty, 1).is_ok() => - { - seen.push(name); - Some(EditColumn { - name: name.into(), - type_name: ty.into(), - }) - } - _ => None, - }; - columns.push(editable); - } - - // Unique indexes of the table, in the order the server listed them - // (primary key first). - let mut candidates: Vec<(bool, Vec<&KeyPart>)> = Vec::new(); - for k in keys - .iter() - .filter(|k| k.schema == schema && k.table == table) - { - match candidates.last_mut() { - Some((_, parts)) if parts[0].index == k.index => parts.push(k), - _ => candidates.push((k.primary, vec![k])), - } - } - let primary = candidates.iter().any(|(p, _)| *p); - candidates.retain(|(p, parts)| { - if primary { - *p - } else { - parts.iter().all(|k| !k.nullable) - } - }); - let Some((_, first)) = candidates.first() else { - return Err(format!("Read-only: table {table} has no primary key.")); - }; - for (_, parts) in &candidates { - let positions: Option> = parts - .iter() - .map(|k| { - columns - .iter() - .position(|c| c.as_ref().is_some_and(|c| c.name == k.column)) - }) - .collect(); - let Some(key) = positions else { continue }; - // A key shown twice, or one browse mode had to add, means the table - // appears more than once (a self join): rows would be ambiguous. - let shown_twice = parts.iter().any(|k| { - visible - .iter() - .filter(|c| of_table(c) && c.column.as_deref() == Some(k.column.as_str())) - .count() - > 1 - }); - let added = described.iter().any(|c| { - c.hidden - && of_table(c) - && parts - .iter() - .any(|k| c.column.as_deref() == Some(k.column.as_str())) - }); - if shown_twice || added { - return Err(format!( - "Read-only: the result shows table {table} more than once." - )); - } - return Ok(EditTarget { - schema: Some(schema.into()), - table: table.into(), - columns, - key, - }); - } - let names: Vec<&str> = first.iter().map(|k| k.column.as_str()).collect(); - Err(format!( - "Read-only: add the {} columns ({}) to the query to edit rows.", - if primary { "primary key" } else { "key" }, - names.join(", ") - )) -} - -/// Base name (lowercase) and arguments of a type such as `decimal(10,2)`; -/// `None` when the text is not a plain type name. -fn parse_type(type_name: &str) -> Option<(String, Vec)> { - let t = type_name.trim(); - let (base, args) = match t.split_once('(') { - Some((base, rest)) => (base.trim(), Some(rest.strip_suffix(')')?)), - None => (t, None), - }; - if base.is_empty() || !base.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { - return None; - } - let args = match args { - Some(a) => a - .split(',') - .map(|p| { - let p = p.trim().to_ascii_lowercase(); - (p == "max" || (!p.is_empty() && p.chars().all(|c| c.is_ascii_digit()))) - .then_some(p) - }) - .collect::>>()?, - None => Vec::new(), - }; - Some((base.to_ascii_lowercase(), args)) -} - -fn is_binary_type(base: &str) -> bool { - matches!( - base, - "binary" | "varbinary" | "image" | "hierarchyid" | "geometry" | "geography" - ) -} - -/// SQL that converts parameter `@P{n}` (text in the driver's display format) -/// to the column type. Styles are explicit, so DATEFORMAT and LANGUAGE never -/// change the result. -fn value_expr(type_name: &str, n: usize) -> AppResult { - let unsupported = - || AppError::invalid(format!("Columns of type {type_name} cannot be edited.")); - let (base, args) = parse_type(type_name).ok_or_else(unsupported)?; - let ty = if args.is_empty() { - base.clone() - } else { - format!("{base}({})", args.join(",")) - }; - let p = format!("@P{n}"); - Ok(match base.as_str() { - // Plain-text forms of these types do not depend on session settings; - // bit takes true/false or 1/0. - "bit" | "tinyint" | "smallint" | "int" | "bigint" | "decimal" | "numeric" | "money" - | "smallmoney" | "float" | "real" | "uniqueidentifier" | "time" => { - format!("CAST({p} AS {ty})") - } - // ODBC canonical (yyyy-mm-dd hh:mi:ss.fffffff [+hh:mm]). - "date" | "datetime" | "datetime2" | "smalldatetime" | "datetimeoffset" => { - format!("CONVERT({ty}, {p}, 121)") - } - // The nvarchar parameter converts to the column on assignment. - "char" | "varchar" | "text" | "nchar" | "nvarchar" | "ntext" | "sysname" | "xml" => p, - // Style 1: 0x-prefixed hexadecimal. - "binary" | "varbinary" => format!("CONVERT({ty}, {p}, 1)"), - "image" => format!("CONVERT(varbinary(max), {p}, 1)"), - "hierarchyid" | "geometry" | "geography" => { - format!("CAST(CONVERT(varbinary(max), {p}, 1) AS {ty})") - } - // timestamp/rowversion, sql_variant, user CLR types. - _ => return Err(unsupported()), - }) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ChangeOp { - Update, - Delete, - Insert, -} - -/// One statement of an apply with its parameters (`@P1`...). -#[derive(Debug)] -struct ChangeSql { - op: ChangeOp, - sql: String, - params: Vec>, -} - -fn target_column(target: &EditTarget, index: usize) -> AppResult<&EditColumn> { - target - .columns - .get(index) - .and_then(Option::as_ref) - .ok_or_else(|| { - AppError::invalid(format!( - "Column {} of the result cannot be edited.", - index + 1 - )) - }) -} - -/// Binds a value and returns the expression that converts it. -fn bind( - params: &mut Vec>, - column: &EditColumn, - value: &Option, -) -> AppResult { - if let Some(v) = value { - let binary = parse_type(&column.type_name).is_some_and(|(b, _)| is_binary_type(&b)); - if binary && v.contains(PREVIEW_MARK) { - return Err(AppError::invalid( - "This value is only a preview and cannot be saved.", - )); - } - } - params.push(value.clone()); - value_expr(&column.type_name, params.len()) -} - -fn where_key( - target: &EditTarget, - key: &[Option], - params: &mut Vec>, -) -> AppResult { - if key.len() != target.key.len() { - return Err(AppError::invalid("The row key does not match the result.")); - } - let mut parts = Vec::with_capacity(key.len()); - for (&index, value) in target.key.iter().zip(key) { - let column = target_column(target, index)?; - let name = quote_ident(&column.name); - parts.push(match value { - None => format!("{name} IS NULL"), - Some(_) => format!("{name} = {}", bind(params, column, value)?), - }); - } - Ok(parts.join(" AND ")) -} - -/// Edited values by table column, the last one winning. -fn assignments<'a>( - target: &'a EditTarget, - values: &'a [crate::model::CellValue], -) -> AppResult)>> { - let mut out: Vec<(&EditColumn, &Option)> = Vec::new(); - for v in values { - let column = target_column(target, v.column)?; - match out.iter_mut().find(|(c, _)| c.name == column.name) { - Some(slot) => slot.1 = &v.value, - None => out.push((column, &v.value)), - } - } - Ok(out) -} - -/// Statement for one grid change; `None` for an update with nothing to set. -fn change_sql( - target: &EditTarget, - change: &RowChange, - identity: &[String], -) -> AppResult> { - let table = qualified(target.schema.as_deref(), &target.table); - let mut params = Vec::new(); - let (op, sql) = match change { - RowChange::Update { key, values } => { - let values = assignments(target, values)?; - if values.is_empty() { - return Ok(None); - } - let mut sets = Vec::with_capacity(values.len()); - for (column, value) in values { - if identity.contains(&column.name) { - return Err(AppError::invalid(format!( - "Column {} is an identity column and cannot be changed.", - column.name - ))); - } - let expr = bind(&mut params, column, value)?; - sets.push(format!("{} = {expr}", quote_ident(&column.name))); - } - let filter = where_key(target, key, &mut params)?; - ( - ChangeOp::Update, - format!("UPDATE {table} SET {} WHERE {filter}", sets.join(", ")), - ) - } - RowChange::Delete { key } => { - let filter = where_key(target, key, &mut params)?; - ( - ChangeOp::Delete, - format!("DELETE FROM {table} WHERE {filter}"), - ) - } - RowChange::Insert { values } => { - let mut names = Vec::new(); - let mut exprs = Vec::new(); - for (column, value) in assignments(target, values)? { - if identity.contains(&column.name) { - if value.is_none() { - continue; - } - return Err(AppError::invalid(format!( - "Column {} is an identity column: leave it empty so the server numbers the row (an explicit value needs IDENTITY_INSERT).", - column.name - ))); - } - exprs.push(bind(&mut params, column, value)?); - names.push(quote_ident(&column.name)); - } - let sql = if names.is_empty() { - format!("INSERT INTO {table} DEFAULT VALUES") - } else { - format!( - "INSERT INTO {table} ({}) VALUES ({})", - names.join(", "), - exprs.join(", ") - ) - }; - (ChangeOp::Insert, sql) - } - }; - Ok(Some(ChangeSql { op, sql, params })) -} - -/// 0-based character offset where the given 1-based line starts. -fn line_start(sql: &str, line: u32) -> Option { - if line == 0 { - return None; - } - if line == 1 { - return Some(0); - } - let mut current = 1; - for (pos, c) in sql.chars().enumerate() { - if c == '\n' { - current += 1; - if current == line { - return Some(pos + 1); - } - } - } - None -} - -fn column_info(c: &Column) -> ColumnInfo { - let ty = c.column_type(); - ColumnInfo { - name: c.name().to_string(), - type_name: type_label(ty).to_string(), - kind: value_kind(ty), - } -} - -fn type_label(ty: ColumnType) -> &'static str { - use ColumnType as T; - match ty { - T::Null => "null", - T::Bit | T::Bitn => "bit", - T::Int1 => "tinyint", - T::Int2 => "smallint", - T::Int4 | T::Intn => "int", - T::Int8 => "bigint", - T::Float4 => "real", - T::Float8 | T::Floatn => "float", - T::Money => "money", - T::Money4 => "smallmoney", - T::Decimaln => "decimal", - T::Numericn => "numeric", - T::Datetime4 => "smalldatetime", - T::Datetime | T::Datetimen => "datetime", - T::Daten => "date", - T::Timen => "time", - T::Datetime2 => "datetime2", - T::DatetimeOffsetn => "datetimeoffset", - T::Guid => "uniqueidentifier", - T::BigVarBin => "varbinary", - T::BigBinary => "binary", - T::Image => "image", - T::BigVarChar => "varchar", - T::BigChar => "char", - T::NVarchar => "nvarchar", - T::NChar => "nchar", - T::Text => "text", - T::NText => "ntext", - T::Xml => "xml", - T::Udt => "udt", - T::SSVariant => "sql_variant", - } -} - -fn value_kind(ty: ColumnType) -> ValueKind { - use ColumnType as T; - match ty { - T::Int1 - | T::Int2 - | T::Int4 - | T::Int8 - | T::Intn - | T::Float4 - | T::Float8 - | T::Floatn - | T::Money - | T::Money4 - | T::Decimaln - | T::Numericn => ValueKind::Number, - T::Bit | T::Bitn => ValueKind::Bool, - T::Datetime4 - | T::Datetime - | T::Datetimen - | T::Daten - | T::Timen - | T::Datetime2 - | T::DatetimeOffsetn => ValueKind::Temporal, - T::BigVarBin | T::BigBinary | T::Image | T::Udt => ValueKind::Binary, - T::BigVarChar - | T::BigChar - | T::NVarchar - | T::NChar - | T::Text - | T::NText - | T::Xml - | T::Guid => ValueKind::Text, - T::Null | T::SSVariant => ValueKind::Other, - } -} - -/// Formats a value the way SSMS shows it, without losing digits. -fn cell(ty: ColumnType, data: &ColumnData<'_>) -> Option { - match data { - ColumnData::U8(v) => v.map(|v| v.to_string()), - ColumnData::I16(v) => v.map(|v| v.to_string()), - ColumnData::I32(v) => v.map(|v| v.to_string()), - ColumnData::I64(v) => v.map(|v| v.to_string()), - ColumnData::F32(v) => v.map(|v| float(v.to_string(), f64::from(v))), - // money and smallmoney arrive as f64 holding value / 10^4. - ColumnData::F64(v) if matches!(ty, ColumnType::Money | ColumnType::Money4) => v.map(money), - ColumnData::F64(v) => v.map(|v| float(v.to_string(), v)), - ColumnData::Bit(v) => v.map(|b| if b { "true" } else { "false" }.to_string()), - ColumnData::String(v) => v.as_ref().map(|s| s.to_string()), - ColumnData::Guid(v) => v.map(|g| g.to_string().to_ascii_uppercase()), - ColumnData::Binary(v) => v.as_ref().map(|b| hex(b)), - ColumnData::Numeric(v) => v.map(numeric), - ColumnData::Xml(v) => v.as_ref().map(|x| x.to_string()), - ColumnData::DateTime(v) => v.map(datetime), - ColumnData::SmallDateTime(v) => v.map(smalldatetime), - ColumnData::Time(v) => v.map(time), - ColumnData::Date(v) => v.map(date), - ColumnData::DateTime2(v) => v.map(datetime2), - ColumnData::DateTimeOffset(v) => v.map(datetimeoffset), - } -} - -/// Shortest round-trip text; exponent form for very large or small values. -fn float(text: String, v: f64) -> String { - let abs = v.abs(); - if abs != 0.0 && !(1e-5..1e16).contains(&abs) { - let exp = format!("{v:e}"); - match exp.split_once('e') { - Some((m, e)) if e.starts_with('-') => format!("{m}E{e}"), - Some((m, e)) => format!("{m}E+{e}"), - None => exp, - } - } else { - text - } -} - -fn numeric(n: Numeric) -> String { - decimal(n.value(), u32::from(n.scale())) -} - -fn money(v: f64) -> String { - // Exact for |value| below 2^53 / 10^4 (about 900 billion). - decimal((v * 10_000.0).round() as i128, 4) -} - -/// Integer `value` scaled by 10^-`scale`, with exactly `scale` decimals. -fn decimal(value: i128, scale: u32) -> String { - let digits = value.unsigned_abs().to_string(); - let scale = scale as usize; - let mut s = String::with_capacity(digits.len() + 3); - if value < 0 { - s.push('-'); - } - if scale == 0 { - s.push_str(&digits); - } else if digits.len() > scale { - let (int, frac) = digits.split_at(digits.len() - scale); - let _ = write!(s, "{int}.{frac}"); - } else { - let _ = write!(s, "0.{digits:0>scale$}"); - } - s -} - -/// Uppercase hexadecimal with the 0x prefix, as SSMS shows binary values. -fn hex(bytes: &[u8]) -> String { - let shown = &bytes[..bytes.len().min(super::binary_limit(BINARY_PREVIEW_BYTES))]; - let mut s = String::with_capacity(shown.len() * 2 + 2); - s.push_str("0x"); - for b in shown { - let _ = write!(s, "{b:02X}"); - } - if bytes.len() > shown.len() { - let _ = write!(s, "… ({} bytes)", bytes.len()); - } - s -} - -/// Proleptic Gregorian date for a day count relative to 1970-01-01. -fn civil_from_days(days: i64) -> (i64, u32, u32) { - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z.rem_euclid(146_097); - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let day = (doy - (153 * mp + 2) / 5 + 1) as u32; - let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32; - let year = yoe + era * 400 + i64::from(month <= 2); - (year, month, day) -} - -fn ymd(days_since_epoch: i64) -> String { - let (y, m, d) = civil_from_days(days_since_epoch); - format!("{y:04}-{m:02}-{d:02}") -} - -/// `hh:mm:ss[.fffffff]` from 10^-scale second increments since midnight. -fn clock(increments: u64, scale: u8) -> String { - let pow = 10u64.pow(u32::from(scale)); - let secs = increments / pow; - let mut s = format!("{:02}:{:02}:{:02}", secs / 3600, secs / 60 % 60, secs % 60); - if scale > 0 { - let frac = increments % pow; - let _ = write!(s, ".{frac:0width$}", width = scale as usize); - } - s -} - -fn date(d: Date) -> String { - ymd(i64::from(d.days()) - DAYS_0001_TO_EPOCH) -} - -fn time(t: Time) -> String { - clock(t.increments(), t.scale()) -} - -fn datetime2(dt: DateTime2) -> String { - format!("{} {}", date(dt.date()), time(dt.time())) -} - -/// The wire value is UTC; SSMS shows the local time with its offset. -fn datetimeoffset(dto: DateTimeOffset) -> String { - let dt = dto.datetime2(); - let scale = dt.time().scale(); - let pow = i128::from(10u64.pow(u32::from(scale))); - let day = 86_400 * pow; - let offset = i128::from(dto.offset()); - let total = - i128::from(dt.date().days()) * day + i128::from(dt.time().increments()) + offset * 60 * pow; - let days = total.div_euclid(day) as i64; - let increments = total.rem_euclid(day) as u64; - let sign = if offset < 0 { '-' } else { '+' }; - let abs = offset.unsigned_abs(); - format!( - "{} {} {sign}{:02}:{:02}", - ymd(days - DAYS_0001_TO_EPOCH), - clock(increments, scale), - abs / 60, - abs % 60 - ) -} - -/// `datetime` counts 1/300 s; SSMS rounds it to milliseconds (.000/.003/.007). -fn datetime(dt: DateTime) -> String { - let fragments = dt.seconds_fragments(); - let secs = u64::from(fragments / 300); - let millis = (u64::from(fragments % 300) * 10 + 1) / 3; - format!( - "{} {}.{millis:03}", - ymd(i64::from(dt.days()) - DAYS_1900_TO_EPOCH), - clock(secs, 0) - ) -} - -/// `smalldatetime` counts whole minutes. -fn smalldatetime(dt: SmallDateTime) -> String { - format!( - "{} {}", - ymd(i64::from(dt.days()) - DAYS_1900_TO_EPOCH), - clock(u64::from(dt.seconds_fragments()) * 60, 0) - ) -} - -fn connection_error(e: tiberius::error::Error) -> AppError { - let mut err = map_error(e, None); - err.kind = ErrorKind::Connection; - err -} - -pub fn map_error(e: tiberius::error::Error, sql: Option<&str>) -> AppError { - use tiberius::error::Error as E; - match e { - E::Server(t) => server_error( - t.code(), - t.class(), - t.state(), - t.message(), - t.procedure(), - t.line(), - sql, - ), - E::Io { kind, message } => { - if matches!( - kind, - std::io::ErrorKind::UnexpectedEof - | std::io::ErrorKind::ConnectionReset - | std::io::ErrorKind::ConnectionAborted - | std::io::ErrorKind::BrokenPipe - ) { - AppError::connection("The connection to the server was closed.") - } else { - AppError::connection(message) - } - } - E::Tls(message) => AppError::connection(format!("TLS: {message}")), - E::Routing { host, port } => AppError::connection(format!( - "The server redirected the connection to {host}:{port}." - )), - E::Protocol(m) => AppError::connection(format!("Protocol error: {m}")), - other => AppError::new(ErrorKind::Database, other.to_string()), - } -} - -/// Server error with SSMS-style code (`Msg 208, Level 16, State 1`) and the -/// start of the reported line as position. -fn server_error( - number: u32, - class: u8, - state: u8, - message: &str, - procedure: &str, - line: u32, - sql: Option<&str>, -) -> AppError { - let mut err = AppError::new(ErrorKind::Database, message.trim_end()); - err.code = Some(format!("Msg {number}, Level {class}, State {state}")); - if procedure.is_empty() { - if line > 0 { - err.detail = Some(format!("Line {line}")); - } - err.position = sql.and_then(|s| line_start(s, line)); - } else { - err.detail = Some(format!("Procedure {procedure}, Line {line}")); - } - if matches!(number, LOGIN_FAILED | CANNOT_OPEN_DATABASE) || class >= 20 { - err.kind = ErrorKind::Connection; - } - err -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Arc; - - #[test] - fn row_limit_only_for_plain_queries() { - assert!(row_limit_applies("select * from t")); - assert!(row_limit_applies( - "-- x\nWITH c AS (SELECT 1 a) SELECT * FROM c" - )); - assert!(row_limit_applies( - "SELECT 'insert into' AS x, [update] FROM t" - )); - assert!(row_limit_applies("SELECT N'set' FROM t /* delete */")); - assert!(row_limit_applies( - "SELECT * FROM t ORDER BY 1 OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY" - )); - assert!(!row_limit_applies("SELECT * INTO #t FROM s")); - assert!(!row_limit_applies("SELECT 1 UPDATE t SET a = 1")); - assert!(!row_limit_applies( - "WITH c AS (SELECT 1 a) DELETE FROM t WHERE a IN (SELECT a FROM c)" - )); - assert!(!row_limit_applies("UPDATE t SET a = 1")); - assert!(!row_limit_applies("EXEC sp_who")); - assert!(!row_limit_applies("SELECT 1; EXEC p")); - } - - #[test] - fn words_skip_literals_and_comments() { - assert_eq!( - sql_words("select 'it''s' /* a /* b */ c */ [x]] y] \"q\" -- z\n from @v"), - ["SELECT", "FROM", "@V"] - ); - } - - #[test] - fn line_offsets_are_in_chars() { - let sql = "SELECT 'ã';\nSELECT x\nFROM t"; - assert_eq!(line_start(sql, 1), Some(0)); - assert_eq!(line_start(sql, 2), Some(12)); - assert_eq!(line_start(sql, 3), Some(21)); - assert_eq!(line_start(sql, 4), None); - assert_eq!(line_start(sql, 0), None); - } - - #[test] - fn server_errors_keep_code_and_line() { - let e = server_error( - 208, - 16, - 1, - "Invalid object name 'x'.", - "", - 2, - Some("SELECT 1;\nSELECT * FROM x"), - ); - assert_eq!(e.code.as_deref(), Some("Msg 208, Level 16, State 1")); - assert_eq!(e.position, Some(10)); - assert_eq!(e.kind, ErrorKind::Database); - let e = server_error(50000, 16, 1, "boom", "dbo.p", 7, Some("EXEC dbo.p")); - assert_eq!(e.position, None); - assert_eq!(e.detail.as_deref(), Some("Procedure dbo.p, Line 7")); - let e = server_error(18456, 14, 1, "Login failed for user 'x'.", "", 1, None); - assert_eq!(e.kind, ErrorKind::Connection); - assert_eq!(e.code.as_deref(), Some("Msg 18456, Level 14, State 1")); - } - - #[test] - fn decimals_keep_every_digit() { - assert_eq!(decimal(123_456_789, 4), "12345.6789"); - assert_eq!(decimal(-50, 2), "-0.50"); - assert_eq!(decimal(5, 3), "0.005"); - assert_eq!(decimal(42, 0), "42"); - assert_eq!(decimal(0, 2), "0.00"); - assert_eq!( - numeric(Numeric::new_with_scale( - 12_345_678_901_234_567_890_123_456_789_012_345_678, - 10 - )), - "1234567890123456789012345678.9012345678" - ); - assert_eq!(money(-12.5), "-12.5000"); - assert_eq!(money(123_456_789.123_4), "123456789.1234"); - assert_eq!(money(0.0001), "0.0001"); - } - - #[test] - fn floats_use_exponent_only_at_extremes() { - assert_eq!(float(1.5f64.to_string(), 1.5), "1.5"); - assert_eq!(float(1e20f64.to_string(), 1e20), "1E+20"); - assert_eq!(float(1.5e-7f64.to_string(), 1.5e-7), "1.5E-7"); - assert_eq!(float(0f64.to_string(), 0.0), "0"); - } - - #[test] - fn dates_and_times() { - assert_eq!(ymd(0), "1970-01-01"); - assert_eq!(date(Date::new(0)), "0001-01-01"); - assert_eq!(date(Date::new(3_652_058)), "9999-12-31"); - assert_eq!(date(Date::new(738_624)), "2023-04-15"); - assert_eq!(time(Time::new(495_301_234_567, 7)), "13:45:30.1234567"); - assert_eq!(time(Time::new(4_953_012, 2)), "13:45:30.12"); - assert_eq!(time(Time::new(49_530, 0)), "13:45:30"); - assert_eq!( - datetime2(DateTime2::new(Date::new(738_624), Time::new(0, 3))), - "2023-04-15 00:00:00.000" - ); - // 1900-01-01 + 45000 days, 13:45:30 and 299/300 s. - assert_eq!( - datetime(DateTime::new( - 45_000, - (13 * 3600 + 45 * 60 + 30) * 300 + 299 - )), - "2023-03-17 13:45:30.997" - ); - assert_eq!(datetime(DateTime::new(0, 2)), "1900-01-01 00:00:00.007"); - assert_eq!( - datetime(DateTime::new(-53_690, 0)), - "1753-01-01 00:00:00.000" - ); - assert_eq!( - smalldatetime(SmallDateTime::new(45_000, 13 * 60 + 45)), - "2023-03-17 13:45:00" - ); - } - - #[test] - fn datetimeoffset_shows_local_time() { - // 2023-04-15 22:30:00.123 UTC at -03:00 and +03:00. - let utc = DateTime2::new(Date::new(738_624), Time::new(81_000_123, 3)); - assert_eq!( - datetimeoffset(DateTimeOffset::new(utc, -180)), - "2023-04-15 19:30:00.123 -03:00" - ); - assert_eq!( - datetimeoffset(DateTimeOffset::new(utc, 180)), - "2023-04-16 01:30:00.123 +03:00" - ); - assert_eq!( - datetimeoffset(DateTimeOffset::new(utc, 330)), - "2023-04-16 04:00:00.123 +05:30" - ); - } - - #[test] - fn cells_by_type() { - assert_eq!( - cell(ColumnType::Bitn, &ColumnData::Bit(Some(true))), - Some("true".into()) - ); - assert_eq!( - cell(ColumnType::Money, &ColumnData::F64(Some(-12.5))), - Some("-12.5000".into()) - ); - assert_eq!( - cell(ColumnType::Float8, &ColumnData::F64(Some(-12.5))), - Some("-12.5".into()) - ); - assert_eq!( - cell( - ColumnType::BigVarBin, - &ColumnData::Binary(Some(vec![0x0a, 0xff].into())) - ), - Some("0x0AFF".into()) - ); - let g = tiberius::Uuid::parse_str("6f9619ff-8b86-d011-b42d-00c04fc964ff").unwrap(); - assert_eq!( - cell(ColumnType::Guid, &ColumnData::Guid(Some(g))), - Some("6F9619FF-8B86-D011-B42D-00C04FC964FF".into()) - ); - assert_eq!(cell(ColumnType::Int4, &ColumnData::I32(None)), None); - } - - #[test] - fn literals_and_labels() { - assert_eq!(nstr("o'neil"), "N'o''neil'"); - assert_eq!(server_label("16.0.4135.4", 3), "SQL Server 16.0.4135.4"); - assert_eq!(server_label("12.0.2000.8", 5), "Azure SQL 12.0.2000.8"); - } - - fn col(table: &str, column: &str, ty: &str) -> Described { - Described { - schema: Some("dbo".into()), - table: Some(table.into()), - column: Some(column.into()), - type_name: Some(ty.into()), - ..Default::default() - } - } - - fn expr(ty: &str) -> Described { - Described { - type_name: Some(ty.into()), - ..Default::default() - } - } - - fn key(table: &str, index: i64, primary: bool, column: &str, nullable: bool) -> KeyPart { - KeyPart { - schema: "dbo".into(), - table: table.into(), - index, - primary, - column: column.into(), - nullable, - } - } - - #[test] - fn detection_finds_table_and_key() { - let described = [ - col("t", "name", "nvarchar(40)"), - expr("int"), - col("t", "b", "int"), - col("t", "a", "int"), - Described { - computed: true, - ..col("t", "total", "int") - }, - col("t", "ver", "timestamp"), - ]; - let keys = [key("t", 1, true, "a", false), key("t", 1, true, "b", false)]; - let t = edit_target(&described, &keys, 6).unwrap(); - assert_eq!(t.schema.as_deref(), Some("dbo")); - assert_eq!(t.table, "t"); - assert_eq!(t.key, [3, 2]); - let c = t.columns[0].as_ref().unwrap(); - assert_eq!( - (c.name.as_str(), c.type_name.as_str()), - ("name", "nvarchar(40)") - ); - assert!(t.columns[1].is_none()); - assert!(t.columns[4].is_none(), "computed"); - assert!(t.columns[5].is_none(), "rowversion"); - } - - #[test] - fn detection_read_only_reasons() { - let pk = [key("t", 1, true, "id", false)]; - // Two tables. - let err = edit_target(&[col("t", "id", "int"), col("u", "id", "int")], &pk, 2).unwrap_err(); - assert!(err.contains("several tables"), "{err}"); - // No table at all. - let err = edit_target(&[expr("int")], &pk, 1).unwrap_err(); - assert_eq!(err, ONLY_TABLE_ROWS); - // Describe error. - let failed = Described { - error: Some("uses a temp table".into()), - ..Default::default() - }; - assert_eq!(edit_target(&[failed], &pk, 1).unwrap_err(), ONLY_TABLE_ROWS); - // Column count does not match the result. - assert!(edit_target(&[col("t", "id", "int")], &pk, 2).is_err()); - // Key missing; browse mode added it as a hidden column. - let hidden = Described { - hidden: true, - ..col("t", "id", "int") - }; - let err = edit_target(&[col("t", "name", "nvarchar(5)"), hidden], &pk, 1).unwrap_err(); - assert_eq!( - err, - "Read-only: add the primary key columns (id) to the query to edit rows." - ); - // No key at all; a unique index on a nullable column does not count. - let err = edit_target( - &[col("t", "id", "int")], - &[key("t", 2, false, "id", true)], - 1, - ) - .unwrap_err(); - assert_eq!(err, "Read-only: table t has no primary key."); - // A NOT NULL unique key is used when there is no primary key. - let t = edit_target( - &[col("t", "x", "int"), col("t", "code", "varchar(5)")], - &[key("t", 2, false, "code", false)], - 2, - ) - .unwrap(); - assert_eq!(t.key, [1]); - // Another database. - let other = Described { - other_db: true, - ..col("t", "id", "int") - }; - assert!(edit_target(&[other], &pk, 1) - .unwrap_err() - .contains("another database")); - // Self join: the key shows twice. - let err = edit_target(&[col("t", "id", "int"), col("t", "id", "int")], &pk, 2).unwrap_err(); - assert!(err.contains("more than once"), "{err}"); - // Self join: browse mode added the other instance's key. - let err = edit_target( - &[ - col("t", "id", "int"), - col("t", "name", "int"), - Described { - hidden: true, - ..col("t", "id", "int") - }, - ], - &pk, - 2, - ) - .unwrap_err(); - assert!(err.contains("more than once"), "{err}"); - } - - #[test] - fn identifiers_are_bracket_quoted() { - assert_eq!(quote_ident("a]b"), "[a]]b]"); - assert_eq!( - qualified(Some("Sales Dept"), "Order Items"), - "[Sales Dept].[Order Items]" - ); - assert_eq!(qualified(None, "t"), "[t]"); - } - - #[test] - fn values_convert_with_fixed_styles() { - let v = |t: &str| value_expr(t, 2).unwrap(); - assert_eq!(v("decimal(10, 2)"), "CAST(@P2 AS decimal(10,2))"); - assert_eq!(v("BIT"), "CAST(@P2 AS bit)"); - assert_eq!(v("datetime2(7)"), "CONVERT(datetime2(7), @P2, 121)"); - assert_eq!( - v("datetimeoffset(3)"), - "CONVERT(datetimeoffset(3), @P2, 121)" - ); - assert_eq!(v("datetime"), "CONVERT(datetime, @P2, 121)"); - assert_eq!(v("time(3)"), "CAST(@P2 AS time(3))"); - assert_eq!(v("varbinary(max)"), "CONVERT(varbinary(max), @P2, 1)"); - assert_eq!(v("binary(4)"), "CONVERT(binary(4), @P2, 1)"); - assert_eq!(v("image"), "CONVERT(varbinary(max), @P2, 1)"); - assert_eq!( - v("hierarchyid"), - "CAST(CONVERT(varbinary(max), @P2, 1) AS hierarchyid)" - ); - assert_eq!(v("nvarchar(40)"), "@P2"); - assert_eq!(v("uniqueidentifier"), "CAST(@P2 AS uniqueidentifier)"); - for bad in [ - "timestamp", - "sql_variant", - "int); DROP TABLE x; --", - "decimal(10,2", - "varchar(-1)", - "", - ] { - assert!(value_expr(bad, 1).is_err(), "{bad}"); - } - } - - fn target() -> EditTarget { - let c = |name: &str, ty: &str| { - Some(EditColumn { - name: name.into(), - type_name: ty.into(), - }) - }; - EditTarget { - schema: Some("dbo".into()), - table: "Order Items".into(), - columns: vec![ - c("Item Id", "int"), - c("name", "nvarchar(40)"), - None, - c("data", "varbinary(max)"), - c("code", "char(3)"), - ], - key: vec![0, 4], - } - } - - fn cv(column: usize, value: Option<&str>) -> crate::model::CellValue { - crate::model::CellValue { - column, - value: value.map(str::to_string), - } - } - - #[test] - fn change_statements() { - let t = target(); - let s = change_sql( - &t, - &RowChange::Update { - key: vec![Some("7".into()), None], - values: vec![cv(1, Some("it's")), cv(3, None)], - }, - &[], - ) - .unwrap() - .unwrap(); - assert_eq!(s.op, ChangeOp::Update); - assert_eq!( - s.sql, - "UPDATE [dbo].[Order Items] SET [name] = @P1, [data] = CONVERT(varbinary(max), @P2, 1) \ - WHERE [Item Id] = CAST(@P3 AS int) AND [code] IS NULL" - ); - assert_eq!(s.params, [Some("it's".into()), None, Some("7".into())]); - - let s = change_sql( - &t, - &RowChange::Delete { - key: vec![Some("7".into()), Some("ab ".into())], - }, - &[], - ) - .unwrap() - .unwrap(); - assert_eq!( - s.sql, - "DELETE FROM [dbo].[Order Items] WHERE [Item Id] = CAST(@P1 AS int) AND [code] = @P2" - ); - - let s = change_sql( - &t, - &RowChange::Insert { - values: vec![cv(1, Some("a")), cv(1, Some("b")), cv(0, None)], - }, - &["Item Id".into()], - ) - .unwrap() - .unwrap(); - assert_eq!(s.op, ChangeOp::Insert); - assert_eq!( - s.sql, - "INSERT INTO [dbo].[Order Items] ([name]) VALUES (@P1)" - ); - assert_eq!(s.params, [Some("b".into())]); - - let s = change_sql(&t, &RowChange::Insert { values: vec![] }, &[]) - .unwrap() - .unwrap(); - assert_eq!(s.sql, "INSERT INTO [dbo].[Order Items] DEFAULT VALUES"); - - // Nothing to set. - let none = change_sql( - &t, - &RowChange::Update { - key: vec![Some("1".into()), Some("x".into())], - values: vec![], - }, - &[], - ) - .unwrap(); - assert!(none.is_none()); - } - - #[test] - fn invalid_changes_are_rejected() { - let t = target(); - let key = || vec![Some("1".into()), Some("x".into())]; - let invalid = |change: RowChange, identity: &[String]| { - let err = change_sql(&t, &change, identity).unwrap_err(); - assert_eq!(err.kind, ErrorKind::Invalid); - err.message - }; - // Expression column. - let m = invalid( - RowChange::Update { - key: key(), - values: vec![cv(2, Some("1"))], - }, - &[], - ); - assert!(m.contains("Column 3"), "{m}"); - // Truncated binary preview. - let m = invalid( - RowChange::Update { - key: key(), - values: vec![cv(3, Some("0x00FF… (40000 bytes)"))], - }, - &[], - ); - assert_eq!(m, "This value is only a preview and cannot be saved."); - // Identity value on insert and identity change on update. - let id = ["Item Id".to_string()]; - let m = invalid( - RowChange::Insert { - values: vec![cv(0, Some("5"))], - }, - &id, - ); - assert!(m.contains("IDENTITY_INSERT"), "{m}"); - let m = invalid( - RowChange::Update { - key: key(), - values: vec![cv(0, Some("5"))], - }, - &id, - ); - assert!(m.contains("identity"), "{m}"); - // Key of the wrong length. - invalid( - RowChange::Delete { - key: vec![Some("1".into())], - }, - &[], - ); - // Text that only looks like a preview is fine. - assert!(change_sql( - &t, - &RowChange::Update { - key: key(), - values: vec![cv(1, Some("see… (below)"))], - }, - &[], - ) - .is_ok()); - } - - // ---- Integration tests against a real server (see CONTRIBUTING). ---- - - fn test_profile() -> Option<(ConnectionProfile, String)> { - let host = std::env::var("LQ_MSSQL_HOST").ok()?; - let profile = ConnectionProfile { - engine: crate::model::Engine::Sqlserver, - host, - port: std::env::var("LQ_MSSQL_PORT") - .ok() - .and_then(|p| p.parse().ok()) - .unwrap_or(1433), - user: std::env::var("LQ_MSSQL_USER").unwrap_or_else(|_| "sa".into()), - database: std::env::var("LQ_MSSQL_DB").unwrap_or_else(|_| "master".into()), - ssl_mode: SslMode::Prefer, - ..Default::default() - }; - let password = std::env::var("LQ_MSSQL_PASSWORD").unwrap_or_default(); - Some((profile, password)) - } - - async fn open() -> Option { - let (profile, password) = test_profile()?; - Some(connect(&profile, Some(&password)).await.expect("connect")) - } - - async fn run(s: &MsSession, sql: &str, max_rows: usize) -> AppResult { - s.execute(&ExecRequest { - sql: sql.into(), - max_rows, - }) - .await - } - - #[tokio::test] - #[ignore] - async fn mssql_session_info() { - let Some(s) = open().await else { return }; - assert!( - s.server_version.starts_with("SQL Server "), - "{}", - s.server_version - ); - assert!(s.current_user.is_some()); - assert_eq!(s.current_schema.as_deref(), Some("dbo")); - let (profile, _) = test_profile().unwrap(); - let err = match connect(&profile, Some("wrong-password")).await { - Err(e) => e, - Ok(_) => panic!("login with a wrong password succeeded"), - }; - assert_eq!(err.kind, ErrorKind::Connection); - assert_eq!(err.code.as_deref(), Some("Msg 18456, Level 14, State 1")); - } - - #[tokio::test] - #[ignore] - async fn mssql_formats_values() { - let Some(s) = open().await else { return }; - let r = run( - &s, - "SELECT CAST(12345.6789 AS decimal(18,4)), CAST(-0.5 AS numeric(5,2)), - CAST(123456789.1234 AS money), CAST(-12.5 AS smallmoney), - CAST(1 AS bit), CAST(0 AS bit), - CAST('2024-05-01 13:45:30.1234567' AS datetime2(7)), - CAST('2024-05-01 13:45:30.12' AS datetime2(2)), - CAST('2024-05-01T13:45:30.123+03:00' AS datetimeoffset(3)), - CAST('2024-05-01 13:45:30.997' AS datetime), - CAST('2024-05-01 13:45' AS smalldatetime), - CAST('2024-05-01' AS date), CAST('13:45:30.5' AS time(1)), - CAST('6f9619ff-8b86-d011-b42d-00c04fc964ff' AS uniqueidentifier), - 0x0A0BFF, CAST('1' AS xml), N'ação', CAST(NULL AS int), - CAST(1.5 AS float), CAST(9223372036854775807 AS bigint), - CAST(255 AS tinyint), CAST(-32768 AS smallint), CAST('x ' AS char(3))", - 0, - ) - .await - .expect("select"); - let expected = [ - "12345.6789", - "-0.50", - "123456789.1234", - "-12.5000", - "true", - "false", - "2024-05-01 13:45:30.1234567", - "2024-05-01 13:45:30.12", - "2024-05-01 13:45:30.123 +03:00", - "2024-05-01 13:45:30.997", - "2024-05-01 13:45:00", - "2024-05-01", - "13:45:30.5", - "6F9619FF-8B86-D011-B42D-00C04FC964FF", - "0x0A0BFF", - "1", - "ação", - ]; - let row = &r.rows[0]; - for (i, want) in expected.iter().enumerate() { - assert_eq!(row[i].as_deref(), Some(*want), "column {}", i + 1); - } - assert_eq!(row[17], None); - assert_eq!(row[18].as_deref(), Some("1.5")); - assert_eq!(row[19].as_deref(), Some("9223372036854775807")); - assert_eq!(row[20].as_deref(), Some("255")); - assert_eq!(row[21].as_deref(), Some("-32768")); - assert_eq!(row[22].as_deref(), Some("x ")); - let cols = r.columns.unwrap(); - assert_eq!(cols[0].kind, ValueKind::Number); - assert_eq!(cols[6].kind, ValueKind::Temporal); - assert_eq!(cols[14].kind, ValueKind::Binary); - } - - #[tokio::test] - #[ignore] - async fn mssql_row_limit() { - let Some(s) = open().await else { return }; - run(&s, "CREATE TABLE #lq_limit (id int)", 0).await.unwrap(); - let r = run( - &s, - "INSERT INTO #lq_limit SELECT TOP (30) 1 FROM sys.all_objects", - 0, - ) - .await - .unwrap(); - assert_eq!(r.rows_affected, Some(30)); - - let r = run(&s, "SELECT * FROM #lq_limit", 10).await.unwrap(); - assert_eq!(r.rows.len(), 10); - assert!(r.truncated); - let r = run(&s, "SELECT TOP (10) * FROM #lq_limit", 10) - .await - .unwrap(); - assert_eq!(r.rows.len(), 10); - assert!(!r.truncated); - - // ROWCOUNT was reset: the UPDATE touches every row. - let r = run(&s, "UPDATE #lq_limit SET id = 2", 10).await.unwrap(); - assert_eq!(r.rows_affected, Some(30)); - // Not a plain SELECT: limited on the client, rows still all inserted. - let r = run(&s, "SELECT * INTO #lq_copy FROM #lq_limit", 10) - .await - .unwrap(); - assert_eq!(r.rows_affected, Some(30)); - let r = run(&s, "EXEC('SELECT * FROM #lq_copy')", 5).await.unwrap(); - assert_eq!(r.rows.len(), 5); - assert!(r.truncated); - } - - #[tokio::test] - #[ignore] - async fn mssql_error_code_and_position() { - let Some(s) = open().await else { return }; - let err = run(&s, "SELECT 1;\nSELECT * FROM dbo.lq_missing_table", 0) - .await - .unwrap_err(); - assert_eq!(err.kind, ErrorKind::Database); - assert_eq!(err.code.as_deref(), Some("Msg 208, Level 16, State 1")); - assert_eq!(err.position, Some(10)); - // The session keeps working. - let r = run(&s, "SELECT 1", 0).await.unwrap(); - assert_eq!(r.rows[0][0].as_deref(), Some("1")); - // PRINT runs; tiberius does not surface its text. - run(&s, "PRINT 'hello'", 0).await.unwrap(); - } - - #[tokio::test] - #[ignore] - async fn mssql_manual_transactions() { - let Some(s) = open().await else { return }; - run(&s, "CREATE TABLE #lq_tx (id int)", 0).await.unwrap(); - - let st = s.set_autocommit(false).await.unwrap(); - assert!(!st.autocommit && !st.in_transaction); - let r = run(&s, "INSERT INTO #lq_tx VALUES (1)", 0).await.unwrap(); - assert!(r.in_transaction); - let st = s.end_transaction(false).await.unwrap(); - assert!(!st.in_transaction); - let r = run(&s, "SELECT COUNT(*) FROM #lq_tx", 0).await.unwrap(); - assert_eq!(r.rows[0][0].as_deref(), Some("0")); - - run(&s, "INSERT INTO #lq_tx VALUES (2)", 0).await.unwrap(); - let st = s.end_transaction(true).await.unwrap(); - assert!(!st.in_transaction); - - run(&s, "INSERT INTO #lq_tx VALUES (3)", 0).await.unwrap(); - assert!(s.tx_state().in_transaction); - // Back to autocommit commits pending work. - let st = s.set_autocommit(true).await.unwrap(); - assert!(st.autocommit && !st.in_transaction); - let r = run(&s, "SELECT COUNT(*) FROM #lq_tx", 0).await.unwrap(); - assert_eq!(r.rows[0][0].as_deref(), Some("2")); - assert!(!r.in_transaction); - - // Explicit BEGIN TRAN in autocommit mode is tracked too. - let r = run(&s, "BEGIN TRAN", 0).await.unwrap(); - assert!(r.in_transaction); - let r = run(&s, "ROLLBACK", 0).await.unwrap(); - assert!(!r.in_transaction); - } - - #[tokio::test] - #[ignore] - async fn mssql_metadata() { - let Some(s) = open().await else { return }; - run( - &s, - "DROP TABLE IF EXISTS dbo.lq_meta; - CREATE TABLE dbo.lq_meta (id int NOT NULL PRIMARY KEY, name nvarchar(40) NULL, - amount decimal(10,2), data varbinary(max), - at datetime2(3))", - 0, - ) - .await - .unwrap(); - let schemas = s.list_schemas().await.unwrap(); - assert_eq!(schemas.first().map(String::as_str), Some("dbo")); - assert!(!schemas.iter().any(|n| n == "db_owner")); - let objects = s.list_objects("dbo").await.unwrap(); - assert!(objects - .iter() - .any(|o| o.name == "lq_meta" && o.kind == "table")); - let sys = s.list_objects("sys").await.unwrap(); - assert!(sys.iter().any(|o| o.name == "objects" && o.kind == "view")); - let cols = s.list_columns("dbo", "lq_meta").await.unwrap(); - let types: Vec<&str> = cols.iter().map(|c| c.type_name.as_str()).collect(); - assert_eq!( - types, - [ - "int", - "nvarchar(40)", - "decimal(10,2)", - "varbinary(max)", - "datetime2(3)" - ] - ); - assert!(cols[0].primary_key && !cols[0].nullable); - assert!(!cols[1].primary_key && cols[1].nullable); - run(&s, "DROP TABLE dbo.lq_meta", 0).await.unwrap(); - } - - #[tokio::test] - #[ignore] - async fn mssql_cancel() { - let Some(s) = open().await else { return }; - let s = Arc::new(s); - let running = { - let s = s.clone(); - tokio::spawn(async move { run(&s, "WAITFOR DELAY '00:00:30'", 0).await }) - }; - tokio::time::sleep(Duration::from_secs(1)).await; - s.cancel().await.unwrap(); - let err = running.await.unwrap().unwrap_err(); - assert_eq!(err.kind, ErrorKind::Cancelled); - let r = run(&s, "SELECT 2", 0).await.unwrap(); - assert_eq!(r.rows[0][0].as_deref(), Some("2")); - } - - // ---- Grid editing ---- - - fn reason(r: &ExecResult) -> &str { - assert!(r.editable.is_none(), "unexpectedly editable"); - r.read_only_reason.as_deref().expect("a read-only reason") - } - - async fn apply( - s: &MsSession, - target: &EditTarget, - changes: Vec, - ) -> AppResult { - s.apply_changes(&ApplyRequest { - target: target.clone(), - changes, - }) - .await - } - - async fn scalar(s: &MsSession, sql: &str) -> Option { - run(s, sql, 0).await.unwrap().rows[0][0].clone() - } - - #[tokio::test] - #[ignore] - async fn mssql_edit_detection() { - let Some(s) = open().await else { return }; - run( - &s, - "DROP TABLE IF EXISTS dbo.lq_edit_items, dbo.lq_edit_owner, dbo.lq_edit_nokey; - CREATE TABLE dbo.lq_edit_items (id int NOT NULL PRIMARY KEY, name nvarchar(40), - qty int, total AS qty * 2, ver rowversion); - CREATE TABLE dbo.lq_edit_owner (id int NOT NULL PRIMARY KEY, item_id int); - CREATE TABLE dbo.lq_edit_nokey (a int, b int); - INSERT INTO dbo.lq_edit_items (id, name, qty) VALUES (1, N'a', 1); - INSERT INTO dbo.lq_edit_owner VALUES (1, 1); - INSERT INTO dbo.lq_edit_nokey VALUES (1, 2);", - 0, - ) - .await - .unwrap(); - - let r = run( - &s, - "SELECT name, id, qty + 1 AS next, total, ver FROM dbo.lq_edit_items", - 0, - ) - .await - .unwrap(); - let t = r.editable.expect("editable"); - assert!(r.read_only_reason.is_none()); - assert_eq!(t.schema.as_deref(), Some("dbo")); - assert_eq!(t.table, "lq_edit_items"); - assert_eq!(t.key, [1]); - let name = t.columns[0].as_ref().unwrap(); - assert_eq!( - (name.name.as_str(), name.type_name.as_str()), - ("name", "nvarchar(40)") - ); - assert_eq!(t.columns[1].as_ref().unwrap().type_name, "int"); - assert!(t.columns[2].is_none(), "expression"); - assert!(t.columns[3].is_none(), "computed"); - assert!(t.columns[4].is_none(), "rowversion"); - - let r = run( - &s, - "SELECT i.id, i.name, o.id AS owner FROM dbo.lq_edit_items i - JOIN dbo.lq_edit_owner o ON o.item_id = i.id", - 0, - ) - .await - .unwrap(); - assert!(reason(&r).contains("several tables"), "{}", reason(&r)); - - // Only columns of one table from a join: editable. - let r = run( - &s, - "SELECT i.id, i.name FROM dbo.lq_edit_items i - JOIN dbo.lq_edit_owner o ON o.item_id = i.id", - 0, - ) - .await - .unwrap(); - assert!(r.editable.is_some(), "{:?}", r.read_only_reason); - - let r = run(&s, "SELECT a, b FROM dbo.lq_edit_nokey", 0) - .await - .unwrap(); - reason(&r); - let r = run(&s, "SELECT name, qty FROM dbo.lq_edit_items", 0) - .await - .unwrap(); - assert!(reason(&r).contains("(id)"), "{}", reason(&r)); - let r = run(&s, "SELECT 1 AS x", 0).await.unwrap(); - reason(&r); - let r = run(&s, "EXEC('SELECT id FROM dbo.lq_edit_items')", 0) - .await - .unwrap(); - assert_eq!(reason(&r), ONLY_TABLE_ROWS); - // A limited query is still described. - let r = run(&s, "SELECT id, name FROM dbo.lq_edit_items", 1) - .await - .unwrap(); - assert!(r.editable.is_some()); - - // Manual commit: describing never leaves a transaction behind. - s.set_autocommit(false).await.unwrap(); - let r = run(&s, "SELECT 1 AS x", 0).await.unwrap(); - assert!(!r.in_transaction); - assert_eq!(scalar(&s, "SELECT @@TRANCOUNT").await.as_deref(), Some("0")); - let r = run(&s, "SELECT id, name FROM dbo.lq_edit_items", 0) - .await - .unwrap(); - assert!(r.editable.is_some()); - s.end_transaction(false).await.unwrap(); - s.set_autocommit(true).await.unwrap(); - - run( - &s, - "DROP TABLE dbo.lq_edit_items, dbo.lq_edit_owner, dbo.lq_edit_nokey", - 0, - ) - .await - .unwrap(); - } - - #[tokio::test] - #[ignore] - async fn mssql_edit_apply() { - let Some(s) = open().await else { return }; - run( - &s, - "DROP TABLE IF EXISTS dbo.lq_edit_rows; - CREATE TABLE dbo.lq_edit_rows (id int IDENTITY PRIMARY KEY, - name nvarchar(40) NOT NULL, qty int NULL); - INSERT INTO dbo.lq_edit_rows (name, qty) VALUES (N'a', 1), (N'b', 2), (N'c', 3);", - 0, - ) - .await - .unwrap(); - let r = run( - &s, - "SELECT id, name, qty FROM dbo.lq_edit_rows ORDER BY id", - 0, - ) - .await - .unwrap(); - let t = r.editable.expect("editable"); - let res = apply( - &s, - &t, - vec![ - RowChange::Update { - key: vec![Some("1".into())], - values: vec![cv(1, Some("a2")), cv(2, None)], - }, - RowChange::Delete { - key: vec![Some("2".into())], - }, - RowChange::Insert { - values: vec![cv(1, Some("d")), cv(0, None)], - }, - ], - ) - .await - .unwrap(); - assert_eq!((res.updated, res.deleted, res.inserted), (1, 1, 1)); - assert!(!res.in_transaction); - let all = "SELECT STRING_AGG(name + ':' + ISNULL(CAST(qty AS varchar(10)), 'null'), ',') - WITHIN GROUP (ORDER BY id) FROM dbo.lq_edit_rows"; - assert_eq!(scalar(&s, all).await.as_deref(), Some("a2:null,c:3,d:null")); - - // An identity value on insert is refused before anything runs. - let err = apply( - &s, - &t, - vec![RowChange::Insert { - values: vec![cv(0, Some("50")), cv(1, Some("x"))], - }], - ) - .await - .unwrap_err(); - assert_eq!(err.kind, ErrorKind::Invalid); - assert!(!s.tx_state().in_transaction); - - // A key that matches nothing rolls back the earlier changes. - let err = apply( - &s, - &t, - vec![ - RowChange::Update { - key: vec![Some("1".into())], - values: vec![cv(1, Some("changed"))], - }, - RowChange::Update { - key: vec![Some("999".into())], - values: vec![cv(1, Some("ghost"))], - }, - ], - ) - .await - .unwrap_err(); - assert_eq!(err.kind, ErrorKind::Database); - assert_eq!( - err.message, - "Row 2 was not saved: 0 rows matched its key (changed or removed by someone else)." - ); - assert!(!s.tx_state().in_transaction); - assert_eq!(scalar(&s, all).await.as_deref(), Some("a2:null,c:3,d:null")); - - // A server error (NOT NULL) maps like execute and rolls back. - let err = apply( - &s, - &t, - vec![ - RowChange::Delete { - key: vec![Some("3".into())], - }, - RowChange::Update { - key: vec![Some("1".into())], - values: vec![cv(1, None)], - }, - ], - ) - .await - .unwrap_err(); - assert_eq!(err.code.as_deref(), Some("Msg 515, Level 16, State 2")); - assert_eq!(err.detail.as_deref(), Some("Row 2 was not saved.")); - assert_eq!(scalar(&s, all).await.as_deref(), Some("a2:null,c:3,d:null")); - - // Manual commit: the changes stay in the open transaction. - s.set_autocommit(false).await.unwrap(); - let change = |name: &str| { - vec![RowChange::Update { - key: vec![Some("1".into())], - values: vec![cv(1, Some(name))], - }] - }; - let res = apply(&s, &t, change("m1")).await.unwrap(); - assert!(res.in_transaction && s.tx_state().in_transaction); - s.end_transaction(false).await.unwrap(); - assert_eq!(scalar(&s, all).await.as_deref(), Some("a2:null,c:3,d:null")); - s.end_transaction(true).await.unwrap(); - apply(&s, &t, change("m2")).await.unwrap(); - // A failure inside the transaction undoes only this call. - let mut failing = change("m3"); - failing.push(RowChange::Delete { - key: vec![Some("999".into())], - }); - apply(&s, &t, failing).await.unwrap_err(); - assert!(s.tx_state().in_transaction); - s.end_transaction(true).await.unwrap(); - s.set_autocommit(true).await.unwrap(); - assert_eq!(scalar(&s, all).await.as_deref(), Some("m2:null,c:3,d:null")); - - // An explicit transaction in autocommit mode is joined, not committed. - run(&s, "BEGIN TRAN", 0).await.unwrap(); - let res = apply(&s, &t, change("x1")).await.unwrap(); - assert!(res.in_transaction); - run(&s, "ROLLBACK", 0).await.unwrap(); - assert_eq!(scalar(&s, all).await.as_deref(), Some("m2:null,c:3,d:null")); - - run(&s, "DROP TABLE dbo.lq_edit_rows", 0).await.unwrap(); - } - - #[tokio::test] - #[ignore] - async fn mssql_edit_round_trip() { - let Some(s) = open().await else { return }; - run( - &s, - "DROP TABLE IF EXISTS dbo.lq_edit_types; - CREATE TABLE dbo.lq_edit_types ( - id int NOT NULL PRIMARY KEY, dec decimal(18,4), num numeric(5,2), mon money, - smon smallmoney, ti tinyint, si smallint, i int, bi bigint, fl float, re real, - b bit, d date, dt datetime, sdt smalldatetime, dt2 datetime2(7), - dto datetimeoffset(3), tm time(3), g uniqueidentifier, s nvarchar(100), - vs varchar(100), ch char(5), bin varbinary(20), fbin binary(4), x xml, - n int NULL); - INSERT INTO dbo.lq_edit_types VALUES ( - 1, 12345.6789, -0.5, 123456789.1234, -12.5, 255, -32768, -7, - 9223372036854775807, 0.1, 1.5, 1, '2024-05-21', '2024-05-21T13:45:30.997', - '2024-05-21T13:45:00', '2024-05-21T13:45:30.1234567', - '2024-05-21T13:45:30.123+05:30', '13:45:30.5', - '6f9619ff-8b86-d011-b42d-00c04fc964ff', N'it''s \"q\"' + CHAR(10) + N'ação', - 'plain', 'ab', 0x0A0BFF, 0x00000001, N'1', NULL)", - 0, - ) - .await - .unwrap(); - // Settings that would change implicit conversions must not matter. - run(&s, "SET DATEFORMAT ydm; SET LANGUAGE Deutsch", 0) - .await - .unwrap(); - let select = "SELECT * FROM dbo.lq_edit_types"; - let before = run(&s, select, 0).await.unwrap(); - let t = before.editable.clone().expect("editable"); - let row = &before.rows[0]; - let values = (1..row.len()).map(|i| crate::model::CellValue { - column: i, - value: row[i].clone(), - }); - let res = apply( - &s, - &t, - vec![RowChange::Update { - key: vec![row[0].clone()], - values: values.collect(), - }], - ) - .await - .unwrap(); - assert_eq!(res.updated, 1); - let after = run(&s, select, 0).await.unwrap(); - let names: Vec<&str> = before - .columns - .as_ref() - .unwrap() - .iter() - .map(|c| c.name.as_str()) - .collect(); - for (i, name) in names.iter().enumerate() { - assert_eq!(after.rows[0][i], before.rows[0][i], "column {name}"); - } - - // New values typed in the displayed format. - let typed = [ - ("dt2", "2023-12-31 23:59:59.0000001"), - ("dto", "2023-01-02 03:04:05.678 -03:00"), - ("dt", "2023-01-13 00:00:00.003"), - ("d", "2023-01-13"), - ("b", "false"), - ("bin", "0x"), - ("dec", "-0.0001"), - ]; - let values = typed - .iter() - .map(|(name, v)| cv(names.iter().position(|n| n == name).unwrap(), Some(v))) - .collect(); - apply( - &s, - &t, - vec![RowChange::Update { - key: vec![Some("1".into())], - values, - }], - ) - .await - .unwrap(); - let after = run(&s, select, 0).await.unwrap(); - for (name, v) in typed { - let i = names.iter().position(|n| *n == name).unwrap(); - assert_eq!(after.rows[0][i].as_deref(), Some(v), "column {name}"); - } - run( - &s, - "SET DATEFORMAT mdy; SET LANGUAGE us_english; DROP TABLE dbo.lq_edit_types", - 0, - ) - .await - .unwrap(); - } - - #[tokio::test] - #[ignore] - async fn mssql_edit_quoted_names() { - let Some(s) = open().await else { return }; - run( - &s, - "DROP TABLE IF EXISTS dbo.[lq_edit_Mixed Case]; - CREATE TABLE dbo.[lq_edit_Mixed Case] ([Item Id] int NOT NULL PRIMARY KEY, - [Some]]Name] nvarchar(20)); - INSERT INTO dbo.[lq_edit_Mixed Case] VALUES (1, N'one');", - 0, - ) - .await - .unwrap(); - let r = run( - &s, - "SELECT [Some]]Name], [Item Id] FROM dbo.[lq_edit_Mixed Case]", - 0, - ) - .await - .unwrap(); - let t = r.editable.expect("editable"); - assert_eq!(t.table, "lq_edit_Mixed Case"); - assert_eq!(t.key, [1]); - assert_eq!(t.columns[0].as_ref().unwrap().name, "Some]Name"); - let res = apply( - &s, - &t, - vec![ - RowChange::Update { - key: vec![Some("1".into())], - values: vec![cv(0, Some("uno"))], - }, - RowChange::Insert { - values: vec![cv(1, Some("2")), cv(0, Some("dos"))], - }, - RowChange::Insert { - values: vec![cv(1, Some("3"))], - }, - RowChange::Delete { - key: vec![Some("3".into())], - }, - ], - ) - .await - .unwrap(); - assert_eq!((res.updated, res.deleted, res.inserted), (1, 1, 2)); - let r = run( - &s, - "SELECT STRING_AGG([Some]]Name], ',') WITHIN GROUP (ORDER BY [Item Id]) - FROM dbo.[lq_edit_Mixed Case]", - 0, - ) - .await - .unwrap(); - assert_eq!(r.rows[0][0].as_deref(), Some("uno,dos")); - run(&s, "DROP TABLE dbo.[lq_edit_Mixed Case]", 0) - .await - .unwrap(); - } - - #[tokio::test] - #[ignore] - async fn result_view_sql() { - let Some((profile, password)) = test_profile() else { - return; - }; - let s = crate::drivers::Session::open(&profile, Some(&password)) - .await - .expect("connect"); - crate::drivers::view_fixtures::check(&s, "sqlserver").await; - } - - #[tokio::test] - #[ignore] - async fn ddl_sql() { - let Some((profile, password)) = test_profile() else { - return; - }; - let s = crate::drivers::Session::open(&profile, Some(&password)) - .await - .expect("connect"); - crate::drivers::ddl_fixtures::check(&s, "sqlserver", "dbo").await; - } - - #[tokio::test] - #[ignore] - async fn export_import_round_trip() { - let Some((profile, password)) = test_profile() else { - return; - }; - let s = crate::drivers::Session::open(&profile, Some(&password)) - .await - .expect("connect"); - crate::transfer::round_trip::check(&s, "dbo").await; - } -} diff --git a/src-tauri/src/drivers/tns.rs b/src-tauri/src/drivers/tns.rs deleted file mode 100644 index 743a338..0000000 --- a/src-tauri/src/drivers/tns.rs +++ /dev/null @@ -1,609 +0,0 @@ -//! Oracle network configuration: finds `tnsnames.ora` the way Oracle clients -//! do and reads it without requiring UTF-8. -//! -//! Search order: `TNS_ADMIN`, `ORACLE_HOME/network/admin`, the Oracle homes -//! registered in the Windows registry, Oracle clients and Instant Clients on -//! the library path, then the system folders used on Linux and macOS. -//! -//! Corporate `tnsnames.ora` files are often saved as Latin-1 (accented -//! comments). The driver's own lookup rejects such files, so aliases are -//! resolved here and the driver receives the full descriptor. - -use std::collections::{HashMap, HashSet}; -use std::path::{Path, PathBuf}; - -use serde::Serialize; - -use crate::error::{AppError, AppResult}; - -const TNSNAMES: &str = "tnsnames.ora"; -const MAX_IFILE_DEPTH: usize = 8; - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct TnsEntry { - pub alias: String, - pub descriptor: String, - pub host: Option, - pub port: Option, - pub service_name: Option, - pub sid: Option, - pub protocol: Option, -} - -/// A folder with a `tnsnames.ora`, as shown in the "Oracle client" picker. -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct TnsSource { - pub dir: String, - /// Oracle home name (`OraClient19Home1`) or the folder itself. - pub label: String, - /// Where it was found: `TNS_ADMIN`, `ORACLE_HOME`, `Windows registry`... - pub origin: String, - pub entries: Vec, - pub error: Option, -} - -#[derive(Debug, Clone)] -struct Candidate { - dir: PathBuf, - label: String, - origin: String, -} - -/// Every folder with a `tnsnames.ora` found on this machine, in search order. -pub fn discover() -> Vec { - let env = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty()); - let mut seen = HashSet::new(); - candidates(&env) - .into_iter() - .filter(|c| c.dir.join(TNSNAMES).is_file()) - .filter(|c| seen.insert(path_key(&c.dir))) - .map(|c| read_source(&c.dir, c.label, c.origin)) - .collect() -} - -/// Reads a folder picked by the user. Accepts the `network/admin` folder, -/// an Oracle home or Instant Client folder, or the `tnsnames.ora` file. -pub fn read_folder(path: &str) -> AppResult { - let dir = normalize_dir(Path::new(path.trim())) - .ok_or_else(|| AppError::not_found(format!("No {TNSNAMES} found in {path}.")))?; - let label = dir.display().to_string(); - Ok(read_source(&dir, label, "Selected folder".into())) -} - -/// Resolves an alias to its descriptor. With `config_dir`, only that folder -/// is used; otherwise the discovered folders are searched in order. -pub fn resolve(alias: &str, config_dir: Option<&str>) -> AppResult<(String, PathBuf)> { - let alias = alias.trim(); - if alias.is_empty() { - return Err(AppError::invalid("Choose a TNS alias.")); - } - let sources = match config_dir.filter(|d| !d.trim().is_empty()) { - Some(dir) => vec![read_folder(dir)?], - None => discover(), - }; - if sources.is_empty() { - return Err(AppError::connection(format!( - "No {TNSNAMES} found. Set TNS_ADMIN, install an Oracle client or choose the folder in the connection." - ))); - } - for source in &sources { - let dir = PathBuf::from(&source.dir); - if let Some(entry) = find(&source.entries, alias, default_domain(&dir).as_deref()) { - return Ok((entry.descriptor.clone(), dir)); - } - } - let searched: Vec = sources - .iter() - .map(|s| Path::new(&s.dir).join(TNSNAMES).display().to_string()) - .collect(); - Err(AppError::connection(format!( - "TNS alias \"{alias}\" was not found in {}.", - searched.join(", ") - ))) -} - -/// The first discovered folder, used for `sqlnet.ora` and aliases typed in a -/// custom connect string when the profile has no folder of its own. -pub fn default_dir() -> Option { - discover().into_iter().next().map(|s| PathBuf::from(s.dir)) -} - -/// Aliases match without case; `NAMES.DEFAULT_DOMAIN` from `sqlnet.ora` is -/// appended when the bare name is not defined, as Oracle clients do. -fn find<'a>(entries: &'a [TnsEntry], alias: &str, domain: Option<&str>) -> Option<&'a TnsEntry> { - let exact = entries.iter().find(|e| e.alias.eq_ignore_ascii_case(alias)); - exact.or_else(|| { - let domain = domain?; - if alias.contains('.') { - return None; - } - let qualified = format!("{alias}.{domain}"); - entries - .iter() - .find(|e| e.alias.eq_ignore_ascii_case(&qualified)) - }) -} - -fn default_domain(dir: &Path) -> Option { - let text = decode(&std::fs::read(dir.join("sqlnet.ora")).ok()?); - parse(&text) - .into_iter() - .find(|(keys, _)| { - keys.iter() - .any(|k| k.eq_ignore_ascii_case("names.default_domain")) - }) - .map(|(_, value)| value.trim().to_string()) - .filter(|v| !v.is_empty()) -} - -fn read_source(dir: &Path, label: String, origin: String) -> TnsSource { - let mut entries = Vec::new(); - let mut error = None; - let mut visited = HashSet::new(); - if let Err(e) = read_file(&dir.join(TNSNAMES), dir, &mut entries, &mut visited, 0) { - error = Some(e); - } - // A later definition replaces an earlier one, keeping its position. - let mut index: HashMap = HashMap::new(); - let mut unique: Vec = Vec::new(); - for entry in entries { - match index.get(&entry.alias.to_ascii_lowercase()) { - Some(&i) => unique[i] = entry, - None => { - index.insert(entry.alias.to_ascii_lowercase(), unique.len()); - unique.push(entry); - } - } - } - TnsSource { - dir: dir.display().to_string(), - label, - origin, - entries: unique, - error, - } -} - -fn read_file( - file: &Path, - dir: &Path, - out: &mut Vec, - visited: &mut HashSet, - depth: usize, -) -> Result<(), String> { - if depth > MAX_IFILE_DEPTH || !visited.insert(path_key(file)) { - return Err(format!( - "IFILE cycle or nesting too deep at {}", - file.display() - )); - } - let bytes = std::fs::read(file).map_err(|e| format!("{}: {e}", file.display()))?; - for (keys, value) in parse(&decode(&bytes)) { - if keys.len() == 1 && keys[0].eq_ignore_ascii_case("ifile") { - let included = dir.join(value.trim().trim_matches('"')); - read_file(&included, dir, out, visited, depth + 1)?; - continue; - } - for alias in keys { - out.push(entry(alias, &value)); - } - } - Ok(()) -} - -fn entry(alias: String, value: &str) -> TnsEntry { - let descriptor = compact(value); - TnsEntry { - host: param(&descriptor, "HOST"), - port: param(&descriptor, "PORT").and_then(|p| p.parse().ok()), - service_name: param(&descriptor, "SERVICE_NAME"), - sid: param(&descriptor, "SID"), - protocol: param(&descriptor, "PROTOCOL").map(|p| p.to_ascii_uppercase()), - alias, - descriptor, - } -} - -/// UTF-8 when valid, otherwise Latin-1 (every byte is a code point). -fn decode(bytes: &[u8]) -> String { - let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes); - match std::str::from_utf8(bytes) { - Ok(s) => s.to_string(), - Err(_) => bytes.iter().map(|&b| b as char).collect(), - } -} - -fn compact(value: &str) -> String { - value.split_whitespace().collect::>().join(" ") -} - -/// First `(KEY = value)` in a descriptor, case-insensitive. -fn param(descriptor: &str, key: &str) -> Option { - let bytes = descriptor.as_bytes(); - let mut i = 0; - while let Some(off) = descriptor[i..].find('(') { - let mut j = i + off + 1; - while j < bytes.len() && bytes[j].is_ascii_whitespace() { - j += 1; - } - let end = j + key.len(); - if end <= bytes.len() && bytes[j..end].eq_ignore_ascii_case(key.as_bytes()) { - let mut k = end; - while k < bytes.len() && bytes[k].is_ascii_whitespace() { - k += 1; - } - if bytes.get(k) == Some(&b'=') { - let rest = &descriptor[k + 1..]; - let value = rest.split(')').next().unwrap_or("").trim(); - if !value.is_empty() && !value.starts_with('(') { - return Some(value.to_string()); - } - } - } - i = i + off + 1; - } - None -} - -/// Parses `name[, name...] = value` entries. A value starting with `(` runs -/// until its parentheses balance; any other value ends at the line break. -/// `#` starts a comment. -fn parse(text: &str) -> Vec<(Vec, String)> { - let chars: Vec = text.chars().collect(); - let n = chars.len(); - let mut i = 0; - let mut out = Vec::new(); - - let skip_comment = |i: &mut usize| { - while *i < n && chars[*i] != '\n' { - *i += 1; - } - }; - - loop { - // Whitespace and comments before the names. - while i < n && (chars[i].is_whitespace() || chars[i] == '#') { - if chars[i] == '#' { - skip_comment(&mut i); - } else { - i += 1; - } - } - if i >= n { - break; - } - - // Names up to '='. - let mut names = String::new(); - let mut malformed = false; - while i < n && chars[i] != '=' { - match chars[i] { - '#' => skip_comment(&mut i), - '(' | ')' => { - malformed = true; - i += 1; - } - c => { - names.push(c); - i += 1; - } - } - } - if i >= n { - break; - } - i += 1; // '=' - - // Value. - while i < n && chars[i].is_whitespace() { - i += 1; - } - let mut value = String::new(); - if i < n && chars[i] == '(' { - let mut depth = 0usize; - while i < n { - let c = chars[i]; - if c == '#' { - skip_comment(&mut i); - continue; - } - value.push(c); - i += 1; - if c == '(' { - depth += 1; - } else if c == ')' { - depth = depth.saturating_sub(1); - if depth == 0 { - break; - } - } - } - } else { - while i < n && chars[i] != '\n' && chars[i] != '#' { - value.push(chars[i]); - i += 1; - } - } - - if malformed { - continue; - } - // Each name is the last word before a comma; stray text before it - // (an unterminated line) is ignored. - let keys: Vec = names - .split(',') - .filter_map(|part| part.split_whitespace().last().map(str::to_string)) - .collect(); - let value = value.trim().to_string(); - if !keys.is_empty() && !value.is_empty() { - out.push((keys, value)); - } - } - out -} - -fn path_key(path: &Path) -> String { - let p = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); - let s = p.display().to_string(); - if cfg!(windows) { - s.to_lowercase() - } else { - s - } -} - -/// A folder holding `tnsnames.ora`: the folder itself, its `network/admin` -/// (Oracle home or Instant Client folder) or the parent of the file. -fn normalize_dir(path: &Path) -> Option { - if path.is_file() { - return path.parent().map(Path::to_path_buf); - } - [path.to_path_buf(), path.join("network").join("admin")] - .into_iter() - .find(|d| d.join(TNSNAMES).is_file()) -} - -fn client_library_in(dir: &Path) -> bool { - let Ok(read) = std::fs::read_dir(dir) else { - return false; - }; - read.flatten().any(|e| { - let name = e.file_name().to_string_lossy().to_ascii_lowercase(); - name == "oci.dll" - || name.starts_with("libclntsh.so") - || name.starts_with("libclntsh.") && name.ends_with(".dylib") - }) -} - -fn candidates(env: &dyn Fn(&str) -> Option) -> Vec { - let mut out = Vec::new(); - let mut push = |dir: PathBuf, label: String, origin: &str| { - out.push(Candidate { - dir, - label, - origin: origin.to_string(), - }); - }; - - if let Some(dir) = env("TNS_ADMIN") { - push( - PathBuf::from(dir.trim()), - dir.trim().to_string(), - "TNS_ADMIN", - ); - } - if let Some(home) = env("ORACLE_HOME") { - let home = PathBuf::from(home.trim()); - push( - home.join("network").join("admin"), - home.display().to_string(), - "ORACLE_HOME", - ); - } - - for (dir, label, origin) in registry_homes() { - push(dir, label, origin); - } - - let mut lib_vars = vec!["PATH"]; - if !cfg!(windows) { - lib_vars.extend(["LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"]); - } - for var in lib_vars { - let Some(value) = env(var) else { continue }; - for dir in std::env::split_paths(&value) { - if !client_library_in(&dir) { - continue; - } - // Instant Client keeps network/admin next to the library; a full - // client has it next to its bin folder. - push( - dir.join("network").join("admin"), - dir.display().to_string(), - "Instant Client on PATH", - ); - if let Some(home) = dir.parent() { - push( - home.join("network").join("admin"), - home.display().to_string(), - "Oracle client on PATH", - ); - } - } - } - - if !cfg!(windows) { - for dir in ["/etc", "/var/opt/oracle"] { - push(PathBuf::from(dir), dir.to_string(), "System folder"); - } - } - out -} - -/// Oracle homes registered by Windows installers (HKLM\SOFTWARE\ORACLE\KEY_*). -#[cfg(windows)] -fn registry_homes() -> Vec<(PathBuf, String, &'static str)> { - use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ}; - use winreg::RegKey; - - let mut out = Vec::new(); - let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); - for root in ["SOFTWARE\\ORACLE", "SOFTWARE\\WOW6432Node\\ORACLE"] { - let Ok(oracle) = hklm.open_subkey_with_flags(root, KEY_READ) else { - continue; - }; - if let Ok(dir) = oracle.get_value::("TNS_ADMIN") { - out.push((PathBuf::from(&dir), dir, "Windows registry")); - } - for name in oracle.enum_keys().flatten() { - if !name.to_ascii_uppercase().starts_with("KEY_") { - continue; - } - let Ok(key) = oracle.open_subkey_with_flags(&name, KEY_READ) else { - continue; - }; - let home_name: String = key - .get_value("ORACLE_HOME_NAME") - .unwrap_or_else(|_| name.trim_start_matches("KEY_").to_string()); - if let Ok(dir) = key.get_value::("TNS_ADMIN") { - out.push((PathBuf::from(dir), home_name.clone(), "Windows registry")); - } - if let Ok(home) = key.get_value::("ORACLE_HOME") { - out.push(( - PathBuf::from(home).join("network").join("admin"), - home_name, - "Oracle home", - )); - } - } - } - out -} - -#[cfg(not(windows))] -fn registry_homes() -> Vec<(PathBuf, String, &'static str)> { - Vec::new() -} - -#[cfg(test)] -mod tests { - use super::*; - - const SAMPLE: &str = r#" -# Produção — comentário com acento -ERP, ERP.WORLD = - (DESCRIPTION = - (ADDRESS = (PROTOCOL = TCP)(HOST = erp-db.example)(PORT = 1521)) # inline comment - (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = erppdb)) - ) - -legacy=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=old)(PORT=2484))(CONNECT_DATA=(SID=ORCL))) -EZ = db.example:1521/sales -"#; - - #[test] - fn parses_aliases_descriptors_and_fields() { - let entries: Vec = parse(SAMPLE) - .into_iter() - .flat_map(|(keys, value)| keys.into_iter().map(move |k| entry(k, &value))) - .collect(); - let names: Vec<&str> = entries.iter().map(|e| e.alias.as_str()).collect(); - assert_eq!(names, ["ERP", "ERP.WORLD", "legacy", "EZ"]); - let erp = &entries[0]; - assert_eq!(erp.host.as_deref(), Some("erp-db.example")); - assert_eq!(erp.port, Some(1521)); - assert_eq!(erp.service_name.as_deref(), Some("erppdb")); - assert!(!erp.descriptor.contains("inline comment")); - assert!(erp.descriptor.starts_with("(DESCRIPTION = (ADDRESS")); - assert_eq!(entries[2].sid.as_deref(), Some("ORCL")); - assert_eq!(entries[2].protocol.as_deref(), Some("TCPS")); - assert_eq!(entries[3].descriptor, "db.example:1521/sales"); - assert_eq!(entries[3].host, None); - } - - #[test] - fn decodes_latin1_files() { - let bytes = b"# Produ\xe7\xe3o\nA=(DESCRIPTION=(ADDRESS=(HOST=h)(PORT=1)))\n"; - let text = decode(bytes); - assert!(text.contains("Produção")); - assert_eq!(parse(&text).len(), 1); - } - - #[test] - fn reads_folders_with_ifile_and_default_domain() { - let dir = std::env::temp_dir().join(format!("lq-tns-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write( - dir.join(TNSNAMES), - "IFILE = extra.ora\nSALES.WORLD=(DESCRIPTION=(ADDRESS=(HOST=a)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=s)))\n", - ) - .unwrap(); - std::fs::write( - dir.join("extra.ora"), - "HR = (DESCRIPTION=(ADDRESS=(HOST=b)(PORT=1522)))\n", - ) - .unwrap(); - std::fs::write(dir.join("sqlnet.ora"), "NAMES.DEFAULT_DOMAIN = WORLD\n").unwrap(); - - let source = read_folder(dir.to_str().unwrap()).unwrap(); - let names: Vec<&str> = source.entries.iter().map(|e| e.alias.as_str()).collect(); - assert_eq!(names, ["HR", "SALES.WORLD"]); - - let (descriptor, found) = resolve("sales", Some(dir.to_str().unwrap())).unwrap(); - assert!(descriptor.contains("SERVICE_NAME=s")); - assert_eq!(path_key(&found), path_key(&dir)); - let (hr, _) = resolve("hr", Some(dir.to_str().unwrap())).unwrap(); - assert!(hr.contains("HOST=b")); - assert!(resolve("missing", Some(dir.to_str().unwrap())).is_err()); - - // The Oracle home / Instant Client folder works too. - let home = dir.join("home"); - std::fs::create_dir_all(home.join("network").join("admin")).unwrap(); - std::fs::write( - home.join("network").join("admin").join(TNSNAMES), - "X=(DESCRIPTION=(ADDRESS=(HOST=x)))", - ) - .unwrap(); - assert_eq!( - read_folder(home.to_str().unwrap()).unwrap().entries[0].alias, - "X" - ); - - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn finds_client_folders_from_the_environment() { - let root = std::env::temp_dir().join(format!("lq-tns-env-{}", std::process::id())); - let instant = root.join("instantclient_23_5"); - std::fs::create_dir_all(&instant).unwrap(); - let lib = if cfg!(windows) { - "oci.dll" - } else { - "libclntsh.so.23.1" - }; - std::fs::write(instant.join(lib), b"").unwrap(); - let admin = root.join("admin"); - let path = std::env::join_paths([instant.clone()]) - .unwrap() - .into_string() - .unwrap(); - - let env = |name: &str| match name { - "TNS_ADMIN" => Some(admin.display().to_string()), - "ORACLE_HOME" => Some(root.join("product").display().to_string()), - "PATH" => Some(path.clone()), - _ => None, - }; - let found = candidates(&env); - assert_eq!(found[0].origin, "TNS_ADMIN"); - assert_eq!(found[0].dir, admin); - assert_eq!(found[1].origin, "ORACLE_HOME"); - assert!(found.iter().any(|c| c.origin == "Instant Client on PATH" - && c.dir == instant.join("network").join("admin"))); - - let _ = std::fs::remove_dir_all(&root); - } -} diff --git a/src-tauri/src/drivers/view_fixtures.rs b/src-tauri/src/drivers/view_fixtures.rs deleted file mode 100644 index 5ef62ff..0000000 --- a/src-tauri/src/drivers/view_fixtures.rs +++ /dev/null @@ -1,42 +0,0 @@ -//! Runs the SQL the result grid writes to sort and filter a result that hit -//! the row limit (`src/lib/view.ts`) against a real database. The statements -//! and the ids they must return come from `src/lib/view.fixtures.json`, which -//! the frontend tests keep in step with `viewSql`. - -use super::Session; -use crate::model::ExecRequest; - -const FIXTURES: &str = include_str!("../../../src/lib/view.fixtures.json"); - -/// `dialect` as in the frontend: `postgres`, `oracle`, `mysql`, `sqlserver` -/// or `sqlite`. -pub async fn check(s: &Session, dialect: &str) { - let fixtures: serde_json::Value = serde_json::from_str(FIXTURES).expect("view fixtures"); - let cases = fixtures["dialects"][dialect]["cases"] - .as_array() - .unwrap_or_else(|| panic!("no view fixtures for {dialect}")); - assert!(!cases.is_empty()); - for case in cases { - let label = case["label"].as_str().unwrap_or_default(); - let sql = case["sql"].as_str().expect("sql"); - let expected: Vec = case["ids"] - .as_array() - .expect("ids") - .iter() - .map(|v| v.as_str().unwrap_or_default().to_string()) - .collect(); - let result = s - .execute(&ExecRequest { - sql: sql.into(), - max_rows: 100, - }) - .await - .unwrap_or_else(|e| panic!("{dialect}, {label}: {e}\n{sql}")); - let ids: Vec = result - .rows - .iter() - .map(|row| row[0].clone().unwrap_or_default()) - .collect(); - assert_eq!(ids, expected, "{dialect}, {label}:\n{sql}"); - } -} diff --git a/src-tauri/src/error.rs b/src-tauri/src/error.rs deleted file mode 100644 index ef99380..0000000 --- a/src-tauri/src/error.rs +++ /dev/null @@ -1,95 +0,0 @@ -use serde::Serialize; - -/// Error returned by Tauri commands. Serialized as an object so the UI can -/// highlight the error position in the editor and show the database's native -/// code (SQLSTATE on PostgreSQL, ORA-NNNNN on Oracle). -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct AppError { - pub kind: ErrorKind, - pub message: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub code: Option, - /// Position (0-based, in characters) within the executed SQL. - #[serde(skip_serializing_if = "Option::is_none")] - pub position: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub detail: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub hint: Option, -} - -#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ErrorKind { - /// Error returned by the server while executing SQL. - Database, - /// Network failure, authentication failure or closed session. - Connection, - /// The profile has no saved password and none was provided. - PasswordRequired, - NotFound, - Cancelled, - Invalid, - Internal, -} - -impl AppError { - pub fn new(kind: ErrorKind, message: impl Into) -> Self { - Self { - kind, - message: message.into(), - code: None, - position: None, - detail: None, - hint: None, - } - } - - pub fn internal(message: impl Into) -> Self { - Self::new(ErrorKind::Internal, message) - } - - pub fn invalid(message: impl Into) -> Self { - Self::new(ErrorKind::Invalid, message) - } - - pub fn not_found(message: impl Into) -> Self { - Self::new(ErrorKind::NotFound, message) - } - - pub fn connection(message: impl Into) -> Self { - Self::new(ErrorKind::Connection, message) - } -} - -impl std::fmt::Display for AppError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match &self.code { - Some(code) => write!(f, "{code}: {}", self.message), - None => f.write_str(&self.message), - } - } -} - -impl std::error::Error for AppError {} - -impl From for AppError { - fn from(e: std::io::Error) -> Self { - Self::internal(e.to_string()) - } -} - -impl From for AppError { - fn from(e: serde_json::Error) -> Self { - Self::internal(e.to_string()) - } -} - -impl From for AppError { - fn from(e: keyring::Error) -> Self { - Self::internal(format!("System credential store: {e}")) - } -} - -pub type AppResult = Result; diff --git a/src-tauri/src/import/datagrip.rs b/src-tauri/src/import/datagrip.rs deleted file mode 100644 index fd7b064..0000000 --- a/src-tauri/src/import/datagrip.rs +++ /dev/null @@ -1,1451 +0,0 @@ -//! DataGrip and other JetBrains IDEs: `dataSources.xml` (global, in the IDE -//! config folder, or per project in `.idea`) with user names and SSH/SSL -//! settings in `dataSources.local.xml` next to it. Passwords live in the OS -//! keychain or KeePass and are not imported. -//! -//! Also holds the small XML reader and checks shared by the pgAdmin and SQL -//! Developer importers. - -use std::collections::{HashMap, HashSet}; -use std::path::{Path, PathBuf}; - -use quick_xml::events::{BytesStart, Event}; -use quick_xml::{Reader, XmlVersion}; - -use super::{jdbc, pgadmin, ImportCandidate, Parsed}; -use crate::error::{AppError, AppResult}; -use crate::model::{ConnectionProfile, Engine, OracleConnectType, OraclePrivilege, SslMode}; - -pub fn default_files() -> Vec<(String, PathBuf)> { - let mut found = Found::default(); - let home = super::home(); - for (label, root) in product_dirs(home.as_deref()) { - let options = root.join("options"); - found.add(format!("{label} · Global"), options.join("dataSources.xml")); - for project in subdirs(&root.join("projects")) { - found.add_project(&label, &project); - } - for project in recent_projects(&options.join("recentProjects.xml"), home.as_deref()) { - found.add_project(&label, &project); - } - } - if let Some(home) = &home { - for project in subdirs(&home.join("DataGripProjects")) { - found.add_project("DataGrip", &project); - } - } - found.files -} - -#[derive(Default)] -struct Found { - files: Vec<(String, PathBuf)>, - seen: HashSet, -} - -impl Found { - fn add(&mut self, label: String, path: PathBuf) { - if !path.is_file() { - return; - } - let id = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone()); - let mut id = id.to_string_lossy().replace('\\', "/"); - if cfg!(windows) || cfg!(target_os = "macos") { - id = id.to_lowercase(); - } - if self.seen.insert(id) { - self.files.push((label, path)); - } - } - - fn add_project(&mut self, product: &str, project: &Path) { - let name = project - .file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_else(|| project.display().to_string()); - self.add( - format!("{product} · {name}"), - project.join(".idea").join("dataSources.xml"), - ); - } -} - -/// IDE config folders as (label, folder holding `options`). -fn product_dirs(home: Option<&Path>) -> Vec<(String, PathBuf)> { - let mut bases = Vec::new(); - if let Some(dir) = super::config_dir() { - bases.push(dir.join("JetBrains")); - } - if let Some(home) = home { - if cfg!(target_os = "linux") { - // Flatpak builds keep their own XDG config folder. - for app in subdirs(&home.join(".var").join("app")) { - bases.push(app.join("config").join("JetBrains")); - } - } - } - let mut out = Vec::new(); - for base in bases { - for dir in subdirs(&base) { - if dir.join("options").is_dir() { - out.push((product_label(&dir_name(&dir)), dir)); - } - } - } - // Before 2020.1: ~/.DataGrip2019.3/config (Windows, Linux) and - // ~/Library/Preferences/DataGrip2019.3 (macOS). - if let Some(home) = home { - for dir in subdirs(home) { - let name = dir_name(&dir); - if let Some(product) = name.strip_prefix('.') { - let config = dir.join("config"); - if config.join("options").is_dir() && product.contains(char::is_numeric) { - out.push((product_label(product), config)); - } - } - } - if cfg!(target_os = "macos") { - for dir in subdirs(&home.join("Library").join("Preferences")) { - let name = dir_name(&dir); - if dir.join("options").join("dataSources.xml").is_file() { - out.push((product_label(&name), dir)); - } - } - } - } - out -} - -fn dir_name(dir: &Path) -> String { - dir.file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_default() -} - -/// "DataGrip2024.1" → "DataGrip 2024.1". -fn product_label(name: &str) -> String { - match name.find(|c: char| c.is_ascii_digit()) { - Some(i) if i > 0 => format!("{} {}", &name[..i], &name[i..]), - _ => name.to_string(), - } -} - -/// Subfolders sorted by name; empty when the folder cannot be read. -pub(super) fn subdirs(dir: &Path) -> Vec { - let Ok(entries) = std::fs::read_dir(dir) else { - return Vec::new(); - }; - let mut out: Vec = entries - .flatten() - .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false)) - .map(|e| e.path()) - .collect(); - out.sort(); - out -} - -/// Project folders listed in the IDE's `recentProjects.xml`. -fn recent_projects(file: &Path, home: Option<&Path>) -> Vec { - let Ok(text) = read_text(file) else { - return Vec::new(); - }; - let Some(root) = parse_xml(&text) else { - return Vec::new(); - }; - let mut paths = Vec::new(); - collect_recent(&root, false, &mut paths); - paths - .into_iter() - .map(|p| { - let p = match home { - Some(h) => p.replace("$USER_HOME$", &h.to_string_lossy()), - None => p, - }; - PathBuf::from(p) - }) - .filter(|p| p.is_absolute()) - .collect() -} - -fn collect_recent(node: &XmlNode, in_recent_paths: bool, out: &mut Vec) { - for child in &node.children { - match child.name.as_str() { - // additionalInfo map: . - "entry" => { - if let Some(k) = child.attr("key").filter(|k| !k.is_empty()) { - out.push(k.to_string()); - } - } - // recentPaths list: