diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f933cc883..b981cbedd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -157,6 +157,14 @@ jobs: - name: Install dependencies run: pnpm install + - name: Install PostgreSQL plugin for web e2e + run: | + mkdir -p e2e/web/fixtures/plugins/postgresql + curl -sL "https://github.com/TabularisDB/tabularis-postgresql-plugin/releases/download/v1.0.0-rc.16/default.tabularium" -o e2e/web/fixtures/plugins/postgresql/.tabularium + curl -sL "https://github.com/TabularisDB/tabularis-postgresql-plugin/releases/download/v1.0.0-rc.16/postgresql-plugin-linux-x64.zip" -o /tmp/pg-plugin.zip + unzip -o /tmp/pg-plugin.zip -d e2e/web/fixtures/plugins/postgresql/ + chmod +x e2e/web/fixtures/plugins/postgresql/postgresql-plugin + - name: Install browser engines run: pnpm exec playwright install --with-deps chromium firefox webkit diff --git a/.github/workflows/pg-integration.yml b/.github/workflows/pg-integration.yml deleted file mode 100644 index 6bf1a8f0e..000000000 --- a/.github/workflows/pg-integration.yml +++ /dev/null @@ -1,97 +0,0 @@ -name: Integration Tests (PostgreSQL) - -concurrency: - group: pg-integration-${{ github.ref }} - cancel-in-progress: true - -on: - push: - branches: [main] - paths: - - 'src-tauri/**' - - '.github/workflows/pg-integration.yml' - - 'tests/fixtures/**' - pull_request: - branches: [main] - paths: - - 'src-tauri/**' - - '.github/workflows/pg-integration.yml' - - 'tests/fixtures/**' - workflow_dispatch: - inputs: - regenerate_golden: - description: 'Regenerate golden files and upload as an artifact for review (does not commit)' - type: boolean - default: false - -jobs: - test-postgres: - runs-on: blacksmith-4vcpu-ubuntu-2404 - - services: - postgres: - image: postgres:16 - ports: - - 54320:5432 - env: - POSTGRES_USER: postgres - POSTGRES_PASSWORD: password - POSTGRES_DB: testdb - options: >- - --volume /tmp/tabularis-pg-socket:/var/run/postgresql - --health-cmd pg_isready - --health-interval 10s - --health-timeout 5s - --health-retries 5 - - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: Seed PostgreSQL databases - run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends postgresql-client - bash tests/fixtures/seed_postgres.sh - - - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@stable - - - name: Cache cargo registry and build - uses: actions/cache@v6 - with: - path: | - ~/.cargo/registry - ~/.cargo/git - src-tauri/target - key: ${{ runner.os }}-cargo-pg-${{ hashFiles('src-tauri/Cargo.lock') }} - restore-keys: | - ${{ runner.os }}-cargo-pg- - - - name: Install system dependencies - run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libsoup-3.0-dev build-essential libssl-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev - - - name: Prepare Tauri frontend resource directory - run: mkdir -p packages/web-ui/dist - - - name: Run PostgreSQL integration tests - working-directory: src-tauri - env: - RUST_TEST_THREADS: "1" - REGENERATE_GOLDEN: ${{ (github.event_name == 'workflow_dispatch' && inputs.regenerate_golden) && '1' || '' }} - run: cargo test --test postgres_integration -- --include-ignored - - - name: Verify PostgreSQL socket and TCP TLS settings - working-directory: src-tauri - env: - PG_UNIX_SOCKET: /tmp/tabularis-pg-socket/.s.PGSQL.5432 - run: cargo test --test socket_integration postgres_socket_tls_and_tcp_regression -- --ignored --exact - - - name: Upload golden files - if: github.event_name == 'workflow_dispatch' && inputs.regenerate_golden - uses: actions/upload-artifact@v7 - with: - name: golden-files - path: src-tauri/tests/postgres_integration/golden/ diff --git a/.github/workflows/postgres-integration.yml b/.github/workflows/postgres-integration.yml new file mode 100644 index 000000000..20d99a6fc --- /dev/null +++ b/.github/workflows/postgres-integration.yml @@ -0,0 +1,97 @@ +name: Integration Tests (PostgreSQL plugin) + +concurrency: + group: postgres-integration-${{ github.ref }} + cancel-in-progress: true + +on: + push: + branches: [main] + paths: + - 'src-tauri/**' + - '.github/workflows/postgres-integration.yml' + pull_request: + branches: [main] + paths: + - 'src-tauri/**' + - '.github/workflows/postgres-integration.yml' + workflow_dispatch: + +env: + # The release the host's plugin contract is tested against: Unix sockets and + # the table-copy RPCs. Must be at least MINIMUM_PLUGIN_VERSIONS in + # src-tauri/src/plugins/force_install.rs; keep the web-e2e fixture in ci.yml + # on the same release. + PG_PLUGIN_VERSION: v1.0.0-rc.16 + +jobs: + test-postgres-plugin: + runs-on: blacksmith-4vcpu-ubuntu-2404 + + services: + postgres: + image: postgres:16 + ports: + - 54320:54320 + env: + POSTGRES_PASSWORD: password + POSTGRES_DB: testdb + # One port for TCP and for the socket file name (.s.PGSQL.54320). + PGPORT: "54320" + options: >- + --volume /tmp/tabularis-pg-socket:/var/run/postgresql + --health-cmd "pg_isready -U postgres -d testdb" + --health-interval 5s + --health-timeout 5s + --health-retries 20 + + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + + - name: Cache cargo registry and build + uses: actions/cache@v6 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + src-tauri/target + key: ${{ runner.os }}-cargo-postgres-${{ hashFiles('src-tauri/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo-postgres- + + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y libwebkit2gtk-4.1-dev libsoup-3.0-dev build-essential libssl-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev postgresql-client + + - name: Prepare Tauri frontend resource directory + run: mkdir -p packages/web-ui/dist + + - name: Install the PostgreSQL plugin + run: | + plugin_dir="$RUNNER_TEMP/xdg/tabularis/plugins/drivers/postgresql" + mkdir -p "$plugin_dir" + base="https://github.com/TabularisDB/tabularis-postgresql-plugin/releases/download/${PG_PLUGIN_VERSION}" + curl -fsSL "$base/default.tabularium" -o "$plugin_dir/.tabularium" + curl -fsSL "$base/postgresql-plugin-linux-x64.zip" -o "$RUNNER_TEMP/pg-plugin.zip" + unzip -o "$RUNNER_TEMP/pg-plugin.zip" -d "$plugin_dir" + chmod +x "$plugin_dir/postgresql-plugin" + echo "XDG_DATA_HOME=$RUNNER_TEMP/xdg" >> "$GITHUB_ENV" + echo "TABULARIS_TEST_PG_PLUGIN_DIR=$plugin_dir" >> "$GITHUB_ENV" + + - name: Verify PostgreSQL socket and TCP connections through the plugin + working-directory: src-tauri + env: + PG_UNIX_SOCKET: /tmp/tabularis-pg-socket + run: cargo test --test socket_integration postgresql_plugin_honors_unix_socket_path -- --ignored --exact + + - name: Copy tables through the plugin + working-directory: src-tauri + env: + RUST_TEST_THREADS: "1" + TABULARIS_TEST_PSQL: psql postgresql://postgres:password@127.0.0.1:54320/testdb + run: cargo test --test postgres_plugin_table_copy -- --include-ignored diff --git a/docs/web/WEB_MANUAL_PARITY_AUDIT.md b/docs/web/WEB_MANUAL_PARITY_AUDIT.md index c24910ebd..b83bec561 100644 --- a/docs/web/WEB_MANUAL_PARITY_AUDIT.md +++ b/docs/web/WEB_MANUAL_PARITY_AUDIT.md @@ -27,7 +27,7 @@ The sign-off applies to the implementation and documented limitations at this ba | Results/data grid | Shared grid editing, insertion, deletion, referenced records, and BLOB display/save continue through Tauri and native file selection. | The same record service is used over RPC; BLOB uploads, previews, and single-use downloads avoid exposing host paths. | Browser sandbox file semantics require opaque transfer tokens while database mutations remain identical. | Browser BLOB and result transfers retain explicit size limits and downloads depend on browser download handling. | `packages/web-ui/tests/components/ui/DataGrid.test.tsx`
`packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/application/records_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | | Multiple result windows | Desktop keeps native secondary windows and Tauri route/event adapters for detached results and JSON views. | Browser mode opens an opaque session route in a tab and synchronizes through the shared route-session host. | A browser tab is the platform-equivalent independent surface and avoids reproducing native window management. | An in-memory detached session shows an explicit expired state after its owner is gone; popup blockers can require user action. | `packages/web-ui/tests/pages/SecondaryWindowPages.test.tsx`
`packages/web-ui/tests/platform/secondaryWindowSessions.test.ts`
`packages/web-ui/tests/platform/tauriCapabilities.test.ts` | Approved by Web UI parity reviewer on 2026-08-22 | | ER/schema diagram | Desktop opens schema and ER diagrams in native secondary windows and saves through the native dialog. | Browser mode opens the same diagram component at an opaque route and downloads through a token or browser save. | Routes and downloads replace native window and filesystem primitives without changing diagram generation. | Browser tab and download behavior is subject to popup and download policies; no native always-on-top behavior is reproduced. | `packages/web-ui/tests/platform/secondaryWindowSessions.test.ts`
`packages/web-ui/tests/utils/schemaDiagram.test.ts`
`src-tauri/src/application/generic_exports_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | -| Views/routines/triggers | Existing create, inspect, edit, refresh, and drop flows remain in the shared UI over Tauri commands. | Database-authorized RPC routes the same object commands to shared services. | Object DDL and metadata semantics are transport-independent. | Availability and exact DDL support remain driver-capability and database-version dependent, matching desktop behavior. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/transport/web/rpc_tests.rs`
`src-tauri/tests/postgres_integration/parity_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | +| Views/routines/triggers | Existing create, inspect, edit, refresh, and drop flows remain in the shared UI over Tauri commands. | Database-authorized RPC routes the same object commands to shared services. | Object DDL and metadata semantics are transport-independent. | Availability and exact DDL support remain driver-capability and database-version dependent, matching desktop behavior. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/transport/web/rpc_tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | | User management | Desktop user, grant, privilege, lock, password, create, and drop operations remain available for supporting drivers. | Sensitive database-authorized RPC exposes the same operations and shared validation. | There is no browser-specific workflow change, but authorization remains explicit because these operations are sensitive. | Feature availability follows driver support; current rich user-management behavior is primarily MySQL-oriented. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/transport/web/rpc_tests.rs`
`src-tauri/src/drivers/mysql/tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | | Notebooks | Desktop notebook CRUD, execution, outline, charts, history, parameters, and import/export remain in the shared React implementation. | The same notebook format and services run over RPC; browser imports and exports use opaque transfers and downloads. | Browser file exchange is adapted while notebook content and execution stay identical. | Download location is browser-controlled and server-side notebook storage remains scoped to the Tabularis data directory. | `packages/web-ui/tests/api/contract/transportContract.ts`
`packages/web-ui/tests/utils/notebookTransfer.test.ts`
`src-tauri/src/application/notebooks/tests.rs` | Approved by Web UI parity reviewer on 2026-08-22 | | Dump/import | Desktop jobs keep native file targets, cancellation, and progress through existing commands and events. | Browser uploads source SQL or archives, runs the same server-side jobs, receives scoped progress, and downloads generated dumps. | Opaque streaming transfers replace trusted native paths and preserve long-running job semantics. | Tool availability and database-specific dump fidelity depend on installed drivers or external utilities; transfer limits remain enforced. | `packages/web-ui/tests/api/contract/transportContract.ts`
`src-tauri/src/application/database_transfers_tests.rs`
`packages/web-ui/tests/utils/dumpUtils.test.ts` | Approved by Web UI parity reviewer on 2026-08-22 | diff --git a/docs/web/WEB_MODE_CONTAINERS.md b/docs/web/WEB_MODE_CONTAINERS.md index 29a0e4877..c8620e67a 100644 --- a/docs/web/WEB_MODE_CONTAINERS.md +++ b/docs/web/WEB_MODE_CONTAINERS.md @@ -62,9 +62,16 @@ The entrypoint translates these into `tabularis web` flags. Arguments after the | `TABULARIS_PORT` | `8080` | Port inside the container. | | `TABULARIS_HOST` | `0.0.0.0` | Bind address inside the container. | | `TABULARIS_DEBUG` | `false` | Debug logging. | +| `TABULARIS_DISABLE_PLUGIN_AUTO_INSTALL` | `false` | Stops the server downloading the PostgreSQL plugin on start. See [PostgreSQL connections](#postgresql-connections). | `TABULARIS_WEB_PASSWORD`, `TABULARIS_WEB_PROXY_SECRET` and `TABULARIS_SECRET_KEY` also accept a `_FILE` variant pointing at a Docker or Kubernetes secret file. +## PostgreSQL connections + +PostgreSQL is provided by the standalone `postgresql` plugin, not by the server itself. When the server starts and a saved connection uses PostgreSQL (the old built-in `postgres` id, which is rewritten to `postgresql`, or `postgresql`), it installs and activates the plugin from the plugin registry in the background if it is missing. A failed download is logged and tried again on the next start, and the server starts either way. + +For an air-gapped or locked-down host, set `TABULARIS_DISABLE_PLUGIN_AUTO_INSTALL=true` so the server never downloads anything on its own, and install the plugin yourself: place it under the plugins directory in `/data`, or install it from **Settings → Plugins** while the host can reach the registry. Until it is installed, PostgreSQL connections report `Unsupported driver: postgresql` with a note naming the plugin. The `--mcp` process behaves the same way, using the same environment variable. + ## Stored credentials Containers have no OS keychain. The image sets `TABULARIS_SECRET_STORE=file`, which keeps every secret the desktop app would put in the keychain (database and SSH passwords, connection URIs, plugin secrets, AI keys) in `/data/secrets.enc.json`, encrypted with AES-256-GCM under a key derived from `TABULARIS_SECRET_KEY` with Argon2id. diff --git a/e2e/helpers/navigation.ts b/e2e/helpers/navigation.ts index 52b739ba6..d978e0f1e 100644 --- a/e2e/helpers/navigation.ts +++ b/e2e/helpers/navigation.ts @@ -212,30 +212,14 @@ export async function openMultiDbConnection( // 1. Open the catalogue. await clickAddConnection(); - // 2. Pick the PostgreSQL card. Locally there are two (builtin "Deprecated" at - // [0] and plugin "Relational" at [1]); in CI the plugin may not be installed - // (only the builtin at [0]). Pick the non-deprecated one, or the only one. + // 2. Pick the PostgreSQL card. With the built-in driver removed, only the + // plugin card remains. await browser.waitUntil( async () => (await $$('button[aria-label="Connect to PostgreSQL"]')).length > 0, {timeout: 20000, timeoutMsg: 'PostgreSQL catalogue card never rendered'}, ); const pgCards = await $$('button[aria-label="Connect to PostgreSQL"]'); - // Pick the PLUGIN PostgreSQL card (not the builtin "Deprecated" one). The - // plugin supports list_databases for the multi-db nested feature. Both cards - // exist in CI (builtin "postgres" + plugin "postgresql"). Use WDIO's - // element.click() which reliably triggers React's onClick. - let targetIndex = 0; - if (pgCards.length > 1) { - // The plugin card is the one NOT containing "Deprecated" text. - const isDeprecated = await browser.execute(() => - Array.from(document.querySelectorAll('button[aria-label="Connect to PostgreSQL"]')).map( - (c) => c.textContent?.includes('Deprecated') ?? false, - ), - ); - const idx = isDeprecated.findIndex((d: boolean) => !d); - targetIndex = idx >= 0 ? idx : 0; - } - await pgCards[targetIndex].click(); + await pgCards[0].click(); await browser.pause(2000); // wait for the form to render // 3. Fill the form via native input event dispatch (React controlled inputs). diff --git a/e2e/web/tests/web-ui-matrix.spec.ts b/e2e/web/tests/web-ui-matrix.spec.ts index cf6b4df2c..eb2be184a 100644 --- a/e2e/web/tests/web-ui-matrix.spec.ts +++ b/e2e/web/tests/web-ui-matrix.spec.ts @@ -62,7 +62,7 @@ const databaseFixtures: DatabaseFixture[] = [ { name: 'postgres', params: { - driver: 'postgres', + driver: 'postgresql', host: process.env.TABULARIS_E2E_POSTGRES_HOST ?? '127.0.0.1', port: Number.parseInt(process.env.TABULARIS_E2E_POSTGRES_PORT ?? '45432', 10), username: process.env.TABULARIS_E2E_POSTGRES_USER ?? 'postgres', diff --git a/packages/web-ui/src/components/banners/PostgresPluginMigrationBanner.tsx b/packages/web-ui/src/components/banners/PostgresPluginMigrationBanner.tsx deleted file mode 100644 index c67d586a8..000000000 --- a/packages/web-ui/src/components/banners/PostgresPluginMigrationBanner.tsx +++ /dev/null @@ -1,73 +0,0 @@ -import {AlertTriangle, X} from 'lucide-react'; -import {useTranslation} from 'react-i18next'; -import type {MigrationBannerVariant} from '@/hooks/useBuiltinDriverMigration'; - -interface PostgresPluginMigrationBannerProps { - /** "nudge" → the "try the plugin" message; "offline" → the "couldn't be - * downloaded" message. Driven by the connectivity gate in the hook. */ - variant: MigrationBannerVariant; - /** Tentative removal date for the built-in driver (e.g. `"2026-10-05"`), - * read from `PluginManifest.deprecated.removal_date` — the same manifest - * field the deprecated-driver badge/tooltip use — so the two surfaces - * can't drift out of sync the way a second hardcoded date in this - * component's translation string would. `undefined` renders the - * no-date variant of the nudge message. */ - removalDate: string | undefined; - /** Called when the user dismisses the banner (persists the dismissal). */ - onDismiss: () => void; - /** Called when the user clicks "Review connections" (nudge variant only). */ - onReview?: () => void; -} - -/** - * Inline (non-modal) dismissible banner nudging the user toward the - * PostgreSQL plugin. Rendered inside the Connections page, not stacked in - * App.tsx's launch-time modals — a non-blocking recommendation, not a - * required confirmation. - * - * Two variants: the nudge (plugin ready, registry reachable) and the honest - * offline message (plugin not downloaded / registry unreachable). The - * offline variant never offers a "Switch to plugin" action it can't back up. - */ -export const PostgresPluginMigrationBanner = ({ - variant, - removalDate, - onDismiss, - onReview, -}: PostgresPluginMigrationBannerProps) => { - const {t} = useTranslation(); - - return ( -
- -
- {variant === 'nudge' ? ( - - {removalDate - ? t('migration.banner.nudgeWithDate', {date: removalDate}) - : t('migration.banner.nudge')} - - ) : ( - - {t('migration.banner.offline')} - - )} - {variant === 'nudge' && onReview && ( - - )} -
- -
- ); -}; diff --git a/packages/web-ui/src/components/connections/ActionButtons.tsx b/packages/web-ui/src/components/connections/ActionButtons.tsx index 59095d837..a89d81d83 100644 --- a/packages/web-ui/src/components/connections/ActionButtons.tsx +++ b/packages/web-ui/src/components/connections/ActionButtons.tsx @@ -1,8 +1,7 @@ import {useTranslation} from 'react-i18next'; -import {Power, Edit, Copy, Trash2, ArrowLeftRight} from 'lucide-react'; +import {Power, Edit, Copy, Trash2} from 'lucide-react'; import clsx from 'clsx'; import type {SavedConnection} from '@/contexts/DatabaseContext'; -import type {MigrationDirection} from '@/utils/connections'; import {useConnectionCapabilities} from '@/hooks/useConnectionCapabilities'; export interface ActionButtonsProps { @@ -14,10 +13,6 @@ export interface ActionButtonsProps { onEdit: () => void; onDuplicate: () => void; onDelete: () => void; - /** "to-plugin" / "to-builtin" shows the migration button; `null` hides it — - * only relevant during a built-in driver's deprecation window. */ - migrationDirection?: MigrationDirection; - onMigrate?: () => void; } const BUTTON_CLASS = @@ -38,29 +33,11 @@ export const ActionButtons = ({ onEdit, onDuplicate, onDelete, - migrationDirection, - onMigrate, }: ActionButtonsProps) => { const {t} = useTranslation(); const {canUpdate, canDuplicate, canDelete} = useConnectionCapabilities(); return ( <> - {canUpdate && migrationDirection && onMigrate && ( - - )} {isOpen ? ( - - - {/* Content */} -
- {candidateRows.length === 0 ? ( -

{t('migration.checklist.noGaps')}

- ) : ( - candidateRows.map(({conn, gaps, isUriBased}) => { - const status = rowStatus[conn.id]; - return ( -
- toggleChecked(conn.id)} - disabled={migrating} - className="mt-1 accent-accent-primary" - /> -
-
- - {conn.name} - - {status === 'running' && ( - - - {testingIds.has(conn.id) && ( - - {t('migration.checklist.testing')} - - )} - - )} - {status === 'ok' && ( - - )} - {(status === 'connection' || - status === 'process' || - status === 'failed') && ( - - )} -
- {gaps.length > 0 && manifest && ( -
- {gaps.map((gap) => { - const reported = alreadyReported( - manifest.id, - gap.feature, - ); - return ( -
- - {gapLabel(gap.feature)} - - {reported ? ( - - {t( - 'migration.checklist.alreadyReported', - )} - - ) : ( - - )} -
- ); - })} -
- )} - {isUriBased && ( -

- {t('migration.checklist.uriWarning')} -

- )} -
-
- ); - }) - )} -
- - {/* Footer */} -
- {migrating && ( -

- {t('migration.checklist.migratingNotice')} -

- )} -
- - -
-
- - - ); -}; diff --git a/packages/web-ui/src/contexts/DatabaseContext.ts b/packages/web-ui/src/contexts/DatabaseContext.ts index ab55fe5ad..5ba20e080 100644 --- a/packages/web-ui/src/contexts/DatabaseContext.ts +++ b/packages/web-ui/src/contexts/DatabaseContext.ts @@ -75,8 +75,7 @@ export interface SavedConnection { ssm_enabled?: boolean; ssm_target?: string; startup_script?: string; - /** SSL/TLS mode (e.g. "verify-ca"); empty/absent means SSL is off. Used - * by findUnsupportedFeatures to detect a plugin capability gap. */ + /** SSL/TLS mode (e.g. "verify-ca"); empty/absent means SSL is off. */ ssl_mode?: string; /** Raw driver-specific connection URI, when present at runtime (never * persisted to disk — see connection_uri_in_keychain below). */ diff --git a/packages/web-ui/src/contexts/DatabaseProvider.tsx b/packages/web-ui/src/contexts/DatabaseProvider.tsx index 8e01663ef..183c03b19 100644 --- a/packages/web-ui/src/contexts/DatabaseProvider.tsx +++ b/packages/web-ui/src/contexts/DatabaseProvider.tsx @@ -2217,6 +2217,17 @@ export const DatabaseProvider = ({children}: {children: ReactNode}) => { }; }, [client]); + // A plugin installed in the background may have moved saved connections off + // a built-in driver id; reload them so the list shows the new id. + useEffect(() => { + const unlisten = client.subscribe('tabularis://plugin-activated', () => { + void loadConnections(); + }); + return () => { + unlisten.then((fn) => fn()); + }; + }, [client, loadConnections]); + // Listen for backend health-check failures and clean up dead connections. useEffect(() => { const unlisten = client.subscribe('connection-health-failed', (payload) => { diff --git a/packages/web-ui/src/contexts/SettingsContext.ts b/packages/web-ui/src/contexts/SettingsContext.ts index 1bddb42b7..ec464cc14 100644 --- a/packages/web-ui/src/contexts/SettingsContext.ts +++ b/packages/web-ui/src/contexts/SettingsContext.ts @@ -200,18 +200,6 @@ export interface Settings { columnMaskingPatterns?: string[]; /** Per-connection `table.column` include/exclude overrides, keyed by connection id. */ columnMaskingOverrides?: Record; - // Built-in driver migration - /** Whether the user has dismissed the PostgreSQL-plugin migration banner. - * Absent/undefined → banner is eligible to show. Resurfaces automatically - * if a builtin-postgres connection appears that wasn't in - * `postgresPluginMigrationBannerDismissedFor` at dismissal time — the same - * "did-the-condition-change" gating `WhatsNewModal` uses for its own - * version comparison. */ - postgresPluginMigrationBannerDismissed?: boolean; - /** Connection ids that existed (on the builtin driver) at the moment the - * banner was dismissed. A builtin connection id not in this list means the - * trigger condition changed since the dismissal, so the banner shows again. */ - postgresPluginMigrationBannerDismissedFor?: string[]; /** Append-only record of every connection migrated between built-in and * plugin drivers. Kept even after an undo. */ driverMigrationHistory?: DriverMigrationRecord[]; diff --git a/packages/web-ui/src/hooks/useBuiltinDriverMigration.ts b/packages/web-ui/src/hooks/useBuiltinDriverMigration.ts deleted file mode 100644 index f69029ce8..000000000 --- a/packages/web-ui/src/hooks/useBuiltinDriverMigration.ts +++ /dev/null @@ -1,524 +0,0 @@ -/** - * Hook backing the built-in → plugin driver migration nudge and action. - * - * Parameterized by `(builtinId, pluginId)` so the next deprecation (mysql, - * sqlite) is a new call site, not a redesign. A thin postgres-specific wrapper - * (`useBuiltinPostgresMigration`) covers this rollout. - * - * Owns: connection detection, banner dismissal, the connectivity gate (nudge - * only when the plugin is installed + active and the registry is reachable), - * and the migration action itself — auto-disconnect, flip the driver via - * `update_connection`, run a post-migration `test_connection`, reopen if it - * was open before, expose undo (the same disconnect/flip/reopen in reverse), - * and record the migration. Deliberately does NOT own toast display — - * `migrateConnection`/`undoMigration` resolve with an outcome and leave it to - * the caller (a toast in `Connections.tsx`; per-row status in - * `MigrationChecklistModal`) to decide what to do with it. - * - * Fast Refresh: this file exports only hooks. Pure helpers live in `utils/`. - */ - -import {useCallback, useEffect, useMemo, useRef} from 'react'; - -import {useDatabase} from './useDatabase'; -import {useDrivers} from './useDrivers'; -import {useConnectionCatalogue} from './useConnectionCatalogue'; -import {useSettings} from './useSettings'; -import {useTabularisClient} from './useTabularisClient'; -import {findConnectionsForDrivers} from '@/utils/connectionManager'; -import type {SavedConnection} from '@/contexts/DatabaseContext'; -import type {ConnectionParameters} from '@/api/contract'; - -/** Which surface the banner should show. Driven by the connectivity gate. */ -/** The saved connection's parameters with only the driver swapped. */ -function paramsWithDriver(conn: SavedConnection | undefined, driver: string): ConnectionParameters { - return {database: '', ...conn?.params, driver}; -} - -export type MigrationBannerVariant = 'nudge' | 'offline'; - -/** Result of a migration attempt, driving the toast / undo / report UI. */ -export interface MigrationOutcome { - /** Connection that was migrated. */ - connectionId: string; - connectionName: string; - /** "ok" the post-migration test succeeded; "connection" / "process" on an - * expected failure. "failed" is the catch-all for anything unexpected - * before that point (e.g. the connection was deleted concurrently, or - * `update_connection` itself rejected) — `migrateConnection` never throws, - * it resolves to this instead, so a bulk-migration loop can't abort or - * wedge on one connection's failure. */ - status: 'ok' | 'connection' | 'process' | 'failed'; - /** Error message when status === "connection" or "failed". */ - error?: string; - /** Startup error text when status === "process", if the plugin reported one. */ - startupError?: string; - /** Plugin id, needed to word/build the process-level failure and issue report. */ - pluginId?: string; - /** Only meaningful when status === "connection": true when a same-connection - * re-test against the built-in driver also failed, meaning the plugin isn't - * to blame — the target was never reachable in the first place. */ - preexisting?: boolean; -} - -/** Result of an undo attempt. `undoMigration` never throws either — callers - * check `ok` and surface `error` themselves (there's no outcome-toast - * plumbing for undo the way there is for `migrateConnection`). */ -export interface UndoOutcome { - ok: boolean; - error?: string; -} - -/** Snapshot of the migration state the banner (and per-connection actions) consume. */ -export interface BuiltinDriverMigrationState { - /** The built-in driver id this instance was parameterized with (e.g. - * `"postgres"`). Exposed so a caller that only holds the hook's return - * value — not the `(builtinId, pluginId)` arguments used to create it — - * can still build driver-specific UI (e.g. an issue-report URL) without - * re-hardcoding the pair the hook itself is already parameterized by. */ - builtinId: string; - /** The replacement plugin id this instance was parameterized with (e.g. - * `"postgresql"`). See `builtinId`. */ - pluginId: string; - /** Saved connections still on the built-in driver (the trigger set). */ - builtinConnections: SavedConnection[]; - /** True when at least one saved connection is on the built-in driver. */ - needsMigration: boolean; - /** True when the replacement plugin is installed and active. */ - pluginReady: boolean; - /** True when the registry catalogue fetch failed (persistent offline). */ - registryOffline: boolean; - /** Whether the banner should render and which variant. `null` = hidden. */ - banner: {visible: boolean; variant: MigrationBannerVariant} | null; - /** Dismiss the banner (persists). */ - dismissBanner: () => void; - /** Migrate one connection to the plugin. Never rejects — resolves with the - * outcome (including unexpected failures, as `status: "failed"`), so the - * caller decides what to do with it (e.g. Connections.tsx shows a toast; - * MigrationChecklistModal's bulk loop drives its own per-row status UI - * instead — deliberately not both, see the resolver's own comments). */ - migrateConnection: (connectionId: string) => Promise; - /** Undo a migration: flip the driver back. Never rejects — resolves with - * `{ ok: false, error }` on failure so the caller can surface it. */ - undoMigration: (connectionId: string) => Promise; -} - -/** - * Hook for the built-in → plugin migration. Parameterized by driver pair so - * future deprecations reuse it. - */ -export function useBuiltinDriverMigration( - builtinId: string, - pluginId: string, -): BuiltinDriverMigrationState { - const { - connections, - loadConnections, - connect, - disconnect, - openConnectionIds, - connectionDataMap, - } = useDatabase(); - const {allDrivers, installedPlugins} = useDrivers(); - const {registryOffline} = useConnectionCatalogue( - connections.some((connection) => connection.params.driver === builtinId), - ); - const {settings, updateSetting} = useSettings(); - const client = useTabularisClient(); - - // `undoMigration` is handed to callers that invoke it later, from a - // closure captured well before the click that actually triggers it — the - // outcome toast in Connections.tsx builds its "Undo" action at the moment - // migrateConnection is *called*, then the user clicks it seconds later, by - // which point the connection has already flipped drivers and - // `connectionDataMap`/`openConnectionIds` have moved on. A `useCallback` - // dependency array only produces a fresh closure on the *next render*, not - // retroactively for a reference some other component is still holding, so - // undoMigration reads these through refs — always the render's latest - // value — instead of through its useCallback's own closure. Synced in a - // `useEffect`, not assigned directly during render (the more common - // version of this idiom, e.g. `PluginsTab.tsx`'s `settingsRef`): the - // `react-hooks/refs` rule flags a ref write during render as unsafe for - // the React Compiler to reorder around, and an effect still runs before - // any event handler (including this closure's eventual invocation) could - // observe a stale value. - const connectionsRef = useRef(connections); - const openConnectionIdsRef = useRef(openConnectionIds); - const connectionDataMapRef = useRef(connectionDataMap); - useEffect(() => { - connectionsRef.current = connections; - openConnectionIdsRef.current = openConnectionIds; - connectionDataMapRef.current = connectionDataMap; - }, [connections, openConnectionIds, connectionDataMap]); - - // Connections still on the built-in driver — the trigger condition and the - // set eligible to migrate. - const builtinConnections = useMemo( - () => connections.filter((c) => c.params.driver === builtinId), - [connections, builtinId], - ); - - const needsMigration = builtinConnections.length > 0; - - // The plugin is "ready" when it's both installed and active — `useDrivers` - // returns manifests for installed drivers; `activeExternalDrivers` marks - // activation. This is the gate that keeps the nudge from outrunning the - // install (see the design doc's connectivity section). - const pluginInstalled = useMemo( - () => - installedPlugins.some((p) => p.id === pluginId) || - allDrivers.some((d) => d.id === pluginId), - [installedPlugins, allDrivers, pluginId], - ); - const pluginActive = useMemo(() => { - const active = settings.activeExternalDrivers ?? []; - return active.includes(pluginId); - }, [settings.activeExternalDrivers, pluginId]); - const pluginReady = pluginInstalled && pluginActive; - - // Connectivity gate: the nudge only shows when the plugin is present and - // the registry is reachable. When the registry is offline (persistent - // failure), the banner either stays suppressed or shows the honest - // "couldn't be downloaded" variant — never a "Switch to plugin" nudge it - // can't back up. - // - // Dismissal is the deliberate opt-out (no separate "don't show again" - // checkbox) — but it only holds for the connections that existed at - // dismissal time. A builtin connection id not in - // `postgresPluginMigrationBannerDismissedFor` means the trigger condition - // changed since the dismissal, so the banner resurfaces — the same - // "did-the-condition-change" gating `WhatsNewModal` uses for its own - // version comparison. - const dismissedForIds = settings.postgresPluginMigrationBannerDismissedFor ?? []; - const dismissed = - settings.postgresPluginMigrationBannerDismissed === true && - builtinConnections.every((c) => dismissedForIds.includes(c.id)); - const banner = useMemo(() => { - if (!needsMigration || dismissed) return null; - if (!pluginReady || registryOffline) return {visible: true, variant: 'offline' as const}; - return {visible: true, variant: 'nudge' as const}; - }, [needsMigration, dismissed, pluginReady, registryOffline]); - - const dismissBanner = useCallback(() => { - // Sequential and awaited, not fire-and-forget in parallel: updateSetting - // merges against a snapshot of state captured at call time, so two - // concurrent calls can each start from the same stale snapshot and the - // second write silently drops the first's field. Awaiting serializes them. - void (async () => { - await updateSetting('postgresPluginMigrationBannerDismissed', true); - await updateSetting( - 'postgresPluginMigrationBannerDismissedFor', - builtinConnections.map((c) => c.id), - ); - })(); - }, [updateSetting, builtinConnections]); - - const recordMigration = useCallback( - async (connectionId: string, fromDriver: string, toDriver: string) => { - // Updater form, not `[...settings.driverMigrationHistory, record]`: - // MigrationChecklistModal's bulk loop calls `migrateConnection` (and - // therefore this) repeatedly in a tight sequence, all against the same - // `settings` snapshot from whichever render started the loop. Reading - // `prev` inside `updateSetting`'s own functional update means each - // call appends onto the result of the write immediately before it, - // not onto that one shared pre-loop snapshot — otherwise every write - // but the last silently discards the ones before it. - await updateSetting('driverMigrationHistory', (prev) => [ - ...(prev ?? []), - { - connectionId, - fromDriver, - toDriver, - // ISO-8601 timestamp of the migration. - migratedAt: new Date().toISOString(), - toastDismissed: false, - }, - ]); - }, - [updateSetting], - ); - - // Migrate one connection: auto-disconnect if open, flip the driver, run a - // post-migration test, reopen if it was open before, and record the - // outcome. The undo path mirrors this (see below). Never rejects: every - // awaited call up through the driver-flip is wrapped, so a bulk caller - // looping over many connections can't have one failure abort the batch or - // leave its own loop state (e.g. a "migrating" flag) stuck permanently on. - const migrateConnection = useCallback( - async (connectionId: string): Promise => { - const conn = connections.find((c) => c.id === connectionId); - const name = conn?.name ?? connectionId; - const fromDriver = builtinId; - - // Disconnect first if the connection is currently open — reuses the - // same helper the plugin-uninstall flow uses. Captured before the flow - // runs so the reconnect below only fires when this call actually - // closed the connection, not on every outcome unconditionally (e.g. a - // connection that was already closed has nothing to reopen). - const openForBuiltin = findConnectionsForDrivers(openConnectionIds, connectionDataMap, [ - builtinId, - ]); - const wasOpen = openForBuiltin.includes(connectionId); - let disconnected = false; - - // The rest of the outcome logic is unchanged from before reconnect - // support — extracted into `run` so every one of its several early - // `return outcome` statements returns from `run`, not from - // `migrateConnection`, letting the single reconnect attempt below run - // exactly once regardless of which branch produced the outcome. - const run = async (): Promise => { - try { - if (wasOpen) { - await disconnect(connectionId); - disconnected = true; - } - - // Flip the driver. `update_connection` handles the persistence; for a - // connection-URI connection it drops the stored URI on the driver - // change (by design), which the pre-flight warning (Chunk 4) surfaces - // before the user ever gets here. - await client.call('update_connection', { - id: connectionId, - name: conn?.name ?? connectionId, - params: paramsWithDriver(conn, pluginId), - detectJsonInTextColumns: conn?.detect_json_in_text_columns - ? true - : undefined, - environment: conn?.environment ?? undefined, - }); - await loadConnections(); - await recordMigration(connectionId, fromDriver, pluginId); - } catch (e) { - const error = e instanceof Error ? e.message : String(e); - const outcome: MigrationOutcome = { - connectionId, - connectionName: name, - status: 'failed', - error, - pluginId, - }; - return outcome; - } - - // The plugin process never starting is a different failure than the - // connection itself failing — detectable because the registry never - // picked up the driver (get_registered_drivers won't list it), rather - // than by relying solely on get_plugin_startup_errors()'s one-shot - // drain (which PluginsTab's own mount effect may have already emptied) - // to detect the failure. Skipping the connection test in this case - // avoids attributing a plugin-startup failure to the connection's own - // credentials. - let registeredDrivers: Array<{id: string}>; - try { - registeredDrivers = await client.call('get_registered_drivers', undefined); - } catch (e) { - const error = e instanceof Error ? e.message : String(e); - const outcome: MigrationOutcome = { - connectionId, - connectionName: name, - status: 'failed', - error, - pluginId, - }; - return outcome; - } - const pluginRegistered = registeredDrivers.some((d) => d.id === pluginId); - if (!pluginRegistered) { - // Best-effort: if the drain still has this plugin's error (nobody - // else read it first), surface the specific message; otherwise fall - // back to a generic one in the UI. - let startupError: string | undefined; - try { - const startupErrors = await client.call( - 'get_plugin_startup_errors', - undefined, - ); - startupError = startupErrors.find((e) => e.plugin_id === pluginId)?.error; - } catch { - // Non-fatal — the UI falls back to a generic message. - } - const outcome: MigrationOutcome = { - connectionId, - connectionName: name, - status: 'process', - pluginId, - startupError, - }; - return outcome; - } - - // Post-migration test to catch a bad outcome before declaring success. - try { - await client.call('test_connection', { - request: { - params: paramsWithDriver(conn, pluginId), - connection_id: connectionId, - }, - }); - const outcome: MigrationOutcome = { - connectionId, - connectionName: name, - status: 'ok', - }; - return outcome; - } catch (e) { - const error = e instanceof Error ? e.message : String(e); - - // The plugin test failing isn't necessarily the plugin's fault — - // re-test with the built-in driver, same connection_id, before - // blaming the plugin. `test_connection` resolves the keychain - // password from connection_id regardless of which driver the - // request claims, so this works even though the connection is - // already persisted on `pluginId` at this point. - let preexisting = false; - try { - await client.call('test_connection', { - request: { - params: paramsWithDriver(conn, builtinId), - connection_id: connectionId, - }, - }); - } catch { - preexisting = true; - } - - const outcome: MigrationOutcome = { - connectionId, - connectionName: name, - status: 'connection', - error, - pluginId, - preexisting, - }; - return outcome; - } - }; - - const outcome = await run(); - - // Reopen using whichever driver ended up persisted — `connect` always - // re-fetches the connection's params from the backend rather than - // trusting this closure's (possibly stale) `conn`, so it reflects the - // flip whether it succeeded, failed outright, or the plugin never - // registered. A reconnect failure is not folded into `outcome`: it's - // already recorded into `connectionDataMap[connectionId].error` by - // `connect` itself — the same slot the sidebar/tab UI already renders - // for a failed connection — so surfacing it again here would just be a - // second, redundant channel for the same fact, and swallowing it keeps - // the migration outcome this function returns describing only the - // migration, not an unrelated reconnect attempt. - if (disconnected) { - try { - await connect(connectionId); - } catch { - // Already surfaced via connectionDataMap[connectionId].error. - } - } - - return outcome; - }, - [ - client, - connections, - builtinId, - pluginId, - openConnectionIds, - connectionDataMap, - connect, - disconnect, - loadConnections, - recordMigration, - ], - ); - - // Undo: disconnect if open, flip the driver back to the built-in, refresh, - // and reopen if it was open before — the same disconnect/reconnect - // symmetry as migrateConnection, since undo is exactly its inverse. Never - // rejects — resolves to `{ ok: false, error }` so the caller (there's no - // outcome-toast plumbing for undo, unlike migrateConnection) can surface it. - // - // Reads connections/openConnectionIds/connectionDataMap through the refs - // above, not the values this useCallback closed over: Connections.tsx's - // outcome toast captures this exact function reference at the moment - // migrateConnection is called (well before the migration — and any - // subsequent disconnect/reconnect — actually completes), then invokes it - // later when the user clicks "Undo". By then connectionDataMap has moved - // on to the connection's *plugin* driver, but this closure was fixed at - // creation time to whatever connectionDataMap looked like beforehand — so - // the `[pluginId]` lookup below found nothing, `wasOpen` came out `false`, - // and undo silently skipped the disconnect/reconnect pair even though the - // connection was live and open on the plugin the whole time. The refs are - // updated on every render regardless of whether this particular - // useCallback instance was recreated, so even a stale-looking closure - // still reads current state when it's finally invoked. - const undoMigration = useCallback( - async (connectionId: string): Promise => { - const connections = connectionsRef.current; - const openConnectionIds = openConnectionIdsRef.current; - const connectionDataMap = connectionDataMapRef.current; - const conn = connections.find((c) => c.id === connectionId); - // The connection is on `pluginId` at this point (undo runs after a - // completed migration), so look for it open under that id, mirroring - // migrateConnection's `[builtinId]` lookup before its own flip. - const openForPlugin = findConnectionsForDrivers(openConnectionIds, connectionDataMap, [ - pluginId, - ]); - const wasOpen = openForPlugin.includes(connectionId); - let disconnected = false; - - let outcome: UndoOutcome; - try { - if (wasOpen) { - await disconnect(connectionId); - disconnected = true; - } - await client.call('update_connection', { - id: connectionId, - name: conn?.name ?? connectionId, - params: paramsWithDriver(conn, builtinId), - detectJsonInTextColumns: conn?.detect_json_in_text_columns ? true : undefined, - environment: conn?.environment ?? undefined, - }); - await loadConnections(); - outcome = {ok: true}; - } catch (e) { - const error = e instanceof Error ? e.message : String(e); - outcome = {ok: false, error}; - } - - // Reopen using whichever driver ended up persisted — see - // migrateConnection's matching comment for why a reconnect failure - // isn't folded into `outcome`: it's already surfaced through - // connectionDataMap[connectionId].error, the same slot the - // sidebar/tab UI already renders for a failed connection. - if (disconnected) { - try { - await connect(connectionId); - } catch { - // Already surfaced via connectionDataMap[connectionId].error. - } - } - - return outcome; - }, - [client, builtinId, pluginId, connect, disconnect, loadConnections], - ); - - return { - builtinId, - pluginId, - builtinConnections, - needsMigration, - pluginReady, - registryOffline, - banner, - dismissBanner, - migrateConnection, - undoMigration, - }; -} - -/** Thin postgres-specific wrapper for the current rollout. */ -export function useBuiltinPostgresMigration(): BuiltinDriverMigrationState { - return useBuiltinDriverMigration('postgres', 'postgresql'); -} diff --git a/packages/web-ui/src/hooks/useConnectionCatalogue.ts b/packages/web-ui/src/hooks/useConnectionCatalogue.ts index 2a571aaf2..18cdf137e 100644 --- a/packages/web-ui/src/hooks/useConnectionCatalogue.ts +++ b/packages/web-ui/src/hooks/useConnectionCatalogue.ts @@ -18,7 +18,6 @@ import { import {pluginKind} from '@/utils/plugins'; const BUILTIN_META: Record = { - postgres: {engine: 'postgres', paradigms: ['sql']}, mysql: {engine: 'mysql', paradigms: ['sql']}, sqlite: {engine: 'sqlite', paradigms: ['sql']}, }; diff --git a/packages/web-ui/src/hooks/useDrivers.ts b/packages/web-ui/src/hooks/useDrivers.ts index d9626418f..c529b01db 100644 --- a/packages/web-ui/src/hooks/useDrivers.ts +++ b/packages/web-ui/src/hooks/useDrivers.ts @@ -7,46 +7,6 @@ import {useSettings} from './useSettings'; import {useTabularisClient} from './useTabularisClient'; const FALLBACK_DRIVERS: PluginManifest[] = [ - { - id: 'postgres', - name: 'PostgreSQL', - version: '1.0.0', - description: 'PostgreSQL databases', - default_port: 5432, - is_builtin: true, - default_username: 'postgres', - color: '#3b82f6', - icon: 'postgres', - settings: [ - { - key: 'poolMaxSize', - label: 'Pool Max Size', - type: 'number', - default: 10, - description: 'Maximum number of PostgreSQL connections kept in the pool.', - }, - ], - capabilities: { - schemas: true, - views: true, - routines: true, - file_based: false, - folder_based: false, - connection_string: true, - connection_string_example: 'postgres://user:pass@localhost:5432/db', - identifier_quote: '"', - alter_primary_key: true, - auto_increment_keyword: '', - serial_type: 'SERIAL', - inline_pk: false, - alter_column: true, - create_foreign_keys: true, - supports_ssl: true, - query_timeout: true, - sql_dialect: 'postgres', - read_only_queries: true, - }, - }, { id: 'mysql', name: 'MySQL', diff --git a/packages/web-ui/src/hooks/useSqlDiagnosticsOptions.ts b/packages/web-ui/src/hooks/useSqlDiagnosticsOptions.ts index 3683b5818..947f15d46 100644 --- a/packages/web-ui/src/hooks/useSqlDiagnosticsOptions.ts +++ b/packages/web-ui/src/hooks/useSqlDiagnosticsOptions.ts @@ -45,7 +45,6 @@ export function useSqlDiagnosticsOptions( materializedViews, isLoadingTables, isLoadingViews, - activeDriver, activeSchema, activeCapabilities, activeDatabaseName, @@ -56,7 +55,10 @@ export function useSqlDiagnosticsOptions( const settingsContext = useContext(SettingsContext); const settingEnabled = settingsContext?.settings.sqlDiagnosticsEnabled === true; - const active = settingEnabled && (options?.enabled ?? true) && activeDriver === 'postgres'; + const active = + settingEnabled && + (options?.enabled ?? true) && + activeCapabilities?.sql_dialect === 'postgres'; const schema = options?.schema ?? activeSchema; const tabDatabase = options?.database ?? null; const isNestedMultiDb = isSchemaBasedMultiDb(activeCapabilities, selectedDatabases); diff --git a/packages/web-ui/src/i18n/locales/de.json b/packages/web-ui/src/i18n/locales/de.json index f96f35529..39844dd30 100644 --- a/packages/web-ui/src/i18n/locales/de.json +++ b/packages/web-ui/src/i18n/locales/de.json @@ -117,7 +117,11 @@ "development": "Entwicklung", "staging": "Staging", "production": "Produktion", - "short": { "development": "DEV", "staging": "STAGING", "production": "PROD" }, + "short": { + "development": "DEV", + "staging": "STAGING", + "production": "PROD" + }, "banner": "Produktion — {{name}}", "warnTitle": "Produktionsdatenbank", "warnMessage": "Sie sind dabei, Produktionsdaten auf \"{{name}}\" zu ändern. Wirklich fortfahren?", @@ -1213,12 +1217,6 @@ "label": "Zeitzone", "description": "Sitzungszeitzone, die nach dem Verbindungsaufbau an MySQL gesendet wird." } - }, - "postgres": { - "poolMaxSize": { - "label": "Maximale Pool-Größe", - "description": "Maximale Anzahl von PostgreSQL-Verbindungen, die im Pool gehalten werden." - } } } }, @@ -2270,7 +2268,6 @@ "analyzeMismatchTooltip": "Ein Plan enthält tatsächliche Ausführungsmetriken (EXPLAIN ANALYZE), während der andere nur Schätzungen enthält", "pinSnapshot": "Anheften", "unpinSnapshot": "Lösen", - "time": "Zeit", "formatText": "Text", "aiAnalysis": "KI-Analyse", "aiAnalysisTitle": "KI-Analyse des Abfrageplans", @@ -3503,56 +3500,7 @@ "updateConfirm": "Auf v{{version}} aktualisieren", "alreadyInstalled": "Version {{version}} ist bereits installiert." }, - "migration": { - "banner": { - "nudge": "Probieren Sie das neue PostgreSQL-Plugin — der integrierte PostgreSQL-Treiber wird ausgemustert. Das Plugin hat dieselben Funktionen und erhält schneller Updates.", - "nudgeWithDate": "Probieren Sie das neue PostgreSQL-Plugin — der integrierte PostgreSQL-Treiber wird ausgemustert (vorläufig {{date}}). Das Plugin hat dieselben Funktionen und erhält schneller Updates.", - "offline": "Das PostgreSQL-Plugin konnte nicht heruntergeladen werden — wir versuchen es beim nächsten Start erneut. Prüfen Sie Ihre Verbindung oder Ihr Netzwerk, falls dies weiterhin auftritt.", - "reviewConnections": "Verbindungen prüfen" - }, - "switchToPlugin": "Zum Plugin wechseln", - "switchToBuiltin": "Zum integrierten Treiber zurück wechseln", - "confirm": { - "title": "Zum Plugin wechseln?", - "message": "{{name}} zum PostgreSQL-Plugin wechseln? Falls aktuell verbunden, wird die Verbindung getrennt und mit dem Plugin neu aufgebaut.", - "uriMessage": "{{name}} zum PostgreSQL-Plugin wechseln? Die im Schlüsselbund gespeicherte Verbindungszeichenfolge wird nicht übernommen — Sie müssen sie erneut eingeben, um sich wieder zu verbinden.", - "confirmLabel": "Wechseln", - "confirmLabelUri": "Wechseln & später neu eingeben", - "undoTitle": "Zurück zum integrierten Treiber wechseln?", - "undoMessage": "{{name}} zurück zum integrierten PostgreSQL-Treiber wechseln? Falls aktuell verbunden, wird die Verbindung getrennt und mit dem integrierten Treiber neu aufgebaut.", - "undoConfirmLabel": "Zurückwechseln" - }, - "toast": { - "success": "Wechselte {{name}} zum PostgreSQL-Plugin.", - "connectionFailure": "Verbindung zu {{name}} über das Plugin fehlgeschlagen: {{error}}", - "connectionFailurePreexisting": "Verbindung zu {{name}} ist mit beiden Treibern fehlgeschlagen: {{error}}. Kein Plugin-Problem — der Wechsel zum Plugin wurde trotzdem beibehalten.", - "processFailureWithError": "Das PostgreSQL-Plugin konnte nicht gestartet werden: {{error}}. Das betrifft nicht speziell {{name}} — es wurde keine Verbindung versucht.", - "processFailure": "Das PostgreSQL-Plugin konnte nicht gestartet werden. Das betrifft nicht speziell {{name}} — es wurde keine Verbindung versucht.", - "failed": "{{name}} konnte nicht zum Plugin gewechselt werden: {{error}}", - "undo": "Rückgängig", - "undoFailed": "{{name}} konnte nicht zurück zum integrierten Treiber gewechselt werden: {{error}}", - "reportIssue": "Problem melden" - }, - "checklist": { - "title": "Verbindungen prüfen", - "subtitle_one": "{{count}} Verbindung nutzt noch den integrierten Treiber", - "subtitle_other": "{{count}} Verbindungen nutzen noch den integrierten Treiber", - "migrateSelected_one": "{{count}} ausgewählte migrieren", - "migrateSelected_other": "{{count}} ausgewählte migrieren", - "reportThisGap": "Problem melden", - "alreadyReported": "Gemeldet", - "testing": "Verbindung wird getestet…", - "uriWarning": "Die im Schlüsselbund gespeicherte Verbindungszeichenfolge wird nicht übernommen — Sie müssen sie nach der Migration erneut eingeben.", - "noGaps": "Keine Verbindungen zu prüfen.", - "close": "Schließen", - "migratingNotice": "Die Migration läuft auch nach dem Schließen dieses Fensters weiter.", - "gap": { - "ssl": "Verwendet SSL/TLS, vom Plugin noch nicht unterstützt", - "connection_uri": "Verwendet eine Verbindungszeichenfolge, vom Plugin noch nicht unterstützt" - } - } - }, - "triggers":{ + "triggers": { "nativeSqlHelp": "Vollständige Trigger-Anweisung im SQL-Dialekt der Datenbank eingeben. Bestehende Trigger werden beim Speichern nicht vorher gelöscht.", "originalRestored": "Der ursprüngliche Trigger wurde wiederhergestellt.", "restoreFailed": "Die Wiederherstellung des ursprünglichen Triggers ist ebenfalls fehlgeschlagen: ", @@ -3670,10 +3618,107 @@ "themePackages": { "import": "Theme importieren", "registryMismatch": "Dieses Paket stammt aus einer anderen Registry. Ändern Sie die konfigurierte Registry ausdrücklich, bevor Sie es aktualisieren.", - "importedTheme": "Importiertes Design", "manage": "Designs verwalten", "importJSON": "Tabularis-JSON importieren", "importVSCode": "Aus VS Code importieren", "edit": "Persönliches Design bearbeiten", "localPackage": "Lokales Paket", "installTitle": "Design-Paket installieren", "installSubtitle": "Deklaratives Design aus der konfigurierten Registry. Es wird kein Code ausgeführt.", "discover": "Designs unter Plugins durchsuchen", "refresh": "Liste aktualisieren", "preview": "Vorschau", "apply": "Anwenden", "confirm": "Bestätigen", "duplicate": "Als persönliches Design kopieren", "exportJSON": "Eigenständiges JSON exportieren", "exportPackage": "Autorenpaket exportieren", "remove": "Löschen", "update": "Paket aktualisieren", "disable": "Paket deaktivieren", "enable": "Paket aktivieren", "removePackage": "Paket deinstallieren", "disabled": "Deaktiviert", "file": "Designdatei", "name": "Designname", "mode": "Modus / Basis", "detectMode": "Erkennen (bei Unklarheit auswählen)", "source": "Design-JSON", "search": "Designs suchen", "loading": "Wird geladen…", "noThemes": "Keine Designs in dieser Registry verfügbar.", "details": "Details / Installation", "readme": "README / Bildschirmfotos", "version": "Paketversion", "latest": "Neueste Version", "install": "Paket installieren / ersetzen", "chooseArchive": "ZIP-Archiv auswählen", "screenshots": "Screenshots (extern öffnen)", "externalMedia": "Bilder und andere entfernte Medien werden nicht automatisch geladen. Links öffnen sich im Browser.", "snapshotEditor": "Exaktes Editor-JSON", "snapshotEditorHelp": "Dieser unabhängige Snapshot steuert die SQL-Farben anstelle des alten Alias. Änderungen werden als Vorschau angezeigt und gegen die ursprüngliche Revision gespeichert.", "recover": "Unterbrochene Installationen wiederherstellen", "recoveryExplanation": "Unvollständige Theme-Transaktionen ausdrücklich prüfen und wiederherstellen. Dies kann unterbrochene Installationen reparieren, wählt aber kein Theme aus und ändert keine gespeicherten Einstellungen.", "recoveryDone": "Wiederherstellungsprüfung abgeschlossen. Verbleibende Meldungen stehen unten.", "catalogIssues": "Katalogdiagnose", "fileTooLarge": "Die Datei überschreitet das Importlimit.", "previewHint": "Die Vorschau ist vorübergehend. Abbrechen stellt das gespeicherte Design wieder her; Anwenden speichert die Auswahl.", "previewReady": "Vorschau aktiv. Prüfen Sie Anwendung und Editor vor der Bestätigung.", "licenseNotice": "Import oder Export gewährt keine Weiterverbreitungsrechte. Urheberangaben beibehalten und Lizenz vor der Veröffentlichung prüfen.", "acknowledge": "Ich verstehe und akzeptiere die aufgeführten Konvertierungsgrenzen.", "applyAfterSave": "Nach dem Speichern anwenden", "savedNotApplied": "Design gespeichert, Auswahl fehlgeschlagen. Nicht erneut importieren; gespeichertes Design auswählen.", "installHint": "Die Installation ersetzt das gesamte Paket, wählt aber keine Variante. Vorschau, lokaler Import und Auswahl zählen nicht als Downloads.", "installedHint": "Paket installiert. Schließen und unter Erscheinungsbild eine Variante auswählen.", "committedRefreshFailed": "Vorgang abgeschlossen, Katalogaktualisierung fehlgeschlagen. Liste vor einem erneuten Versuch aktualisieren.", "missing": "Gespeicherte Auswahl nicht verfügbar: {{id}}. Offline-Ersatz ohne Änderung der Einstellung.", "downloads": "Downloads: {{count}}", "downloadsUnavailable": "Downloadanzahl nicht verfügbar", "installedVersion": "Installiert: {{version}}", "minimumVersion": "Benötigt Tabularis {{version}} oder neuer", "incompatible": "Inkompatible Version oder nicht genau ein universelles Archiv vorhanden.", "packageWarning": "Betrifft alle Paketvarianten. Gespeicherte Auswahlen bleiben erhalten und werden bei erneuter Verfügbarkeit wiederhergestellt.", "deleteWarning": "Persönliches Design löschen? Seine gespeicherten Anwendungsauswahlen verwenden danach die Standarddesigns.", "duplicateHint": "Unabhängige, bearbeitbare persönliche Kopie erstellen, ohne sie zu aktivieren.", "exportError": "Paketexport fehlgeschlagen; eigenständiger JSON-Export bleibt verfügbar.", "runtimeWarning": "Die tatsächlich erste unterstützte Version angeben. Eine Entwicklungsversionsnummer beweist keine Kompatibilität alter Clients.", "packageName": "Paketkennung (Kleinbuchstaben)", "minimumRuntime": "Minimale Tabularis-Version", "license": "Lizenztext und Urheberangaben", "rightsAcknowledged": "Ich habe Weiterverbreitungsrechte und Urheberangaben geprüft.", - "groups": { "builtin": "Integriert · offline", "installed": "Installierte Pakete", "personal": "Persönliche Designs" }, "modes": { "light": "Hell", "dark": "Dunkel", "high-contrast": "Hoher Kontrast" }, - "importErrors": { "unrecognized": "Kein erkanntes VS-Code-Design.", "modeRequired": "Modus auswählen und Vorschau erneut öffnen.", "includeOnly": "Reine Include-Designs sind nicht importierbar. Die tatsächlichen Farben bereitstellen.", "noSupportedData": "Keine unterstützten Farben oder SQL-Tokenregeln gefunden.", "invalidColor": "Ungültiger Wert einer unterstützten Farbe.", "invalidRules": "Ungültige oder zu viele Tokenregeln." }, - "diagnostics": { "unsupportedKey": "Nicht unterstütztes Feld", "unsupportedColor": "Nicht unterstützte Farbe", "unsupportedScope": "Nicht unterstützter Bereich", "scopeApproximation": "Angenäherte SQL-Zuordnung", "unsupportedStyle": "Nicht unterstützter Stil", "ignoredInclude": "Include nicht geladen", "ignoredSemanticTokens": "Semantische Tokens ignoriert", "unsupportedReference": "Externe Referenz nicht geladen", "unsupportedSetting": "Nicht unterstützte Einstellung", "tokenAlphaFlattened": "Token-Deckkraft gegen den Basishintergrund berechnet", "modeApproximation": "Modus überschrieben oder angenähert", "diagnosticsTruncated": "Weitere Diagnosen ausgelassen" } + "importedTheme": "Importiertes Design", + "manage": "Designs verwalten", + "importJSON": "Tabularis-JSON importieren", + "importVSCode": "Aus VS Code importieren", + "edit": "Persönliches Design bearbeiten", + "localPackage": "Lokales Paket", + "installTitle": "Design-Paket installieren", + "installSubtitle": "Deklaratives Design aus der konfigurierten Registry. Es wird kein Code ausgeführt.", + "discover": "Designs unter Plugins durchsuchen", + "refresh": "Liste aktualisieren", + "preview": "Vorschau", + "apply": "Anwenden", + "confirm": "Bestätigen", + "duplicate": "Als persönliches Design kopieren", + "exportJSON": "Eigenständiges JSON exportieren", + "exportPackage": "Autorenpaket exportieren", + "remove": "Löschen", + "update": "Paket aktualisieren", + "disable": "Paket deaktivieren", + "enable": "Paket aktivieren", + "removePackage": "Paket deinstallieren", + "disabled": "Deaktiviert", + "file": "Designdatei", + "name": "Designname", + "mode": "Modus / Basis", + "detectMode": "Erkennen (bei Unklarheit auswählen)", + "source": "Design-JSON", + "search": "Designs suchen", + "loading": "Wird geladen…", + "noThemes": "Keine Designs in dieser Registry verfügbar.", + "details": "Details / Installation", + "readme": "README / Bildschirmfotos", + "version": "Paketversion", + "latest": "Neueste Version", + "install": "Paket installieren / ersetzen", + "chooseArchive": "ZIP-Archiv auswählen", + "screenshots": "Screenshots (extern öffnen)", + "externalMedia": "Bilder und andere entfernte Medien werden nicht automatisch geladen. Links öffnen sich im Browser.", + "snapshotEditor": "Exaktes Editor-JSON", + "snapshotEditorHelp": "Dieser unabhängige Snapshot steuert die SQL-Farben anstelle des alten Alias. Änderungen werden als Vorschau angezeigt und gegen die ursprüngliche Revision gespeichert.", + "recover": "Unterbrochene Installationen wiederherstellen", + "recoveryExplanation": "Unvollständige Theme-Transaktionen ausdrücklich prüfen und wiederherstellen. Dies kann unterbrochene Installationen reparieren, wählt aber kein Theme aus und ändert keine gespeicherten Einstellungen.", + "recoveryDone": "Wiederherstellungsprüfung abgeschlossen. Verbleibende Meldungen stehen unten.", + "catalogIssues": "Katalogdiagnose", + "fileTooLarge": "Die Datei überschreitet das Importlimit.", + "previewHint": "Die Vorschau ist vorübergehend. Abbrechen stellt das gespeicherte Design wieder her; Anwenden speichert die Auswahl.", + "previewReady": "Vorschau aktiv. Prüfen Sie Anwendung und Editor vor der Bestätigung.", + "licenseNotice": "Import oder Export gewährt keine Weiterverbreitungsrechte. Urheberangaben beibehalten und Lizenz vor der Veröffentlichung prüfen.", + "acknowledge": "Ich verstehe und akzeptiere die aufgeführten Konvertierungsgrenzen.", + "applyAfterSave": "Nach dem Speichern anwenden", + "savedNotApplied": "Design gespeichert, Auswahl fehlgeschlagen. Nicht erneut importieren; gespeichertes Design auswählen.", + "installHint": "Die Installation ersetzt das gesamte Paket, wählt aber keine Variante. Vorschau, lokaler Import und Auswahl zählen nicht als Downloads.", + "installedHint": "Paket installiert. Schließen und unter Erscheinungsbild eine Variante auswählen.", + "committedRefreshFailed": "Vorgang abgeschlossen, Katalogaktualisierung fehlgeschlagen. Liste vor einem erneuten Versuch aktualisieren.", + "missing": "Gespeicherte Auswahl nicht verfügbar: {{id}}. Offline-Ersatz ohne Änderung der Einstellung.", + "downloads": "Downloads: {{count}}", + "downloadsUnavailable": "Downloadanzahl nicht verfügbar", + "installedVersion": "Installiert: {{version}}", + "minimumVersion": "Benötigt Tabularis {{version}} oder neuer", + "incompatible": "Inkompatible Version oder nicht genau ein universelles Archiv vorhanden.", + "packageWarning": "Betrifft alle Paketvarianten. Gespeicherte Auswahlen bleiben erhalten und werden bei erneuter Verfügbarkeit wiederhergestellt.", + "deleteWarning": "Persönliches Design löschen? Seine gespeicherten Anwendungsauswahlen verwenden danach die Standarddesigns.", + "duplicateHint": "Unabhängige, bearbeitbare persönliche Kopie erstellen, ohne sie zu aktivieren.", + "exportError": "Paketexport fehlgeschlagen; eigenständiger JSON-Export bleibt verfügbar.", + "runtimeWarning": "Die tatsächlich erste unterstützte Version angeben. Eine Entwicklungsversionsnummer beweist keine Kompatibilität alter Clients.", + "packageName": "Paketkennung (Kleinbuchstaben)", + "minimumRuntime": "Minimale Tabularis-Version", + "license": "Lizenztext und Urheberangaben", + "rightsAcknowledged": "Ich habe Weiterverbreitungsrechte und Urheberangaben geprüft.", + "groups": { + "builtin": "Integriert · offline", + "installed": "Installierte Pakete", + "personal": "Persönliche Designs" + }, + "modes": { + "light": "Hell", + "dark": "Dunkel", + "high-contrast": "Hoher Kontrast" + }, + "importErrors": { + "unrecognized": "Kein erkanntes VS-Code-Design.", + "modeRequired": "Modus auswählen und Vorschau erneut öffnen.", + "includeOnly": "Reine Include-Designs sind nicht importierbar. Die tatsächlichen Farben bereitstellen.", + "noSupportedData": "Keine unterstützten Farben oder SQL-Tokenregeln gefunden.", + "invalidColor": "Ungültiger Wert einer unterstützten Farbe.", + "invalidRules": "Ungültige oder zu viele Tokenregeln." + }, + "diagnostics": { + "unsupportedKey": "Nicht unterstütztes Feld", + "unsupportedColor": "Nicht unterstützte Farbe", + "unsupportedScope": "Nicht unterstützter Bereich", + "scopeApproximation": "Angenäherte SQL-Zuordnung", + "unsupportedStyle": "Nicht unterstützter Stil", + "ignoredInclude": "Include nicht geladen", + "ignoredSemanticTokens": "Semantische Tokens ignoriert", + "unsupportedReference": "Externe Referenz nicht geladen", + "unsupportedSetting": "Nicht unterstützte Einstellung", + "tokenAlphaFlattened": "Token-Deckkraft gegen den Basishintergrund berechnet", + "modeApproximation": "Modus überschrieben oder angenähert", + "diagnosticsTruncated": "Weitere Diagnosen ausgelassen" + } }, "linkedGit": { "title": "Git-Änderungen prüfen", diff --git a/packages/web-ui/src/i18n/locales/en.json b/packages/web-ui/src/i18n/locales/en.json index 216c18246..69b3be39c 100644 --- a/packages/web-ui/src/i18n/locales/en.json +++ b/packages/web-ui/src/i18n/locales/en.json @@ -1282,12 +1282,6 @@ "label": "Timezone", "description": "Session timezone sent to MySQL after connect." } - }, - "postgres": { - "poolMaxSize": { - "label": "Pool Max Size", - "description": "Maximum number of PostgreSQL connections kept in the pool." - } } } }, @@ -3621,55 +3615,6 @@ "updateConfirm": "Update to v{{version}}", "alreadyInstalled": "Version {{version}} is already installed." }, - "migration": { - "banner": { - "nudge": "Try the new PostgreSQL plugin — the built-in PostgreSQL driver is being retired. The plugin has the same features and gets updates faster.", - "nudgeWithDate": "Try the new PostgreSQL plugin — the built-in PostgreSQL driver is being retired (tentatively {{date}}). The plugin has the same features and gets updates faster.", - "offline": "The PostgreSQL plugin couldn't be downloaded — we'll retry on the next launch. Check your connection or network if this keeps happening.", - "reviewConnections": "Review connections" - }, - "switchToPlugin": "Switch to plugin", - "switchToBuiltin": "Switch back to built-in", - "confirm": { - "title": "Switch to plugin?", - "message": "Switch {{name}} to the PostgreSQL plugin? If it's currently connected, it'll be disconnected and reopened using the plugin.", - "uriMessage": "Switch {{name}} to the PostgreSQL plugin? Its connection string is stored in the keychain and won't carry over to the plugin — you'll need to re-enter it to reconnect.", - "confirmLabel": "Switch", - "confirmLabelUri": "Switch & re-enter later", - "undoTitle": "Switch back to built-in?", - "undoMessage": "Switch {{name}} back to the built-in PostgreSQL driver? If it's currently connected, it'll be disconnected and reopened using the built-in driver.", - "undoConfirmLabel": "Switch back" - }, - "toast": { - "success": "Switched {{name}} to the PostgreSQL plugin.", - "connectionFailure": "Couldn't connect to {{name}} using the plugin: {{error}}", - "connectionFailurePreexisting": "Couldn't connect to {{name}} with either driver: {{error}}. Not a plugin problem — the switch to the plugin was kept.", - "processFailureWithError": "The PostgreSQL plugin didn't start: {{error}}. This isn't specific to {{name}} — no connection was attempted.", - "processFailure": "The PostgreSQL plugin didn't start. This isn't specific to {{name}} — no connection was attempted.", - "failed": "Couldn't switch {{name}} to the plugin: {{error}}", - "undo": "Undo", - "undoFailed": "Couldn't switch {{name}} back to the built-in driver: {{error}}", - "reportIssue": "Report an issue" - }, - "checklist": { - "title": "Review connections", - "subtitle_one": "{{count}} connection still on the built-in driver", - "subtitle_other": "{{count}} connections still on the built-in driver", - "migrateSelected_one": "Migrate {{count}} selected", - "migrateSelected_other": "Migrate {{count}} selected", - "reportThisGap": "Report this gap", - "alreadyReported": "Reported", - "testing": "Testing connection…", - "uriWarning": "Connection string is stored in the keychain and won't carry over — you'll need to re-enter it after migrating.", - "noGaps": "No connections to review.", - "close": "Close", - "migratingNotice": "Migration continues even after you close this window.", - "gap": { - "ssl": "Uses SSL/TLS, not yet supported by the plugin", - "connection_uri": "Uses a connection string, not yet supported by the plugin" - } - } - }, "connectionCatalogue": { "searchPlaceholder": "Search databases…", "clearSearch": "Clear search", diff --git a/packages/web-ui/src/i18n/locales/es.json b/packages/web-ui/src/i18n/locales/es.json index f4677fae0..b8be34aa4 100644 --- a/packages/web-ui/src/i18n/locales/es.json +++ b/packages/web-ui/src/i18n/locales/es.json @@ -117,7 +117,11 @@ "development": "Desarrollo", "staging": "Staging", "production": "Producción", - "short": { "development": "DEV", "staging": "STAGING", "production": "PROD" }, + "short": { + "development": "DEV", + "staging": "STAGING", + "production": "PROD" + }, "banner": "Producción — {{name}}", "warnTitle": "Base de datos de producción", "warnMessage": "Está a punto de modificar datos de producción en \"{{name}}\". ¿Seguro que desea continuar?", @@ -1244,12 +1248,6 @@ "label": "Zona Horaria", "description": "Zona horaria de sesión enviada a MySQL después de conectar." } - }, - "postgres": { - "poolMaxSize": { - "label": "Tamaño Máximo del Pool", - "description": "Número máximo de conexiones PostgreSQL mantenidas en el pool." - } } } }, @@ -2016,7 +2014,7 @@ "primaryKey": "Clave Primaria", "auto": "Auto" }, - "triggers":{ + "triggers": { "nativeSqlHelp": "Introduce una instrucción de trigger completa en el dialecto SQL de la base de datos. Los triggers existentes se guardan sin eliminarlos antes.", "originalRestored": "Se restauró el trigger original.", "restoreFailed": "La restauración del trigger original también falló: ", @@ -2296,7 +2294,6 @@ "analyzeMismatchTooltip": "Un plan tiene métricas de ejecución reales (EXPLAIN ANALYZE) mientras que el otro solo tiene estimaciones", "pinSnapshot": "Fijar", "unpinSnapshot": "Desfijar", - "time": "Tiempo", "formatText": "Texto", "aiAnalysis": "Analisis IA", "aiAnalysisTitle": "Analisis IA del Plan de Ejecucion", @@ -3440,55 +3437,6 @@ "updateConfirm": "Actualizar a v{{version}}", "alreadyInstalled": "La versión {{version}} ya está instalada." }, - "migration": { - "banner": { - "nudge": "Prueba el nuevo complemento de PostgreSQL — el controlador integrado de PostgreSQL se está retirando. El complemento tiene las mismas funciones y se actualiza más rápido.", - "nudgeWithDate": "Prueba el nuevo complemento de PostgreSQL — el controlador integrado de PostgreSQL se está retirando (provisionalmente {{date}}). El complemento tiene las mismas funciones y se actualiza más rápido.", - "offline": "No se pudo descargar el complemento de PostgreSQL — lo reintentaremos en el próximo inicio. Revisa tu conexión o red si esto sigue ocurriendo.", - "reviewConnections": "Revisar conexiones" - }, - "switchToPlugin": "Cambiar al complemento", - "switchToBuiltin": "Volver al integrado", - "confirm": { - "title": "¿Cambiar al complemento?", - "message": "¿Cambiar {{name}} al complemento de PostgreSQL? Si está conectado actualmente, se desconectará y se volverá a abrir usando el complemento.", - "uriMessage": "¿Cambiar {{name}} al complemento de PostgreSQL? Su cadena de conexión almacenada en el llavero no se transferirá — deberá volver a ingresarla para reconectarse.", - "confirmLabel": "Cambiar", - "confirmLabelUri": "Cambiar y volver a ingresar después", - "undoTitle": "¿Volver al controlador integrado?", - "undoMessage": "¿Volver {{name}} al controlador integrado de PostgreSQL? Si está conectado actualmente, se desconectará y se volverá a abrir usando el controlador integrado.", - "undoConfirmLabel": "Volver" - }, - "toast": { - "success": "Se cambió {{name}} al complemento de PostgreSQL.", - "connectionFailure": "No se pudo conectar a {{name}} usando el complemento: {{error}}", - "connectionFailurePreexisting": "No se pudo conectar a {{name}} con ninguno de los dos controladores: {{error}}. No es un problema del complemento — el cambio al complemento se mantuvo.", - "processFailureWithError": "El complemento de PostgreSQL no se inició: {{error}}. No es específico de {{name}} — no se intentó ninguna conexión.", - "processFailure": "El complemento de PostgreSQL no se inició. No es específico de {{name}} — no se intentó ninguna conexión.", - "failed": "No se pudo cambiar {{name}} al complemento: {{error}}", - "undo": "Deshacer", - "undoFailed": "No se pudo devolver {{name}} al controlador integrado: {{error}}", - "reportIssue": "Reportar un problema" - }, - "checklist": { - "title": "Revisar conexiones", - "subtitle_one": "{{count}} conexión aún en el controlador integrado", - "subtitle_other": "{{count}} conexiones aún en el controlador integrado", - "migrateSelected_one": "Migrar {{count}} seleccionada", - "migrateSelected_other": "Migrar {{count}} seleccionadas", - "reportThisGap": "Reportar este problema", - "alreadyReported": "Reportado", - "testing": "Probando conexión…", - "uriWarning": "La cadena de conexión almacenada en el llavero no se transferirá — deberá volver a ingresarla después de migrar.", - "noGaps": "No hay conexiones para revisar.", - "close": "Cerrar", - "migratingNotice": "La migración continúa incluso si cierras esta ventana.", - "gap": { - "ssl": "Usa SSL/TLS, aún no admitido por el complemento", - "connection_uri": "Usa una cadena de conexión, aún no admitida por el complemento" - } - } - }, "connectionCatalogue": { "searchPlaceholder": "Buscar bases de datos…", "clearSearch": "Borrar búsqueda", @@ -3599,10 +3547,107 @@ "themePackages": { "import": "Importar tema", "registryMismatch": "Este paquete pertenece a otro registro. Cambia explícitamente el registro configurado antes de actualizarlo.", - "importedTheme": "Tema importado", "manage": "Administrar temas", "importJSON": "Importar JSON de Tabularis", "importVSCode": "Importar desde VS Code", "edit": "Editar tema personal", "localPackage": "Paquete local", "installTitle": "Instalar paquete de tema", "installSubtitle": "Tema declarativo del registro configurado. No se ejecuta ningún código.", "discover": "Explorar temas en Plugins", "refresh": "Actualizar lista", "preview": "Vista previa", "apply": "Aplicar", "confirm": "Confirmar", "duplicate": "Duplicar como personal", "exportJSON": "Exportar JSON independiente", "exportPackage": "Exportar paquete de autor", "remove": "Eliminar", "update": "Actualizar paquete", "disable": "Desactivar paquete", "enable": "Activar paquete", "removePackage": "Desinstalar paquete", "disabled": "Desactivado", "file": "Archivo del tema", "name": "Nombre del tema", "mode": "Modo / base", "detectMode": "Detectar (elegir si es ambiguo)", "source": "JSON del tema", "search": "Buscar temas", "loading": "Cargando…", "noThemes": "No hay temas disponibles en este registro.", "details": "Detalles / instalación", "readme": "README / capturas", "version": "Versión del paquete", "latest": "Última versión", "install": "Instalar / sustituir paquete", "chooseArchive": "Elegir archivo ZIP", "screenshots": "Capturas (abrir externamente)", "externalMedia": "Las imágenes y otros medios remotos no se cargan automáticamente. Los enlaces se abren en el navegador.", "snapshotEditor": "JSON exacto del editor", "snapshotEditorHelp": "Esta copia independiente controla los colores SQL en lugar del alias antiguo. Los cambios se previsualizan y se guardan comprobando la revisión original.", "recover": "Recuperar instalaciones interrumpidas", "recoveryExplanation": "Comprobar y recuperar explícitamente las operaciones de temas incompletas. Puede restaurar instalaciones interrumpidas, sin seleccionar un tema ni cambiar las preferencias guardadas.", "recoveryDone": "Comprobaciones de recuperación completadas. Revisa los problemas pendientes a continuación.", "catalogIssues": "Diagnóstico del catálogo", "fileTooLarge": "El archivo supera el límite de importación.", "previewHint": "La vista previa es temporal. Cancelar restaura el tema guardado; Aplicar guarda la elección.", "previewReady": "Vista previa activa. Revise la aplicación y el editor antes de confirmar.", "licenseNotice": "Importar o exportar no concede derechos de redistribución. Conserve la atribución y compruebe la licencia antes de publicar.", "acknowledge": "Comprendo y acepto las limitaciones de conversión indicadas.", "applyAfterSave": "Aplicar después de guardar", "savedNotApplied": "Tema guardado, pero falló la selección. No lo importe de nuevo; seleccione el tema guardado.", "installHint": "La instalación sustituye todo el paquete sin seleccionar una variante. La vista previa, la importación local y la selección no cuentan como descargas.", "installedHint": "Paquete instalado. Cierre y elija una variante en Apariencia.", "committedRefreshFailed": "Operación completada, pero falló la actualización del catálogo. Actualice la lista antes de reintentar.", "missing": "Selección guardada no disponible: {{id}}. Se usa un tema sin conexión sin cambiar la preferencia.", "downloads": "Descargas: {{count}}", "downloadsUnavailable": "Recuento de descargas no disponible", "installedVersion": "Instalada: {{version}}", "minimumVersion": "Requiere Tabularis {{version}} o posterior", "incompatible": "Versión incompatible o sin un único archivo universal.", "packageWarning": "Afecta a todas las variantes. Las selecciones guardadas se conservan y restauran cuando vuelven a estar disponibles.", "deleteWarning": "¿Eliminar este tema personal? Sus selecciones guardadas usarán los temas predeterminados.", "duplicateHint": "Crear una copia personal independiente y editable sin activarla.", "exportError": "Falló la exportación del paquete; sigue disponible el JSON independiente.", "runtimeWarning": "Indique la primera versión realmente compatible. Un número de desarrollo no demuestra compatibilidad con clientes antiguos.", "packageName": "Identificador del paquete (minúsculas)", "minimumRuntime": "Versión mínima de Tabularis", "license": "Texto de licencia y atribución", "rightsAcknowledged": "He verificado los derechos de redistribución y la atribución.", - "groups": { "builtin": "Integrados · sin conexión", "installed": "Paquetes instalados", "personal": "Temas personales" }, "modes": { "light": "Claro", "dark": "Oscuro", "high-contrast": "Alto contraste" }, - "importErrors": { "unrecognized": "Tema de VS Code no reconocido.", "modeRequired": "Elija un modo y repita la vista previa.", "includeOnly": "No se pueden importar temas con solo referencias include. Proporcione los colores reales.", "noSupportedData": "No se encontraron colores o reglas SQL compatibles.", "invalidColor": "Un color compatible tiene un valor no válido.", "invalidRules": "Reglas de tokens no válidas o excesivas." }, - "diagnostics": { "unsupportedKey": "Campo no compatible", "unsupportedColor": "Color no compatible", "unsupportedScope": "Ámbito no compatible", "scopeApproximation": "Asignación SQL aproximada", "unsupportedStyle": "Estilo no compatible", "ignoredInclude": "Include no cargado", "ignoredSemanticTokens": "Tokens semánticos ignorados", "unsupportedReference": "Referencia externa no cargada", "unsupportedSetting": "Ajuste no compatible", "tokenAlphaFlattened": "Opacidad de tokens calculada sobre el fondo base", "modeApproximation": "Modo sustituido o aproximado", "diagnosticsTruncated": "Se omitieron diagnósticos adicionales" } + "importedTheme": "Tema importado", + "manage": "Administrar temas", + "importJSON": "Importar JSON de Tabularis", + "importVSCode": "Importar desde VS Code", + "edit": "Editar tema personal", + "localPackage": "Paquete local", + "installTitle": "Instalar paquete de tema", + "installSubtitle": "Tema declarativo del registro configurado. No se ejecuta ningún código.", + "discover": "Explorar temas en Plugins", + "refresh": "Actualizar lista", + "preview": "Vista previa", + "apply": "Aplicar", + "confirm": "Confirmar", + "duplicate": "Duplicar como personal", + "exportJSON": "Exportar JSON independiente", + "exportPackage": "Exportar paquete de autor", + "remove": "Eliminar", + "update": "Actualizar paquete", + "disable": "Desactivar paquete", + "enable": "Activar paquete", + "removePackage": "Desinstalar paquete", + "disabled": "Desactivado", + "file": "Archivo del tema", + "name": "Nombre del tema", + "mode": "Modo / base", + "detectMode": "Detectar (elegir si es ambiguo)", + "source": "JSON del tema", + "search": "Buscar temas", + "loading": "Cargando…", + "noThemes": "No hay temas disponibles en este registro.", + "details": "Detalles / instalación", + "readme": "README / capturas", + "version": "Versión del paquete", + "latest": "Última versión", + "install": "Instalar / sustituir paquete", + "chooseArchive": "Elegir archivo ZIP", + "screenshots": "Capturas (abrir externamente)", + "externalMedia": "Las imágenes y otros medios remotos no se cargan automáticamente. Los enlaces se abren en el navegador.", + "snapshotEditor": "JSON exacto del editor", + "snapshotEditorHelp": "Esta copia independiente controla los colores SQL en lugar del alias antiguo. Los cambios se previsualizan y se guardan comprobando la revisión original.", + "recover": "Recuperar instalaciones interrumpidas", + "recoveryExplanation": "Comprobar y recuperar explícitamente las operaciones de temas incompletas. Puede restaurar instalaciones interrumpidas, sin seleccionar un tema ni cambiar las preferencias guardadas.", + "recoveryDone": "Comprobaciones de recuperación completadas. Revisa los problemas pendientes a continuación.", + "catalogIssues": "Diagnóstico del catálogo", + "fileTooLarge": "El archivo supera el límite de importación.", + "previewHint": "La vista previa es temporal. Cancelar restaura el tema guardado; Aplicar guarda la elección.", + "previewReady": "Vista previa activa. Revise la aplicación y el editor antes de confirmar.", + "licenseNotice": "Importar o exportar no concede derechos de redistribución. Conserve la atribución y compruebe la licencia antes de publicar.", + "acknowledge": "Comprendo y acepto las limitaciones de conversión indicadas.", + "applyAfterSave": "Aplicar después de guardar", + "savedNotApplied": "Tema guardado, pero falló la selección. No lo importe de nuevo; seleccione el tema guardado.", + "installHint": "La instalación sustituye todo el paquete sin seleccionar una variante. La vista previa, la importación local y la selección no cuentan como descargas.", + "installedHint": "Paquete instalado. Cierre y elija una variante en Apariencia.", + "committedRefreshFailed": "Operación completada, pero falló la actualización del catálogo. Actualice la lista antes de reintentar.", + "missing": "Selección guardada no disponible: {{id}}. Se usa un tema sin conexión sin cambiar la preferencia.", + "downloads": "Descargas: {{count}}", + "downloadsUnavailable": "Recuento de descargas no disponible", + "installedVersion": "Instalada: {{version}}", + "minimumVersion": "Requiere Tabularis {{version}} o posterior", + "incompatible": "Versión incompatible o sin un único archivo universal.", + "packageWarning": "Afecta a todas las variantes. Las selecciones guardadas se conservan y restauran cuando vuelven a estar disponibles.", + "deleteWarning": "¿Eliminar este tema personal? Sus selecciones guardadas usarán los temas predeterminados.", + "duplicateHint": "Crear una copia personal independiente y editable sin activarla.", + "exportError": "Falló la exportación del paquete; sigue disponible el JSON independiente.", + "runtimeWarning": "Indique la primera versión realmente compatible. Un número de desarrollo no demuestra compatibilidad con clientes antiguos.", + "packageName": "Identificador del paquete (minúsculas)", + "minimumRuntime": "Versión mínima de Tabularis", + "license": "Texto de licencia y atribución", + "rightsAcknowledged": "He verificado los derechos de redistribución y la atribución.", + "groups": { + "builtin": "Integrados · sin conexión", + "installed": "Paquetes instalados", + "personal": "Temas personales" + }, + "modes": { + "light": "Claro", + "dark": "Oscuro", + "high-contrast": "Alto contraste" + }, + "importErrors": { + "unrecognized": "Tema de VS Code no reconocido.", + "modeRequired": "Elija un modo y repita la vista previa.", + "includeOnly": "No se pueden importar temas con solo referencias include. Proporcione los colores reales.", + "noSupportedData": "No se encontraron colores o reglas SQL compatibles.", + "invalidColor": "Un color compatible tiene un valor no válido.", + "invalidRules": "Reglas de tokens no válidas o excesivas." + }, + "diagnostics": { + "unsupportedKey": "Campo no compatible", + "unsupportedColor": "Color no compatible", + "unsupportedScope": "Ámbito no compatible", + "scopeApproximation": "Asignación SQL aproximada", + "unsupportedStyle": "Estilo no compatible", + "ignoredInclude": "Include no cargado", + "ignoredSemanticTokens": "Tokens semánticos ignorados", + "unsupportedReference": "Referencia externa no cargada", + "unsupportedSetting": "Ajuste no compatible", + "tokenAlphaFlattened": "Opacidad de tokens calculada sobre el fondo base", + "modeApproximation": "Modo sustituido o aproximado", + "diagnosticsTruncated": "Se omitieron diagnósticos adicionales" + } }, "linkedGit": { "title": "Revisar cambios de Git", diff --git a/packages/web-ui/src/i18n/locales/fr.json b/packages/web-ui/src/i18n/locales/fr.json index c452533a3..5be10252f 100644 --- a/packages/web-ui/src/i18n/locales/fr.json +++ b/packages/web-ui/src/i18n/locales/fr.json @@ -1250,12 +1250,6 @@ "label": "Fuseau horaire", "description": "Fuseau horaire de session envoyé à MySQL après connexion." } - }, - "postgres": { - "poolMaxSize": { - "label": "Taille maximale du pool", - "description": "Nombre maximal de connexions PostgreSQL conservées dans le pool." - } } } }, @@ -3585,55 +3579,6 @@ "updateConfirm": "Mettre à jour vers v{{version}}", "alreadyInstalled": "La version {{version}} est déjà installée." }, - "migration": { - "banner": { - "nudge": "Essayez le nouveau plugin PostgreSQL — le pilote intégré PostgreSQL est en cours de retrait. Le plugin a les mêmes fonctionnalités et se met à jour plus rapidement.", - "nudgeWithDate": "Essayez le nouveau plugin PostgreSQL — le pilote intégré PostgreSQL est en cours de retrait (provisoirement le {{date}}). Le plugin a les mêmes fonctionnalités et se met à jour plus rapidement.", - "offline": "Le plugin PostgreSQL n'a pas pu être téléchargé — une nouvelle tentative aura lieu au prochain lancement. Vérifiez votre connexion ou votre réseau si cela persiste.", - "reviewConnections": "Examiner les connexions" - }, - "switchToPlugin": "Passer au plugin", - "switchToBuiltin": "Revenir au pilote intégré", - "confirm": { - "title": "Passer au plugin ?", - "message": "Faire passer {{name}} au plugin PostgreSQL ? Si la connexion est active, elle sera fermée et rouverte avec le plugin.", - "uriMessage": "Faire passer {{name}} au plugin PostgreSQL ? Sa chaîne de connexion stockée dans le trousseau ne sera pas transférée — vous devrez la ressaisir pour vous reconnecter.", - "confirmLabel": "Basculer", - "confirmLabelUri": "Basculer et ressaisir plus tard", - "undoTitle": "Revenir au pilote intégré ?", - "undoMessage": "Faire revenir {{name}} au pilote PostgreSQL intégré ? Si la connexion est active, elle sera fermée et rouverte avec le pilote intégré.", - "undoConfirmLabel": "Revenir" - }, - "toast": { - "success": "{{name}} a été basculé vers le plugin PostgreSQL.", - "connectionFailure": "Impossible de se connecter à {{name}} avec le plugin : {{error}}", - "connectionFailurePreexisting": "Impossible de se connecter à {{name}} avec l'un ou l'autre pilote : {{error}}. Ce n'est pas un problème du plugin — le passage au plugin a été conservé.", - "processFailureWithError": "Le plugin PostgreSQL n'a pas démarré : {{error}}. Cela ne concerne pas spécifiquement {{name}} — aucune connexion n'a été tentée.", - "processFailure": "Le plugin PostgreSQL n'a pas démarré. Cela ne concerne pas spécifiquement {{name}} — aucune connexion n'a été tentée.", - "failed": "Impossible de basculer {{name}} vers le plugin : {{error}}", - "undo": "Annuler", - "undoFailed": "Impossible de rebasculer {{name}} vers le pilote intégré : {{error}}", - "reportIssue": "Signaler un problème" - }, - "checklist": { - "title": "Examiner les connexions", - "subtitle_one": "{{count}} connexion encore sur le pilote intégré", - "subtitle_other": "{{count}} connexions encore sur le pilote intégré", - "migrateSelected_one": "Migrer {{count}} sélectionnée", - "migrateSelected_other": "Migrer {{count}} sélectionnées", - "reportThisGap": "Signaler ce problème", - "alreadyReported": "Signalé", - "testing": "Test de connexion…", - "uriWarning": "La chaîne de connexion stockée dans le trousseau ne sera pas transférée — vous devrez la ressaisir après la migration.", - "noGaps": "Aucune connexion à examiner.", - "close": "Fermer", - "migratingNotice": "La migration se poursuit même si vous fermez cette fenêtre.", - "gap": { - "ssl": "Utilise SSL/TLS, pas encore prise en charge par le plugin", - "connection_uri": "Utilise une chaîne de connexion, pas encore prise en charge par le plugin" - } - } - }, "connectionCatalogue": { "searchPlaceholder": "Rechercher des bases de données…", "clearSearch": "Effacer la recherche", diff --git a/packages/web-ui/src/i18n/locales/it.json b/packages/web-ui/src/i18n/locales/it.json index 5d0fa3b1b..cb0ba2f03 100644 --- a/packages/web-ui/src/i18n/locales/it.json +++ b/packages/web-ui/src/i18n/locales/it.json @@ -101,7 +101,7 @@ "matchCase": "Maiuscole/minuscole", "matchCaseHint": "Distingue maiuscole e minuscole (LIKE). Deseleziona per ignorarle (ILIKE)." }, - "triggers":{ + "triggers": { "nativeSqlHelp": "Inserisci un’istruzione trigger completa nel dialetto SQL del database. I trigger esistenti vengono salvati senza essere prima eliminati.", "originalRestored": "Il trigger originale è stato ripristinato.", "restoreFailed": "Anche il ripristino del trigger originale è fallito: ", @@ -125,7 +125,11 @@ "development": "Sviluppo", "staging": "Staging", "production": "Produzione", - "short": { "development": "DEV", "staging": "STAGING", "production": "PROD" }, + "short": { + "development": "DEV", + "staging": "STAGING", + "production": "PROD" + }, "banner": "Produzione — {{name}}", "warnTitle": "Database di produzione", "warnMessage": "Stai per modificare dati di produzione su \"{{name}}\". Vuoi davvero continuare?", @@ -1280,12 +1284,6 @@ "label": "Fuso Orario", "description": "Fuso orario della sessione inviato a MySQL dopo la connessione." } - }, - "postgres": { - "poolMaxSize": { - "label": "Dimensione Massima del Pool", - "description": "Numero massimo di connessioni PostgreSQL mantenute nel pool." - } } } }, @@ -2331,7 +2329,6 @@ "analyzeMismatchTooltip": "Un piano ha metriche di esecuzione effettive (EXPLAIN ANALYZE) mentre l'altro ha solo stime", "pinSnapshot": "Fissa", "unpinSnapshot": "Sblocca", - "time": "Tempo", "formatText": "Testo", "aiAnalysis": "Analisi AI", "aiAnalysisTitle": "Analisi AI del Piano di Esecuzione", @@ -3539,55 +3536,6 @@ "updateConfirm": "Aggiorna a v{{version}}", "alreadyInstalled": "La versione {{version}} è già installata." }, - "migration": { - "banner": { - "nudge": "Prova il nuovo plugin PostgreSQL — il driver integrato PostgreSQL è in fase di ritiro. Il plugin ha le stesse funzionalità e si aggiorna più velocemente.", - "nudgeWithDate": "Prova il nuovo plugin PostgreSQL — il driver integrato PostgreSQL è in fase di ritiro (provvisoriamente il {{date}}). Il plugin ha le stesse funzionalità e si aggiorna più velocemente.", - "offline": "Il plugin PostgreSQL non è stato scaricato — riproveremo al prossimo avvio. Controlla la connessione o la rete se il problema persiste.", - "reviewConnections": "Rivedi connessioni" - }, - "switchToPlugin": "Passa al plugin", - "switchToBuiltin": "Torna al driver integrato", - "confirm": { - "title": "Passare al plugin?", - "message": "Passare {{name}} al plugin PostgreSQL? Se è attualmente connesso, verrà disconnesso e riaperto usando il plugin.", - "uriMessage": "Passare {{name}} al plugin PostgreSQL? La stringa di connessione salvata nel portachiavi non verrà trasferita — dovrai reinserirla per riconnetterti.", - "confirmLabel": "Passa", - "confirmLabelUri": "Passa e reinserisci più tardi", - "undoTitle": "Tornare al driver integrato?", - "undoMessage": "Far tornare {{name}} al driver PostgreSQL integrato? Se è attualmente connesso, verrà disconnesso e riaperto usando il driver integrato.", - "undoConfirmLabel": "Torna" - }, - "toast": { - "success": "{{name}} è stato passato al plugin PostgreSQL.", - "connectionFailure": "Impossibile connettersi a {{name}} usando il plugin: {{error}}", - "connectionFailurePreexisting": "Impossibile connettersi a {{name}} con entrambi i driver: {{error}}. Non è un problema del plugin — il passaggio al plugin è stato mantenuto.", - "processFailureWithError": "Il plugin PostgreSQL non si è avviato: {{error}}. Non riguarda specificamente {{name}} — non è stata tentata alcuna connessione.", - "processFailure": "Il plugin PostgreSQL non si è avviato. Non riguarda specificamente {{name}} — non è stata tentata alcuna connessione.", - "failed": "Impossibile passare {{name}} al plugin: {{error}}", - "undo": "Annulla", - "undoFailed": "Impossibile riportare {{name}} al driver integrato: {{error}}", - "reportIssue": "Segnala un problema" - }, - "checklist": { - "title": "Rivedi connessioni", - "subtitle_one": "{{count}} connessione ancora sul driver integrato", - "subtitle_other": "{{count}} connessioni ancora sul driver integrato", - "migrateSelected_one": "Migra {{count}} selezionata", - "migrateSelected_other": "Migra {{count}} selezionate", - "reportThisGap": "Segnala questo problema", - "alreadyReported": "Segnalato", - "testing": "Test della connessione…", - "uriWarning": "La stringa di connessione salvata nel portachiavi non verrà trasferita — dovrai reinserirla dopo la migrazione.", - "noGaps": "Nessuna connessione da rivedere.", - "close": "Chiudi", - "migratingNotice": "La migrazione continua anche se chiudi questa finestra.", - "gap": { - "ssl": "Usa SSL/TLS, non ancora supportato dal plugin", - "connection_uri": "Usa una stringa di connessione, non ancora supportata dal plugin" - } - } - }, "connectionCatalogue": { "searchPlaceholder": "Cerca database…", "clearSearch": "Cancella ricerca", @@ -3698,10 +3646,107 @@ "themePackages": { "import": "Importa tema", "registryMismatch": "Il pacchetto appartiene a un altro registro. Modifica esplicitamente il registro configurato prima di aggiornarlo.", - "importedTheme": "Tema importato", "manage": "Gestisci temi", "importJSON": "Importa JSON Tabularis", "importVSCode": "Importa da VS Code", "edit": "Modifica tema personale", "localPackage": "Pacchetto locale", "installTitle": "Installa pacchetto tema", "installSubtitle": "Tema dichiarativo dal registro configurato. Nessun codice viene eseguito.", "discover": "Sfoglia i temi in Plugin", "refresh": "Aggiorna elenco", "preview": "Anteprima", "apply": "Applica", "confirm": "Conferma", "duplicate": "Duplica come personale", "exportJSON": "Esporta JSON autonomo", "exportPackage": "Esporta pacchetto autore", "remove": "Elimina", "update": "Aggiorna pacchetto", "disable": "Disabilita pacchetto", "enable": "Abilita pacchetto", "removePackage": "Disinstalla pacchetto", "disabled": "Disabilitato", "file": "File del tema", "name": "Nome del tema", "mode": "Modalità / base", "detectMode": "Rileva (scegli se ambiguo)", "source": "JSON del tema", "search": "Cerca temi", "loading": "Caricamento…", "noThemes": "Nessun tema disponibile nel registro.", "details": "Dettagli / installazione", "readme": "README / schermate", "version": "Versione del pacchetto", "latest": "Ultima versione", "install": "Installa / sostituisci pacchetto", "chooseArchive": "Scegli archivio ZIP", "screenshots": "Schermate (apertura esterna)", "externalMedia": "Immagini e altri contenuti remoti non vengono caricati automaticamente. I collegamenti si aprono nel browser.", "snapshotEditor": "JSON esatto dell’editor", "snapshotEditorHelp": "Questo snapshot indipendente controlla i colori SQL al posto dell’alias legacy. Le modifiche vengono mostrate in anteprima e salvate verificando la revisione originale.", "recover": "Recupera installazioni interrotte", "recoveryExplanation": "Controlla e recupera esplicitamente le operazioni sui temi rimaste incomplete. Può ripristinare installazioni interrotte, senza selezionare temi né cambiare le preferenze salvate.", "recoveryDone": "Controlli di recupero completati. Esamina gli eventuali problemi riportati sotto.", "catalogIssues": "Diagnostica del catalogo", "fileTooLarge": "Il file supera il limite di importazione.", "previewHint": "L'anteprima è temporanea. Annulla ripristina il tema salvato; Applica salva la scelta.", "previewReady": "Anteprima attiva. Controlla applicazione ed editor prima di confermare.", "licenseNotice": "Importare o esportare non concede diritti di redistribuzione. Conserva l'attribuzione e verifica la licenza prima di pubblicare.", "acknowledge": "Comprendo e accetto i limiti di conversione elencati.", "applyAfterSave": "Applica dopo il salvataggio", "savedNotApplied": "Tema salvato, ma selezione fallita. Non importarlo di nuovo: seleziona il tema salvato.", "installHint": "L'installazione sostituisce l'intero pacchetto senza scegliere una variante. Anteprima, importazione locale e selezione non contano come download.", "installedHint": "Pacchetto installato. Chiudi e scegli esplicitamente una variante in Aspetto.", "committedRefreshFailed": "Operazione completata, ma aggiornamento del catalogo fallito. Aggiorna l'elenco prima di riprovare.", "missing": "Selezione salvata non disponibile: {{id}}. Uso un tema offline senza modificare la preferenza.", "downloads": "Download: {{count}}", "downloadsUnavailable": "Conteggio download non disponibile", "installedVersion": "Installata: {{version}}", "minimumVersion": "Richiede Tabularis {{version}} o successivo", "incompatible": "Versione incompatibile o priva di un unico archivio universale.", "packageWarning": "L'operazione riguarda tutte le varianti. Le selezioni salvate vengono conservate e ripristinate quando nuovamente disponibili.", "deleteWarning": "Eliminare il tema personale? Le sue selezioni salvate useranno i temi predefiniti.", "duplicateHint": "Crea una copia personale indipendente e modificabile, senza attivarla.", "exportError": "Esportazione del pacchetto fallita; resta disponibile il JSON autonomo.", "runtimeWarning": "Inserisci la prima versione realmente compatibile. Il numero di una build di sviluppo non garantisce la compatibilità dei vecchi client.", "packageName": "Identificatore del pacchetto (minuscolo)", "minimumRuntime": "Versione minima di Tabularis", "license": "Testo di licenza e attribuzione", "rightsAcknowledged": "Ho verificato i diritti di redistribuzione e l'attribuzione.", - "groups": { "builtin": "Integrati · offline", "installed": "Pacchetti installati", "personal": "Temi personali" }, "modes": { "light": "Chiaro", "dark": "Scuro", "high-contrast": "Alto contrasto" }, - "importErrors": { "unrecognized": "Tema VS Code non riconosciuto.", "modeRequired": "Scegli una modalità e ripeti l'anteprima.", "includeOnly": "I temi con soli riferimenti include non sono importabili. Fornisci i colori effettivi.", "noSupportedData": "Nessun colore o regola SQL supportati.", "invalidColor": "Un colore supportato ha un valore non valido.", "invalidRules": "Regole dei token non valide o eccessive." }, - "diagnostics": { "unsupportedKey": "Campo non supportato", "unsupportedColor": "Colore non supportato", "unsupportedScope": "Ambito non supportato", "scopeApproximation": "Mappatura SQL approssimata", "unsupportedStyle": "Stile non supportato", "ignoredInclude": "Include non caricato", "ignoredSemanticTokens": "Token semantici ignorati", "unsupportedReference": "Riferimento esterno non caricato", "unsupportedSetting": "Impostazione non supportata", "tokenAlphaFlattened": "Opacità dei token calcolata sullo sfondo di base", "modeApproximation": "Modalità sostituita o approssimata", "diagnosticsTruncated": "Ulteriori diagnostiche omesse" } + "importedTheme": "Tema importato", + "manage": "Gestisci temi", + "importJSON": "Importa JSON Tabularis", + "importVSCode": "Importa da VS Code", + "edit": "Modifica tema personale", + "localPackage": "Pacchetto locale", + "installTitle": "Installa pacchetto tema", + "installSubtitle": "Tema dichiarativo dal registro configurato. Nessun codice viene eseguito.", + "discover": "Sfoglia i temi in Plugin", + "refresh": "Aggiorna elenco", + "preview": "Anteprima", + "apply": "Applica", + "confirm": "Conferma", + "duplicate": "Duplica come personale", + "exportJSON": "Esporta JSON autonomo", + "exportPackage": "Esporta pacchetto autore", + "remove": "Elimina", + "update": "Aggiorna pacchetto", + "disable": "Disabilita pacchetto", + "enable": "Abilita pacchetto", + "removePackage": "Disinstalla pacchetto", + "disabled": "Disabilitato", + "file": "File del tema", + "name": "Nome del tema", + "mode": "Modalità / base", + "detectMode": "Rileva (scegli se ambiguo)", + "source": "JSON del tema", + "search": "Cerca temi", + "loading": "Caricamento…", + "noThemes": "Nessun tema disponibile nel registro.", + "details": "Dettagli / installazione", + "readme": "README / schermate", + "version": "Versione del pacchetto", + "latest": "Ultima versione", + "install": "Installa / sostituisci pacchetto", + "chooseArchive": "Scegli archivio ZIP", + "screenshots": "Schermate (apertura esterna)", + "externalMedia": "Immagini e altri contenuti remoti non vengono caricati automaticamente. I collegamenti si aprono nel browser.", + "snapshotEditor": "JSON esatto dell’editor", + "snapshotEditorHelp": "Questo snapshot indipendente controlla i colori SQL al posto dell’alias legacy. Le modifiche vengono mostrate in anteprima e salvate verificando la revisione originale.", + "recover": "Recupera installazioni interrotte", + "recoveryExplanation": "Controlla e recupera esplicitamente le operazioni sui temi rimaste incomplete. Può ripristinare installazioni interrotte, senza selezionare temi né cambiare le preferenze salvate.", + "recoveryDone": "Controlli di recupero completati. Esamina gli eventuali problemi riportati sotto.", + "catalogIssues": "Diagnostica del catalogo", + "fileTooLarge": "Il file supera il limite di importazione.", + "previewHint": "L'anteprima è temporanea. Annulla ripristina il tema salvato; Applica salva la scelta.", + "previewReady": "Anteprima attiva. Controlla applicazione ed editor prima di confermare.", + "licenseNotice": "Importare o esportare non concede diritti di redistribuzione. Conserva l'attribuzione e verifica la licenza prima di pubblicare.", + "acknowledge": "Comprendo e accetto i limiti di conversione elencati.", + "applyAfterSave": "Applica dopo il salvataggio", + "savedNotApplied": "Tema salvato, ma selezione fallita. Non importarlo di nuovo: seleziona il tema salvato.", + "installHint": "L'installazione sostituisce l'intero pacchetto senza scegliere una variante. Anteprima, importazione locale e selezione non contano come download.", + "installedHint": "Pacchetto installato. Chiudi e scegli esplicitamente una variante in Aspetto.", + "committedRefreshFailed": "Operazione completata, ma aggiornamento del catalogo fallito. Aggiorna l'elenco prima di riprovare.", + "missing": "Selezione salvata non disponibile: {{id}}. Uso un tema offline senza modificare la preferenza.", + "downloads": "Download: {{count}}", + "downloadsUnavailable": "Conteggio download non disponibile", + "installedVersion": "Installata: {{version}}", + "minimumVersion": "Richiede Tabularis {{version}} o successivo", + "incompatible": "Versione incompatibile o priva di un unico archivio universale.", + "packageWarning": "L'operazione riguarda tutte le varianti. Le selezioni salvate vengono conservate e ripristinate quando nuovamente disponibili.", + "deleteWarning": "Eliminare il tema personale? Le sue selezioni salvate useranno i temi predefiniti.", + "duplicateHint": "Crea una copia personale indipendente e modificabile, senza attivarla.", + "exportError": "Esportazione del pacchetto fallita; resta disponibile il JSON autonomo.", + "runtimeWarning": "Inserisci la prima versione realmente compatibile. Il numero di una build di sviluppo non garantisce la compatibilità dei vecchi client.", + "packageName": "Identificatore del pacchetto (minuscolo)", + "minimumRuntime": "Versione minima di Tabularis", + "license": "Testo di licenza e attribuzione", + "rightsAcknowledged": "Ho verificato i diritti di redistribuzione e l'attribuzione.", + "groups": { + "builtin": "Integrati · offline", + "installed": "Pacchetti installati", + "personal": "Temi personali" + }, + "modes": { + "light": "Chiaro", + "dark": "Scuro", + "high-contrast": "Alto contrasto" + }, + "importErrors": { + "unrecognized": "Tema VS Code non riconosciuto.", + "modeRequired": "Scegli una modalità e ripeti l'anteprima.", + "includeOnly": "I temi con soli riferimenti include non sono importabili. Fornisci i colori effettivi.", + "noSupportedData": "Nessun colore o regola SQL supportati.", + "invalidColor": "Un colore supportato ha un valore non valido.", + "invalidRules": "Regole dei token non valide o eccessive." + }, + "diagnostics": { + "unsupportedKey": "Campo non supportato", + "unsupportedColor": "Colore non supportato", + "unsupportedScope": "Ambito non supportato", + "scopeApproximation": "Mappatura SQL approssimata", + "unsupportedStyle": "Stile non supportato", + "ignoredInclude": "Include non caricato", + "ignoredSemanticTokens": "Token semantici ignorati", + "unsupportedReference": "Riferimento esterno non caricato", + "unsupportedSetting": "Impostazione non supportata", + "tokenAlphaFlattened": "Opacità dei token calcolata sullo sfondo di base", + "modeApproximation": "Modalità sostituita o approssimata", + "diagnosticsTruncated": "Ulteriori diagnostiche omesse" + } }, "linkedGit": { "title": "Esamina le modifiche Git", diff --git a/packages/web-ui/src/i18n/locales/ja.json b/packages/web-ui/src/i18n/locales/ja.json index 14f5f07d4..beb124531 100644 --- a/packages/web-ui/src/i18n/locales/ja.json +++ b/packages/web-ui/src/i18n/locales/ja.json @@ -1231,12 +1231,6 @@ "label": "タイムゾーン", "description": "接続後に MySQL に送信するセッションタイムゾーンです。" } - }, - "postgres": { - "poolMaxSize": { - "label": "プール最大サイズ", - "description": "プールに保持する PostgreSQL 接続の最大数です。" - } } } }, @@ -3529,55 +3523,6 @@ "updateConfirm": "v{{version}} に更新", "alreadyInstalled": "バージョン {{version}} は既にインストールされています。" }, - "migration": { - "banner": { - "nudge": "新しい PostgreSQL プラグインをお試しください —組み込みの PostgreSQL ドライバーは廃止予定です。プラグインは同じ機能を持ち、より早く更新されます。", - "nudgeWithDate": "新しい PostgreSQL プラグインをお試しください —組み込みの PostgreSQL ドライバーは廃止予定です({{date}}を予定)。プラグインは同じ機能を持ち、より早く更新されます。", - "offline": "PostgreSQL プラグインをダウンロードできませんでした —次回起動時に再試行します。続く場合は接続やネットワークを確認してください。", - "reviewConnections": "接続を確認" - }, - "switchToPlugin": "プラグインに切り替え", - "switchToBuiltin": "組み込みドライバーに戻す", - "confirm": { - "title": "プラグインに切り替えますか?", - "message": "{{name}} を PostgreSQL プラグインに切り替えますか?現在接続中の場合は切断され、プラグインで再接続されます。", - "uriMessage": "{{name}} を PostgreSQL プラグインに切り替えますか?キーチェーンに保存されている接続文字列は引き継がれません —再接続するには再入力が必要です。", - "confirmLabel": "切り替え", - "confirmLabelUri": "切り替えて後で再入力", - "undoTitle": "組み込みドライバーに戻しますか?", - "undoMessage": "{{name}} を組み込みの PostgreSQL ドライバーに戻しますか?現在接続中の場合は切断され、組み込みドライバーで再接続されます。", - "undoConfirmLabel": "戻す" - }, - "toast": { - "success": "{{name}} を PostgreSQL プラグインに切り替えました。", - "connectionFailure": "プラグインを使用して {{name}} に接続できませんでした: {{error}}", - "connectionFailurePreexisting": "{{name}} はどちらのドライバでも接続できませんでした: {{error}}。プラグインの問題ではありません — プラグインへの切り替えはそのまま維持されます。", - "processFailureWithError": "PostgreSQL プラグインが起動しませんでした: {{error}}。これは {{name}} 固有の問題ではありません —接続は試行されませんでした。", - "processFailure": "PostgreSQL プラグインが起動しませんでした。これは {{name}} 固有の問題ではありません —接続は試行されませんでした。", - "failed": "{{name}} をプラグインに切り替えられませんでした: {{error}}", - "undo": "元に戻す", - "undoFailed": "{{name}} を組み込みドライバーに戻せませんでした: {{error}}", - "reportIssue": "問題を報告" - }, - "checklist": { - "title": "接続を確認", - "subtitle_one": "{{count}} 件の接続がまだ組み込みドライバーを使用しています", - "subtitle_other": "{{count}} 件の接続がまだ組み込みドライバーを使用しています", - "migrateSelected_one": "選択した {{count}} 件を移行", - "migrateSelected_other": "選択した {{count}} 件を移行", - "reportThisGap": "この問題を報告", - "alreadyReported": "報告済み", - "testing": "接続をテスト中…", - "uriWarning": "キーチェーンに保存されている接続文字列は引き継がれません —移行後に再入力が必要です。", - "noGaps": "確認する接続はありません。", - "close": "閉じる", - "migratingNotice": "このウィンドウを閉じても、移行はバックグラウンドで続行されます。", - "gap": { - "ssl": "SSL/TLS を使用しています。プラグインはまだ未対応です", - "connection_uri": "接続文字列を使用しています。プラグインはまだ未対応です" - } - } - }, "connectionCatalogue": { "searchPlaceholder": "データベースを検索…", "clearSearch": "検索をクリア", diff --git a/packages/web-ui/src/i18n/locales/ko.json b/packages/web-ui/src/i18n/locales/ko.json index e38dfea31..38aae07c8 100644 --- a/packages/web-ui/src/i18n/locales/ko.json +++ b/packages/web-ui/src/i18n/locales/ko.json @@ -1184,12 +1184,6 @@ "label": "시간대", "description": "연결 후 MySQL로 전송되는 세션 시간대입니다." } - }, - "postgres": { - "poolMaxSize": { - "label": "풀 최대 크기", - "description": "풀에 유지할 PostgreSQL 연결의 최대 개수입니다." - } } } }, @@ -3557,55 +3551,6 @@ "title": "연결 테스트 로그", "showLog": "로그 보기" }, - "migration": { - "banner": { - "nudge": "새 PostgreSQL 플러그인을 사용해 보세요 —내장 PostgreSQL 드라이버가 폐지 예정입니다. 플러그인은 동일한 기능을 가지며 더 빠르게 업데이트됩니다.", - "nudgeWithDate": "새 PostgreSQL 플러그인을 사용해 보세요 —내장 PostgreSQL 드라이버가 폐지 예정입니다({{date}} 잠정). 플러그인은 동일한 기능을 가지며 더 빠르게 업데이트됩니다.", - "offline": "PostgreSQL 플러그인을 다운로드할 수 없습니다 —다음 실행 시 다시 시도합니다. 계속되면 연결이나 네트워크를 확인하세요.", - "reviewConnections": "연결 검토" - }, - "switchToPlugin": "플러그인으로 전환", - "switchToBuiltin": "내장 드라이버로 되돌리기", - "confirm": { - "title": "플러그인으로 전환하시겠습니까?", - "message": "{{name}}을(를) PostgreSQL 플러그인으로 전환하시겠습니까? 현재 연결되어 있다면 연결이 끊기고 플러그인으로 다시 열립니다.", - "uriMessage": "{{name}}을(를) PostgreSQL 플러그인으로 전환하시겠습니까? 키체인에 저장된 연결 문자열은 유지되지 않습니다 —다시 연결하려면 재입력해야 합니다.", - "confirmLabel": "전환", - "confirmLabelUri": "전환 후 나중에 재입력", - "undoTitle": "내장 드라이버로 되돌리시겠습니까?", - "undoMessage": "{{name}}을(를) 내장 PostgreSQL 드라이버로 되돌리시겠습니까? 현재 연결되어 있다면 연결이 끊기고 내장 드라이버로 다시 열립니다.", - "undoConfirmLabel": "되돌리기" - }, - "toast": { - "success": "{{name}}을(를) PostgreSQL 플러그인으로 전환했습니다.", - "connectionFailure": "플러그인을 사용하여 {{name}}에 연결할 수 없습니다: {{error}}", - "connectionFailurePreexisting": "{{name}}은(는) 두 드라이버 모두로 연결할 수 없습니다: {{error}}. 플러그인 문제가 아닙니다 — 플러그인으로의 전환은 유지됩니다.", - "processFailureWithError": "PostgreSQL 플러그인이 시작되지 않았습니다: {{error}}. {{name}}에 국한된 문제가 아닙니다 —연결이 시도되지 않았습니다.", - "processFailure": "PostgreSQL 플러그인이 시작되지 않았습니다. {{name}}에 국한된 문제가 아닙니다 —연결이 시도되지 않았습니다.", - "failed": "{{name}}을(를) 플러그인으로 전환할 수 없습니다: {{error}}", - "undo": "실행 취소", - "undoFailed": "{{name}}을(를) 내장 드라이버로 다시 전환할 수 없습니다: {{error}}", - "reportIssue": "문제 신고" - }, - "checklist": { - "title": "연결 검토", - "subtitle_one": "{{count}}개 연결이 아직 내장 드라이버를 사용 중", - "subtitle_other": "{{count}}개 연결이 아직 내장 드라이버를 사용 중", - "migrateSelected_one": "선택한 {{count}}개 마이그레이션", - "migrateSelected_other": "선택한 {{count}}개 마이그레이션", - "reportThisGap": "이 문제 신고", - "alreadyReported": "신고됨", - "testing": "연결 테스트 중…", - "uriWarning": "키체인에 저장된 연결 문자열은 유지되지 않습니다 —마이그레이션 후 다시 입력해야 합니다.", - "noGaps": "검토할 연결이 없습니다.", - "close": "닫기", - "migratingNotice": "이 창을 닫아도 마이그레이션은 계속 진행됩니다.", - "gap": { - "ssl": "SSL/TLS를 사용하며, 플러그인에서 아직 지원되지 않음", - "connection_uri": "연결 문자열을 사용하며, 플러그인에서 아직 지원되지 않음" - } - } - }, "themePackages": { "import": "테마 가져오기", "registryMismatch": "이 패키지는 다른 레지스트리에 속합니다. 업데이트하기 전에 설정된 레지스트리를 명시적으로 변경하세요.", diff --git a/packages/web-ui/src/i18n/locales/pt-BR.json b/packages/web-ui/src/i18n/locales/pt-BR.json index 20a71d3bd..bef1009ae 100644 --- a/packages/web-ui/src/i18n/locales/pt-BR.json +++ b/packages/web-ui/src/i18n/locales/pt-BR.json @@ -1275,12 +1275,6 @@ "label": "Fuso Horário", "description": "Fuso horário de sessão enviado ao MySQL após a conexão." } - }, - "postgres": { - "poolMaxSize": { - "label": "Tamanho Máximo do Pool", - "description": "Número máximo de conexões PostgreSQL mantidas no pool." - } } } }, @@ -3618,55 +3612,6 @@ "updateConfirm": "Atualizar para v{{version}}", "alreadyInstalled": "A versão {{version}} já está instalada." }, - "migration": { - "banner": { - "nudge": "Experimente o novo plugin do PostgreSQL — o driver integrado do PostgreSQL está sendo descontinuado. O plugin tem os mesmos recursos e recebe atualizações mais rápido.", - "nudgeWithDate": "Experimente o novo plugin do PostgreSQL — o driver integrado do PostgreSQL está sendo descontinuado (provisoriamente em {{date}}). O plugin tem os mesmos recursos e recebe atualizações mais rápido.", - "offline": "O plugin do PostgreSQL não pôde ser baixado — tentaremos novamente no próximo início. Verifique sua conexão ou rede se isso persistir.", - "reviewConnections": "Revisar conexões" - }, - "switchToPlugin": "Mudar para o plugin", - "switchToBuiltin": "Voltar para o integrado", - "confirm": { - "title": "Mudar para o plugin?", - "message": "Mudar {{name}} para o plugin do PostgreSQL? Se estiver conectado atualmente, será desconectado e reaberto usando o plugin.", - "uriMessage": "Mudar {{name}} para o plugin do PostgreSQL? A string de conexão armazenada no chaveiro não será transferida — você precisará digitá-la novamente para reconectar.", - "confirmLabel": "Mudar", - "confirmLabelUri": "Mudar e digitar novamente depois", - "undoTitle": "Voltar para o driver integrado?", - "undoMessage": "Voltar {{name}} para o driver integrado do PostgreSQL? Se estiver conectado atualmente, será desconectado e reaberto usando o driver integrado.", - "undoConfirmLabel": "Voltar" - }, - "toast": { - "success": "{{name}} foi alterado para o plugin do PostgreSQL.", - "connectionFailure": "Não foi possível conectar a {{name}} usando o plugin: {{error}}", - "connectionFailurePreexisting": "Não foi possível conectar a {{name}} com nenhum dos drivers: {{error}}. Não é um problema do plugin — a troca para o plugin foi mantida.", - "processFailureWithError": "O plugin do PostgreSQL não iniciou: {{error}}. Isso não é específico de {{name}} — nenhuma conexão foi tentada.", - "processFailure": "O plugin do PostgreSQL não iniciou. Isso não é específico de {{name}} — nenhuma conexão foi tentada.", - "failed": "Não foi possível alterar {{name}} para o plugin: {{error}}", - "undo": "Desfazer", - "undoFailed": "Não foi possível voltar {{name}} para o driver integrado: {{error}}", - "reportIssue": "Reportar um problema" - }, - "checklist": { - "title": "Revisar conexões", - "subtitle_one": "{{count}} conexão ainda no driver integrado", - "subtitle_other": "{{count}} conexões ainda no driver integrado", - "migrateSelected_one": "Migrar {{count}} selecionada", - "migrateSelected_other": "Migrar {{count}} selecionadas", - "reportThisGap": "Reportar este problema", - "alreadyReported": "Reportado", - "testing": "Testando conexão…", - "uriWarning": "A string de conexão armazenada no chaveiro não será transferida — você precisará digitá-la novamente após a migração.", - "noGaps": "Nenhuma conexão para revisar.", - "close": "Fechar", - "migratingNotice": "A migração continua mesmo se você fechar esta janela.", - "gap": { - "ssl": "Usa SSL/TLS, ainda não suportado pelo plugin", - "connection_uri": "Usa uma string de conexão, ainda não suportada pelo plugin" - } - } - }, "connectionCatalogue": { "searchPlaceholder": "Buscar bancos de dados…", "clearSearch": "Limpar busca", diff --git a/packages/web-ui/src/i18n/locales/ru.json b/packages/web-ui/src/i18n/locales/ru.json index 6d2ab81be..4569e4b53 100644 --- a/packages/web-ui/src/i18n/locales/ru.json +++ b/packages/web-ui/src/i18n/locales/ru.json @@ -1214,12 +1214,6 @@ "label": "Часовой пояс", "description": "Часовой пояс сессии, отправляемый в MySQL после подключения." } - }, - "postgres": { - "poolMaxSize": { - "label": "Максимальный размер пула", - "description": "Максимальное количество подключений PostgreSQL, сохраняемых в пуле." - } } } }, @@ -3657,55 +3651,6 @@ "title": "Журнал теста подключения", "showLog": "Показать журнал" }, - "migration": { - "banner": { - "nudge": "Попробуйте новый плагин PostgreSQL — встроенный драйвер PostgreSQL выводится из эксплуатации. Плагин имеет те же функции и обновляется быстрее.", - "nudgeWithDate": "Попробуйте новый плагин PostgreSQL — встроенный драйвер PostgreSQL выводится из эксплуатации (предварительно {{date}}). Плагин имеет те же функции и обновляется быстрее.", - "offline": "Не удалось загрузить плагин PostgreSQL — повторим при следующем запуске. Проверьте подключение или сеть, если это повторяется.", - "reviewConnections": "Просмотреть подключения" - }, - "switchToPlugin": "Перейти на плагин", - "switchToBuiltin": "Вернуться к встроенному", - "confirm": { - "title": "Переключиться на плагин?", - "message": "Переключить {{name}} на плагин PostgreSQL? Если подключение активно, оно будет закрыто и переоткрыто через плагин.", - "uriMessage": "Переключить {{name}} на плагин PostgreSQL? Строка подключения, сохранённая в keychain, не будет перенесена — потребуется ввести её заново для повторного подключения.", - "confirmLabel": "Переключить", - "confirmLabelUri": "Переключить и ввести позже", - "undoTitle": "Вернуться к встроенному драйверу?", - "undoMessage": "Вернуть {{name}} к встроенному драйверу PostgreSQL? Если подключение активно, оно будет закрыто и переоткрыто через встроенный драйвер.", - "undoConfirmLabel": "Вернуть" - }, - "toast": { - "success": "{{name}} переключено на плагин PostgreSQL.", - "connectionFailure": "Не удалось подключиться к {{name}} через плагин: {{error}}", - "connectionFailurePreexisting": "Не удалось подключиться к {{name}} ни через один из драйверов: {{error}}. Проблема не в плагине — переключение на плагин сохранено.", - "processFailureWithError": "Плагин PostgreSQL не запустился: {{error}}. Это не связано конкретно с {{name}} — подключение не выполнялось.", - "processFailure": "Плагин PostgreSQL не запустился. Это не связано конкретно с {{name}} — подключение не выполнялось.", - "failed": "Не удалось переключить {{name}} на плагин: {{error}}", - "undo": "Отменить", - "undoFailed": "Не удалось переключить {{name}} обратно на встроенный драйвер: {{error}}", - "reportIssue": "Сообщить о проблеме" - }, - "checklist": { - "title": "Просмотреть подключения", - "subtitle_one": "{{count}} подключение всё ещё на встроенном драйвере", - "subtitle_other": "{{count}} подключений всё ещё на встроенном драйвере", - "migrateSelected_one": "Перенести {{count}} выбранное", - "migrateSelected_other": "Перенести {{count}} выбранных", - "reportThisGap": "Сообщить об этой проблеме", - "alreadyReported": "Сообщено", - "testing": "Проверка подключения…", - "uriWarning": "Строка подключения, сохранённая в keychain, не будет перенесена — потребуется ввести её заново после переноса.", - "noGaps": "Нет подключений для просмотра.", - "close": "Закрыть", - "migratingNotice": "Миграция продолжается, даже если вы закроете это окно.", - "gap": { - "ssl": "Использует SSL/TLS, пока не поддерживается плагином", - "connection_uri": "Использует строку подключения, пока не поддерживается плагином" - } - } - }, "themePackages": { "import": "Импортировать тему", "registryMismatch": "Этот пакет относится к другому реестру. Перед обновлением явно измените настроенный реестр.", diff --git a/packages/web-ui/src/i18n/locales/tl.json b/packages/web-ui/src/i18n/locales/tl.json index 780b81b6e..08445d7ca 100644 --- a/packages/web-ui/src/i18n/locales/tl.json +++ b/packages/web-ui/src/i18n/locales/tl.json @@ -1250,12 +1250,6 @@ "label": "Timezone", "description": "Session timezone na ipinapadala sa MySQL pagkatapos kumonekta." } - }, - "postgres": { - "poolMaxSize": { - "label": "Pool Max Size", - "description": "Maximum na bilang ng PostgreSQL connections na pinapanatili sa pool." - } } } }, @@ -3634,55 +3628,6 @@ "title": "Log ng pagsubok ng koneksyon", "showLog": "Ipakita ang log" }, - "migration": { - "banner": { - "nudge": "Try the new PostgreSQL plugin — the built-in PostgreSQL driver is being retired. The plugin has the same features and gets updates faster.", - "nudgeWithDate": "Try the new PostgreSQL plugin — the built-in PostgreSQL driver is being retired (tentatively {{date}}). The plugin has the same features and gets updates faster.", - "offline": "The PostgreSQL plugin couldn't be downloaded — we'll retry on the next launch. Check your connection or network if this keeps happening.", - "reviewConnections": "Review connections" - }, - "switchToPlugin": "Switch to plugin", - "switchToBuiltin": "Switch back to built-in", - "confirm": { - "title": "Lumipat sa plugin?", - "message": "Lumipat ang {{name}} sa PostgreSQL plugin? Kung kasalukuyang konektado, ito ay magdiskonekta at mabubuksan muli gamit ang plugin.", - "uriMessage": "Lumipat ang {{name}} sa PostgreSQL plugin? Ang connection string na naka-imbak sa keychain ay hindi madadala — kakailanganin mong ilagay ulit ito para makakonekta.", - "confirmLabel": "Lumipat", - "confirmLabelUri": "Lumipat at ilagay ulit mamaya", - "undoTitle": "Bumalik sa built-in driver?", - "undoMessage": "Ibalik ang {{name}} sa built-in na PostgreSQL driver? Kung kasalukuyang konektado, ito ay magdiskonekta at mabubuksan muli gamit ang built-in driver.", - "undoConfirmLabel": "Ibalik" - }, - "toast": { - "success": "Na-switch ang {{name}} sa PostgreSQL plugin.", - "connectionFailure": "Hindi makakonekta sa {{name}} gamit ang plugin: {{error}}", - "connectionFailurePreexisting": "Hindi makakonekta sa {{name}} gamit ang alinman sa dalawang driver: {{error}}. Hindi ito problema ng plugin — nanatili ang paglipat sa plugin.", - "processFailureWithError": "Hindi nag-start ang PostgreSQL plugin: {{error}}. Hindi ito partikular sa {{name}} — walang sinubukang koneksyon.", - "processFailure": "Hindi nag-start ang PostgreSQL plugin. Hindi ito partikular sa {{name}} — walang sinubukang koneksyon.", - "failed": "Hindi ma-switch ang {{name}} sa plugin: {{error}}", - "undo": "I-undo", - "undoFailed": "Hindi maibalik ang {{name}} sa built-in driver: {{error}}", - "reportIssue": "I-report ang isyu" - }, - "checklist": { - "title": "Suriin ang mga koneksyon", - "subtitle_one": "{{count}} koneksyon na nasa built-in driver pa rin", - "subtitle_other": "{{count}} koneksyon na nasa built-in driver pa rin", - "migrateSelected_one": "Ilipat ang {{count}} napili", - "migrateSelected_other": "Ilipat ang {{count}} napili", - "reportThisGap": "I-report ang isyung ito", - "alreadyReported": "Na-report", - "testing": "Sinusubukan ang koneksyon…", - "uriWarning": "Ang connection string na naka-imbak sa keychain ay hindi madadala — kakailanganin mong ilagay ulit ito pagkatapos lumipat.", - "noGaps": "Walang koneksyon na susuriin.", - "close": "Isara", - "migratingNotice": "Magpapatuloy ang migration kahit isara mo ang window na ito.", - "gap": { - "ssl": "Gumagamit ng SSL/TLS, hindi pa suportado ng plugin", - "connection_uri": "Gumagamit ng connection string, hindi pa suportado ng plugin" - } - } - }, "themePackages": { "import": "Mag-import ng tema", "registryMismatch": "Ang package na ito ay mula sa ibang registry. Tahasang palitan ang naka-configure na registry bago ito i-update.", diff --git a/packages/web-ui/src/i18n/locales/vi.json b/packages/web-ui/src/i18n/locales/vi.json index 02a875a80..7c9c24cce 100644 --- a/packages/web-ui/src/i18n/locales/vi.json +++ b/packages/web-ui/src/i18n/locales/vi.json @@ -1268,12 +1268,6 @@ "label": "Múi giờ", "description": "Múi giờ của phiên được gửi tới MySQL sau khi kết nối." } - }, - "postgres": { - "poolMaxSize": { - "label": "Kích thước pool tối đa", - "description": "Số kết nối PostgreSQL tối đa được giữ trong pool." - } } } }, @@ -3579,55 +3573,6 @@ "updateConfirm": "Cập nhật lên v{{version}}", "alreadyInstalled": "Phiên bản {{version}} đã được cài." }, - "migration": { - "banner": { - "nudge": "Hãy thử plugin PostgreSQL mới — driver PostgreSQL tích hợp sẵn sắp bị ngừng. Plugin có đầy đủ tính năng tương tự và được cập nhật nhanh hơn.", - "nudgeWithDate": "Hãy thử plugin PostgreSQL mới — driver PostgreSQL tích hợp sẵn sắp bị ngừng (dự kiến {{date}}). Plugin có đầy đủ tính năng tương tự và được cập nhật nhanh hơn.", - "offline": "Không tải được plugin PostgreSQL — sẽ thử lại ở lần khởi động sau. Nếu lỗi này cứ lặp lại, hãy kiểm tra kết nối mạng.", - "reviewConnections": "Xem lại các kết nối" - }, - "switchToPlugin": "Chuyển sang plugin", - "switchToBuiltin": "Quay lại driver tích hợp sẵn", - "confirm": { - "title": "Chuyển sang plugin?", - "message": "Chuyển {{name}} sang plugin PostgreSQL? Nếu kết nối đang mở, nó sẽ bị ngắt và mở lại bằng plugin.", - "uriMessage": "Chuyển {{name}} sang plugin PostgreSQL? Connection string của kết nối này đang lưu trong keychain và sẽ không được chuyển sang plugin — bạn sẽ phải nhập lại để kết nối.", - "confirmLabel": "Chuyển", - "confirmLabelUri": "Chuyển và nhập lại sau", - "undoTitle": "Quay lại driver tích hợp sẵn?", - "undoMessage": "Chuyển {{name}} về driver PostgreSQL tích hợp sẵn? Nếu kết nối đang mở, nó sẽ bị ngắt và mở lại bằng driver tích hợp sẵn.", - "undoConfirmLabel": "Quay lại" - }, - "toast": { - "success": "Đã chuyển {{name}} sang plugin PostgreSQL.", - "connectionFailure": "Không kết nối được tới {{name}} bằng plugin: {{error}}", - "connectionFailurePreexisting": "Không kết nối được tới {{name}} bằng cả hai driver: {{error}}. Đây không phải lỗi của plugin — kết nối vẫn được giữ ở plugin.", - "processFailureWithError": "Plugin PostgreSQL không khởi động được: {{error}}. Lỗi này không riêng gì {{name}} — chưa có kết nối nào được thử.", - "processFailure": "Plugin PostgreSQL không khởi động được. Lỗi này không riêng gì {{name}} — chưa có kết nối nào được thử.", - "failed": "Không chuyển được {{name}} sang plugin: {{error}}", - "undo": "Hoàn tác", - "undoFailed": "Không chuyển được {{name}} về driver tích hợp sẵn: {{error}}", - "reportIssue": "Báo lỗi" - }, - "checklist": { - "title": "Xem lại các kết nối", - "subtitle_one": "{{count}} kết nối vẫn đang dùng driver tích hợp sẵn", - "subtitle_other": "{{count}} kết nối vẫn đang dùng driver tích hợp sẵn", - "migrateSelected_one": "Chuyển {{count}} kết nối đã chọn", - "migrateSelected_other": "Chuyển {{count}} kết nối đã chọn", - "reportThisGap": "Báo thiếu sót này", - "alreadyReported": "Đã báo", - "testing": "Đang kiểm tra kết nối…", - "uriWarning": "Connection string đang lưu trong keychain và sẽ không được chuyển theo — bạn sẽ phải nhập lại sau khi chuyển.", - "noGaps": "Không có kết nối nào cần xem lại.", - "close": "Đóng", - "migratingNotice": "Quá trình chuyển vẫn tiếp tục kể cả khi bạn đóng cửa sổ này.", - "gap": { - "ssl": "Dùng SSL/TLS, plugin chưa hỗ trợ", - "connection_uri": "Dùng connection string, plugin chưa hỗ trợ" - } - } - }, "connectionCatalogue": { "searchPlaceholder": "Tìm cơ sở dữ liệu…", "clearSearch": "Xóa tìm kiếm", diff --git a/packages/web-ui/src/i18n/locales/zh-TW.json b/packages/web-ui/src/i18n/locales/zh-TW.json index 87b901089..5062f065d 100644 --- a/packages/web-ui/src/i18n/locales/zh-TW.json +++ b/packages/web-ui/src/i18n/locales/zh-TW.json @@ -1274,12 +1274,6 @@ "label": "時區", "description": "連線建立後傳送給 MySQL 的工作階段時區。" } - }, - "postgres": { - "poolMaxSize": { - "label": "連線池最大大小", - "description": "連線池中保留的 PostgreSQL 連線最大數量。" - } } } }, @@ -3545,55 +3539,6 @@ "updateConfirm": "更新到 v{{version}}", "alreadyInstalled": "版本 {{version}} 已安裝。" }, - "migration": { - "banner": { - "nudge": "試試新的 PostgreSQL 外掛 —內建 PostgreSQL 驅動程式正在退役。外掛功能相同且更新更快。", - "nudgeWithDate": "試試新的 PostgreSQL 外掛 —內建 PostgreSQL 驅動程式正在退役(暫定 {{date}})。外掛功能相同且更新更快。", - "offline": "PostgreSQL 外掛無法下載 —下次啟動時會重試。如果持續出現,請檢查您的連線或網路。", - "reviewConnections": "檢視連線" - }, - "switchToPlugin": "切換到外掛", - "switchToBuiltin": "切回內建驅動程式", - "confirm": { - "title": "切換到外掛?", - "message": "將 {{name}} 切換到 PostgreSQL 外掛?如果目前已連線,將斷開連線並使用外掛重新開啟。", - "uriMessage": "將 {{name}} 切換到 PostgreSQL 外掛?儲存在鑰匙圈中的連線字串不會被帶過來 —您需要重新輸入才能重新連線。", - "confirmLabel": "切換", - "confirmLabelUri": "切換並稍後重新輸入", - "undoTitle": "切回內建驅動程式?", - "undoMessage": "將 {{name}} 切回內建 PostgreSQL 驅動程式?如果目前已連線,將斷開連線並使用內建驅動程式重新開啟。", - "undoConfirmLabel": "切回" - }, - "toast": { - "success": "已將 {{name}} 切換到 PostgreSQL 外掛。", - "connectionFailure": "無法使用外掛連線到 {{name}}:{{error}}", - "connectionFailurePreexisting": "無法使用任一驅動程式連線到 {{name}}:{{error}}。這不是外掛的問題——切換到外掛的操作已保留。", - "processFailureWithError": "PostgreSQL 外掛未啟動:{{error}}。這與 {{name}} 無關 —未嘗試連線。", - "processFailure": "PostgreSQL 外掛未啟動。這與 {{name}} 無關 —未嘗試連線。", - "failed": "無法將 {{name}} 切換到外掛:{{error}}", - "undo": "復原", - "undoFailed": "無法將 {{name}} 切換回內建驅動程式:{{error}}", - "reportIssue": "報告問題" - }, - "checklist": { - "title": "檢視連線", - "subtitle_one": "還有 {{count}} 個連線使用內建驅動程式", - "subtitle_other": "還有 {{count}} 個連線使用內建驅動程式", - "migrateSelected_one": "遷移已選的 {{count}} 個", - "migrateSelected_other": "遷移已選的 {{count}} 個", - "reportThisGap": "報告此問題", - "alreadyReported": "已報告", - "testing": "正在測試連線…", - "uriWarning": "儲存在鑰匙圈中的連線字串不會被帶過來 —遷移後需要重新輸入。", - "noGaps": "沒有需要檢視的連線。", - "close": "關閉", - "migratingNotice": "即使關閉此視窗,遷移仍會繼續。", - "gap": { - "ssl": "使用 SSL/TLS,外掛尚不支援", - "connection_uri": "使用連線字串,外掛尚不支援" - } - } - }, "connectionCatalogue": { "searchPlaceholder": "搜尋資料庫…", "clearSearch": "清除搜尋", diff --git a/packages/web-ui/src/i18n/locales/zh.json b/packages/web-ui/src/i18n/locales/zh.json index 258de07de..c47a1783a 100644 --- a/packages/web-ui/src/i18n/locales/zh.json +++ b/packages/web-ui/src/i18n/locales/zh.json @@ -117,7 +117,11 @@ "development": "开发", "staging": "预发布", "production": "生产", - "short": { "development": "DEV", "staging": "STAGING", "production": "PROD" }, + "short": { + "development": "DEV", + "staging": "STAGING", + "production": "PROD" + }, "banner": "生产 — {{name}}", "warnTitle": "生产数据库", "warnMessage": "您即将修改“{{name}}”上的生产数据。确定要继续吗?", @@ -1170,12 +1174,6 @@ "label": "时区", "description": "连接建立后发送给 MySQL 的会话时区。" } - }, - "postgres": { - "poolMaxSize": { - "label": "连接池最大大小", - "description": "连接池中保留的 PostgreSQL 连接最大数量。" - } } } }, @@ -1381,7 +1379,7 @@ "notifyLongQueriesThreshold": "通知阈值", "notifyLongQueriesThresholdDesc": "仅通知运行时间不短于此值的查询。" }, - "triggers":{ + "triggers": { "nativeSqlHelp": "请输入符合数据库 SQL 方言的完整触发器语句。保存现有触发器时不会先将其删除。", "originalRestored": "已恢复原始触发器。", "restoreFailed": "恢复原始触发器也失败了:", @@ -2150,7 +2148,7 @@ "estRows": "预估行数", "actualRows": "实际行数", "cost": "成本", - "time": "时间", + "time": "耗时", "loops": "循环", "filter": "过滤条件", "indexCondition": "索引条件", @@ -2236,7 +2234,6 @@ "analyzeMismatchTooltip": "其中一个执行计划具有实际执行指标(EXPLAIN ANALYZE),而另一个仅有预估值", "pinSnapshot": "固定", "unpinSnapshot": "取消固定", - "time": "耗时", "formatText": "文本", "aiAnalysis": "AI 分析", "aiAnalysisTitle": "AI 执行计划分析", @@ -3442,55 +3439,6 @@ "updateConfirm": "更新到 v{{version}}", "alreadyInstalled": "版本 {{version}} 已安装。" }, - "migration": { - "banner": { - "nudge": "试试新的 PostgreSQL 插件 —内置 PostgreSQL 驱动正在退役。插件功能相同且更新更快。", - "nudgeWithDate": "试试新的 PostgreSQL 插件 —内置 PostgreSQL 驱动正在退役(暂定 {{date}})。插件功能相同且更新更快。", - "offline": "PostgreSQL 插件无法下载 —下次启动时会重试。如果持续出现,请检查您的连接或网络。", - "reviewConnections": "查看连接" - }, - "switchToPlugin": "切换到插件", - "switchToBuiltin": "切回内置驱动", - "confirm": { - "title": "切换到插件?", - "message": "将 {{name}} 切换到 PostgreSQL 插件?如果当前已连接,将断开连接并使用插件重新打开。", - "uriMessage": "将 {{name}} 切换到 PostgreSQL 插件?存储在密钥链中的连接字符串不会被带过来 —您需要重新输入才能重新连接。", - "confirmLabel": "切换", - "confirmLabelUri": "切换并稍后重新输入", - "undoTitle": "切回内置驱动?", - "undoMessage": "将 {{name}} 切回内置 PostgreSQL 驱动?如果当前已连接,将断开连接并使用内置驱动重新打开。", - "undoConfirmLabel": "切回" - }, - "toast": { - "success": "已将 {{name}} 切换到 PostgreSQL 插件。", - "connectionFailure": "无法使用插件连接到 {{name}}:{{error}}", - "connectionFailurePreexisting": "无法使用任一驱动程序连接到 {{name}}:{{error}}。这不是插件的问题——切换到插件的操作已保留。", - "processFailureWithError": "PostgreSQL 插件未启动:{{error}}。这与 {{name}} 无关 —未尝试连接。", - "processFailure": "PostgreSQL 插件未启动。这与 {{name}} 无关 —未尝试连接。", - "failed": "无法将 {{name}} 切换到插件:{{error}}", - "undo": "撤销", - "undoFailed": "无法将 {{name}} 切换回内置驱动程序:{{error}}", - "reportIssue": "报告问题" - }, - "checklist": { - "title": "查看连接", - "subtitle_one": "还有 {{count}} 个连接使用内置驱动", - "subtitle_other": "还有 {{count}} 个连接使用内置驱动", - "migrateSelected_one": "迁移已选的 {{count}} 个", - "migrateSelected_other": "迁移已选的 {{count}} 个", - "reportThisGap": "报告此问题", - "alreadyReported": "已报告", - "testing": "正在测试连接…", - "uriWarning": "存储在密钥链中的连接字符串不会被带过来 —迁移后需要重新输入。", - "noGaps": "没有需要查看的连接。", - "close": "关闭", - "migratingNotice": "即使关闭此窗口,迁移仍会继续。", - "gap": { - "ssl": "使用 SSL/TLS,插件尚不支持", - "connection_uri": "使用连接字符串,插件尚不支持" - } - } - }, "connectionCatalogue": { "searchPlaceholder": "搜索数据库…", "clearSearch": "清除搜索", @@ -3601,10 +3549,107 @@ "themePackages": { "import": "导入主题", "registryMismatch": "此软件包来自其他注册表。更新前,请明确更改已配置的注册表。", - "importedTheme": "导入的主题", "manage": "管理主题", "importJSON": "导入 Tabularis JSON", "importVSCode": "从 VS Code 导入", "edit": "编辑个人主题", "localPackage": "本地主题包", "installTitle": "安装主题包", "installSubtitle": "来自已配置注册表的声明式主题。不会执行任何代码。", "discover": "在插件中浏览主题", "refresh": "刷新", "preview": "预览", "apply": "应用", "confirm": "确认", "duplicate": "复制为个人主题", "exportJSON": "导出独立 JSON", "exportPackage": "导出作者主题包", "remove": "删除", "update": "更新主题包", "disable": "禁用主题包", "enable": "启用主题包", "removePackage": "卸载主题包", "disabled": "已禁用", "file": "主题文件", "name": "主题名称", "mode": "模式 / 基础", "detectMode": "自动检测(不明确时请选择)", "source": "主题 JSON", "search": "搜索主题", "loading": "加载中…", "noThemes": "此注册表中没有可用主题。", "details": "详情 / 安装", "readme": "README / 截图", "version": "主题包版本", "latest": "最新版本", "install": "安装 / 替换主题包", "chooseArchive": "选择 ZIP 文件", "screenshots": "截图(在外部打开)", "externalMedia": "不会自动加载图片及其他远程媒体。链接会在浏览器中打开。", "snapshotEditor": "精确的编辑器 JSON", "snapshotEditorHelp": "此独立快照代替旧版别名控制 SQL 颜色。更改会先预览,保存时会检查原始修订版本。", "recover": "恢复中断的安装", "recoveryExplanation": "明确检查并恢复未完成的主题操作。这可能恢复中断的安装,但不会选择主题或更改已保存的偏好设置。", "recoveryDone": "恢复检查已完成。请查看下方剩余的问题。", "catalogIssues": "目录诊断", "fileTooLarge": "文件超出导入大小限制。", "previewHint": "预览是临时的。取消会恢复已保存主题;应用会保存选择。", "previewReady": "正在预览。确认前请检查应用和编辑器。", "licenseNotice": "导入或导出不授予再分发权。发布前请保留署名并核实许可证。", "acknowledge": "我理解并接受上述转换限制。", "applyAfterSave": "保存后应用", "savedNotApplied": "主题已保存,但选择失败。请勿重复导入;请选择已保存的主题。", "installHint": "安装会替换整个主题包,但不会选择变体。预览、本地导入和选择不会计入下载次数。", "installedHint": "主题包已安装。关闭此窗口并在外观设置中选择变体。", "committedRefreshFailed": "操作已完成,但目录刷新失败。重试前请刷新列表。", "missing": "已保存的选择不可用:{{id}}。使用离线后备主题,不更改偏好。", "downloads": "下载次数:{{count}}", "downloadsUnavailable": "下载次数不可用", "installedVersion": "已安装:{{version}}", "minimumVersion": "需要 Tabularis {{version}} 或更新版本", "incompatible": "此版本不兼容,或未提供唯一的通用资源包。", "packageWarning": "此操作影响包内所有变体。已保存的选择会保留,并在再次可用时恢复。", "deleteWarning": "删除此个人主题?其已保存的应用选择将使用默认主题。", "duplicateHint": "创建独立、可编辑的个人副本,不自动启用。", "exportError": "主题包导出失败;仍可导出独立 JSON。", "runtimeWarning": "请输入实际首次支持的版本。开发版本号不能证明旧客户端兼容性。", "packageName": "主题包标识(小写)", "minimumRuntime": "最低 Tabularis 版本", "license": "许可证及署名文本", "rightsAcknowledged": "我已核实再分发权和署名。", - "groups": { "builtin": "内置 · 离线", "installed": "已安装主题包", "personal": "个人主题" }, "modes": { "light": "浅色", "dark": "深色", "high-contrast": "高对比度" }, - "importErrors": { "unrecognized": "无法识别此 VS Code 主题。", "modeRequired": "请选择模式,然后重新预览。", "includeOnly": "无法导入仅含 include 的主题。请提供实际颜色数据。", "noSupportedData": "未找到支持的颜色或 SQL 词法规则。", "invalidColor": "某个支持的颜色值无效。", "invalidRules": "词法规则无效或过多。" }, - "diagnostics": { "unsupportedKey": "不支持的字段", "unsupportedColor": "不支持的颜色", "unsupportedScope": "不支持的作用域", "scopeApproximation": "近似 SQL 作用域映射", "unsupportedStyle": "不支持的样式", "ignoredInclude": "未加载 include", "ignoredSemanticTokens": "已忽略语义词法标记", "unsupportedReference": "未加载外部引用", "unsupportedSetting": "不支持的设置", "tokenAlphaFlattened": "词法标记不透明度按基础背景计算", "modeApproximation": "模式已覆盖或近似转换", "diagnosticsTruncated": "已省略其他诊断信息" } + "importedTheme": "导入的主题", + "manage": "管理主题", + "importJSON": "导入 Tabularis JSON", + "importVSCode": "从 VS Code 导入", + "edit": "编辑个人主题", + "localPackage": "本地主题包", + "installTitle": "安装主题包", + "installSubtitle": "来自已配置注册表的声明式主题。不会执行任何代码。", + "discover": "在插件中浏览主题", + "refresh": "刷新", + "preview": "预览", + "apply": "应用", + "confirm": "确认", + "duplicate": "复制为个人主题", + "exportJSON": "导出独立 JSON", + "exportPackage": "导出作者主题包", + "remove": "删除", + "update": "更新主题包", + "disable": "禁用主题包", + "enable": "启用主题包", + "removePackage": "卸载主题包", + "disabled": "已禁用", + "file": "主题文件", + "name": "主题名称", + "mode": "模式 / 基础", + "detectMode": "自动检测(不明确时请选择)", + "source": "主题 JSON", + "search": "搜索主题", + "loading": "加载中…", + "noThemes": "此注册表中没有可用主题。", + "details": "详情 / 安装", + "readme": "README / 截图", + "version": "主题包版本", + "latest": "最新版本", + "install": "安装 / 替换主题包", + "chooseArchive": "选择 ZIP 文件", + "screenshots": "截图(在外部打开)", + "externalMedia": "不会自动加载图片及其他远程媒体。链接会在浏览器中打开。", + "snapshotEditor": "精确的编辑器 JSON", + "snapshotEditorHelp": "此独立快照代替旧版别名控制 SQL 颜色。更改会先预览,保存时会检查原始修订版本。", + "recover": "恢复中断的安装", + "recoveryExplanation": "明确检查并恢复未完成的主题操作。这可能恢复中断的安装,但不会选择主题或更改已保存的偏好设置。", + "recoveryDone": "恢复检查已完成。请查看下方剩余的问题。", + "catalogIssues": "目录诊断", + "fileTooLarge": "文件超出导入大小限制。", + "previewHint": "预览是临时的。取消会恢复已保存主题;应用会保存选择。", + "previewReady": "正在预览。确认前请检查应用和编辑器。", + "licenseNotice": "导入或导出不授予再分发权。发布前请保留署名并核实许可证。", + "acknowledge": "我理解并接受上述转换限制。", + "applyAfterSave": "保存后应用", + "savedNotApplied": "主题已保存,但选择失败。请勿重复导入;请选择已保存的主题。", + "installHint": "安装会替换整个主题包,但不会选择变体。预览、本地导入和选择不会计入下载次数。", + "installedHint": "主题包已安装。关闭此窗口并在外观设置中选择变体。", + "committedRefreshFailed": "操作已完成,但目录刷新失败。重试前请刷新列表。", + "missing": "已保存的选择不可用:{{id}}。使用离线后备主题,不更改偏好。", + "downloads": "下载次数:{{count}}", + "downloadsUnavailable": "下载次数不可用", + "installedVersion": "已安装:{{version}}", + "minimumVersion": "需要 Tabularis {{version}} 或更新版本", + "incompatible": "此版本不兼容,或未提供唯一的通用资源包。", + "packageWarning": "此操作影响包内所有变体。已保存的选择会保留,并在再次可用时恢复。", + "deleteWarning": "删除此个人主题?其已保存的应用选择将使用默认主题。", + "duplicateHint": "创建独立、可编辑的个人副本,不自动启用。", + "exportError": "主题包导出失败;仍可导出独立 JSON。", + "runtimeWarning": "请输入实际首次支持的版本。开发版本号不能证明旧客户端兼容性。", + "packageName": "主题包标识(小写)", + "minimumRuntime": "最低 Tabularis 版本", + "license": "许可证及署名文本", + "rightsAcknowledged": "我已核实再分发权和署名。", + "groups": { + "builtin": "内置 · 离线", + "installed": "已安装主题包", + "personal": "个人主题" + }, + "modes": { + "light": "浅色", + "dark": "深色", + "high-contrast": "高对比度" + }, + "importErrors": { + "unrecognized": "无法识别此 VS Code 主题。", + "modeRequired": "请选择模式,然后重新预览。", + "includeOnly": "无法导入仅含 include 的主题。请提供实际颜色数据。", + "noSupportedData": "未找到支持的颜色或 SQL 词法规则。", + "invalidColor": "某个支持的颜色值无效。", + "invalidRules": "词法规则无效或过多。" + }, + "diagnostics": { + "unsupportedKey": "不支持的字段", + "unsupportedColor": "不支持的颜色", + "unsupportedScope": "不支持的作用域", + "scopeApproximation": "近似 SQL 作用域映射", + "unsupportedStyle": "不支持的样式", + "ignoredInclude": "未加载 include", + "ignoredSemanticTokens": "已忽略语义词法标记", + "unsupportedReference": "未加载外部引用", + "unsupportedSetting": "不支持的设置", + "tokenAlphaFlattened": "词法标记不透明度按基础背景计算", + "modeApproximation": "模式已覆盖或近似转换", + "diagnosticsTruncated": "已省略其他诊断信息" + } }, "linkedGit": { "title": "查看 Git 更改", diff --git a/packages/web-ui/src/pages/Connections.tsx b/packages/web-ui/src/pages/Connections.tsx index bb0134fd4..70a92e173 100644 --- a/packages/web-ui/src/pages/Connections.tsx +++ b/packages/web-ui/src/pages/Connections.tsx @@ -24,7 +24,6 @@ import { FolderTree, ChevronDown, AppWindow, - ArrowLeftRight, Loader2, } from 'lucide-react'; import {useDatabase} from '@/hooks/useDatabase'; @@ -42,7 +41,6 @@ import { groupDropZone, type ConnectionDropPosition, type GroupDropPosition, - migrationDirectionForDriver, } from '@/utils/connections'; import {fuzzyFilter} from '@/utils/fuzzy'; import {useOpenConnectionInNewWindow} from '@/hooks/useOpenConnectionInNewWindow'; @@ -53,7 +51,6 @@ import {GroupHeader} from '@/components/connections/GroupHeader'; import {ConnectionCard} from '@/components/connections/ConnectionCard'; import {ConnectionListItem} from '@/components/connections/ConnectionListItem'; import {ConnectionErrorBanner} from '@/components/ConnectionErrorBanner'; -import {PostgresPluginMigrationBanner} from '@/components/banners/PostgresPluginMigrationBanner'; import {BetaBadge} from '@/components/ui/BetaBadge'; import {useCreateSqliteDatabase} from '@/hooks/useCreateSqliteDatabase'; import {useTabularisClient} from '@/hooks/useTabularisClient'; @@ -61,15 +58,7 @@ import {usePlatformCapabilities} from '@/hooks/usePlatformCapabilities'; import {saveGeneratedFile} from '@/utils/connectionFiles'; import {requestOpenDataFiles} from '@/utils/dataFiles'; import {buildEditorRoute, type ConnectionsRouteState} from '@/routing'; -import { - useBuiltinPostgresMigration, - type MigrationOutcome, -} from '@/hooks/useBuiltinDriverMigration'; -import {useConnectionCatalogue} from '@/hooks/useConnectionCatalogue'; -import {useToast} from '@/hooks/useToast'; import {useEscapeKey} from '@/hooks/useEscapeKey'; -import {buildPluginIssueUrl, resolvePluginRepoUrl} from '@/utils/pluginIssueReport'; -import {APP_VERSION} from '@/version'; const NewConnectionModal = lazy(() => import('../components/modals/NewConnectionModal').then((m) => ({ @@ -81,11 +70,6 @@ const ImportFromAppModal = lazy(() => default: m.ImportFromAppModal, })), ); -const MigrationChecklistModal = lazy(() => - import('../components/modals/MigrationChecklistModal').then((m) => ({ - default: m.MigrationChecklistModal, - })), -); let autoConnectAttempted = false; @@ -117,17 +101,13 @@ export const Connections = () => { loadConnections, connections: contextConnections, } = useDatabase(); - const {drivers, allDrivers, installedPlugins} = useDrivers(); + const {drivers, allDrivers} = useDrivers(); const {tags, refresh: refreshTags} = useConnectionTags(); const openConnectionInNewWindow = useOpenConnectionInNewWindow(); const {createSqliteDatabase, isCreating: isCreatingSqliteDatabase} = useCreateSqliteDatabase(); - const migration = useBuiltinPostgresMigration(); - const {registry: catalogueRegistry} = useConnectionCatalogue(false); - const {showToast} = useToast(); const [isModalOpen, setIsModalOpen] = useState(false); const [isImportAppModalOpen, setIsImportAppModalOpen] = useState(false); const [isImportMenuOpen, setIsImportMenuOpen] = useState(false); - const [isMigrationChecklistOpen, setIsMigrationChecklistOpen] = useState(false); const importMenuBtnRef = useRef(null); const [importMenuPos, setImportMenuPos] = useState({top: 0, right: 0}); const closeImportMenu = useCallback(() => setIsImportMenuOpen(false), []); @@ -208,145 +188,6 @@ export const Connections = () => { // the only way back — the per-connection action stays bidirectional even // after this toast is dismissed. // - // Called directly where migrateConnection resolves (in handleMigrate's - // onConfirm below), not from a useEffect watching a "lastOutcome" piece of - // hook state — `migrateConnection` already resolves with the outcome, so - // routing it through state just to re-derive a toast from it on the next - // render violated .rules/react.md #2 (no synchronous setState-in-effect) - // for no benefit. It also meant every migrateConnection call anywhere — - // including MigrationChecklistModal's bulk "Migrate N selected" loop, - // which has its own per-row status UI — set that same shared state and - // fired this toast a second time on top of the checklist's own feedback. - const {builtinId, pluginId: defaultPluginId, undoMigration} = migration; - const showMigrationOutcomeToast = useCallback( - (outcome: MigrationOutcome) => { - const handleUndo = () => { - void undoMigration(outcome.connectionId).then((result) => { - if (!result.ok) { - showToast( - t('migration.toast.undoFailed', { - name: outcome.connectionName, - error: result.error ?? 'unknown error', - }), - {kind: 'error', duration: 0}, - ); - } - }); - }; - - const handleReportIssue = (failureMode: 'connection' | 'process') => { - const pluginId = outcome.pluginId ?? defaultPluginId; - const registryEntry = catalogueRegistry.find((p) => p.id === pluginId); - const repoUrl = resolvePluginRepoUrl(pluginId, registryEntry?.repo_url); - if (!repoUrl) { - // No registry entry and no known fallback — nothing to link to; the - // toast action simply has nowhere to send the user. - return; - } - const installed = installedPlugins.find((p) => p.id === pluginId); - const url = buildPluginIssueUrl({ - pluginId, - pluginVersion: - installed?.version ?? registryEntry?.installed_version ?? 'unknown', - repoUrl, - appVersion: APP_VERSION, - os: navigator.platform, - template: 'migration-failure', - failureMode, - error: outcome.error ?? outcome.startupError ?? 'unknown error', - migratedFromDriver: builtinId, - }); - void platform.openExternalUrl(url); - }; - - if (outcome.status === 'ok') { - showToast(t('migration.toast.success', {name: outcome.connectionName}), { - kind: 'success', - duration: 0, - actions: [{label: t('migration.toast.undo'), onClick: handleUndo}], - }); - } else if (outcome.status === 'connection' && outcome.preexisting) { - // The built-in driver couldn't reach this host either — not a - // plugin regression, so no "Report an issue" action. - showToast( - t('migration.toast.connectionFailurePreexisting', { - name: outcome.connectionName, - error: outcome.error, - }), - { - kind: 'warning', - duration: 0, - actions: [{label: t('migration.toast.undo'), onClick: handleUndo}], - }, - ); - } else if (outcome.status === 'connection') { - showToast( - t('migration.toast.connectionFailure', { - name: outcome.connectionName, - error: outcome.error, - }), - { - kind: 'error', - duration: 0, - actions: [ - {label: t('migration.toast.undo'), onClick: handleUndo}, - { - label: t('migration.toast.reportIssue'), - onClick: () => handleReportIssue('connection'), - }, - ], - }, - ); - } else if (outcome.status === 'process') { - showToast( - outcome.startupError - ? t('migration.toast.processFailureWithError', { - name: outcome.connectionName, - error: outcome.startupError, - }) - : t('migration.toast.processFailure', {name: outcome.connectionName}), - { - kind: 'error', - duration: 0, - actions: [ - {label: t('migration.toast.undo'), onClick: handleUndo}, - { - label: t('migration.toast.reportIssue'), - onClick: () => handleReportIssue('process'), - }, - ], - }, - ); - } else { - // status === "failed": something unexpected happened before the driver - // flip could even be confirmed (e.g. the connection vanished - // concurrently, or the write itself errored) — Undo is still offered - // since flipping back to the built-in driver is safe either way. - showToast( - t('migration.toast.failed', { - name: outcome.connectionName, - error: outcome.error ?? 'unknown error', - }), - { - kind: 'error', - duration: 0, - actions: [{label: t('migration.toast.undo'), onClick: handleUndo}], - }, - ); - } - }, - [ - builtinId, - defaultPluginId, - undoMigration, - catalogueRegistry, - installedPlugins, - platform, - showToast, - t, - ], - ); - useEffect(() => { if (autoConnectAttempted) return; // Dedicated connection windows have their own URL-driven restore flow. @@ -781,47 +622,6 @@ export const Connections = () => { // connection gets an extra warning: the driver flip drops the stored URI // (by design), so re-entering it after switching is the tradeoff being // confirmed, not a surprise discovered after the fact. - const handleMigrate = (conn: SavedConnection, direction: 'to-plugin' | 'to-builtin') => { - const isUriBased = conn.params.connection_uri_in_keychain === true; - if (direction === 'to-plugin') { - setConfirmModal({ - title: t('migration.confirm.title'), - message: isUriBased - ? t('migration.confirm.uriMessage', {name: conn.name}) - : t('migration.confirm.message', {name: conn.name}), - confirmLabel: isUriBased - ? t('migration.confirm.confirmLabelUri') - : t('migration.confirm.confirmLabel'), - variant: isUriBased ? 'warning' : 'info', - onConfirm: () => { - setConfirmModal(null); - void migration.migrateConnection(conn.id).then(showMigrationOutcomeToast); - }, - }); - } else { - setConfirmModal({ - title: t('migration.confirm.undoTitle'), - message: t('migration.confirm.undoMessage', {name: conn.name}), - confirmLabel: t('migration.confirm.undoConfirmLabel'), - variant: 'info', - onConfirm: () => { - setConfirmModal(null); - void migration.undoMigration(conn.id).then((result) => { - if (!result.ok) { - showToast( - t('migration.toast.undoFailed', { - name: conn.name, - error: result.error ?? 'unknown error', - }), - {kind: 'error', duration: 0}, - ); - } - }); - }, - }); - } - }; - const openEdit = async (conn: SavedConnection) => { if (isConnectionOpenAnywhere(conn.id)) { await disconnect(conn.id); @@ -900,12 +700,6 @@ export const Connections = () => { dropAxis: connectionDrop?.axis ?? 'y', selectionActive: selectedIds.size > 0, onToggleSelect: canSelect ? () => toggleSelect(conn.id) : undefined, - onMigrate: caps.canUpdate - ? () => { - const direction = migrationDirectionForDriver(conn.params.driver, allDrivers); - if (direction) handleMigrate(conn, direction); - } - : undefined, }); const handleConnectionMouseDown = ( @@ -1356,18 +1150,6 @@ export const Connections = () => { )} {/* ── Built-in → plugin migration banner ────────────────────────────── */} - {migration.banner?.visible && ( - d.id === migration.builtinId)?.deprecated - ?.removal_date - } - onDismiss={migration.dismissBanner} - onReview={() => setIsMigrationChecklistOpen(true)} - /> - )} - {/* ── Selection bar (bulk actions) ──────────────────────────────────── */} {selectedIds.size > 0 && (
@@ -1727,25 +1509,6 @@ export const Connections = () => { onImported={() => void loadConnections()} /> )} - {isMigrationChecklistOpen && ( - setIsMigrationChecklistOpen(false)} - connections={migration.builtinConnections} - manifest={allDrivers.find((d) => d.id === migration.pluginId)} - repoUrl={resolvePluginRepoUrl( - migration.pluginId, - catalogueRegistry.find((p) => p.id === migration.pluginId)?.repo_url, - )} - pluginVersion={ - installedPlugins.find((p) => p.id === migration.pluginId)?.version ?? - catalogueRegistry.find((p) => p.id === migration.pluginId) - ?.installed_version ?? - 'unknown' - } - migrateConnection={migration.migrateConnection} - /> - )} { if (conn) void handleOpenInNewWindow(conn); }, }, - // Bidirectional "Switch to plugin" / "Switch back to builtin" - // per-connection action. Direction is driven by the current - // driver — always available, even after the banner is - // dismissed. Uses the same confirm flow as the card button. - ...(() => { - if (!conn || !caps.canUpdate) return []; - const direction = migrationDirectionForDriver( - conn.params.driver, - allDrivers, - ); - if (!direction) return []; - return [ - {separator: true as const}, - { - label: - direction === 'to-plugin' - ? t('migration.switchToPlugin') - : t('migration.switchToBuiltin'), - icon: ArrowLeftRight, - action: () => handleMigrate(conn, direction), - }, - ]; - })(), ...(caps.canEditOrganization && hasAvailableGroups ? [ {separator: true as const}, diff --git a/packages/web-ui/src/types/plugins.ts b/packages/web-ui/src/types/plugins.ts index 7c96a79ee..85bb7d1b4 100644 --- a/packages/web-ui/src/types/plugins.ts +++ b/packages/web-ui/src/types/plugins.ts @@ -113,6 +113,8 @@ export interface DriverCapabilities { readonly?: boolean; /** Implements the protected execute_read_only_query RPC. Defaults to false. */ read_only_queries?: boolean; + /** Implements the lossless `read_rows`, `insert_records` and `release_session` RPCs, so tables can be copied row by row to or from this driver. Requires `sql_dialect: "postgres"`. Defaults to false. */ + table_copy?: boolean; /** Offers "Export table to SQL" on table nodes. Defaults to true; non-SQL plugins set false. */ table_export?: boolean; /** Offers "Import table from SQL" on database and schema nodes. Defaults to true; ignored (off) when readonly. */ diff --git a/packages/web-ui/src/utils/connections.ts b/packages/web-ui/src/utils/connections.ts index b570df82b..f1317266f 100644 --- a/packages/web-ui/src/utils/connections.ts +++ b/packages/web-ui/src/utils/connections.ts @@ -11,7 +11,7 @@ import {hasOptedIntoDatabaseSelection} from './database'; export type DatabaseDriver = string; -export const BUILTIN_DRIVER_IDS = ['postgres', 'mysql', 'sqlite'] as const; +export const BUILTIN_DRIVER_IDS = ['mysql', 'sqlite'] as const; export type BuiltinDriverId = (typeof BUILTIN_DRIVER_IDS)[number]; /** Which direction a per-connection migration action would go, or `null` if @@ -27,7 +27,7 @@ export type MigrationDirection = 'to-plugin' | 'to-builtin' | null; * triggering an action for a driver nothing actually handles yet. Add a pair * here in the same commit that wires its `useBuiltinDriverMigration` call. */ -const MIGRATABLE_DRIVER_PAIRS: ReadonlySet = new Set(['postgres:postgresql']); +const MIGRATABLE_DRIVER_PAIRS: ReadonlySet = new Set(); /** * Determine whether a connection's current driver is a deprecated built-in @@ -325,10 +325,11 @@ export function getDefaultPort(driver: DatabaseDriver | PluginManifest): number return driver.default_port ?? 0; } switch (driver) { - case 'postgres': - return 5432; case 'mysql': return 3306; + case 'postgres': + case 'postgresql': + return 5432; case 'sqlite': return 0; // SQLite doesn't use ports default: @@ -361,7 +362,7 @@ export function validateConnectionParams( // For remote drivers, host is required const local = capabilities != null ? isLocalDriver(capabilities) : params.driver === 'sqlite'; - const isBuiltInSocketDriver = params.driver === 'mysql' || params.driver === 'postgres'; + const isBuiltInSocketDriver = params.driver === 'mysql'; const socketDestination = !params.k8s_enabled && !params.ssm_enabled && @@ -437,10 +438,11 @@ export function getDriverLabel(driver: DatabaseDriver | PluginManifest): string return driver.name; } switch (driver) { - case 'postgres': - return 'PostgreSQL'; case 'mysql': return 'MySQL'; + case 'postgres': + case 'postgresql': + return 'PostgreSQL'; case 'sqlite': return 'SQLite'; default: diff --git a/packages/web-ui/src/utils/driverIcons.tsx b/packages/web-ui/src/utils/driverIcons.tsx index 57d379102..f4413c241 100644 --- a/packages/web-ui/src/utils/driverIcons.tsx +++ b/packages/web-ui/src/utils/driverIcons.tsx @@ -1,23 +1,5 @@ import type {ReactNode} from 'react'; -/** - * PostgreSQL — Slonik elephant silhouette - */ -export const PostgreSQLIcon = ({size = 14}: {size?: number}): ReactNode => ( - -); - /** * MySQL — dolphin silhouette */ diff --git a/packages/web-ui/src/utils/driverUI.tsx b/packages/web-ui/src/utils/driverUI.tsx index aefc3a396..49ccdb442 100644 --- a/packages/web-ui/src/utils/driverUI.tsx +++ b/packages/web-ui/src/utils/driverUI.tsx @@ -4,7 +4,7 @@ import {lazy, Suspense} from 'react'; import type {ReactNode} from 'react'; import type {PluginManifest} from '@/types/plugins'; import type {SavedConnection} from '@/contexts/DatabaseContext'; -import {PostgreSQLIcon, MySQLIcon, SQLiteIcon} from './driverIcons'; +import {MySQLIcon, SQLiteIcon} from './driverIcons'; import {RegistryDriverIcon} from '@/components/RegistryDriverIcon'; const FALLBACK_COLOR = '#64748b'; // slate-500 @@ -52,8 +52,6 @@ export function getDriverIcon(manifest: PluginManifest | undefined | null, size // Brand icons for built-in drivers switch (iconName) { - case 'postgres': - return ; case 'mysql': return ; case 'sqlite': diff --git a/packages/web-ui/src/utils/findUnsupportedFeatures.ts b/packages/web-ui/src/utils/findUnsupportedFeatures.ts deleted file mode 100644 index 50a631cb1..000000000 --- a/packages/web-ui/src/utils/findUnsupportedFeatures.ts +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Capability-gap detection for the built-in-to-plugin driver migration. - * - * Compares what a connection actually uses against a plugin's declared - * `DriverCapabilities` and returns the named gaps. A connection with an - * unsupported feature stays *unchecked by default* in the migration checklist - * but is still shown with the specific gap named inline, so the user can - * report it rather than being silently excluded. - * - * What this compares: the real `DriverCapabilities` surface — `supports_ssl`, - * `connection_uri`, `connection_string`, etc. - * - * What it deliberately does NOT compare: SSH tunneling, IAM auth, and - * Kubernetes port-forwarding. Those are app-level features, transparent to - * every driver — `test_connection` opens the tunnel and rewrites `params.port` - * to the local forwarded port before the driver sees the connection. The - * driver trait has no SSH/tunnel/IAM methods, and `DriverCapabilities` has no - * fields for them, so a connection using them migrates cleanly and must never - * appear as a gap here. - */ - -import type {PluginManifest} from '@/types/plugins'; - -/** The slice of connection params this function needs. Defined locally - * rather than imported from one of the several `ConnectionParams` variants so - * this pure util depends on no Tauri/command shape — only the fields it reads. */ -export interface MigrationConnectionParams { - /** Raw driver-specific connection URI in use (or restorable from keychain). */ - connection_uri?: string; - /** True when the URI can be restored from the OS keychain. */ - connection_uri_in_keychain?: boolean; - /** SSL mode, non-empty when TLS is configured (e.g. "verify-ca"). */ - ssl_mode?: string; - /** A decomposed connection string is in use (host/port/database fields). */ - host?: string; - port?: number; -} - -/** A named capability gap a connection uses that the plugin doesn't declare. */ -export interface UnsupportedFeature { - /** Stable feature key for dedup / "report this gap" tracking. */ - feature: 'ssl' | 'connection_uri'; - /** Human-readable description shown inline in the migration checklist. */ - label: string; -} - -/** - * Return the capabilities a connection uses that the plugin does not declare. - * Empty when the plugin covers everything the connection needs. - * - * Pure: no side effects, no I/O — straightforward to unit-test. - */ -export function findUnsupportedFeatures( - connection: MigrationConnectionParams, - manifest: PluginManifest, -): UnsupportedFeature[] { - const caps = manifest.capabilities; - const gaps: UnsupportedFeature[] = []; - - // SSL: the connection has a non-empty ssl_mode but the plugin declares no - // SSL support. - if (connection.ssl_mode && connection.ssl_mode.trim() !== '' && !caps.supports_ssl) { - gaps.push({feature: 'ssl', label: 'uses SSL/TLS, not yet supported by the plugin'}); - } - - // Connection URI: the connection uses a raw URI (present now or restorable - // from the keychain) but the plugin declares it can't accept a connection - // string at all. This checks `connection_string` (whether the plugin's - // connection form accepts a URI as an input, defaulting to true), NOT - // `connection_uri` (whether the plugin needs the URI passed through - // verbatim instead of decomposed — a structural requirement for drivers - // like MongoDB's `mongodb+srv://`, irrelevant to whether postgres-style - // decomposition is possible). A plugin that decomposes URIs just fine - // (`connection_uri: false`, e.g. the postgresql plugin, same as builtin - // postgres) is not a gap; only a plugin that rejects connection strings - // outright (`connection_string: false`) is. - const usesUri = - (connection.connection_uri !== undefined && connection.connection_uri !== '') || - connection.connection_uri_in_keychain === true; - // `connection_string` defaults to true (backward-compat default in the - // Rust struct); absent/undefined means supported, not unsupported. - const supportsConnectionString = caps.connection_string ?? caps.connectionString ?? true; - if (usesUri && !supportsConnectionString) { - gaps.push({ - feature: 'connection_uri', - label: 'uses a connection string, not yet supported by the plugin', - }); - } - - return gaps; -} diff --git a/packages/web-ui/tests/components/banners/PostgresPluginMigrationBanner.test.tsx b/packages/web-ui/tests/components/banners/PostgresPluginMigrationBanner.test.tsx deleted file mode 100644 index 40fbe1d5e..000000000 --- a/packages/web-ui/tests/components/banners/PostgresPluginMigrationBanner.test.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import {describe, it, expect, vi} from 'vitest'; -import {render, screen} from '@testing-library/react'; -import {PostgresPluginMigrationBanner} from '@/components/banners/PostgresPluginMigrationBanner'; - -describe('PostgresPluginMigrationBanner', () => { - const onDismiss = vi.fn(); - const onReview = vi.fn(); - - it('renders the plain nudge message when no removal date is known', () => { - render( - , - ); - expect(screen.getByText('migration.banner.nudge')).toBeInTheDocument(); - expect(screen.queryByText(/nudgeWithDate/)).not.toBeInTheDocument(); - }); - - it("renders the with-date variant, interpolating the manifest's removal_date", () => { - // The date is read from PluginManifest.deprecated.removal_date (the same - // field the deprecated-driver badge/tooltip use) rather than hardcoded - // in this component — this test's date value deliberately does not - // match any date literal that used to live in the translation string, - // to prove it's actually threaded through as a prop. - render( - , - ); - expect(screen.getByText('migration.banner.nudgeWithDate')).toBeInTheDocument(); - }); - - it('renders the offline message regardless of removalDate', () => { - render( - , - ); - expect(screen.getByText('migration.banner.offline')).toBeInTheDocument(); - expect(screen.queryByText(/nudge/)).not.toBeInTheDocument(); - }); -}); diff --git a/packages/web-ui/tests/components/connections/ActionButtons.test.tsx b/packages/web-ui/tests/components/connections/ActionButtons.test.tsx index bc3c6ac06..1f2a1e899 100644 --- a/packages/web-ui/tests/components/connections/ActionButtons.test.tsx +++ b/packages/web-ui/tests/components/connections/ActionButtons.test.tsx @@ -26,14 +26,12 @@ function renderButtons(capabilities?: ConnectionCapabilities) { onEdit: vi.fn(), onDuplicate: vi.fn(), onDelete: vi.fn(), - onMigrate: vi.fn(), }; const buttons = ( ); @@ -58,7 +56,6 @@ describe('ActionButtons', () => { 'connections.edit', 'connections.clone', 'connections.delete', - 'migration.switchToPlugin', ]) { expect(screen.getByTitle(title)).toBeInTheDocument(); } @@ -74,12 +71,7 @@ describe('ActionButtons', () => { const handlers = renderButtons(MANAGED); expect(screen.getByTitle('connections.connect')).toBeInTheDocument(); - for (const title of [ - 'connections.edit', - 'connections.clone', - 'connections.delete', - 'migration.switchToPlugin', - ]) { + for (const title of ['connections.edit', 'connections.clone', 'connections.delete']) { expect(screen.queryByTitle(title)).not.toBeInTheDocument(); } fireEvent.click(screen.getByTitle('connections.connect')); diff --git a/packages/web-ui/tests/components/modals/MigrationChecklistModal.test.tsx b/packages/web-ui/tests/components/modals/MigrationChecklistModal.test.tsx deleted file mode 100644 index 6143bccec..000000000 --- a/packages/web-ui/tests/components/modals/MigrationChecklistModal.test.tsx +++ /dev/null @@ -1,634 +0,0 @@ -import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest'; -import {render, screen, fireEvent, waitFor, act} from '@testing-library/react'; -import {MigrationChecklistModal} from '@/components/modals/MigrationChecklistModal'; -import type {SavedConnection} from '@/contexts/DatabaseContext'; -import type {PluginManifest} from '@/types/plugins'; -import type {MigrationOutcome} from '@/hooks/useBuiltinDriverMigration'; -import {openUrl} from '@tauri-apps/plugin-opener'; - -vi.mock('@/hooks/usePlatformCapabilities', () => import('../../support/tauriBackedHooks')); -const settingsMock = { - settings: {} as {knownCapabilityGaps?: Record}, - updateSetting: vi.fn<(key: string, value: unknown) => Promise>(), -}; - -vi.mock('@/hooks/useSettings', () => ({ - useSettings: () => settingsMock, -})); - -const makeManifest = (capabilities: Partial): PluginManifest => ({ - id: 'postgresql', - name: 'PostgreSQL', - version: '1.0.0', - description: '', - default_port: 5432, - capabilities: { - schemas: true, - views: true, - routines: true, - file_based: false, - folder_based: false, - identifier_quote: '"', - alter_primary_key: true, - ...capabilities, - } as PluginManifest['capabilities'], -}); - -const makeConn = ( - id: string, - name: string, - params: Partial = {}, -): SavedConnection => ({ - id, - name, - params: {driver: 'postgres', database: 'db', ...params}, -}); - -const outcomeFor = (connectionId: string): MigrationOutcome => ({ - connectionId, - connectionName: connectionId, - status: 'ok', -}); - -describe('MigrationChecklistModal', () => { - const onClose = vi.fn(); - let migrateConnection: ReturnType; - - beforeEach(() => { - vi.clearAllMocks(); - settingsMock.settings = {}; - settingsMock.updateSetting.mockReset(); - settingsMock.updateSetting.mockResolvedValue(undefined); - migrateConnection = vi.fn(async (id: string) => outcomeFor(id)); - }); - - it('renders nothing when isOpen is false', () => { - const {container} = render( - , - ); - expect(container).toBeEmptyDOMElement(); - }); - - it('closes on Escape, same as the X button', () => { - render( - , - ); - - fireEvent.keyDown(window, {key: 'Escape'}); - - expect(onClose).toHaveBeenCalledTimes(1); - }); - - describe("mounts fresh with whatever data it's given", () => { - // Connections.tsx conditionally mounts this component - // ({isMigrationChecklistOpen && }), so - // every mount is a genuine cold start with real props already in hand — - // the "Review connections" link that mounts it only renders once the - // banner has resolved to "nudge", which itself requires connections and - // the plugin manifest to have already loaded. A plain useState - // initializer is enough; there's no route to mounting before that data - // exists, so no rising-edge-of-isOpen effect is needed to re-derive - // anything after the fact. - it('checks a clean connection immediately on mount', () => { - const manifest = makeManifest({supports_ssl: true, connection_uri: true}); - const cleanConn = makeConn('c1', 'Clean Connection'); - - render( - , - ); - - expect(screen.getByRole('checkbox')).toBeChecked(); - expect( - screen.getByText(/migration\.checklist\.migrateSelected/).closest('button'), - ).not.toBeDisabled(); - }); - - it("keeps a migrated row visible and a user's manual uncheck intact when connections shrinks mid-open", async () => { - // A connection dropping out of `connections` as it migrates (during a - // bulk run) must not make its row disappear, and must not reset the - // checked state for the remaining rows — candidateRows is a snapshot - // taken once at mount, independent of later `connections` prop churn. - const manifest = makeManifest({supports_ssl: true, connection_uri: true}); - const conns = [makeConn('c1', 'Conn 1'), makeConn('c2', 'Conn 2')]; - - const {rerender} = render( - , - ); - const checkboxes = screen.getAllByRole('checkbox'); - // Manually uncheck c2 — a user override that must survive prop churn. - fireEvent.click(checkboxes[1]); - expect(checkboxes[1]).not.toBeChecked(); - - // c1 migrates and drops out of the `connections` prop, as - // Connections.tsx's `migration.builtinConnections` would do mid-batch. - rerender( - , - ); - - // Both rows still render — c1's row doesn't vanish just because it - // dropped out of `connections` — and c2's manual uncheck still holds. - expect(screen.getByText('Conn 1')).toBeInTheDocument(); - expect(screen.getByText('Conn 2')).toBeInTheDocument(); - const checkboxesAfter = screen.getAllByRole('checkbox'); - expect(checkboxesAfter).toHaveLength(2); - expect(checkboxesAfter[1]).not.toBeChecked(); - }); - - it('derives a fresh default selection on each new mount', () => { - const manifest = makeManifest({supports_ssl: true, connection_uri: true}); - const conn = makeConn('c1', 'Conn 1'); - - const {unmount} = render( - , - ); - fireEvent.click(screen.getByRole('checkbox')); // user unchecks it - expect(screen.getByRole('checkbox')).not.toBeChecked(); - - // Closing unmounts the component (Connections.tsx's conditional - // render), and reopening mounts a brand-new instance — the same - // lifecycle transition `{isMigrationChecklistOpen && <... />}` performs. - unmount(); - render( - , - ); - - // Back to the default: checked, since it's still gap-free. - expect(screen.getByRole('checkbox')).toBeChecked(); - }); - }); - - describe('default checked/unchecked state', () => { - it('checks a connection with no capability gap by default', () => { - const manifest = makeManifest({supports_ssl: true, connection_uri: true}); - const conn = makeConn('c1', 'Clean Connection'); - render( - , - ); - const checkbox = screen.getByRole('checkbox'); - expect(checkbox).toBeChecked(); - }); - - it('leaves a connection with an SSL gap unchecked by default', () => { - const manifest = makeManifest({supports_ssl: false}); - const conn = makeConn('c1', 'SSL Connection', {ssl_mode: 'verify-ca'}); - render( - , - ); - const checkbox = screen.getByRole('checkbox'); - expect(checkbox).not.toBeChecked(); - // The gap is named inline. - expect(screen.getByText('migration.checklist.gap.ssl')).toBeInTheDocument(); - }); - - it('still lets the user check a gapped connection manually', () => { - const manifest = makeManifest({supports_ssl: false}); - const conn = makeConn('c1', 'SSL Connection', {ssl_mode: 'verify-ca'}); - render( - , - ); - const checkbox = screen.getByRole('checkbox'); - fireEvent.click(checkbox); - expect(checkbox).toBeChecked(); - }); - }); - - describe('Report this gap', () => { - it('opens the capability-gap issue URL and records knownCapabilityGaps', async () => { - const manifest = makeManifest({supports_ssl: false}); - const conn = makeConn('c1', 'SSL Connection', {ssl_mode: 'verify-ca'}); - render( - , - ); - fireEvent.click(screen.getByText('migration.checklist.reportThisGap')); - - await waitFor(() => expect(openUrl).toHaveBeenCalledTimes(1)); - const url = (openUrl as ReturnType).mock.calls[0][0] as string; - expect(url).toContain('template=capability-gap.yml'); - expect(url).toContain('feature=ssl'); - expect(url).toContain('plugin_version=1.2.3'); - - await waitFor(() => - expect(settingsMock.updateSetting).toHaveBeenCalledWith('knownCapabilityGaps', { - postgresql: ['ssl'], - }), - ); - }); - - it('shows an already-reported state instead of the button when the gap was previously filed', () => { - settingsMock.settings = {knownCapabilityGaps: {postgresql: ['ssl']}}; - const manifest = makeManifest({supports_ssl: false}); - const conn = makeConn('c1', 'SSL Connection', {ssl_mode: 'verify-ca'}); - render( - , - ); - expect(screen.queryByText('migration.checklist.reportThisGap')).not.toBeInTheDocument(); - expect(screen.getByText('migration.checklist.alreadyReported')).toBeInTheDocument(); - }); - - it('disables the report action when repoUrl is unavailable', () => { - const manifest = makeManifest({supports_ssl: false}); - const conn = makeConn('c1', 'SSL Connection', {ssl_mode: 'verify-ca'}); - render( - , - ); - expect( - screen.getByText('migration.checklist.reportThisGap').closest('button'), - ).toBeDisabled(); - }); - }); - - describe('bulk migrate', () => { - it('migrates only checked connections, sequentially', async () => { - const manifest = makeManifest({supports_ssl: true, connection_uri: true}); - const conns = [makeConn('c1', 'Conn 1'), makeConn('c2', 'Conn 2')]; - render( - , - ); - // Both connections are gap-free, so both start checked. - fireEvent.click(screen.getByText(/migration\.checklist\.migrateSelected/)); - - await waitFor(() => expect(migrateConnection).toHaveBeenCalledTimes(2)); - expect(migrateConnection).toHaveBeenCalledWith('c1'); - expect(migrateConnection).toHaveBeenCalledWith('c2'); - }); - - it('keeps every row visible with its own status, and shrinks the footer count, as connections drops out mid-run', async () => { - // Regression: Connections.tsx passes migration.builtinConnections, - // which shrinks as each row's own migrateConnection call flips its - // driver — this simulates that by rerendering with a shorter - // `connections` prop from inside the mocked migrateConnection, exactly - // as the real loadConnections()-driven update would land mid-batch. - const manifest = makeManifest({supports_ssl: true, connection_uri: true}); - const conns = [makeConn('c1', 'Conn 1'), makeConn('c2', 'Conn 2')]; - let rerenderWithShrunkConnections: (() => void) | null = null; - migrateConnection = vi.fn(async (id: string) => { - rerenderWithShrunkConnections?.(); - return outcomeFor(id); - }); - - const {rerender} = render( - , - ); - rerenderWithShrunkConnections = () => - rerender( - , - ); - - fireEvent.click(screen.getByText(/migration\.checklist\.migrateSelected/)); - - // Both rows stay visible and reach "ok" even though `connections` - // dropped to empty after the first call — candidateRows doesn't track - // the live prop mid-run. - await waitFor(() => expect(migrateConnection).toHaveBeenCalledTimes(2)); - expect(screen.getByText('Conn 1')).toBeInTheDocument(); - expect(screen.getByText('Conn 2')).toBeInTheDocument(); - - // Each id is dropped from `checked` as it completes, so the button - // ends up disabled once nothing is left checked — not stuck stale at - // the original selection — and a further click can't re-run - // migrateConnection on either already-migrated connection. - const migrateButtonAfter = screen - .getByText(/migration\.checklist\.migrateSelected/) - .closest('button'); - await waitFor(() => expect(migrateButtonAfter).toBeDisabled()); - fireEvent.click(migrateButtonAfter!); - expect(migrateConnection).toHaveBeenCalledTimes(2); // unchanged - }); - - it('continues the batch and clears the migrating flag when one migration rejects unexpectedly', async () => { - // migrateConnection's real implementation never rejects (it resolves a - // "failed" outcome instead), but this guards the modal's own loop - // defensively: if it ever did throw, one bad connection must not abort - // the remaining batch or leave `migrating` stuck true forever. - const manifest = makeManifest({supports_ssl: true, connection_uri: true}); - const conns = [makeConn('c1', 'Conn 1'), makeConn('c2', 'Conn 2')]; - migrateConnection = vi.fn(async (id: string) => { - if (id === 'c1') throw new Error('unexpected'); - return outcomeFor(id); - }); - render( - , - ); - const migrateButton = screen - .getByText(/migration\.checklist\.migrateSelected/) - .closest('button'); - fireEvent.click(migrateButton!); - - await waitFor(() => expect(migrateConnection).toHaveBeenCalledTimes(2)); - expect(migrateConnection).toHaveBeenCalledWith('c1'); - expect(migrateConnection).toHaveBeenCalledWith('c2'); - // The migrate button is now legitimately disabled — both checked ids - // completed and were removed from `checked`, so there's nothing left - // to select — but `migrating` itself must have cleared (checkboxes - // are re-enabled), proving the throw in c1's attempt didn't leave the - // loop's `finally` unreached. - await waitFor(() => { - for (const checkbox of screen.getAllByRole('checkbox')) { - expect(checkbox).not.toBeDisabled(); - } - }); - }); - - it('does not migrate an unchecked (gapped) connection', async () => { - const manifest = makeManifest({supports_ssl: false}); - const conns = [ - makeConn('c1', 'Gapped', {ssl_mode: 'verify-ca'}), - makeConn('c2', 'Clean'), - ]; - render( - , - ); - fireEvent.click(screen.getByText(/migration\.checklist\.migrateSelected/)); - - await waitFor(() => expect(migrateConnection).toHaveBeenCalledTimes(1)); - expect(migrateConnection).toHaveBeenCalledWith('c2'); - expect(migrateConnection).not.toHaveBeenCalledWith('c1'); - }); - - it('disables the migrate button when nothing is checked', () => { - const manifest = makeManifest({supports_ssl: false}); - const conn = makeConn('c1', 'Gapped', {ssl_mode: 'verify-ca'}); - render( - , - ); - expect( - screen.getByText(/migration\.checklist\.migrateSelected/).closest('button'), - ).toBeDisabled(); - }); - }); - - describe('in-progress feedback', () => { - afterEach(() => { - vi.useRealTimers(); - }); - - it('shows a testing-connection label only once a running row has been pending a few seconds', async () => { - vi.useFakeTimers(); - const manifest = makeManifest({supports_ssl: true, connection_uri: true}); - const conn = makeConn('c1', 'Conn 1'); - let resolveMigration: (outcome: MigrationOutcome) => void = () => {}; - migrateConnection = vi.fn( - () => - new Promise((resolve) => { - resolveMigration = resolve; - }), - ); - render( - , - ); - - fireEvent.click(screen.getByText(/migration\.checklist\.migrateSelected/)); - await act(async () => { - await Promise.resolve(); - }); - expect(migrateConnection).toHaveBeenCalledTimes(1); - - // Not yet — the row only just started running. - expect(screen.queryByText('migration.checklist.testing')).not.toBeInTheDocument(); - - await act(async () => { - vi.advanceTimersByTime(3000); - }); - expect(screen.getByText('migration.checklist.testing')).toBeInTheDocument(); - - await act(async () => { - resolveMigration(outcomeFor('c1')); - await Promise.resolve(); - }); - }); - - it('shows the migrating notice in the footer only while the batch is running', async () => { - const manifest = makeManifest({supports_ssl: true, connection_uri: true}); - const conn = makeConn('c1', 'Conn 1'); - let resolveMigration: (outcome: MigrationOutcome) => void = () => {}; - migrateConnection = vi.fn( - () => - new Promise((resolve) => { - resolveMigration = resolve; - }), - ); - render( - , - ); - expect( - screen.queryByText('migration.checklist.migratingNotice'), - ).not.toBeInTheDocument(); - - fireEvent.click(screen.getByText(/migration\.checklist\.migrateSelected/)); - await waitFor(() => expect(migrateConnection).toHaveBeenCalledTimes(1)); - expect(screen.getByText('migration.checklist.migratingNotice')).toBeInTheDocument(); - - await act(async () => { - resolveMigration(outcomeFor('c1')); - await Promise.resolve(); - }); - await waitFor(() => - expect( - screen.queryByText('migration.checklist.migratingNotice'), - ).not.toBeInTheDocument(), - ); - }); - }); - - describe('URI pre-flight', () => { - it('shows an inline warning for a connection-URI-based connection', () => { - const manifest = makeManifest({supports_ssl: true, connection_uri: true}); - const conn = makeConn('c1', 'URI Connection', {connection_uri_in_keychain: true}); - render( - , - ); - expect(screen.getByText('migration.checklist.uriWarning')).toBeInTheDocument(); - }); - }); - - it('shows an empty state when there are no connections to review', () => { - render( - , - ); - expect(screen.getByText('migration.checklist.noGaps')).toBeInTheDocument(); - }); -}); diff --git a/packages/web-ui/tests/contexts/DatabaseProvider.test.tsx b/packages/web-ui/tests/contexts/DatabaseProvider.test.tsx index acc2c45fb..caaae7a81 100644 --- a/packages/web-ui/tests/contexts/DatabaseProvider.test.tsx +++ b/packages/web-ui/tests/contexts/DatabaseProvider.test.tsx @@ -3,6 +3,7 @@ import {renderHook, waitFor, act} from '@testing-library/react'; import {DatabaseProvider} from '@/contexts/DatabaseProvider'; import {ToastContext} from '@/contexts/ToastContext'; import {useDatabase} from '@/hooks/useDatabase'; +import {useTabularisClient} from '@/hooks/useTabularisClient'; import {invoke, isTauri} from '@tauri-apps/api/core'; import React from 'react'; @@ -204,6 +205,33 @@ describe('DatabaseProvider', () => { ).toHaveLength(2); }); + it('reloads saved connections when a plugin is activated in the background', async () => { + const wrapper = ({children}: {children: React.ReactNode}) => + React.createElement(DatabaseProvider, null, children); + vi.mocked(invoke).mockImplementation(async (command) => + command === 'get_connections_with_groups' + ? {connections: mockConnections, groups: []} + : [], + ); + const client = useTabularisClient(); + const {result} = renderHook(() => useDatabase(), {wrapper}); + await waitFor(() => expect(client.subscribe).toHaveBeenCalled()); + const loads = () => + vi + .mocked(invoke) + .mock.calls.filter(([command]) => command === 'get_connections_with_groups').length; + const before = loads(); + const activated = vi + .mocked(client.subscribe) + .mock.calls.find(([event]) => event === 'tabularis://plugin-activated'); + expect(activated).toBeDefined(); + await act(async () => { + (activated![1] as (payload: {pluginId: string}) => void)({pluginId: 'postgresql'}); + }); + await waitFor(() => expect(loads()).toBe(before + 1)); + expect(result.current).toBeDefined(); + }); + it('does not reuse or publish a stale bootstrap read after an explicit refresh', async () => { const wrapper = ({children}: {children: React.ReactNode}) => React.createElement(DatabaseProvider, null, children); diff --git a/packages/web-ui/tests/hooks/useBuiltinDriverMigration.test.ts b/packages/web-ui/tests/hooks/useBuiltinDriverMigration.test.ts deleted file mode 100644 index b95b28fd5..000000000 --- a/packages/web-ui/tests/hooks/useBuiltinDriverMigration.test.ts +++ /dev/null @@ -1,603 +0,0 @@ -import {describe, it, expect, vi, beforeEach} from 'vitest'; -import {renderHook, act, waitFor} from '@testing-library/react'; - -// Mock the four context hooks the migration hook composes, plus the client. -// Each test reconfigures the mock returns to drive the connectivity gate. - -const databaseMock = { - connections: [] as Array<{id: string; name: string; params: {driver: string}}>, - loadConnections: vi.fn<() => Promise>().mockResolvedValue(undefined), - connect: vi.fn<(id: string) => Promise>().mockResolvedValue(undefined), - disconnect: vi.fn<(id: string) => Promise>().mockResolvedValue(undefined), - openConnectionIds: [] as string[], - connectionDataMap: {} as Record, -}; - -const driversMock = { - drivers: [], - allDrivers: [] as Array<{id: string}>, - installedPlugins: [] as Array<{id: string}>, - loading: false, - error: null, - refresh: vi.fn(), -}; - -const catalogueMock = { - groups: [], - facets: [], - loading: false, - registryOffline: false, - refresh: vi.fn(), -}; -const settingsMock = { - settings: {}, - updateSetting: vi.fn<(k: string, v: unknown) => Promise>().mockResolvedValue(undefined), -}; - -vi.mock('@tauri-apps/api/core', () => ({invoke: vi.fn()})); -// The hook talks to the backend through the Tabularis client; forward its -// calls to the `invoke` mock so per-command assertions stay transport-agnostic. -vi.mock('@/hooks/useTabularisClient', async () => { - const {invoke} = await import('@tauri-apps/api/core'); - const client = { - call: (command: string, request: unknown) => - invoke(command, request as Record | undefined), - }; - return {useTabularisClient: () => client}; -}); - -vi.mock('@/hooks/useDatabase', () => ({ - useDatabase: () => databaseMock, -})); -vi.mock('@/hooks/useDrivers', () => ({ - useDrivers: () => driversMock, -})); -vi.mock('@/hooks/useConnectionCatalogue', () => ({ - useConnectionCatalogue: () => catalogueMock, -})); -vi.mock('@/hooks/useSettings', () => ({ - useSettings: () => settingsMock, -})); - -import {useBuiltinDriverMigration} from '@/hooks/useBuiltinDriverMigration'; -import {invoke} from '@tauri-apps/api/core'; - -const builtinConn = (id: string) => ({id, name: id, params: {driver: 'postgres'}}); - -/** Default per-command invoke behavior: the plugin is registered and - * test_connection succeeds. Individual tests override specific commands via - * a custom mockImplementation. */ -const mockInvokeDefault = (cmd: string) => { - if (cmd === 'get_registered_drivers') return Promise.resolve([{id: 'postgresql'}]); - if (cmd === 'get_plugin_startup_errors') return Promise.resolve([]); - return Promise.resolve('ok'); -}; - -const setPluginReady = (ready: boolean) => { - driversMock.installedPlugins = ready ? [{id: 'postgresql'}] : []; - driversMock.allDrivers = ready ? [{id: 'postgresql'}] : []; - settingsMock.settings = ready ? {activeExternalDrivers: ['postgresql']} : {}; -}; - -describe('useBuiltinDriverMigration', () => { - beforeEach(() => { - databaseMock.connections = []; - databaseMock.openConnectionIds = []; - databaseMock.connectionDataMap = {}; - driversMock.installedPlugins = []; - driversMock.allDrivers = []; - catalogueMock.registryOffline = false; - settingsMock.settings = {}; - settingsMock.updateSetting.mockClear(); - settingsMock.updateSetting.mockResolvedValue(undefined); - databaseMock.loadConnections.mockClear(); - databaseMock.connect.mockClear(); - databaseMock.connect.mockResolvedValue(undefined); - databaseMock.disconnect.mockClear(); - // Reset invoke to a permissive default; individual tests override. - vi.mocked(invoke).mockReset(); - vi.mocked(invoke).mockImplementation(mockInvokeDefault); - }); - - describe('builtinId/pluginId', () => { - it('exposes the driver pair it was parameterized with', () => { - // A caller holding only the hook's return value (not the arguments - // used to create it) still needs the pair — e.g. Connections.tsx - // builds a driver-specific issue-report URL from it instead of - // re-hardcoding "postgres"/"postgresql". - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - expect(result.current.builtinId).toBe('postgres'); - expect(result.current.pluginId).toBe('postgresql'); - }); - }); - - describe('banner gating', () => { - it('stays hidden when no connection is on the built-in driver', () => { - setPluginReady(true); - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - expect(result.current.banner).toBeNull(); - expect(result.current.needsMigration).toBe(false); - }); - - it('shows the nudge when a built-in connection exists, plugin is ready, registry reachable', () => { - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - expect(result.current.needsMigration).toBe(true); - expect(result.current.banner?.visible).toBe(true); - expect(result.current.banner?.variant).toBe('nudge'); - }); - - it('stays hidden once dismissed for the connections that triggered it', () => { - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - settingsMock.settings = { - activeExternalDrivers: ['postgresql'], - postgresPluginMigrationBannerDismissed: true, - postgresPluginMigrationBannerDismissedFor: ['c1'], - }; - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - expect(result.current.banner).toBeNull(); - }); - - it('resurfaces when a new built-in connection appears after dismissal', () => { - // Dismissal is the deliberate opt-out, but only for the connections that - // existed at the time — a genuinely new trigger (a second builtin - // connection the user hadn't dismissed for) must resurface the banner, - // the same "did-the-condition-change" gating WhatsNewModal uses. - setPluginReady(true); - databaseMock.connections = [builtinConn('c1'), builtinConn('c2')]; - settingsMock.settings = { - activeExternalDrivers: ['postgresql'], - postgresPluginMigrationBannerDismissed: true, - postgresPluginMigrationBannerDismissedFor: ['c1'], // c2 is new - }; - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - expect(result.current.banner?.visible).toBe(true); - expect(result.current.banner?.variant).toBe('nudge'); - }); - - it('shows the offline variant when the registry is offline, not the nudge', () => { - // The connectivity gate: the nudge can't outrun the install. Even with a - // built-in connection, an offline registry yields the honest "couldn't - // be downloaded" message, never a "Switch to plugin" nudge. - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - catalogueMock.registryOffline = true; - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - expect(result.current.banner?.variant).toBe('offline'); - }); - - it('shows the offline variant when the plugin is not installed/active', () => { - // No point nudging toward a migration that can't succeed without the plugin. - databaseMock.connections = [builtinConn('c1')]; - setPluginReady(false); - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - expect(result.current.banner?.variant).toBe('offline'); - expect(result.current.pluginReady).toBe(false); - }); - }); - - describe('dismissal', () => { - it('persists dismissal and records which connections it applies to', async () => { - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - await act(async () => { - result.current.dismissBanner(); - }); - expect(settingsMock.updateSetting).toHaveBeenCalledWith( - 'postgresPluginMigrationBannerDismissed', - true, - ); - expect(settingsMock.updateSetting).toHaveBeenCalledWith( - 'postgresPluginMigrationBannerDismissedFor', - ['c1'], - ); - }); - }); - - describe('migrateConnection', () => { - it('flips the driver, runs a post-migration test, and records an ok outcome', async () => { - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - - let outcome; - await act(async () => { - outcome = await result.current.migrateConnection('c1'); - }); - - expect(outcome.status).toBe('ok'); - // update_connection was invoked with the flipped driver. - expect(invoke).toHaveBeenCalledWith( - 'update_connection', - expect.objectContaining({ - id: 'c1', - params: expect.objectContaining({driver: 'postgresql'}), - }), - ); - // post-migration test_connection was invoked. - expect(invoke).toHaveBeenCalledWith( - 'test_connection', - expect.objectContaining({request: expect.objectContaining({connection_id: 'c1'})}), - ); - // history record persisted, via the updater-function form (see the - // "bulk migration" describe block below for why: a plain - // `[...settings.driverMigrationHistory, record]` read from a stale - // closure loses earlier records when this runs several times in a - // row against the same pre-loop snapshot). - expect(settingsMock.updateSetting).toHaveBeenCalledWith( - 'driverMigrationHistory', - expect.any(Function), - ); - const updater = settingsMock.updateSetting.mock.calls[0][1] as ( - prev: unknown[] | undefined, - ) => unknown[]; - expect(updater(undefined)).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - connectionId: 'c1', - fromDriver: 'postgres', - toDriver: 'postgresql', - }), - ]), - ); - }); - - it('disconnects an open built-in connection before flipping the driver', async () => { - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - databaseMock.openConnectionIds = ['c1']; - databaseMock.connectionDataMap = {c1: {driver: 'postgres'}}; - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - await act(async () => { - await result.current.migrateConnection('c1'); - }); - expect(databaseMock.disconnect).toHaveBeenCalledWith('c1'); - }); - - it('reopens a connection that was open before migrating, on a successful outcome', async () => { - // The confirm dialog promises "it'll be disconnected and reopened" — - // disconnect alone doesn't fulfill that, connect must actually run. - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - databaseMock.openConnectionIds = ['c1']; - databaseMock.connectionDataMap = {c1: {driver: 'postgres'}}; - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - await act(async () => { - await result.current.migrateConnection('c1'); - }); - expect(databaseMock.disconnect).toHaveBeenCalledWith('c1'); - expect(databaseMock.connect).toHaveBeenCalledWith('c1'); - }); - - it('still reopens the connection when the post-migration test fails', async () => { - // A failed test_connection means the outcome status is "connection", not - // "ok" — but the connection was still disconnected to run the flip, so - // it must still be reopened (reopening surfaces its own error via - // connectionDataMap, independent of the migration outcome). - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - databaseMock.openConnectionIds = ['c1']; - databaseMock.connectionDataMap = {c1: {driver: 'postgres'}}; - vi.mocked(invoke).mockImplementation((cmd: string) => { - if (cmd === 'test_connection') return Promise.reject('connection refused'); - return mockInvokeDefault(cmd); - }); - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - let outcome; - await act(async () => { - outcome = await result.current.migrateConnection('c1'); - }); - expect(outcome.status).toBe('connection'); - expect(databaseMock.connect).toHaveBeenCalledWith('c1'); - }); - - it('does not reconnect a connection that was already closed', async () => { - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - // Not in openConnectionIds — the connection was already closed. - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - await act(async () => { - await result.current.migrateConnection('c1'); - }); - expect(databaseMock.disconnect).not.toHaveBeenCalled(); - expect(databaseMock.connect).not.toHaveBeenCalled(); - }); - - it('resolves the migration outcome even when the reconnect itself fails', async () => { - // A reconnect failure surfaces through connectionDataMap[id].error (the - // existing UI path for a failed connection), not by corrupting the - // migration outcome — the migration itself still succeeded. - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - databaseMock.openConnectionIds = ['c1']; - databaseMock.connectionDataMap = {c1: {driver: 'postgres'}}; - databaseMock.connect.mockRejectedValueOnce(new Error('host unreachable')); - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - let outcome; - await act(async () => { - outcome = await result.current.migrateConnection('c1'); - }); - expect(outcome.status).toBe('ok'); - expect(databaseMock.connect).toHaveBeenCalledWith('c1'); - }); - - it('records a connection-level failure when the post-migration test throws', async () => { - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - // update_connection succeeds, the plugin is registered; only the - // post-migration test_connection fails — for both the plugin and the - // built-in fallback re-test, so this is the "preexisting" case. - vi.mocked(invoke).mockImplementation((cmd: string) => { - if (cmd === 'test_connection') return Promise.reject('connection refused'); - return mockInvokeDefault(cmd); - }); - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - let outcome; - await act(async () => { - outcome = await result.current.migrateConnection('c1'); - }); - expect(outcome.status).toBe('connection'); - expect(outcome.error).toContain('connection refused'); - expect(outcome.preexisting).toBe(true); - // Re-tested with the built-in driver, same connection_id, once the - // plugin test failed. - expect(invoke).toHaveBeenCalledWith( - 'test_connection', - expect.objectContaining({ - request: expect.objectContaining({ - connection_id: 'c1', - params: expect.objectContaining({driver: 'postgres'}), - }), - }), - ); - }); - - it('sets preexisting: false when the built-in driver still connects — a real plugin regression', async () => { - // The plugin test fails but the built-in fallback re-test (same - // connection_id, same host) succeeds — this is a genuine plugin - // problem, not a pre-existing connectivity issue, so the fallback - // must not paper over it. - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - vi.mocked(invoke).mockImplementation( - (cmd: string, args?: {request?: {params?: {driver?: string}}}) => { - if (cmd === 'test_connection') { - const driver = args?.request?.params?.driver; - return driver === 'postgres' - ? Promise.resolve('ok') - : Promise.reject('connection refused'); - } - return mockInvokeDefault(cmd); - }, - ); - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - let outcome; - await act(async () => { - outcome = await result.current.migrateConnection('c1'); - }); - expect(outcome.status).toBe('connection'); - expect(outcome.error).toContain('connection refused'); - expect(outcome.preexisting).toBe(false); - }); - - it('resolves a failed outcome instead of rejecting when update_connection itself throws', async () => { - // e.g. the connection was deleted concurrently and the backend's - // update_connection returns Err("Connection not found"). migrateConnection - // must never reject — a caller looping over many connections would abort - // the batch and never reach setMigrating(false) otherwise. - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - vi.mocked(invoke).mockImplementation((cmd: string) => { - if (cmd === 'update_connection') - return Promise.reject(new Error('Connection not found')); - return mockInvokeDefault(cmd); - }); - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - let outcome; - await act(async () => { - outcome = await result.current.migrateConnection('c1'); - }); - expect(outcome.status).toBe('failed'); - expect(outcome.error).toContain('Connection not found'); - }); - - it('resolves a failed outcome when get_registered_drivers itself throws', async () => { - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - vi.mocked(invoke).mockImplementation((cmd: string) => { - if (cmd === 'get_registered_drivers') return Promise.reject(new Error('IPC error')); - return mockInvokeDefault(cmd); - }); - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - let outcome; - await act(async () => { - outcome = await result.current.migrateConnection('c1'); - }); - expect(outcome.status).toBe('failed'); - expect(outcome.error).toContain('IPC error'); - }); - - it("records a process-level failure when the plugin isn't registered after the flip", async () => { - // The registry never picked up the driver — a plugin startup failure, - // not a connection problem. test_connection must not be attempted. - setPluginReady(true); - databaseMock.connections = [builtinConn('c1')]; - vi.mocked(invoke).mockImplementation((cmd: string) => { - if (cmd === 'get_registered_drivers') return Promise.resolve([]); // plugin absent - if (cmd === 'get_plugin_startup_errors') { - return Promise.resolve([ - {plugin_id: 'postgresql', error: 'no such interpreter'}, - ]); - } - if (cmd === 'test_connection') { - throw new Error( - 'test_connection must not be called when the plugin never started', - ); - } - return mockInvokeDefault(cmd); - }); - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - let outcome; - await act(async () => { - outcome = await result.current.migrateConnection('c1'); - }); - expect(outcome.status).toBe('process'); - expect(outcome.startupError).toBe('no such interpreter'); - expect(outcome.pluginId).toBe('postgresql'); - }); - - it("appends every record when migrateConnection runs several times in a row, like the checklist's bulk loop", async () => { - // Regression for the bulk-migration history-loss bug: MigrationChecklistModal - // calls migrateConnection once per checked connection, sequentially, all - // from the same render — so recordMigration must append onto whatever - // updateSetting's own functional update sees as current, not onto a - // `settings.driverMigrationHistory` value captured once before the loop - // started (that would make every write but the last silently overwrite - // the ones before it). Simulate updateSetting's real behavior — an - // updater function reads the *current* accumulated history — rather - // than the plain mock the other tests use. - setPluginReady(true); - databaseMock.connections = [builtinConn('c1'), builtinConn('c2'), builtinConn('c3')]; - let history: unknown[] = []; - settingsMock.updateSetting.mockImplementation( - (key: string, valueOrUpdater: unknown) => { - if (key === 'driverMigrationHistory' && typeof valueOrUpdater === 'function') { - history = (valueOrUpdater as (prev: unknown[]) => unknown[])(history); - } - return Promise.resolve(); - }, - ); - - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - await act(async () => { - await result.current.migrateConnection('c1'); - await result.current.migrateConnection('c2'); - await result.current.migrateConnection('c3'); - }); - - expect(history).toHaveLength(3); - expect(history).toEqual([ - expect.objectContaining({connectionId: 'c1'}), - expect.objectContaining({connectionId: 'c2'}), - expect.objectContaining({connectionId: 'c3'}), - ]); - }); - }); - - describe('undoMigration', () => { - it('flips the driver back to the built-in and resolves ok: true', async () => { - // After a migration, the connection's driver is the plugin; undo reverts. - databaseMock.connections = [{id: 'c1', name: 'c1', params: {driver: 'postgresql'}}]; - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - let outcome; - await act(async () => { - outcome = await result.current.undoMigration('c1'); - }); - expect(invoke).toHaveBeenCalledWith( - 'update_connection', - expect.objectContaining({ - id: 'c1', - params: expect.objectContaining({driver: 'postgres'}), - }), - ); - expect(outcome).toEqual({ok: true}); - }); - - it('resolves ok: false with the error instead of rejecting when update_connection throws', async () => { - // Same never-reject contract as migrateConnection: the caller (a toast - // action button, no surrounding try/catch) needs a value to check, not - // an unhandled rejection. - databaseMock.connections = [{id: 'c1', name: 'c1', params: {driver: 'postgresql'}}]; - vi.mocked(invoke).mockImplementation((cmd: string) => { - if (cmd === 'update_connection') - return Promise.reject(new Error('Connection not found')); - return mockInvokeDefault(cmd); - }); - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - let outcome; - await act(async () => { - outcome = await result.current.undoMigration('c1'); - }); - expect(outcome.ok).toBe(false); - expect(outcome.error).toContain('Connection not found'); - }); - - it('disconnects and reopens a connection that was open (on the plugin id) before undoing', async () => { - databaseMock.connections = [{id: 'c1', name: 'c1', params: {driver: 'postgresql'}}]; - // Undo runs after a completed migration, so the connection is open - // under the plugin id, not the builtin id — the lookup must reflect - // that (the inverse of migrateConnection's [builtinId] lookup). - databaseMock.openConnectionIds = ['c1']; - databaseMock.connectionDataMap = {c1: {driver: 'postgresql'}}; - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - await act(async () => { - await result.current.undoMigration('c1'); - }); - expect(databaseMock.disconnect).toHaveBeenCalledWith('c1'); - expect(databaseMock.connect).toHaveBeenCalledWith('c1'); - }); - - it('still disconnects/reconnects when called from a closure captured before the connection was open', async () => { - // Regression: Connections.tsx's outcome toast builds its "Undo" action - // (which closes over whichever undoMigration reference the hook - // returned) at the moment migrateConnection is *called* — before the - // driver flip, disconnect, and reconnect that migrateConnection itself - // performs have run. If undoMigration read connectionDataMap through - // its own useCallback closure, that closure would be permanently fixed - // to "connection not open under the plugin id yet" from that early - // render, so undo's own [pluginId] lookup would always find nothing — - // wasOpen always false — even though the connection is live and open - // on the plugin by the time the user actually clicks Undo. - databaseMock.connections = [{id: 'c1', name: 'c1', params: {driver: 'postgres'}}]; - databaseMock.openConnectionIds = []; - databaseMock.connectionDataMap = {}; - const {result, rerender} = renderHook(() => - useBuiltinDriverMigration('postgres', 'postgresql'), - ); - const staleUndoMigration = result.current.undoMigration; - - // Simulate the migration completing: driver flips, connection reopens - // under the plugin id, and the provider re-renders with fresh state — - // exactly what happens between the toast being built and the user - // clicking its Undo action. - databaseMock.connections = [{id: 'c1', name: 'c1', params: {driver: 'postgresql'}}]; - databaseMock.openConnectionIds = ['c1']; - databaseMock.connectionDataMap = {c1: {driver: 'postgresql'}}; - rerender(); - - await act(async () => { - await staleUndoMigration('c1'); - }); - - expect(databaseMock.disconnect).toHaveBeenCalledWith('c1'); - expect(databaseMock.connect).toHaveBeenCalledWith('c1'); - }); - - it('does not disconnect/reconnect a connection that was already closed', async () => { - databaseMock.connections = [{id: 'c1', name: 'c1', params: {driver: 'postgresql'}}]; - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - await act(async () => { - await result.current.undoMigration('c1'); - }); - expect(databaseMock.disconnect).not.toHaveBeenCalled(); - expect(databaseMock.connect).not.toHaveBeenCalled(); - }); - - it('resolves ok: true even when the reconnect itself fails', async () => { - databaseMock.connections = [{id: 'c1', name: 'c1', params: {driver: 'postgresql'}}]; - databaseMock.openConnectionIds = ['c1']; - databaseMock.connectionDataMap = {c1: {driver: 'postgresql'}}; - databaseMock.connect.mockRejectedValueOnce(new Error('host unreachable')); - const {result} = renderHook(() => useBuiltinDriverMigration('postgres', 'postgresql')); - let outcome; - await act(async () => { - outcome = await result.current.undoMigration('c1'); - }); - expect(outcome).toEqual({ok: true}); - expect(databaseMock.connect).toHaveBeenCalledWith('c1'); - }); - }); -}); diff --git a/packages/web-ui/tests/hooks/useSqlDiagnosticsOptions.test.ts b/packages/web-ui/tests/hooks/useSqlDiagnosticsOptions.test.ts index b87966702..25da0a59d 100644 --- a/packages/web-ui/tests/hooks/useSqlDiagnosticsOptions.test.ts +++ b/packages/web-ui/tests/hooks/useSqlDiagnosticsOptions.test.ts @@ -26,6 +26,7 @@ const capabilities = { folder_based: false, single_database: false, no_connection_required: false, + sql_dialect: 'postgres', }; const settingsWrapperFor = (overrides: Partial) => @@ -78,7 +79,10 @@ describe('useSqlDiagnosticsOptions', () => { }); it('is off for drivers other than PostgreSQL', () => { - mockDatabase({activeDriver: 'mysql'}); + mockDatabase({ + activeDriver: 'mysql', + activeCapabilities: {...capabilities, sql_dialect: 'mysql'}, + }); const {result} = renderHook(() => useSqlDiagnosticsOptions('conn-1'), { wrapper: settingsWrapperFor({sqlDiagnosticsEnabled: true}), }); diff --git a/packages/web-ui/tests/pages/Connections.test.tsx b/packages/web-ui/tests/pages/Connections.test.tsx index 0f4fabdf2..f61030ff6 100644 --- a/packages/web-ui/tests/pages/Connections.test.tsx +++ b/packages/web-ui/tests/pages/Connections.test.tsx @@ -133,24 +133,6 @@ vi.mock('@/hooks/useCreateSqliteDatabase', () => ({ }), })); -// The migration banner hook pulls in useConnectionCatalogue and others the -// SQLite-creation tests don't otherwise need. Mock it to a hidden-banner -// no-op so the tests stay focused on the SQLite action. -vi.mock('@/hooks/useBuiltinDriverMigration', () => ({ - useBuiltinPostgresMigration: () => ({ - builtinId: 'postgres', - pluginId: 'postgresql', - builtinConnections: [], - needsMigration: false, - pluginReady: false, - registryOffline: false, - banner: null, - dismissBanner: vi.fn(), - migrateConnection: vi.fn(), - undoMigration: vi.fn(), - }), -})); - // Connections.tsx also calls useConnectionCatalogue directly (for the // migration outcome toast's repo_url lookup) — mock it the same way. vi.mock('@/hooks/useConnectionCatalogue', () => ({ diff --git a/packages/web-ui/tests/plugins/pluginIsolationAcceptance.test.ts b/packages/web-ui/tests/plugins/pluginIsolationAcceptance.test.ts index 627089241..2d9b52d31 100644 --- a/packages/web-ui/tests/plugins/pluginIsolationAcceptance.test.ts +++ b/packages/web-ui/tests/plugins/pluginIsolationAcceptance.test.ts @@ -125,7 +125,6 @@ describe('plugin isolation acceptance contract', () => { expect(projectFile('src-tauri/src/drivers/sqlite/mod.rs')).toContain( 'PRAGMA query_only = ON', ); - expect(projectFile('src-tauri/src/drivers/postgres/mod.rs')).toContain('BEGIN READ ONLY'); expect(projectFile('src-tauri/src/drivers/mysql/mod.rs')).toContain( 'START TRANSACTION READ ONLY', ); diff --git a/packages/web-ui/tests/utils/connectionStringParser.test.ts b/packages/web-ui/tests/utils/connectionStringParser.test.ts index a3675ed00..5d92afb1f 100644 --- a/packages/web-ui/tests/utils/connectionStringParser.test.ts +++ b/packages/web-ui/tests/utils/connectionStringParser.test.ts @@ -176,14 +176,21 @@ describe('connectionStringParser', () => { } }); - it('should resolve aliases against builtin drivers when no drivers are provided', () => { - const postgresql = parseConnectionString('postgresql://user@host/db'); + it('should resolve aliases against provided drivers when no builtin fallback exists', () => { + // 'postgres' is no longer in BUILTIN_DRIVER_IDS (the built-in driver + // was removed), so the fallback path can't resolve postgres/postgresql. + // Pass CAPABILITY_DRIVERS explicitly — this mirrors how NewConnectionModal + // calls parseConnectionString in production (always passes drivers). + const postgresql = parseConnectionString( + 'postgresql://user@host/db', + CAPABILITY_DRIVERS, + ); expect(postgresql.success).toBe(true); if (postgresql.success) { expect(postgresql.params.driver).toBe('postgres'); } - const mariadb = parseConnectionString('mariadb://user@host/db'); + const mariadb = parseConnectionString('mariadb://user@host/db', CAPABILITY_DRIVERS); expect(mariadb.success).toBe(true); if (mariadb.success) { expect(mariadb.params.driver).toBe('mysql'); @@ -628,8 +635,8 @@ describe('connectionStringParser', () => { expect(protocols).toContain('sqlite3'); }); - it('should include aliases for builtin drivers when no drivers are provided', () => { - const protocols = getSupportedConnectionStringProtocols(); + it('should include aliases for provided drivers', () => { + const protocols = getSupportedConnectionStringProtocols(CAPABILITY_DRIVERS); expect(protocols).toContain('postgresql'); expect(protocols).toContain('mariadb'); }); @@ -881,7 +888,7 @@ describe('connectionStringParser', () => { describe('connection strings with a % that is not an escape', () => { const params = (connectionString: string) => { - const result = parseConnectionString(connectionString); + const result = parseConnectionString(connectionString, CAPABILITY_DRIVERS); if (!result.success) throw new Error(result.error); return result.params; }; diff --git a/packages/web-ui/tests/utils/connections.test.ts b/packages/web-ui/tests/utils/connections.test.ts index 0ba77420c..5784e584b 100644 --- a/packages/web-ui/tests/utils/connections.test.ts +++ b/packages/web-ui/tests/utils/connections.test.ts @@ -144,10 +144,6 @@ describe('connections', () => { }); describe('getDefaultPort', () => { - it('should return correct default port for PostgreSQL', () => { - expect(getDefaultPort('postgres')).toBe(5432); - }); - it('should return correct default port for MySQL', () => { expect(getDefaultPort('mysql')).toBe(3306); }); @@ -157,7 +153,7 @@ describe('connections', () => { }); it('should return 0 for an unrecognized bare driver id (e.g. a plugin id with no manifest resolved)', () => { - expect(getDefaultPort('postgresql')).toBe(0); + expect(getDefaultPort('unknown-driver')).toBe(0); }); it('should read default_port off a PluginManifest for a non-"postgres" plugin id (issue #614)', () => { @@ -380,10 +376,6 @@ describe('connections', () => { }); describe('getDriverLabel', () => { - it('should return human-readable label for PostgreSQL', () => { - expect(getDriverLabel('postgres')).toBe('PostgreSQL'); - }); - it('should return human-readable label for MySQL', () => { expect(getDriverLabel('mysql')).toBe('MySQL'); }); @@ -393,7 +385,7 @@ describe('connections', () => { }); it('should return an all-caps fallback for an unrecognized bare driver id', () => { - expect(getDriverLabel('postgresql')).toBe('POSTGRESQL'); + expect(getDriverLabel('unknown-driver')).toBe('UNKNOWN-DRIVER'); }); it('should read name off a PluginManifest for a non-"postgres" plugin id (issue #614), not the all-caps fallback', () => { @@ -935,27 +927,9 @@ describe('connections', () => { ...overrides, }); - it('returns "to-plugin" when the current driver is deprecated', () => { - const drivers = [ - baseManifest('postgres', { - deprecated: {replacement_id: 'postgresql', removal_date: '2026-10-05'}, - }), - baseManifest('postgresql'), - ]; - expect(migrationDirectionForDriver('postgres', drivers)).toBe('to-plugin'); - }); - - it('returns "to-builtin" when the current driver is the replacement of a deprecated built-in', () => { - const drivers = [ - baseManifest('postgres', { - deprecated: {replacement_id: 'postgresql', removal_date: '2026-10-05'}, - }), - baseManifest('postgresql'), - ]; - expect(migrationDirectionForDriver('postgresql', drivers)).toBe('to-builtin'); - }); - - it('returns null for a driver unrelated to any deprecation', () => { + it('returns null when no migration pairs are wired', () => { + // The postgres:postgresql pair was removed when the built-in driver + // was deleted. With an empty pairs set, no driver triggers migration. const drivers = [ baseManifest('postgres', { deprecated: {replacement_id: 'postgresql', removal_date: '2026-10-05'}, @@ -964,38 +938,10 @@ describe('connections', () => { baseManifest('mysql'), baseManifest('sqlite'), ]; - expect(migrationDirectionForDriver('mysql', drivers)).toBeNull(); - expect(migrationDirectionForDriver('sqlite', drivers)).toBeNull(); - }); - - it('returns null when no driver is deprecated at all', () => { - const drivers = [baseManifest('postgres'), baseManifest('mysql')]; expect(migrationDirectionForDriver('postgres', drivers)).toBeNull(); - }); - - it('returns null for an unknown driver id', () => { - const drivers = [ - baseManifest('postgres', { - deprecated: {replacement_id: 'postgresql', removal_date: '2026-10-05'}, - }), - ]; - expect(migrationDirectionForDriver('sqlite', drivers)).toBeNull(); - }); - - it('returns null for a deprecated driver with no wired migration hook yet', () => { - // A manifest can carry `deprecated` before its migration hook exists - // (e.g. a future mysql deprecation, wired incrementally). The action - // must stay hidden until the UI actually supports that pair — otherwise - // clicking it would fall through to whatever hook happens to be - // instantiated (postgres today), flipping the driver to the wrong plugin. - const drivers = [ - baseManifest('mysql', { - deprecated: {replacement_id: 'mysql-plugin', removal_date: '2027-01-01'}, - }), - baseManifest('mysql-plugin'), - ]; + expect(migrationDirectionForDriver('postgresql', drivers)).toBeNull(); expect(migrationDirectionForDriver('mysql', drivers)).toBeNull(); - expect(migrationDirectionForDriver('mysql-plugin', drivers)).toBeNull(); + expect(migrationDirectionForDriver('sqlite', drivers)).toBeNull(); }); }); diff --git a/packages/web-ui/tests/utils/driverUI.test.tsx b/packages/web-ui/tests/utils/driverUI.test.tsx index 279414838..6cd1cb9d5 100644 --- a/packages/web-ui/tests/utils/driverUI.test.tsx +++ b/packages/web-ui/tests/utils/driverUI.test.tsx @@ -69,9 +69,9 @@ describe('getDriverIcon', () => { expect(img?.getAttribute('src')).toBe(dataUri); }); - it("still renders the built-in Postgres brand icon for the literal string 'postgres'", () => { + it("returns no built-in icon for the literal string 'postgres' (built-in driver removed)", () => { const {getByTestId} = renderIcon('postgres'); - expect(getByTestId('wrap').querySelector('svg')).not.toBeNull(); + expect(getByTestId('wrap').querySelector('svg')).toBeNull(); expect(getByTestId('wrap').querySelector('img')).toBeNull(); }); @@ -144,9 +144,9 @@ describe('getConnectionIcon', () => { expect(img?.getAttribute('src')).toBe('https://example.com/icon.svg'); }); - it('falls back to the Plugin Icon (built-in brand icon) when there is neither a connection override nor a manifest icon URL', () => { + it('returns no built-in icon for the removed postgres driver id when there is neither a connection override nor a manifest icon URL', () => { const {getByTestId} = renderConnectionIcon(connection(undefined), 'postgres'); - expect(getByTestId('wrap').querySelector('svg')).not.toBeNull(); + expect(getByTestId('wrap').querySelector('svg')).toBeNull(); expect(getByTestId('wrap').querySelector('img')).toBeNull(); }); diff --git a/packages/web-ui/tests/utils/findUnsupportedFeatures.test.ts b/packages/web-ui/tests/utils/findUnsupportedFeatures.test.ts deleted file mode 100644 index a45c223b5..000000000 --- a/packages/web-ui/tests/utils/findUnsupportedFeatures.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import {describe, it, expect} from 'vitest'; -import {findUnsupportedFeatures} from '@/utils/findUnsupportedFeatures'; -import type {DriverCapabilities, PluginManifest} from '@/types/plugins'; - -/** Minimal manifest carrying only the capabilities under test. */ -const makeManifest = (caps: Partial): PluginManifest => ({ - id: 'postgresql', - name: 'PostgreSQL', - version: '1.0.0', - description: '', - default_port: 5432, - capabilities: { - schemas: true, - views: true, - routines: false, - file_based: false, - folder_based: false, - identifier_quote: '"', - alter_primary_key: true, - ...caps, - } as DriverCapabilities, -}); - -describe('findUnsupportedFeatures', () => { - describe('flags a capability the plugin declares false', () => { - it('flags a connection using SSL against supports_ssl: false', () => { - const manifest = makeManifest({supports_ssl: false}); - const gaps = findUnsupportedFeatures({ssl_mode: 'verify-ca'}, manifest); - expect(gaps).toHaveLength(1); - expect(gaps[0].feature).toBe('ssl'); - expect(gaps[0].label).toContain('SSL'); - }); - - it('flags a connection using a connection URI against connection_string: false', () => { - const manifest = makeManifest({connection_string: false}); - const gaps = findUnsupportedFeatures({connection_uri: 'postgres://host/db'}, manifest); - expect(gaps).toHaveLength(1); - expect(gaps[0].feature).toBe('connection_uri'); - }); - - it('flags a URI restorable from the keychain even when the field is empty', () => { - // connection_uri_in_keychain marks a URI that's present at runtime. - const manifest = makeManifest({connection_string: false}); - const gaps = findUnsupportedFeatures({connection_uri_in_keychain: true}, manifest); - expect(gaps).toHaveLength(1); - expect(gaps[0].feature).toBe('connection_uri'); - }); - }); - - describe('returns empty for a fully-covered connection', () => { - it('no gaps when SSL and connection strings are both supported', () => { - const manifest = makeManifest({supports_ssl: true, connection_string: true}); - const gaps = findUnsupportedFeatures( - {ssl_mode: 'verify-ca', connection_uri: 'postgres://host/db'}, - manifest, - ); - expect(gaps).toEqual([]); - }); - - it('no gaps when the connection uses neither feature', () => { - const manifest = makeManifest({supports_ssl: false, connection_string: false}); - const gaps = findUnsupportedFeatures({host: 'localhost', port: 5432}, manifest); - expect(gaps).toEqual([]); - }); - - it('does not flag SSL when ssl_mode is blank', () => { - const manifest = makeManifest({supports_ssl: false}); - const gaps = findUnsupportedFeatures({ssl_mode: ' '}, manifest); - expect(gaps).toEqual([]); - }); - - it('treats connection_string as supported by default when omitted (backward-compat default)', () => { - const manifest = makeManifest({connection_string: undefined}); - const gaps = findUnsupportedFeatures({connection_uri: 'postgres://host/db'}, manifest); - expect(gaps).toEqual([]); - }); - - it('accepts the camelCase connectionString alias as supported', () => { - const manifest = makeManifest({connection_string: undefined, connectionString: true}); - const gaps = findUnsupportedFeatures({connection_uri: 'postgres://host/db'}, manifest); - expect(gaps).toEqual([]); - }); - - it('does not flag a decomposable URI-based connection against a plugin with connection_uri: false (e.g. postgresql, same as builtin)', () => { - // connection_uri (verbatim-passthrough) is unrelated to whether the - // plugin accepts a connection string at all (connection_string). - const manifest = makeManifest({connection_string: true, connection_uri: false}); - const gaps = findUnsupportedFeatures({connection_uri_in_keychain: true}, manifest); - expect(gaps).toEqual([]); - }); - }); - - describe('never flags app-level features', () => { - // SSH tunneling, IAM auth, and Kubernetes port-forwarding are app-level - // (test_connection rewrites params.port to the tunnel's local forwarded - // port before the driver sees the connection). They must never appear as - // gaps regardless of the manifest's capabilities. - it('does not flag SSH-tunneling connections', () => { - const manifest = makeManifest({supports_ssl: false, connection_uri: false}); - // ssh_enabled / ssh_connection_id would be on the params, but the - // function doesn't read them — and shouldn't. Confirm by passing an - // otherwise-clean connection. - const gaps = findUnsupportedFeatures({host: 'localhost', port: 5432}, manifest); - expect(gaps).toEqual([]); - }); - - it('does not flag IAM-auth or k8s-forwarding connections', () => { - const manifest = makeManifest({supports_ssl: false, connection_uri: false}); - const gaps = findUnsupportedFeatures({host: 'localhost', port: 5432}, manifest); - expect(gaps).toEqual([]); - }); - }); -}); diff --git a/plugins/PLUGIN_GUIDE.md b/plugins/PLUGIN_GUIDE.md index 5a73c7d8e..5d5cf60f6 100644 --- a/plugins/PLUGIN_GUIDE.md +++ b/plugins/PLUGIN_GUIDE.md @@ -175,6 +175,7 @@ Upgrade the registry before publishing the new format. Add `id` equal to the **e | `manage_tables` | bool | `true` to enable table and column management UI (Create Table, Add/Modify/Drop Column, Drop Table). Does not control index or FK operations. Defaults to `true`. | | `readonly` | bool | When `true`, the driver is read-only: all data modification operations (INSERT, UPDATE, DELETE) are disabled in the UI. The add/delete row buttons, inline cell editing, and context menu edit actions are hidden. Table and column management is also hidden regardless of `manage_tables`. Defaults to `false`. | | `read_only_queries` | bool | Implements the optional database-enforced `execute_read_only_query` RPC, allowing users to enable read-only mode per connection. Defaults to `false`. See [Optional protected read-only queries](#optional-protected-read-only-queries). | +| `table_copy` | bool | Implements the lossless `read_rows`, `insert_records` and `release_session` RPCs, so the host can copy a table row by row to or from this driver. Requires `sql_dialect: "postgres"`. Defaults to `false`. See [Table copy](#table-copy-optional). | | `table_export` | bool | Offers **Export table to SQL...** on table nodes. Defaults to `true`; set `false` for non-SQL plugins. See [Table Export and Import](#table-export-and-import). | | `table_import` | bool | Offers **Import table from SQL...** on database and schema nodes. Defaults to `true`; set `false` for non-SQL plugins. Always off when `readonly` is `true`. | | `explain` | bool | `true` if the driver implements the `explain_query` method (EXPLAIN / query plan support). Enables the Visual EXPLAIN button in the SQL editor and notebook cells; when `false` or omitted, the Visual EXPLAIN UI is hidden for connections using this driver. Defaults to `false`. | diff --git a/plugins/manifest.schema.json b/plugins/manifest.schema.json index 9ed338f05..30e67c259 100644 --- a/plugins/manifest.schema.json +++ b/plugins/manifest.schema.json @@ -471,6 +471,11 @@ "default": false, "description": "Implements execute_read_only_query with database-enforced write protection. Enables optional read-only mode per connection. Errors must never fall back to ordinary execution." }, + "table_copy": { + "type": "boolean", + "default": false, + "description": "Implements the lossless read_rows, insert_records and release_session RPCs, so the host can copy a table row by row to or from this driver. Requires sql_dialect \"postgres\"; the host plans conversions with PostgreSQL type names." + }, "table_export": { "type": "boolean", "default": true, diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 034804530..cb0d18fd4 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -222,12 +222,6 @@ dependencies = [ "password-hash 0.5.0", ] -[[package]] -name = "array-init" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc" - [[package]] name = "arrayvec" version = "0.7.6" @@ -1425,41 +1419,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "deadpool" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b" -dependencies = [ - "deadpool-runtime", - "lazy_static", - "num_cpus", - "tokio", -] - -[[package]] -name = "deadpool-postgres" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d697d376cbfa018c23eb4caab1fd1883dd9c906a8c034e8d9a3cb06a7e0bef9" -dependencies = [ - "async-trait", - "deadpool", - "getrandom 0.2.17", - "tokio", - "tokio-postgres", - "tracing", -] - -[[package]] -name = "deadpool-runtime" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" -dependencies = [ - "tokio", -] - [[package]] name = "deflate64" version = "0.1.11" @@ -1473,23 +1432,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid", - "der_derive", - "flagset", "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.117", -] - [[package]] name = "deranged" version = "0.5.8" @@ -1901,12 +1847,6 @@ dependencies = [ "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 = "fancy-regex" version = "0.13.0" @@ -2011,12 +1951,6 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" -[[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.9" @@ -3904,16 +3838,6 @@ dependencies = [ "libm", ] -[[package]] -name = "num_cpus" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" -dependencies = [ - "hermit-abi", - "libc", -] - [[package]] name = "num_enum" version = "0.7.5" @@ -4141,15 +4065,6 @@ dependencies = [ "objc2-core-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" @@ -4518,16 +4433,6 @@ dependencies = [ "phf_shared 0.12.1", ] -[[package]] -name = "phf" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" -dependencies = [ - "phf_shared 0.13.1", - "serde", -] - [[package]] name = "phf_codegen" version = "0.8.0" @@ -4641,15 +4546,6 @@ dependencies = [ "siphasher 1.0.2", ] -[[package]] -name = "phf_shared" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" -dependencies = [ - "siphasher 1.0.2", -] - [[package]] name = "pin-project-lite" version = "0.2.17" @@ -4782,40 +4678,6 @@ dependencies = [ "universal-hash", ] -[[package]] -name = "postgres-protocol" -version = "0.6.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ee9dd5fe15055d2b6806f4736aa0c9637217074e224bbec46d4041b91bb9491" -dependencies = [ - "base64 0.22.1", - "byteorder", - "bytes", - "fallible-iterator", - "hmac", - "md-5", - "memchr", - "rand 0.9.2", - "sha2", - "stringprep", -] - -[[package]] -name = "postgres-types" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54b858f82211e84682fecd373f68e1ceae642d8d751a1ebd13f33de6257b3e20" -dependencies = [ - "array-init", - "bytes", - "chrono", - "fallible-iterator", - "postgres-protocol", - "serde_core", - "serde_json", - "uuid", -] - [[package]] name = "potential_utf" version = "0.1.4" @@ -5674,7 +5536,6 @@ dependencies = [ "borsh", "bytes", "num-traits", - "postgres-types", "rand 0.8.5", "rkyv", "serde", @@ -5737,15 +5598,6 @@ dependencies = [ "security-framework 3.7.0", ] -[[package]] -name = "rustls-pemfile" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" -dependencies = [ - "rustls-pki-types", -] - [[package]] name = "rustls-pki-types" version = "1.14.0" @@ -6487,7 +6339,7 @@ dependencies = [ "thiserror 2.0.18", "tracing", "uuid", - "whoami 1.6.1", + "whoami", ] [[package]] @@ -6527,7 +6379,7 @@ dependencies = [ "thiserror 2.0.18", "tracing", "uuid", - "whoami 1.6.1", + "whoami", ] [[package]] @@ -6729,7 +6581,6 @@ dependencies = [ "chrono-tz", "clap", "csv", - "deadpool-postgres", "directories", "ed25519-dalek", "filetime", @@ -6756,8 +6607,6 @@ dependencies = [ "russh-keys", "rust_decimal", "rustls", - "rustls-pemfile", - "rustls-platform-verifier", "semver", "serde", "serde_json", @@ -6780,8 +6629,6 @@ dependencies = [ "tauri-plugin-webdriver-automation", "tempfile", "tokio", - "tokio-postgres", - "tokio-postgres-rustls", "tokio-tungstenite", "tokio-util", "toon-format", @@ -7489,27 +7336,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" -[[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.117", -] - [[package]] name = "tokio" version = "1.50.0" @@ -7538,47 +7364,6 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "tokio-postgres" -version = "0.7.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcea47c8f71744367793f16c2db1f11cb859d28f436bdb4ca9193eb1f787ee42" -dependencies = [ - "async-trait", - "byteorder", - "bytes", - "fallible-iterator", - "futures-channel", - "futures-util", - "log", - "parking_lot", - "percent-encoding", - "phf 0.13.1", - "pin-project-lite", - "postgres-protocol", - "postgres-types", - "rand 0.9.2", - "socket2", - "tokio", - "tokio-util", - "whoami 2.1.1", -] - -[[package]] -name = "tokio-postgres-rustls" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27d684bad428a0f2481f42241f821db42c54e2dc81d8c00db8536c506b0a0144" -dependencies = [ - "const-oid", - "ring", - "rustls", - "tokio", - "tokio-postgres", - "tokio-rustls", - "x509-cert", -] - [[package]] name = "tokio-rustls" version = "0.26.4" @@ -8208,15 +7993,6 @@ 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.2+wasi-0.2.9" @@ -8241,15 +8017,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" -[[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.114" @@ -8582,20 +8349,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" dependencies = [ "libredox", - "wasite 0.1.0", -] - -[[package]] -name = "whoami" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6a5b12f9df4f978d2cfdb1bd3bac52433f44393342d7ee9c25f5a1c14c0f45d" -dependencies = [ - "libc", - "libredox", - "objc2-system-configuration", - "wasite 1.0.2", - "web-sys", + "wasite", ] [[package]] @@ -9411,18 +9165,6 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" -[[package]] -name = "x509-cert" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" -dependencies = [ - "const-oid", - "der", - "spki", - "tls_codec", -] - [[package]] name = "xattr" version = "1.6.1" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 1a2a4853f..4e357103c 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -57,7 +57,7 @@ toon-format = { version = "0.5.0", default-features = false } log = { version = "0.4", features = ["std"] } tauri = { version = "2.10.2", features = ["protocol-asset", "devtools"], optional = true } tauri-plugin-log = { version = "2", optional = true } -sqlx = { version = "0.8.6", features = ["runtime-tokio", "sqlite", "mysql", "postgres", "tls-rustls-ring-native-roots", "chrono", "uuid", "rust_decimal", "json"] } +sqlx = { version = "0.8.6", features = ["runtime-tokio", "sqlite", "mysql", "tls-rustls-ring-native-roots", "chrono", "uuid", "rust_decimal", "json"] } tokio = { version = "1.49.0", features = ["full"] } tokio-util = { version = "0.7", features = ["io"] } axum = { version = "0.7.9", features = ["ws"] } @@ -66,7 +66,7 @@ tower-http = { version = "0.6.8", features = ["fs", "limit"] } open = "5.3.3" openssl = { version = "0.10", features = ["vendored"] } uuid = { version = "1.20.0", features = ["v4", "serde"] } -rust_decimal = { version = "1.36", features = ["db-tokio-postgres", "serde"] } +rust_decimal = { version = "1.36", features = ["serde"] } chrono = { version = "0.4.43", features = ["serde"] } chrono-tz = "0.10" tauri-plugin-dialog = { version = "2.6.0", optional = true } @@ -114,8 +114,6 @@ semver = "1" tauri-plugin-clipboard-manager = { version = "2", optional = true } tauri-plugin-deep-link = { version = "2", optional = true } tauri-plugin-single-instance = { version = "2", features = ["deep-link"], optional = true } -tokio-postgres = { version = "0.7.13", features = ["with-chrono-0_4", "with-uuid-1", "with-serde_json-1", "array-impls"] } -deadpool-postgres = "0.14.1" # sqlx uses `tls-rustls-ring-native-roots` for both the MySQL pool and the # SQLite/embedded paths. `tls-native-tls` is intentionally NOT enabled: # macOS Secure Transport (the native-tls backend on Darwin) is deprecated @@ -126,12 +124,8 @@ deadpool-postgres = "0.14.1" # no such restriction. The `ring-native-roots` flavour keeps the OS trust # store active (so non-IAM users who rely on a corporate CA in the macOS # keychain still work) instead of falling back to the bundled `webpki-roots` -# (which would silently ignore those CAs). The PostgreSQL deadpool path -# uses rustls + `rustls-platform-verifier` for the same reason. -tokio-postgres-rustls = "0.13" +# (which would silently ignore those CAs). rustls = { version = "0.23", default-features = false, features = ["ring", "logging", "std", "tls12"] } -rustls-pemfile = "2" -rustls-platform-verifier = "0.6" notify = "6" ulid = "1.2.1" argon2 = "0.5" diff --git a/src-tauri/resources/guest/host.css b/src-tauri/resources/guest/host.css index 27459899b..75ca1a681 100644 --- a/src-tauri/resources/guest/host.css +++ b/src-tauri/resources/guest/host.css @@ -3786,12 +3786,6 @@ color: color-mix(in oklab, var(--color-accent-warning) 90%, transparent); } } - .text-accent\/50 { - color: var(--color-accent); - @supports (color: color-mix(in lab, red, red)) { - color: color-mix(in oklab, var(--color-accent) 50%, transparent); - } - } .text-accent\/70 { color: var(--color-accent); @supports (color: color-mix(in lab, red, red)) { @@ -3804,12 +3798,6 @@ color: color-mix(in oklab, var(--color-accent) 80%, transparent); } } - .text-accent\/90 { - color: var(--color-accent); - @supports (color: color-mix(in lab, red, red)) { - color: color-mix(in oklab, var(--color-accent) 90%, transparent); - } - } .text-base { color: var(--color-base); } diff --git a/src-tauri/src/application/connection_files_tests.rs b/src-tauri/src/application/connection_files_tests.rs index e9b50509f..43b7c8b2c 100644 --- a/src-tauri/src/application/connection_files_tests.rs +++ b/src-tauri/src/application/connection_files_tests.rs @@ -1193,10 +1193,9 @@ async fn apply_export_payload_renames_imported_profile_name_collisions() { name: "PR993".to_string(), username: "deploy".to_string(), }]; - payload.credential_profile_secrets.insert( - "profile-b".to_string(), - "imported-password".to_string(), - ); + payload + .credential_profile_secrets + .insert("profile-b".to_string(), "imported-password".to_string()); payload.connections[0].params.credential_profile_id = Some("profile-b".to_string()); apply_export_payload( diff --git a/src-tauri/src/application/connections.rs b/src-tauri/src/application/connections.rs index 8d8b44f90..55515c100 100644 --- a/src-tauri/src/application/connections.rs +++ b/src-tauri/src/application/connections.rs @@ -558,8 +558,7 @@ pub fn resolve_icon_asset(data_dir: &Path, relative_path: &str) -> Result Result { - let file = - crate::persistence::load_connections_file(&runtime.paths.connections_file())?; + let file = crate::persistence::load_connections_file(&runtime.paths.connections_file())?; #[cfg(test)] connections_file_read_hooks::fire_after_connections_read_hook(); Ok(file) @@ -2449,7 +2448,9 @@ pub async fn set_selected_databases( if databases.iter().any(|db| db.trim().is_empty()) { return Err("Database names cannot be empty".to_string()); } - let driver = find_connection(&load_connections_snapshot(runtime)?, connection_id)?.params.driver; + let driver = find_connection(&load_connections_snapshot(runtime)?, connection_id)? + .params + .driver; let is_schema_based = crate::drivers::registry::get_driver(&driver) .await .map(|driver| driver.manifest().capabilities.schemas) diff --git a/src-tauri/src/application/connections_tests.rs b/src-tauri/src/application/connections_tests.rs index 83d765fc3..cf8dce6c1 100644 --- a/src-tauri/src/application/connections_tests.rs +++ b/src-tauri/src/application/connections_tests.rs @@ -1952,7 +1952,9 @@ fn collect_secret_values_keeps_other_passwords_when_one_profile_read_fails() { }), ); let values = collect_secret_values(&runtime).unwrap(); - assert!(values.iter().any(|value| value == "readable-profile-secret")); + assert!(values + .iter() + .any(|value| value == "readable-profile-secret")); assert!(values.iter().any(|value| value == "connection-secret")); assert!(!values.iter().any(|value| value == "failing-profile-secret")); } @@ -3925,22 +3927,13 @@ fn update_group_racing_profile_delete_does_not_resurrect_the_profile() { "profile-secret".to_string(), ) .unwrap(); - let group = create_group( - &runtime, - &state, - "Projects".to_string(), - None, - ) - .unwrap(); + let group = create_group(&runtime, &state, "Projects".to_string(), None).unwrap(); let group_id = group.id.clone(); let renamed_group_id = group_id.clone(); let writer_runtime = runtime.clone(); let writer_state = Arc::clone(&state); - let (writer_result, delete_result) = run_profile_delete_after_writer_read( - &runtime, - &state, - profile.id.clone(), - move || { + let (writer_result, delete_result) = + run_profile_delete_after_writer_read(&runtime, &state, profile.id.clone(), move || { update_group( &writer_runtime, &writer_state, @@ -3950,8 +3943,7 @@ fn update_group_racing_profile_delete_does_not_resurrect_the_profile() { None, ) .map(|_| ()) - }, - ); + }); assert_writer_and_profile_delete_both_apply( &runtime, &profile.id, @@ -3990,11 +3982,8 @@ fn update_connection_tag_racing_profile_delete_does_not_resurrect_the_profile() let edited_tag_id = tag_id.clone(); let writer_runtime = runtime.clone(); let writer_state = Arc::clone(&state); - let (writer_result, delete_result) = run_profile_delete_after_writer_read( - &runtime, - &state, - profile.id.clone(), - move || { + let (writer_result, delete_result) = + run_profile_delete_after_writer_read(&runtime, &state, profile.id.clone(), move || { update_connection_tag( &writer_runtime, &writer_state, @@ -4002,8 +3991,7 @@ fn update_connection_tag_racing_profile_delete_does_not_resurrect_the_profile() "Staging".to_string(), "#00ff00".to_string(), ) - }, - ); + }); assert_writer_and_profile_delete_both_apply( &runtime, &profile.id, @@ -4046,11 +4034,8 @@ fn set_selected_databases_racing_profile_delete_does_not_resurrect_the_profile() let selected_connection_id = connection_id.clone(); let writer_runtime = runtime.clone(); let writer_state = Arc::clone(&state); - let (writer_result, delete_result) = run_profile_delete_after_writer_read( - &runtime, - &state, - profile.id.clone(), - move || { + let (writer_result, delete_result) = + run_profile_delete_after_writer_read(&runtime, &state, profile.id.clone(), move || { tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -4061,8 +4046,7 @@ fn set_selected_databases_racing_profile_delete_does_not_resurrect_the_profile() &connection_id, vec!["analytics".to_string(), "warehouse".to_string()], )) - }, - ); + }); assert_writer_and_profile_delete_both_apply( &runtime, &profile.id, @@ -4076,10 +4060,7 @@ fn set_selected_databases_racing_profile_delete_does_not_resurrect_the_profile() .expect("database selection must persist"); assert_eq!( connection.params.database, - DatabaseSelection::Multiple(vec![ - "analytics".to_string(), - "warehouse".to_string() - ]) + DatabaseSelection::Multiple(vec!["analytics".to_string(), "warehouse".to_string()]) ); }, ); @@ -4110,12 +4091,10 @@ fn delete_connection_racing_profile_delete_does_not_resurrect_the_profile() { let deleted_connection_id = connection_id.clone(); let writer_runtime = runtime.clone(); let writer_state = Arc::clone(&state); - let (writer_result, delete_result) = run_profile_delete_after_writer_read( - &runtime, - &state, - profile.id.clone(), - move || delete_connection(&writer_runtime, &writer_state, &connection_id), - ); + let (writer_result, delete_result) = + run_profile_delete_after_writer_read(&runtime, &state, profile.id.clone(), move || { + delete_connection(&writer_runtime, &writer_state, &connection_id) + }); assert_writer_and_profile_delete_both_apply( &runtime, &profile.id, diff --git a/src-tauri/src/application/database_objects.rs b/src-tauri/src/application/database_objects.rs index 5e6e4e3c7..14101031c 100644 --- a/src-tauri/src/application/database_objects.rs +++ b/src-tauri/src/application/database_objects.rs @@ -1440,7 +1440,7 @@ pub async fn map_inferred_column_types( } else { crate::drivers::registry::get_driver(&driver) .await - .ok_or_else(|| format!("Unsupported driver: {driver}"))? + .ok_or_else(|| crate::drivers::registry::unsupported_driver_message(&driver))? }; Ok(kinds .iter() diff --git a/src-tauri/src/application/database_transfers.rs b/src-tauri/src/application/database_transfers.rs index 30dbeed56..05b2e39ec 100644 --- a/src-tauri/src/application/database_transfers.rs +++ b/src-tauri/src/application/database_transfers.rs @@ -1,14 +1,14 @@ use super::connection_files::GeneratedFile; -use super::table_row_transfers; -use crate::table_transfer::TableTransferRequest; use super::file_transfers::{ClaimedUpload, FileTransferStore}; +use super::table_row_transfers; use crate::commands::{register_abort_handle, unregister_abort_handle, AbortHandleMap}; use crate::drivers::driver_trait::{DatabaseDriver, DatabaseSqlCapabilities}; -use crate::drivers::{mysql, postgres, sqlite}; +use crate::drivers::{mysql, sqlite}; use crate::dump_utils::DumpDialect; use crate::models::{ConnectionParams, Pagination, TableColumn}; -use crate::pool_manager::{get_mysql_pool, get_postgres_pool, get_sqlite_pool}; +use crate::pool_manager::{get_mysql_pool, get_sqlite_pool}; use crate::runtime::RuntimeContext; +use crate::table_transfer::TableTransferRequest; use futures::TryStreamExt; use serde::{Deserialize, Serialize}; use sqlx::Row; @@ -232,7 +232,7 @@ pub async fn execute( Ok(serde_json::Value::Null) } DatabaseTransferCommand::GetTableTransferCapabilities => { - json(table_row_transfers::get_capabilities()) + json(table_row_transfers::get_capabilities().await) } DatabaseTransferCommand::PlanTableTransfer { request } => { json(table_row_transfers::plan(runtime, session_id, request).await?) @@ -931,34 +931,6 @@ where yield_every_rows(&mut streamed).await; } } - "postgres" => { - let pool = get_postgres_pool(params).await?; - let client = pool.get().await.map_err(|error| error.to_string())?; - let query_params: Vec = Vec::new(); - let mut rows = std::pin::pin!(client - .query_raw(query, &query_params) - .await - .map_err(|error| error.to_string())?); - let mut columns: Option> = None; - let mut streamed = 0u64; - while let Some(row) = rows.try_next().await.map_err(|error| error.to_string())? { - let names = columns.get_or_insert_with(|| { - row.columns().iter().map(|c| c.name().to_string()).collect() - }); - let cells = (0..row.columns().len()) - .map(|index| { - let column_type = row.columns()[index].type_(); - SqlCell { - value: postgres::extract::extract_value(&row, index, None), - is_json: *column_type == tokio_postgres::types::Type::JSON - || *column_type == tokio_postgres::types::Type::JSONB, - } - }) - .collect::>(); - on_row(names, cells)?; - yield_every_rows(&mut streamed).await; - } - } "sqlite" => { use sqlx::Column; let pool = get_sqlite_pool(params).await?; @@ -1209,39 +1181,6 @@ async fn execute_import( tx.commit().await.map_err(|error| error.to_string())?; emit_import_complete(runtime, session_id, connection_id, executed); } - "postgres" => { - let pool = get_postgres_pool(params).await?; - let mut client = pool.get().await.map_err(|error| error.to_string())?; - let tx = client - .transaction() - .await - .map_err(|error| error.to_string())?; - tx.execute( - &format!( - "SET search_path TO \"{}\"", - schema.unwrap_or("public").replace('"', "\"\"") - ), - &[], - ) - .await - .map_err(|error| error.to_string())?; - tx.execute("SET CONSTRAINTS ALL DEFERRED", &[]) - .await - .map_err(|error| error.to_string())?; - tx.execute("SET LOCAL synchronous_commit=OFF", &[]) - .await - .map_err(|error| error.to_string())?; - let mut executed = 0; - while let Some(statement) = stream.next_statement()? { - tx.execute(&statement, &[]) - .await - .map_err(|error| statement_error(executed, error, &statement))?; - executed += 1; - emit_import_interval(runtime, session_id, connection_id, executed); - } - tx.commit().await.map_err(|error| error.to_string())?; - emit_import_complete(runtime, session_id, connection_id, executed); - } "sqlite" => { let pool = get_sqlite_pool(params).await?; let mut tx = pool.begin().await.map_err(|error| error.to_string())?; diff --git a/src-tauri/src/application/database_transfers_tests.rs b/src-tauri/src/application/database_transfers_tests.rs index 24fa2ae3a..1cdf7ab8a 100644 --- a/src-tauri/src/application/database_transfers_tests.rs +++ b/src-tauri/src/application/database_transfers_tests.rs @@ -603,8 +603,11 @@ async fn session_cleanup_only_aborts_jobs_owned_by_that_session() { } fn postgres_dialect() -> DumpDialect { - let pg = crate::drivers::postgres::PostgresDriver::new(); - DumpDialect::from_capabilities("postgres", &pg.manifest().capabilities) + let caps = crate::drivers::driver_trait::DriverCapabilities { + sql_dialect: Some(crate::drivers::driver_trait::SqlDialect::Postgres), + ..Default::default() + }; + DumpDialect::from_capabilities("postgresql", &caps) } fn column(name: &str, data_type: &str) -> TableColumn { diff --git a/src-tauri/src/application/metadata.rs b/src-tauri/src/application/metadata.rs index 06be56a52..4423a255c 100644 --- a/src-tauri/src/application/metadata.rs +++ b/src-tauri/src/application/metadata.rs @@ -338,7 +338,7 @@ pub async fn get_connection_metadata( crate::application::connections::saved_connection_driver(runtime, connection_id)?; let driver = crate::drivers::registry::get_driver(&driver_id) .await - .ok_or_else(|| format!("Unsupported driver: {driver_id}"))?; + .ok_or_else(|| crate::drivers::registry::unsupported_driver_message(&driver_id))?; if !driver.has_connection_metadata() { return Ok(None); } diff --git a/src-tauri/src/application/mod.rs b/src-tauri/src/application/mod.rs index 4bb1995fe..60b126c42 100644 --- a/src-tauri/src/application/mod.rs +++ b/src-tauri/src/application/mod.rs @@ -10,17 +10,17 @@ pub mod dml_preview; pub mod file_transfers; pub mod generic_exports; pub mod host_settings; -pub mod managed_policy; pub mod linked_folder_git; pub mod linked_folder_search; pub mod linked_folders; +pub mod managed_policy; pub mod mcp_host; pub mod metadata; pub mod notebooks; pub mod operations; pub mod persistence; -pub mod plugin_assets; pub mod plugin_accounts; +pub mod plugin_assets; pub mod plugin_extensions; pub mod plugins; pub mod productivity; @@ -30,10 +30,10 @@ pub mod queries; pub mod query_sessions; pub mod read_only; pub mod records; -pub mod table_row_transfers; pub mod routine_debug; pub mod schema_notes; pub mod secret_redaction; +pub mod table_row_transfers; pub mod table_transfers; pub mod themes; pub mod tunnels; diff --git a/src-tauri/src/application/queries.rs b/src-tauri/src/application/queries.rs index d7159a0e5..8ef2daed3 100644 --- a/src-tauri/src/application/queries.rs +++ b/src-tauri/src/application/queries.rs @@ -423,7 +423,7 @@ pub async fn execute_plugin_read_only_query( } match params.driver.as_str() { - "sqlite" | "postgres" | "mysql" | "mariadb" => { + "sqlite" | "postgresql" | "mysql" | "mariadb" => { execute_bounded_plugin_query(driver.as_ref(), ¶ms, &query, schema.as_deref()).await } _ => Err("This driver does not support sandboxed read-only queries".to_string()), diff --git a/src-tauri/src/application/table_row_transfers.rs b/src-tauri/src/application/table_row_transfers.rs index fe18c592b..d7776801e 100644 --- a/src-tauri/src/application/table_row_transfers.rs +++ b/src-tauri/src/application/table_row_transfers.rs @@ -1,22 +1,24 @@ //! Direct table-to-table row transfer between two saved connections. //! -//! First milestone: PostgreSQL source into a PostgreSQL or SQLite target, -//! append-only, into tables that already exist. Plugin drivers are not -//! supported; `get_table_transfer_capabilities` publishes the pairs that are. +//! Append-only row-by-row copy into tables that already exist. SQLite is read +//! and written directly; a PostgreSQL-dialect plugin that declares +//! `table_copy` is read and written through its `read_rows` and +//! `insert_records` RPCs. -mod postgres; +mod plugin; mod sqlite; use super::database_transfers::{emit_progress, DumpCancellationState}; use crate::drivers::driver_trait::DatabaseDriver; use crate::models::{ConnectionParams, DatabaseSelection}; -use crate::pool_manager::{get_postgres_pool, get_sqlite_pool}; +use crate::pool_manager::get_sqlite_pool; use crate::runtime::RuntimeContext; +use crate::table_transfer::dialect_for_manifest; use crate::table_transfer::{ - apply_conversion, build_table_plan, capabilities, dialect_for_driver, ensure_supported_pair, - ColumnBinding, ConflictMode, PlanInputs, PlanIssue, PlannedTable, TableTransferCapabilities, - TableSelection, TableTransferRequest, TablePlan, TransferDialect, TransferValue, DEFAULT_BATCH_ROWS, - MAX_BATCH_ROWS, + apply_conversion, build_table_plan, capabilities, ensure_supported_pair, ColumnBinding, + ConflictMode, PlanInputs, PlanIssue, PlannedTable, TablePlan, TableSelection, + TableTransferCapabilities, TableTransferRequest, TransferDialect, TransferValue, + DEFAULT_BATCH_ROWS, MAX_BATCH_ROWS, }; use serde::Serialize; use std::sync::atomic::{AtomicBool, Ordering}; @@ -24,10 +26,6 @@ use std::sync::Arc; use uuid::Uuid; pub const TABLE_TRANSFER_PROGRESS_EVENT: &str = "table_transfer_progress"; -const CURSOR_NAME: &str = "tabularis_transfer"; -const SOURCE_SESSION_SETUP: &str = "SET LOCAL TimeZone TO 'UTC'; \ - SET LOCAL DateStyle TO 'ISO, MDY'; \ - SET LOCAL extra_float_digits TO 3"; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] @@ -105,8 +103,8 @@ impl Resolved { } } -pub fn get_capabilities() -> TableTransferCapabilities { - capabilities() +pub async fn get_capabilities() -> TableTransferCapabilities { + capabilities(&crate::drivers::registry::list_drivers().await) } fn non_empty(value: Option<&String>) -> Option<&str> { @@ -122,17 +120,23 @@ async fn resolve_endpoint( ) -> Result { let (driver, mut params) = super::connections::resolve_saved_connection_params(runtime, session_id, connection_id)?; - let dialect = dialect_for_driver(&driver) - .ok_or_else(|| format!("Table transfer does not support the {driver} driver"))?; if let Some(database) = non_empty(database) { params.database = DatabaseSelection::Single(database.to_string()); } let drv = crate::drivers::registry::get_connection_driver(¶ms).await?; + let dialect = dialect_for_manifest(drv.manifest()) + .ok_or_else(|| format!("Table transfer does not support the {driver} driver"))?; let schema = match dialect { TransferDialect::Postgres => non_empty(schema).unwrap_or("public").to_string(), TransferDialect::Sqlite => String::new(), }; - Ok(Endpoint { driver, dialect, params, schema, drv }) + Ok(Endpoint { + driver, + dialect, + params, + schema, + drv, + }) } impl Endpoint { @@ -141,22 +145,14 @@ impl Endpoint { } } -fn is_loopback(host: &str) -> bool { - matches!(host, "localhost" | "127.0.0.1" | "::1" | "[::1]") -} - fn same_host(a: Option<&str>, b: Option<&str>) -> bool { let a = a.unwrap_or("localhost").trim().to_ascii_lowercase(); let b = b.unwrap_or("localhost").trim().to_ascii_lowercase(); a == b || (is_loopback(&a) && is_loopback(&b)) } -fn effective_ssh_user(params: &ConnectionParams) -> Option<&str> { - params - .ssh_user - .as_deref() - .map(str::trim) - .filter(|user| !user.is_empty()) +fn is_loopback(host: &str) -> bool { + matches!(host, "localhost" | "127.0.0.1" | "::1" | "[::1]") } fn same_ssh_route(a: &ConnectionParams, b: &ConnectionParams) -> bool { @@ -168,7 +164,7 @@ fn same_ssh_route(a: &ConnectionParams, b: &ConnectionParams) -> bool { return false; } match (&a.ssh_connection_id, &b.ssh_connection_id) { - (Some(x), Some(y)) => x == y && effective_ssh_user(a) == effective_ssh_user(b), + (Some(x), Some(y)) => x == y, (None, None) => { a.ssh_host == b.ssh_host && a.ssh_port == b.ssh_port && a.ssh_user == b.ssh_user } @@ -178,21 +174,27 @@ fn same_ssh_route(a: &ConnectionParams, b: &ConnectionParams) -> bool { /// True when two resolved connections reach the same database. Saved /// connections are aliases: a different connection id says nothing about -/// whether the data lives in the same place. A tunnel that cannot be proven -/// identical counts as a different route, so only a provable match blocks. -fn reaches_same_database(a: &ConnectionParams, b: &ConnectionParams) -> bool { +/// whether the data lives in the same place. A route that cannot be proven +/// identical counts as a different one, so only a provable match blocks; the +/// server's own identity settles the rest. +fn reaches_same_database( + a: &ConnectionParams, + b: &ConnectionParams, + dialect: TransferDialect, +) -> bool { if a.driver != b.driver { return false; } - match dialect_for_driver(&a.driver) { - Some(TransferDialect::Sqlite) => same_file(a.database.primary(), b.database.primary()), - Some(TransferDialect::Postgres) => { - a.database.primary() == b.database.primary() + match dialect { + TransferDialect::Sqlite => same_file(a.database.primary(), b.database.primary()), + TransferDialect::Postgres => { + a.unix_socket_path().is_none() + && b.unix_socket_path().is_none() + && a.database.primary() == b.database.primary() && same_host(a.host.as_deref(), b.host.as_deref()) && a.port.unwrap_or(5432) == b.port.unwrap_or(5432) && same_ssh_route(a, b) } - None => false, } } @@ -206,64 +208,6 @@ fn same_file(a: &str, b: &str) -> bool { } } -/// What the server says about itself. Host names are only labels: `localhost.`, -/// `127.0.0.1` and a DNS alias can all name one server, so the server's own -/// answer decides when the names do not already prove it. -#[derive(Clone, Debug, PartialEq, Eq)] -struct ServerIdentity { - /// `pg_control_system().system_identifier`: unique per cluster, and the - /// same whatever address or tunnel reached it. Not every role may read it. - system_id: Option, - /// The server-side address and port of the session (NULL on a unix socket). - address: Option<(String, i32)>, - database: String, -} - -/// Some(true) when both identities are the same database, Some(false) when -/// they provably differ, None when they cannot be told apart. -fn compare_identities(a: &ServerIdentity, b: &ServerIdentity) -> Option { - if a.database != b.database { - return Some(false); - } - match (&a.system_id, &b.system_id) { - (Some(x), Some(y)) => return Some(x == y), - (None, None) => {} - // One side is unreadable: the other cannot settle it. - _ => return None, - } - match (&a.address, &b.address) { - // Other differing addresses may still be one server (IPv4 vs IPv6). - (Some((x, xp)), Some((y, yp))) if xp == yp && (x == y || (is_loopback(x) && is_loopback(y))) => { - Some(true) - } - _ => None, - } -} - -async fn probe_identity(params: &ConnectionParams) -> Option { - let pool = get_postgres_pool(params).await.ok()?; - let client = pool.get().await.ok()?; - let row = client - .query_one( - "SELECT current_database()::text, host(inet_server_addr()), inet_server_port()", - &[], - ) - .await - .ok()?; - let database: String = row.try_get(0).ok()?; - let host: Option = row.try_get(1).ok()?; - let port: Option = row.try_get(2).ok()?; - // Outside a transaction a refused read leaves the session usable. - let system_id = match client - .query_opt("SELECT system_identifier::text FROM pg_control_system()", &[]) - .await - { - Ok(Some(row)) => row.try_get::<_, String>(0).ok(), - _ => None, - }; - Some(ServerIdentity { system_id, address: host.zip(port), database }) -} - #[derive(Debug, PartialEq, Eq)] enum SameTable { Yes, @@ -273,16 +217,28 @@ enum SameTable { Unverified, } +/// SQLite folds ASCII case in table names; PostgreSQL keeps quoted names exact. +fn table_names_match(dialect: TransferDialect, a: &str, b: &str) -> bool { + match dialect { + TransferDialect::Sqlite => a.eq_ignore_ascii_case(b), + TransferDialect::Postgres => a == b, + } +} + /// Decides whether the transfer would write a table into itself, whichever /// saved connections the two endpoints came from. async fn same_table(source: &Endpoint, target: &Endpoint, selection: &TableSelection) -> SameTable { if source.schema != target.schema - || selection.source_table != selection.target_table + || !table_names_match( + source.dialect, + &selection.source_table, + &selection.target_table, + ) || source.params.driver != target.params.driver { return SameTable::No; } - if reaches_same_database(&source.params, &target.params) { + if reaches_same_database(&source.params, &target.params, source.dialect) { return SameTable::Yes; } if source.dialect != TransferDialect::Postgres @@ -290,9 +246,12 @@ async fn same_table(source: &Endpoint, target: &Endpoint, selection: &TableSelec { return SameTable::No; } - let (a, b) = tokio::join!(probe_identity(&source.params), probe_identity(&target.params)); + let (a, b) = tokio::join!( + plugin::probe_identity(source.drv.as_ref(), &source.params), + plugin::probe_identity(target.drv.as_ref(), &target.params) + ); match (a, b) { - (Some(a), Some(b)) => match compare_identities(&a, &b) { + (Some(a), Some(b)) => match plugin::compare_identities(&a, &b) { Some(true) => SameTable::Yes, Some(false) => SameTable::No, None => SameTable::Unverified, @@ -310,29 +269,60 @@ async fn plan_tables( if target.drv.manifest().capabilities.readonly || target.params.read_only { issues.push(PlanIssue::new("targetReadOnly", None)); } + // SQLite folds ASCII case in table names, so `dst` and `DST` are one table. let mut seen = std::collections::HashSet::new(); let mut tables = Vec::with_capacity(selections.len()); for selection in selections { - if !seen.insert(selection.target_table.as_str()) { - issues.push(PlanIssue::new("duplicateTargetTable", Some(&selection.target_table))); + let key = match target.dialect { + TransferDialect::Sqlite => selection.target_table.to_ascii_lowercase(), + TransferDialect::Postgres => selection.target_table.clone(), + }; + if !seen.insert(key) { + issues.push(PlanIssue::new( + "duplicateTargetTable", + Some(&selection.target_table), + )); } - let source_columns = source + let mut source_columns = source .drv .get_columns(&source.params, &selection.source_table, source.schema_arg()) .await?; - let target_columns = target + let mut target_columns = target .drv .get_columns(&target.params, &selection.target_table, target.schema_arg()) .await?; + for (endpoint, columns, table) in [ + (source, &mut source_columns, &selection.source_table), + (target, &mut target_columns, &selection.target_table), + ] { + if endpoint.dialect == TransferDialect::Postgres { + plugin::enrich_columns( + endpoint.drv.as_ref(), + &endpoint.params, + &endpoint.schema, + table, + columns, + ) + .await; + } + } let verdict = same_table(source, target, selection).await; - let estimated_rows = if source_columns.is_empty() { - None - } else { - let pool = get_postgres_pool(&source.params).await?; - postgres::estimate_rows(&pool, &source.schema, &selection.source_table).await - }; + let estimated_rows = + if source.dialect == TransferDialect::Postgres && !source_columns.is_empty() { + plugin::estimate_rows( + source.drv.as_ref(), + &source.params, + &source.schema, + &selection.source_table, + ) + .await + } else { + None + }; let target_strict = if target.dialect == TransferDialect::Sqlite - && target_columns.iter().any(|c| c.data_type.trim().eq_ignore_ascii_case("ANY")) + && target_columns + .iter() + .any(|c| c.data_type.trim().eq_ignore_ascii_case("ANY")) { let pool = get_sqlite_pool(&target.params).await?; sqlite::is_strict_table(&pool, &selection.target_table).await @@ -349,7 +339,10 @@ async fn plan_tables( same_table: verdict == SameTable::Yes, }); if verdict == SameTable::Unverified { - planned.plan.issues.push(PlanIssue::new("targetIdentityUnverified", None)); + planned + .plan + .issues + .push(PlanIssue::new("targetIdentityUnverified", None)); planned.plan.blocking = true; } tables.push(planned); @@ -381,10 +374,19 @@ async fn resolve( request.target_schema.as_ref(), ) .await?; - ensure_supported_pair(&source.driver, &target.driver)?; + ensure_supported_pair( + &crate::drivers::registry::list_drivers().await, + &source.driver, + &target.driver, + )?; let (tables, issues) = plan_tables(&source, &target, &request.tables).await?; - Ok(Resolved { source, target, tables, issues }) + Ok(Resolved { + source, + target, + tables, + issues, + }) } pub async fn plan( @@ -410,7 +412,10 @@ fn transfer_key(session_id: Option, transfer_id: &str) -> String { pub fn cancel_session_transfers(state: &DumpCancellationState, session_id: Uuid) { let prefix = format!("web:{session_id}:"); - let flags = state.table_transfers.lock().unwrap_or_else(|e| e.into_inner()); + let flags = state + .table_transfers + .lock() + .unwrap_or_else(|e| e.into_inner()); for (key, flag) in flags.iter() { if key.starts_with(&prefix) { flag.store(true, Ordering::SeqCst); @@ -423,7 +428,10 @@ pub fn cancel( session_id: Option, transfer_id: &str, ) -> Result<(), String> { - let flags = state.table_transfers.lock().unwrap_or_else(|e| e.into_inner()); + let flags = state + .table_transfers + .lock() + .unwrap_or_else(|e| e.into_inner()); match flags.get(&transfer_key(session_id, transfer_id)) { Some(flag) => { flag.store(true, Ordering::SeqCst); @@ -444,7 +452,10 @@ struct Registration { impl Drop for Registration { fn drop(&mut self) { self.flag.store(true, Ordering::SeqCst); - self.state.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.key); + self.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&self.key); } } @@ -474,17 +485,26 @@ pub async fn run( let flag = Arc::new(AtomicBool::new(false)); let key = transfer_key(session_id, &transfer_id); { - let mut flags = state.table_transfers.lock().unwrap_or_else(|e| e.into_inner()); + let mut flags = state + .table_transfers + .lock() + .unwrap_or_else(|e| e.into_inner()); if flags.contains_key(&key) { return Err("A table transfer with this id is already running".to_string()); } flags.insert(key.clone(), flag.clone()); } - let _registration = Registration { state: state.table_transfers.clone(), key, flag: flag.clone() }; + let _registration = Registration { + state: state.table_transfers.clone(), + key, + flag: flag.clone(), + }; // The plan is rebuilt here: a client-supplied plan is never trusted. let resolved = resolve(runtime, session_id, &request).await?; if resolved.blocking() { - return Err("The transfer plan has blocking issues. Review the plan before starting".to_string()); + return Err( + "The transfer plan has blocking issues. Review the plan before starting".to_string(), + ); } let job = Job { runtime: runtime.clone(), @@ -494,7 +514,10 @@ pub async fn run( source: resolved.source, target: resolved.target, conflict: request.conflict, - batch_rows: request.batch_rows.unwrap_or(DEFAULT_BATCH_ROWS).clamp(1, MAX_BATCH_ROWS), + batch_rows: request + .batch_rows + .unwrap_or(DEFAULT_BATCH_ROWS) + .clamp(1, MAX_BATCH_ROWS), total_tables: resolved.tables.len(), }; let tables = resolved.tables; @@ -565,7 +588,7 @@ fn emit(job: &Job, index: usize, planned: &PlannedTable, result: &TableTransferT } enum Sink { - Postgres(deadpool_postgres::Object), + Plugin, Sqlite(sqlx::Pool), } @@ -579,8 +602,17 @@ impl Sink { conflict: ConflictMode, ) -> Result<(u64, u64), String> { match self { - Self::Postgres(client) => { - postgres::write_batch(client, &target.schema, table, bindings, rows, conflict).await + Self::Plugin => { + plugin::write_batch( + target.drv.as_ref(), + &target.params, + &target.schema, + table, + bindings, + rows, + conflict, + ) + .await } Self::Sqlite(pool) => sqlite::write_batch(pool, table, bindings, rows, conflict).await, } @@ -589,13 +621,7 @@ impl Sink { async fn open_sink(target: &Endpoint) -> Result { Ok(match target.dialect { - TransferDialect::Postgres => Sink::Postgres( - get_postgres_pool(&target.params) - .await? - .get() - .await - .map_err(|_| "Could not get a target connection".to_string())?, - ), + TransferDialect::Postgres => Sink::Plugin, TransferDialect::Sqlite => Sink::Sqlite(get_sqlite_pool(&target.params).await?), }) } @@ -608,48 +634,166 @@ async fn copy_table( planned: &PlannedTable, result: &mut TableTransferTableResult, ) -> Result { - let bindings = &planned.bindings; - let pool = get_postgres_pool(&job.source.params).await?; - let mut source = pool - .get() - .await - .map_err(|_| "Could not get a source connection".to_string())?; let mut sink = open_sink(&job.target).await?; - let describe = |e: tokio_postgres::Error| postgres::describe_error(&e); - - // A read-only repeatable-read transaction gives one consistent snapshot - // and guarantees the source is never modified. - let tx = source - .build_transaction() - .isolation_level(tokio_postgres::IsolationLevel::RepeatableRead) - .read_only(true) - .start() - .await - .map_err(describe)?; - tx.batch_execute(SOURCE_SESSION_SETUP).await.map_err(describe)?; - let select = postgres::select_sql(&job.source.schema, &planned.plan.source_table, bindings); - tx.batch_execute(&format!("DECLARE {CURSOR_NAME} NO SCROLL CURSOR FOR {select}")) + match job.source.dialect { + TransferDialect::Sqlite => copy_from_sqlite(job, index, planned, result, &mut sink).await, + TransferDialect::Postgres => copy_from_plugin(job, index, planned, result, &mut sink).await, + } +} + +/// Writes one converted batch and accounts for it. `Some` ends the table: the +/// transfer was cancelled before the write. +async fn flush_batch( + job: &Job, + index: usize, + planned: &PlannedTable, + result: &mut TableTransferTableResult, + sink: &mut Sink, + batch: &[Vec], +) -> Result, String> { + result.rows_read += batch.len() as u64; + if job.cancel.load(Ordering::SeqCst) { + return Ok(Some(TransferStatus::Cancelled)); + } + match sink + .write( + &job.target, + &planned.plan.target_table, + &planned.bindings, + batch, + job.conflict, + ) .await - .map_err(describe)?; - let fetch = format!("FETCH FORWARD {} FROM {CURSOR_NAME}", job.batch_rows); + { + Ok((written, skipped)) => { + result.rows_written += written; + result.rows_skipped += skipped; + emit(job, index, planned, result); + Ok(None) + } + Err(error) => { + result.rows_failed = batch.len() as u64; + Err(error) + } + } +} + +async fn copy_from_plugin( + job: &Job, + index: usize, + planned: &PlannedTable, + result: &mut TableTransferTableResult, + sink: &mut Sink, +) -> Result { + let session = format!("tabularis_xfer_{}", Uuid::new_v4().simple()); + let outcome = read_plugin_pages(job, index, planned, result, sink, &session).await; + // Every exit path, including cancel and failure, ends the pinned snapshot. + job.source.drv.release_session(&session).await; + outcome +} + +async fn read_plugin_pages( + job: &Job, + index: usize, + planned: &PlannedTable, + result: &mut TableTransferTableResult, + sink: &mut Sink, + session: &str, +) -> Result { + let select = plugin::select_sql( + &job.source.schema, + &planned.plan.source_table, + &planned.bindings, + ); + let limit = u32::try_from(job.batch_rows).unwrap_or(u32::MAX); + let mut ordinal = 0u64; + let mut page_number = 1u32; + loop { + if job.cancel.load(Ordering::SeqCst) { + return Ok(TransferStatus::Cancelled); + } + let page = job + .source + .drv + .read_rows( + &job.source.params, + &select, + limit, + page_number, + None, + session, + ) + .await + .map_err(|error| plugin::describe_error(&error))?; + plugin::check_page_complete(&page, limit, &job.source.drv.manifest().version)?; + if page.rows.is_empty() { + return Ok(TransferStatus::Completed); + } + let batch = + plugin::convert_page(&page, &planned.bindings, &mut ordinal).inspect_err(|_| { + result.rows_failed = page.rows.len() as u64; + })?; + if let Some(status) = flush_batch(job, index, planned, result, sink, &batch).await? { + return Ok(status); + } + if !page.has_more { + return Ok(TransferStatus::Completed); + } + page_number = page_number.saturating_add(1); + } +} + +async fn copy_from_sqlite( + job: &Job, + index: usize, + planned: &PlannedTable, + result: &mut TableTransferTableResult, + sink: &mut Sink, +) -> Result { + use futures::TryStreamExt; + + let bindings = &planned.bindings; + let pool = get_sqlite_pool(&job.source.params).await?; + + // One read transaction pins a snapshot for the whole copy, and one + // advancing SELECT walks the table once. LIMIT/OFFSET paging would + // re-scan and discard every earlier row on each batch (quadratic). + let mut tx = pool.begin().await.map_err(|e| e.to_string())?; + + let columns: Vec = bindings + .iter() + .map(|b| format!("\"{}\"", b.source_column.replace('"', "\"\""))) + .collect(); + let select = format!( + "SELECT {} FROM \"{}\"", + columns.join(", "), + planned.plan.source_table.replace('"', "\"\"") + ); + let mut stream = sqlx::query(&select).fetch(&mut *tx); let mut ordinal = 0u64; loop { if job.cancel.load(Ordering::SeqCst) { return Ok(TransferStatus::Cancelled); } - let fetched = tx.query(fetch.as_str(), &[]).await.map_err(describe)?; - if fetched.is_empty() { + let mut rows = Vec::with_capacity(job.batch_rows); + while rows.len() < job.batch_rows { + match stream.try_next().await.map_err(|e| e.to_string())? { + Some(row) => rows.push(row), + None => break, + } + } + if rows.is_empty() { return Ok(TransferStatus::Completed); } - let mut batch = Vec::with_capacity(fetched.len()); - for row in &fetched { + let mut batch = Vec::with_capacity(rows.len()); + for row in &rows { ordinal += 1; let mut converted = Vec::with_capacity(bindings.len()); for (position, binding) in bindings.iter().enumerate() { - let value = postgres::read_cell(row, position, binding.source_kind)?; + let value = sqlite_read_cell(row, position, binding.source_kind)?; let value = apply_conversion(&binding.conversion, value).map_err(|error| { - result.rows_failed = fetched.len() as u64; + result.rows_failed = rows.len() as u64; format!( "Source row {ordinal}, column \"{}\" was rejected ({}). Nothing from this batch was written", binding.source_column, @@ -660,24 +804,81 @@ async fn copy_table( } batch.push(converted); } - result.rows_read += batch.len() as u64; - if job.cancel.load(Ordering::SeqCst) { - return Ok(TransferStatus::Cancelled); + if let Some(status) = flush_batch(job, index, planned, result, sink, &batch).await? { + return Ok(status); } - match sink - .write(&job.target, &planned.plan.target_table, bindings, &batch, job.conflict) - .await - { - Ok((written, skipped)) => { - result.rows_written += written; - result.rows_skipped += skipped; - emit(job, index, planned, result); - } - Err(error) => { - result.rows_failed = batch.len() as u64; - return Err(error); - } + } +} + +/// Reads a cell from a SQLite source row by position. +fn sqlite_read_cell( + row: &sqlx::sqlite::SqliteRow, + index: usize, + kind: crate::table_transfer::SourceKind, +) -> Result { + use crate::table_transfer::SourceKind; + use sqlx::Row; + + let wrong = || "A source column returned an unexpected type".to_string(); + match kind { + SourceKind::Bool => { + // SQLite stores booleans as integers (0, 1, 2, …). Preserve the + // raw integer instead of coercing to bool — coercing via `v != 0` + // would turn 2 into 1, a lossy change in a transfer marked "Exact." + let v: Option = row.try_get(index).map_err(|_| wrong())?; + Ok(v.map_or(TransferValue::Null, TransferValue::Int)) + } + SourceKind::Int => { + let v: Option = row.try_get(index).map_err(|_| wrong())?; + Ok(v.map_or(TransferValue::Null, TransferValue::Int)) + } + SourceKind::Float => { + let v: Option = row.try_get(index).map_err(|_| wrong())?; + Ok(v.map_or(TransferValue::Null, TransferValue::Float)) + } + SourceKind::Text => { + let v: Option = row.try_get(index).map_err(|_| wrong())?; + Ok(v.map_or(TransferValue::Null, TransferValue::Text)) } + // A BLOB column has no affinity and can hold any storage class, and a + // NUMERIC column holds integers and reals as well as text. sqlx would + // decode TEXT as bytes and reject non-text as a string, so read these + // by the value's own storage class. + SourceKind::Bytes | SourceKind::Decimal => sqlite_read_stored(row, index), + _ => { + let v: Option = row.try_get(index).map_err(|_| wrong())?; + Ok(v.map_or(TransferValue::Null, TransferValue::Text)) + } + } +} + +/// Reads a cell as whatever SQLite actually stored, keeping its storage +/// class. A declared type only sets an affinity, so the value's own class is +/// the only reliable guide to how it must be decoded and written back. +fn sqlite_read_stored( + row: &sqlx::sqlite::SqliteRow, + index: usize, +) -> Result { + use sqlx::{Row, TypeInfo, ValueRef}; + + let wrong = || "A source column returned an unexpected type".to_string(); + let raw = row.try_get_raw(index).map_err(|_| wrong())?; + if raw.is_null() { + return Ok(TransferValue::Null); + } + let class = raw.type_info().name().to_owned(); + match class.as_str() { + "INTEGER" => Ok(TransferValue::Int(row.try_get(index).map_err(|_| wrong())?)), + "REAL" => Ok(TransferValue::Float( + row.try_get(index).map_err(|_| wrong())?, + )), + "TEXT" => Ok(TransferValue::Text( + row.try_get(index).map_err(|_| wrong())?, + )), + "BLOB" => Ok(TransferValue::Bytes( + row.try_get(index).map_err(|_| wrong())?, + )), + _ => Err(wrong()), } } diff --git a/src-tauri/src/application/table_row_transfers/plugin.rs b/src-tauri/src/application/table_row_transfers/plugin.rs new file mode 100644 index 000000000..8884c37ee --- /dev/null +++ b/src-tauri/src/application/table_row_transfers/plugin.rs @@ -0,0 +1,520 @@ +//! Row transfer through a plugin driver that declares `table_copy`. +//! +//! The plugin reads and writes typed rows over `read_rows` / `insert_records`; +//! this module maps between that JSON and the transfer's [`TransferValue`], and +//! refuses every value the plugin cannot carry exactly, so nothing is written +//! in a changed form. + +use crate::drivers::driver_trait::{CopyRows, DatabaseDriver}; +use crate::models::{ConnectionParams, TableColumn}; +use crate::table_transfer::{ + apply_conversion, ColumnBinding, ConflictMode, Conversion, ConversionRule, Op, OutKind, + PgTarget, SourceKind, TargetType, TransferValue, +}; +use base64::Engine; +use serde_json::{json, Map, Value}; + +pub(super) fn quote(identifier: &str) -> String { + format!("\"{}\"", identifier.replace('"', "\"\"")) +} + +fn literal(text: &str) -> String { + format!("'{}'", text.replace('\'', "''")) +} + +pub(super) fn qualified(schema: &str, table: &str) -> String { + format!("{}.{}", quote(schema), quote(table)) +} + +/// The `SELECT` a copy reads. +pub(super) fn select_sql(schema: &str, table: &str, bindings: &[ColumnBinding]) -> String { + let columns: Vec = bindings + .iter() + .map(|b| { + let name = quote(&b.source_column); + match b.source_kind { + // `read_rows` returns `null` for a float NaN or Infinity and for a + // date or time of `infinity` or `24:00:00`, and re-renders JSON; the + // text form is exact, and `insert_records` accepts it back. + SourceKind::Float + | SourceKind::Json + | SourceKind::Date + | SourceKind::Time + | SourceKind::Timestamp + | SourceKind::TimestampTz => format!("{name}::text"), + _ => name, + } + }) + .collect(); + format!( + "SELECT {} FROM {}", + columns.join(", "), + qualified(schema, table) + ) +} + +const WRONG_TYPE: &str = "A source column returned an unexpected type"; + +fn blob_bytes(text: &str) -> Option> { + let rest = text.strip_prefix("BLOB:")?; + let (_, after_size) = rest.split_once(':')?; + let (_, data) = after_size.split_once(':')?; + base64::engine::general_purpose::STANDARD.decode(data).ok() +} + +fn parse_float(text: &str) -> Option { + match text { + "NaN" => Some(f64::NAN), + "Infinity" => Some(f64::INFINITY), + "-Infinity" => Some(f64::NEG_INFINITY), + _ => text.parse().ok(), + } +} + +/// Reads one cell of a `read_rows` page as the value the source column holds. +pub(super) fn read_cell(cell: &Value, kind: SourceKind) -> Result { + let wrong = || WRONG_TYPE.to_string(); + if cell.is_null() { + return Ok(TransferValue::Null); + } + match kind { + SourceKind::Bool => cell.as_bool().map(TransferValue::Bool).ok_or_else(wrong), + // The plugin sends an integer beyond 2^53 as a string. + SourceKind::Int => match cell { + Value::Number(n) => n.as_i64().map(TransferValue::Int).ok_or_else(wrong), + Value::String(text) => text.parse().map(TransferValue::Int).map_err(|_| wrong()), + _ => Err(wrong()), + }, + SourceKind::Float => cell + .as_str() + .and_then(parse_float) + .map(TransferValue::Float) + .ok_or_else(wrong), + SourceKind::Bytes => cell + .as_str() + .and_then(blob_bytes) + .map(TransferValue::Bytes) + .ok_or_else(wrong), + _ => cell + .as_str() + .map(|text| TransferValue::Text(text.to_string())) + .ok_or_else(wrong), + } +} + +/// Converts one page into target-ready rows, in the order of `bindings`. +pub(super) fn convert_page( + page: &CopyRows, + bindings: &[ColumnBinding], + ordinal: &mut u64, +) -> Result>, String> { + let mut batch = Vec::with_capacity(page.rows.len()); + for row in &page.rows { + *ordinal += 1; + if row.len() != bindings.len() { + return Err(WRONG_TYPE.to_string()); + } + let mut converted = Vec::with_capacity(bindings.len()); + for (cell, binding) in row.iter().zip(bindings) { + let value = read_cell(cell, binding.source_kind)?; + let value = apply_conversion(&binding.conversion, value).map_err(|error| { + format!( + "Source row {ordinal}, column \"{}\" was rejected ({}). Nothing from this batch was written", + binding.source_column, + error.code() + ) + })?; + converted.push(value); + } + batch.push(converted); + } + Ok(batch) +} + +/// First plugin release whose `read_rows` rewinds its cursor correctly after +/// a page cut short by its response size budget. Earlier releases rewind one +/// row too far, so the next page repeats a row +/// (TabularisDB/tabularis-postgresql-plugin#220). Update this to the release +/// that carries the fix. +const PAGING_FIXED_IN: &str = "1.0.0-rc.16"; + +fn paging_is_safe(plugin_version: &str) -> bool { + match ( + semver::Version::parse(plugin_version), + semver::Version::parse(PAGING_FIXED_IN), + ) { + (Ok(have), Ok(fixed)) => have >= fixed, + _ => false, + } +} + +/// A page shorter than requested that still reports `has_more` was cut by the +/// plugin's size budget. On a plugin that miscounts that rewind, continuing +/// would read a row twice, and the copy would write it twice (or fail on its +/// key), so the copy stops before writing the page. +pub(super) fn check_page_complete( + page: &CopyRows, + requested: u32, + plugin_version: &str, +) -> Result<(), String> { + if page.has_more + && (page.rows.len() as u64) < u64::from(requested) + && !paging_is_safe(plugin_version) + { + return Err(format!( + "The plugin cut a page short because of its response size limit, and this plugin \ + release ({plugin_version}) can repeat rows after such a page. Nothing from that \ + page was written. Update the plugin to {PAGING_FIXED_IN} or later" + )); + } + Ok(()) +} + +fn blob_shaped(text: &str) -> bool { + blob_bytes(text).is_some() +} + +/// True when the exact digits of every number in `text` survive being held as +/// an `f64`, the only number the plugin can pass on. +fn numbers_survive(text: &str) -> bool { + let strict = Conversion { + op: Op::DecimalToFloat { + bits: 64, + allow_non_finite: false, + }, + out: OutKind::Float, + rule: ConversionRule::Checked, + }; + let bytes = text.as_bytes(); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'"' => { + i += 1; + while i < bytes.len() && bytes[i] != b'"' { + i += if bytes[i] == b'\\' { 2 } else { 1 }; + } + i += 1; + } + b'-' | b'0'..=b'9' => { + let start = i; + while i < bytes.len() + && matches!(bytes[i], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') + { + i += 1; + } + let token = &text[start..i]; + if apply_conversion(&strict, TransferValue::Text(token.to_string())).is_err() { + return false; + } + } + _ => i += 1, + } + } + true +} + +fn without_whitespace(text: &str) -> String { + let (mut out, mut in_string, mut escaped) = (String::with_capacity(text.len()), false, false); + for c in text.chars() { + if in_string { + out.push(c); + match (escaped, c) { + (true, _) => escaped = false, + (false, '\\') => escaped = true, + (false, '"') => in_string = false, + _ => {} + } + } else if c == '"' { + in_string = true; + out.push(c); + } else if !c.is_whitespace() { + out.push(c); + } + } + out +} + +/// A json/jsonb cell as the value the plugin writes. The plugin parses a JSON +/// string as text and a JSON `null` as SQL NULL, and holds every number as an +/// `f64`, so a cell that depends on any of those is refused. A `json` column +/// keeps its text as written, so it must also survive being re-serialized; +/// `jsonb` normalizes on its own. +fn json_cell(text: &str, keeps_text: bool) -> Result { + let lossy = || "A JSON value cannot be written exactly (lossy)".to_string(); + let value: Value = serde_json::from_str(text).map_err(|_| lossy())?; + if !matches!( + value, + Value::Object(_) | Value::Array(_) | Value::Number(_) | Value::Bool(_) + ) || !numbers_survive(text) + { + return Err(lossy()); + } + if keeps_text + && without_whitespace(text) != serde_json::to_string(&value).map_err(|_| lossy())? + { + return Err(lossy()); + } + Ok(value) +} + +fn cell_json( + value: &TransferValue, + conversion: &Conversion, + target: &TargetType, +) -> Result { + let mismatch = || "A converted value does not match its bound type".to_string(); + Ok(match (conversion.out, value) { + (_, TransferValue::Null) => Value::Null, + (OutKind::Bool, TransferValue::Bool(v)) => Value::Bool(*v), + (OutKind::Int, TransferValue::Int(v)) => json!(v), + (OutKind::Float, TransferValue::Float(v)) => { + if v.is_nan() { + json!("NaN") + } else if v.is_infinite() { + json!(if *v > 0.0 { "Infinity" } else { "-Infinity" }) + } else { + json!(v) + } + } + (OutKind::Text, TransferValue::Text(text)) => match target { + TargetType::Pg(PgTarget::Json) => json_cell(text, true)?, + TargetType::Pg(PgTarget::Jsonb) => json_cell(text, false)?, + // The plugin reads a text value shaped like a blob as bytes. + _ if blob_shaped(text) => { + return Err("A text value looks like a binary value (lossy)".to_string()) + } + _ => Value::String(text.clone()), + }, + (OutKind::Bytes, TransferValue::Bytes(bytes)) => { + Value::String(crate::drivers::common::encode_blob_full(bytes)) + } + _ => return Err(mismatch()), + }) +} + +/// Names a refused cell without echoing its value. +fn rejected(error: &str, ordinal: usize, column: &str) -> String { + format!( + "Target row {ordinal}, column \"{column}\" cannot be written ({error}). Nothing from this batch was written" + ) +} + +/// Builds the rows `insert_records` takes: one object per row, keyed by target +/// column. +pub(super) fn insert_rows( + bindings: &[ColumnBinding], + rows: &[Vec], +) -> Result>, String> { + rows.iter() + .enumerate() + .map(|(index, row)| { + let mut object = Map::with_capacity(bindings.len()); + for (value, binding) in row.iter().zip(bindings) { + let cell = cell_json(value, &binding.conversion, &binding.target_type) + .map_err(|error| rejected(&error, index + 1, &binding.target_column))?; + object.insert(binding.target_column.clone(), cell); + } + Ok(object) + }) + .collect() +} + +/// A plugin error that quotes the value it could not bind would put row data +/// in a progress message; keep only the part that names the problem. +pub(super) fn describe_error(message: &str) -> String { + if message.contains("Cannot bind '") { + "A value could not be bound to its target column type".to_string() + } else { + message.chars().take(500).collect() + } +} + +/// Writes one batch in one plugin transaction. Returns `(written, skipped)`. +pub(super) async fn write_batch( + driver: &dyn DatabaseDriver, + params: &ConnectionParams, + schema: &str, + table: &str, + bindings: &[ColumnBinding], + rows: &[Vec], + conflict: ConflictMode, +) -> Result<(u64, u64), String> { + let records = insert_rows(bindings, rows)?; + let outcome = driver + .insert_records( + params, + table, + Some(schema), + records, + conflict == ConflictMode::Skip, + ) + .await + .map_err(|error| describe_error(&error))?; + Ok((outcome.affected_rows, outcome.skipped)) +} + +/// Fills in what the plugin's `get_columns` leaves out and a copy needs to be +/// exact: the length of a `varchar`, the fractional-second precision of a time +/// or timestamp (a longer text or finer timestamp would be cut or rounded by +/// the server), and whether the server computes a column, which a copy must +/// not write. +pub(super) async fn enrich_columns( + driver: &dyn DatabaseDriver, + params: &ConnectionParams, + schema: &str, + table: &str, + columns: &mut [TableColumn], +) { + if columns.is_empty() { + return; + } + let sql = format!( + "SELECT column_name, character_maximum_length, datetime_precision, \ + (is_generated = 'ALWAYS' OR identity_generation = 'ALWAYS')::text \ + FROM information_schema.columns WHERE table_schema = {} AND table_name = {}", + literal(schema), + literal(table) + ); + let Ok(result) = driver + .execute_query(params, &sql, None, 1, Some(schema)) + .await + else { + return; + }; + let number = |cell: Option<&Value>| match cell { + Some(Value::Number(n)) => n.as_u64(), + Some(Value::String(text)) => text.parse().ok(), + _ => None, + }; + for row in &result.rows { + let Some(name) = row.first().and_then(Value::as_str) else { + continue; + }; + let Some(column) = columns.iter_mut().find(|c| c.name == name) else { + continue; + }; + if let Some(length) = number(row.get(1)) { + column.character_maximum_length = Some(length); + } + if row.get(3).and_then(Value::as_str) == Some("true") { + column.is_generated = true; + } + if let Some(precision) = number(row.get(2)) { + column.full_type = with_precision(&column.data_type, precision); + } + } +} + +/// `timestamp without time zone` → `timestamp(3) without time zone`. +fn with_precision(data_type: &str, precision: u64) -> Option { + let (base, rest) = data_type.split_once(' ')?; + matches!(base, "time" | "timestamp").then(|| format!("{base}({precision}) {rest}")) +} + +pub(super) async fn estimate_rows( + driver: &dyn DatabaseDriver, + params: &ConnectionParams, + schema: &str, + table: &str, +) -> Option { + let sql = format!( + "SELECT c.reltuples::bigint FROM pg_class c \ + JOIN pg_namespace n ON n.oid = c.relnamespace \ + WHERE n.nspname = {} AND c.relname = {}", + literal(schema), + literal(table) + ); + let result = driver + .execute_query(params, &sql, None, 1, None) + .await + .ok()?; + let cell = result.rows.first()?.first()?; + let estimate = match cell { + Value::Number(n) => n.as_i64()?, + Value::String(text) => text.parse().ok()?, + _ => return None, + }; + (estimate >= 0).then_some(estimate) +} + +/// What the server says about itself. Host names are only labels: `localhost.`, +/// `127.0.0.1` and a DNS alias can all name one server, so the server's own +/// answer decides when the names do not already prove it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct ServerIdentity { + /// `pg_control_system().system_identifier`: unique per cluster, and the + /// same whatever address or tunnel reached it. Not every role may read it. + pub system_id: Option, + /// The server-side address and port of the session (NULL on a unix socket). + pub address: Option<(String, i32)>, + pub database: String, +} + +fn is_loopback(host: &str) -> bool { + matches!(host, "localhost" | "127.0.0.1" | "::1" | "[::1]") +} + +/// Some(true) when both identities are the same database, Some(false) when +/// they provably differ, None when they cannot be told apart. +pub(super) fn compare_identities(a: &ServerIdentity, b: &ServerIdentity) -> Option { + if a.database != b.database { + return Some(false); + } + match (&a.system_id, &b.system_id) { + (Some(x), Some(y)) => return Some(x == y), + (None, None) => {} + // One side is unreadable: the other cannot settle it. + _ => return None, + } + match (&a.address, &b.address) { + // Other differing addresses may still be one server (IPv4 vs IPv6). + (Some((x, xp)), Some((y, yp))) + if xp == yp && (x == y || (is_loopback(x) && is_loopback(y))) => + { + Some(true) + } + _ => None, + } +} + +pub(super) async fn probe_identity( + driver: &dyn DatabaseDriver, + params: &ConnectionParams, +) -> Option { + let first = driver + .execute_query( + params, + "SELECT current_database()::text, host(inet_server_addr()), inet_server_port()", + None, + 1, + None, + ) + .await + .ok()?; + let row = first.rows.first()?; + let database = row.first()?.as_str()?.to_string(); + let host = row.get(1).and_then(Value::as_str).map(str::to_string); + let port = row.get(2).and_then(Value::as_i64).map(|p| p as i32); + // A role that may not read the cluster id still gets the address check. + let system_id = driver + .execute_query( + params, + "SELECT system_identifier::text FROM pg_control_system()", + None, + 1, + None, + ) + .await + .ok() + .and_then(|r| r.rows.first()?.first()?.as_str().map(str::to_string)); + Some(ServerIdentity { + system_id, + address: host.zip(port), + database, + }) +} + +#[cfg(test)] +#[path = "plugin_tests.rs"] +mod tests; diff --git a/src-tauri/src/application/table_row_transfers/plugin_tests.rs b/src-tauri/src/application/table_row_transfers/plugin_tests.rs new file mode 100644 index 000000000..c47bd2baf --- /dev/null +++ b/src-tauri/src/application/table_row_transfers/plugin_tests.rs @@ -0,0 +1,324 @@ +use super::*; +use crate::table_transfer::ConversionRule; +use serde_json::json; + +fn binding( + name: &str, + kind: SourceKind, + out: OutKind, + op: Op, + target: TargetType, +) -> ColumnBinding { + ColumnBinding { + source_column: name.into(), + target_column: name.into(), + source_kind: kind, + target_type: target, + conversion: Conversion { + op, + out, + rule: ConversionRule::Exact, + }, + } +} + +fn text_binding(name: &str, kind: SourceKind, target: PgTarget) -> ColumnBinding { + binding(name, kind, OutKind::Text, Op::Copy, TargetType::Pg(target)) +} + +fn page(rows: Vec>, has_more: bool) -> CopyRows { + serde_json::from_value(json!({ + "columns": [{"name": "c", "type": "text"}], + "rows": rows, + "has_more": has_more, + })) + .unwrap() +} + +#[test] +fn select_reads_floats_dates_and_json_as_exact_text() { + let bindings = [ + text_binding("id", SourceKind::Int, PgTarget::Int(64)), + text_binding("f", SourceKind::Float, PgTarget::Float(64)), + text_binding("d", SourceKind::Date, PgTarget::Date), + text_binding("t", SourceKind::Time, PgTarget::Time { precision: None }), + text_binding( + "ts", + SourceKind::Timestamp, + PgTarget::Timestamp { precision: None }, + ), + text_binding( + "tz", + SourceKind::TimestampTz, + PgTarget::TimestampTz { precision: None }, + ), + text_binding("j", SourceKind::Json, PgTarget::Jsonb), + text_binding("b", SourceKind::Bytes, PgTarget::Bytea), + ]; + assert_eq!( + select_sql("My Schema", "Tab\"le", &bindings), + "SELECT \"id\", \"f\"::text, \"d\"::text, \"t\"::text, \"ts\"::text, \"tz\"::text, \ + \"j\"::text, \"b\" FROM \"My Schema\".\"Tab\"\"le\"" + ); +} + +#[test] +fn cells_decode_by_the_source_kind() { + assert_eq!( + read_cell(&json!(true), SourceKind::Bool), + Ok(TransferValue::Bool(true)) + ); + assert_eq!( + read_cell(&json!(7), SourceKind::Int), + Ok(TransferValue::Int(7)) + ); + // The plugin sends an integer beyond 2^53 as a string. + assert_eq!( + read_cell(&json!("9007199254740993"), SourceKind::Int), + Ok(TransferValue::Int(9_007_199_254_740_993)) + ); + assert_eq!( + read_cell(&json!("1.5"), SourceKind::Float), + Ok(TransferValue::Float(1.5)) + ); + match read_cell(&json!("NaN"), SourceKind::Float) { + Ok(TransferValue::Float(v)) => assert!(v.is_nan()), + other => panic!("{other:?}"), + } + assert_eq!( + read_cell(&json!("-Infinity"), SourceKind::Float), + Ok(TransferValue::Float(f64::NEG_INFINITY)) + ); + assert_eq!( + read_cell( + &json!("BLOB:3:application/octet-stream:AAEC"), + SourceKind::Bytes + ), + Ok(TransferValue::Bytes(vec![0, 1, 2])) + ); + assert_eq!( + read_cell(&json!("2024-01-02"), SourceKind::Date), + Ok(TransferValue::Text("2024-01-02".into())) + ); + assert_eq!( + read_cell(&Value::Null, SourceKind::Int), + Ok(TransferValue::Null) + ); + assert!(read_cell(&json!("x"), SourceKind::Int).is_err()); + assert!(read_cell(&json!(1), SourceKind::Bytes).is_err()); +} + +#[test] +fn a_page_row_with_the_wrong_cell_count_is_refused() { + let bindings = [text_binding( + "a", + SourceKind::Text, + PgTarget::Text { max_len: None }, + )]; + let short = page(vec![vec![json!("a"), json!("b")]], false); + assert!(convert_page(&short, &bindings, &mut 0).is_err()); +} + +#[test] +fn a_rejected_value_names_the_row_and_column_but_never_the_value() { + let bindings = [binding( + "n", + SourceKind::Int, + OutKind::Int, + Op::IntRange { + min: -128, + max: 127, + }, + TargetType::Pg(PgTarget::Int(16)), + )]; + let rows = page(vec![vec![json!(1)], vec![json!(99_999_123)]], false); + let error = convert_page(&rows, &bindings, &mut 0).unwrap_err(); + assert!( + error.contains("row 2") && error.contains("\"n\""), + "{error}" + ); + assert!(!error.contains("99999123"), "{error}"); +} + +#[test] +fn floats_travel_as_text_for_non_finite_values() { + let conversion = Conversion { + op: Op::FloatCheck { + bits: 64, + allow_non_finite: true, + }, + out: OutKind::Float, + rule: ConversionRule::Exact, + }; + let target = TargetType::Pg(PgTarget::Float(64)); + for (value, expected) in [ + (f64::NAN, json!("NaN")), + (f64::INFINITY, json!("Infinity")), + (f64::NEG_INFINITY, json!("-Infinity")), + (1.5, json!(1.5)), + ] { + assert_eq!( + cell_json(&TransferValue::Float(value), &conversion, &target), + Ok(expected) + ); + } +} + +fn text_cell(text: &str, target: PgTarget) -> Result { + let conversion = Conversion { + op: Op::Copy, + out: OutKind::Text, + rule: ConversionRule::Exact, + }; + cell_json( + &TransferValue::Text(text.into()), + &conversion, + &TargetType::Pg(target), + ) +} + +#[test] +fn a_text_value_shaped_like_a_blob_is_refused_not_turned_into_bytes() { + let plain = PgTarget::Text { max_len: None }; + assert!(text_cell("BLOB:1:a:Zg==", plain.clone()).is_err()); + assert_eq!( + text_cell("BLOB: not really", plain.clone()), + Ok(json!("BLOB: not really")) + ); + assert_eq!(text_cell("{1,2}", plain), Ok(json!("{1,2}"))); +} + +#[test] +fn json_values_the_plugin_cannot_write_exactly_are_refused() { + for ok in ["{\"a\":1}", "[1,2,3]", "12.5", "true"] { + assert!(text_cell(ok, PgTarget::Jsonb).is_ok(), "{ok}"); + } + // A string would be written as text, and null as SQL NULL. + for bad in ["\"x\"", "null", "{not json"] { + assert!(text_cell(bad, PgTarget::Jsonb).is_err(), "{bad}"); + } + // Numbers pass through an f64. + assert!(text_cell("12345678901234567890123.5", PgTarget::Jsonb).is_err()); + assert!(text_cell( + "{\"a\":[1,{\"b\":12345678901234567890123}]}", + PgTarget::Jsonb + ) + .is_err()); + // A digit run inside a string is not a number. + assert!(text_cell("{\"a\":\"12345678901234567890123\"}", PgTarget::Jsonb).is_ok()); + // `json` keeps its text, so whitespace and key repeats cannot be kept. + assert!(text_cell("{\"a\":1}", PgTarget::Json).is_ok()); + assert!(text_cell("{\"a\": 1}", PgTarget::Json).is_ok()); + assert!(text_cell("{\"a\":1,\"a\":2}", PgTarget::Json).is_err()); + assert!(text_cell("{\"b\":1,\"a\":2}", PgTarget::Json).is_ok()); +} + +#[test] +fn bytes_are_sent_in_the_full_blob_wire_format() { + let conversion = Conversion { + op: Op::Copy, + out: OutKind::Bytes, + rule: ConversionRule::Exact, + }; + let cell = cell_json( + &TransferValue::Bytes(vec![1, 2, 3]), + &conversion, + &TargetType::Pg(PgTarget::Bytea), + ) + .unwrap(); + assert_eq!(blob_bytes(cell.as_str().unwrap()), Some(vec![1, 2, 3])); +} + +#[test] +fn insert_rows_are_keyed_by_target_column_and_name_the_failing_cell() { + let bindings = [ + text_binding("a", SourceKind::Text, PgTarget::Text { max_len: None }), + text_binding("b", SourceKind::Text, PgTarget::Text { max_len: None }), + ]; + let rows = insert_rows( + &bindings, + &[vec![TransferValue::Text("x".into()), TransferValue::Null]], + ) + .unwrap(); + assert_eq!(rows[0].get("a"), Some(&json!("x"))); + assert_eq!(rows[0].get("b"), Some(&Value::Null)); + let error = insert_rows( + &bindings, + &[ + vec![TransferValue::Text("x".into()), TransferValue::Null], + vec![ + TransferValue::Text("BLOB:1:a:Zg==".into()), + TransferValue::Null, + ], + ], + ) + .unwrap_err(); + assert!( + error.contains("row 2") && error.contains("\"a\""), + "{error}" + ); + assert!(!error.contains("Zg=="), "{error}"); +} + +#[test] +fn a_bind_error_that_quotes_the_value_is_not_passed_on() { + assert_eq!( + describe_error("insert_records: Cannot bind 'SECRET' as integer for target type INTEGER"), + "A value could not be bound to its target column type" + ); + assert!(describe_error("duplicate key value violates unique constraint \"pk\"").contains("pk")); +} + +#[test] +fn a_page_cut_short_by_the_size_budget_stops_an_unfixed_plugin() { + let cut = page(vec![vec![json!("a")]], true); + assert!(check_page_complete(&cut, 500, "1.0.0-rc.15").is_err()); + assert!(check_page_complete(&cut, 500, "1.0.0-rc.16").is_ok()); + assert!(check_page_complete(&cut, 500, "not a version").is_err()); + // A full page, or the last page, is never suspect. + let full = page(vec![vec![json!("a")]], true); + assert!(check_page_complete(&full, 1, "1.0.0-rc.15").is_ok()); + assert!(check_page_complete(&page(vec![vec![json!("a")]], false), 500, "1.0.0-rc.15").is_ok()); +} + +#[test] +fn identities_compare_like_they_did_for_the_built_in_driver() { + let id = |system: Option<&str>, address: Option<(&str, i32)>, database: &str| ServerIdentity { + system_id: system.map(str::to_string), + address: address.map(|(h, p)| (h.to_string(), p)), + database: database.to_string(), + }; + let v6 = id(Some("77"), Some(("::1", 54320)), "testdb"); + let v4 = id(Some("77"), Some(("127.0.0.1", 54320)), "testdb"); + assert_eq!(compare_identities(&v6, &v4), Some(true)); + assert_eq!( + compare_identities(&v4, &id(Some("88"), Some(("127.0.0.1", 54320)), "testdb")), + Some(false) + ); + assert_eq!( + compare_identities(&v4, &id(Some("77"), None, "other")), + Some(false) + ); + let a = id(None, Some(("10.0.0.5", 5432)), "app"); + assert_eq!( + compare_identities(&a, &id(None, Some(("10.0.0.6", 5432)), "app")), + None + ); + assert_eq!( + compare_identities(&a, &id(Some("1"), Some(("10.0.0.5", 5432)), "app")), + None + ); +} + +#[test] +fn with_precision_names_the_fractional_second_digits() { + assert_eq!( + with_precision("timestamp without time zone", 3).as_deref(), + Some("timestamp(3) without time zone") + ); + assert_eq!( + with_precision("time with time zone", 0).as_deref(), + Some("time(0) with time zone") + ); + assert_eq!(with_precision("date", 0), None); +} diff --git a/src-tauri/src/application/table_row_transfers/postgres.rs b/src-tauri/src/application/table_row_transfers/postgres.rs deleted file mode 100644 index 3d5e7d7d5..000000000 --- a/src-tauri/src/application/table_row_transfers/postgres.rs +++ /dev/null @@ -1,202 +0,0 @@ - -use crate::table_transfer::{ColumnBinding, ConflictMode, OutKind, SourceKind, TransferValue}; -use tokio_postgres::types::{ToSql, Type}; -use tokio_postgres::Row; - -const MAX_PARAMS: usize = 60_000; - -pub(super) fn quote(identifier: &str) -> String { - format!("\"{}\"", identifier.replace('"', "\"\"")) -} - -pub(super) fn qualified(schema: &str, table: &str) -> String { - format!("{}.{}", quote(schema), quote(table)) -} - -/// Summarises a database error without echoing row data: server messages for -/// data exceptions quote the offending value and `detail` carries key values. -pub(super) fn describe_error(error: &tokio_postgres::Error) -> String { - let Some(db) = error.as_db_error() else { - return "PostgreSQL connection error".to_string(); - }; - let code = db.code().code(); - let label = match code { - "23505" => "unique constraint violation", - "23502" => "not-null constraint violation", - "23503" => "foreign key violation", - "23514" => "check constraint violation", - "23P01" => "exclusion constraint violation", - c if c.starts_with("22") => "value rejected by the column type", - c if c.starts_with("42") => "permission or schema error", - _ => "database error", - }; - let mut text = format!("{label} [SQLSTATE {code}]"); - if let Some(constraint) = db.constraint() { - text.push_str(&format!(" constraint \"{constraint}\"")); - } - if let Some(column) = db.column() { - text.push_str(&format!(" column \"{column}\"")); - } - text -} - -pub(super) fn select_sql(schema: &str, table: &str, bindings: &[ColumnBinding]) -> String { - let columns: Vec = bindings - .iter() - .map(|b| { - let name = quote(&b.source_column); - match b.source_kind { - SourceKind::Bool | SourceKind::Int | SourceKind::Text | SourceKind::Bytes => name, - _ => format!("{name}::text"), - } - }) - .collect(); - format!("SELECT {} FROM {}", columns.join(", "), qualified(schema, table)) -} - -pub(super) fn read_cell(row: &Row, index: usize, kind: SourceKind) -> Result { - let wrong = || "A source column returned an unexpected type".to_string(); - match kind { - SourceKind::Bool => Ok(row - .try_get::<_, Option>(index) - .map_err(|_| wrong())? - .map_or(TransferValue::Null, TransferValue::Bool)), - SourceKind::Int => { - let value = match *row.columns()[index].type_() { - Type::INT2 => row.try_get::<_, Option>(index).map(|v| v.map(i64::from)), - Type::INT4 => row.try_get::<_, Option>(index).map(|v| v.map(i64::from)), - _ => row.try_get::<_, Option>(index), - }; - Ok(value.map_err(|_| wrong())?.map_or(TransferValue::Null, TransferValue::Int)) - } - SourceKind::Bytes => Ok(row - .try_get::<_, Option>>(index) - .map_err(|_| wrong())? - .map_or(TransferValue::Null, TransferValue::Bytes)), - SourceKind::Float => match row.try_get::<_, Option>(index).map_err(|_| wrong())? { - None => Ok(TransferValue::Null), - Some(text) => text - .parse::() - .map(TransferValue::Float) - .map_err(|_| wrong()), - }, - _ => Ok(row - .try_get::<_, Option>(index) - .map_err(|_| wrong())? - .map_or(TransferValue::Null, TransferValue::Text)), - } -} - -type Param = Box; - -fn param(out: OutKind, value: &TransferValue) -> Result { - Ok(match (out, value) { - (OutKind::Bool, TransferValue::Null) => Box::new(None::), - (OutKind::Bool, TransferValue::Bool(v)) => Box::new(*v), - (OutKind::Int, TransferValue::Null) => Box::new(None::), - (OutKind::Int, TransferValue::Int(v)) => Box::new(*v), - (OutKind::Float, TransferValue::Null) => Box::new(None::), - (OutKind::Float, TransferValue::Float(v)) => Box::new(*v), - (OutKind::Text, TransferValue::Null) => Box::new(None::), - (OutKind::Text, TransferValue::Text(v)) => Box::new(v.clone()), - (OutKind::Bytes, TransferValue::Null) => Box::new(None::>), - (OutKind::Bytes, TransferValue::Bytes(v)) => Box::new(v.clone()), - _ => return Err("A converted value does not match its bound type".to_string()), - }) -} - -fn wire_type(out: OutKind) -> Type { - match out { - OutKind::Bool => Type::BOOL, - OutKind::Int => Type::INT8, - OutKind::Float => Type::FLOAT8, - OutKind::Text => Type::TEXT, - OutKind::Bytes => Type::BYTEA, - } -} - -fn cast_type(binding: &ColumnBinding) -> &'static str { - match &binding.target_type { - crate::table_transfer::TargetType::Pg(target) => target.cast_type(), - crate::table_transfer::TargetType::Sqlite(_) => "text", - } -} - -pub(super) fn insert_sql( - schema: &str, - table: &str, - bindings: &[ColumnBinding], - rows: usize, - conflict: ConflictMode, -) -> String { - let columns: Vec = bindings.iter().map(|b| quote(&b.target_column)).collect(); - let mut next = 1; - let tuples: Vec = (0..rows) - .map(|_| { - let cells: Vec = bindings - .iter() - .map(|b| { - let cell = format!("CAST(${next} AS {})", cast_type(b)); - next += 1; - cell - }) - .collect(); - format!("({})", cells.join(", ")) - }) - .collect(); - let mut sql = format!( - "INSERT INTO {} ({}) VALUES {}", - qualified(schema, table), - columns.join(", "), - tuples.join(", ") - ); - if conflict == ConflictMode::Skip { - sql.push_str(" ON CONFLICT DO NOTHING"); - } - sql -} - -/// Writes one batch in its own transaction. Returns `(written, skipped)`. -pub(super) async fn write_batch( - client: &mut deadpool_postgres::Object, - schema: &str, - table: &str, - bindings: &[ColumnBinding], - rows: &[Vec], - conflict: ConflictMode, -) -> Result<(u64, u64), String> { - let per_statement = (MAX_PARAMS / bindings.len().max(1)).max(1); - let tx = client.transaction().await.map_err(|e| describe_error(&e))?; - let mut written = 0u64; - for chunk in rows.chunks(per_statement) { - let sql = insert_sql(schema, table, bindings, chunk.len(), conflict); - let types: Vec = (0..chunk.len()) - .flat_map(|_| bindings.iter().map(|b| wire_type(b.conversion.out))) - .collect(); - let statement = tx.prepare_typed(&sql, &types).await.map_err(|e| describe_error(&e))?; - let mut params: Vec = Vec::with_capacity(types.len()); - for row in chunk { - for (value, binding) in row.iter().zip(bindings) { - params.push(param(binding.conversion.out, value)?); - } - } - let refs: Vec<&(dyn ToSql + Sync)> = params.iter().map(|p| p.as_ref() as &(dyn ToSql + Sync)).collect(); - written += tx.execute(&statement, &refs).await.map_err(|e| describe_error(&e))?; - } - tx.commit().await.map_err(|e| describe_error(&e))?; - Ok((written, rows.len() as u64 - written)) -} - -pub(super) async fn estimate_rows(pool: &deadpool_postgres::Pool, schema: &str, table: &str) -> Option { - let client = pool.get().await.ok()?; - let row = client - .query_opt( - "SELECT c.reltuples::bigint FROM pg_class c \ - JOIN pg_namespace n ON n.oid = c.relnamespace \ - WHERE n.nspname = $1 AND c.relname = $2", - &[&schema, &table], - ) - .await - .ok()??; - row.try_get::<_, i64>(0).ok().filter(|estimate| *estimate >= 0) -} diff --git a/src-tauri/src/application/table_row_transfers/sqlite.rs b/src-tauri/src/application/table_row_transfers/sqlite.rs index bea354dcc..ca08d56b9 100644 --- a/src-tauri/src/application/table_row_transfers/sqlite.rs +++ b/src-tauri/src/application/table_row_transfers/sqlite.rs @@ -28,7 +28,12 @@ pub(super) async fn is_strict_table(pool: &Pool, table: &str) -> bool { .is_some_and(|strict| strict != 0) } -fn insert_sql(table: &str, bindings: &[ColumnBinding], rows: usize, conflict: ConflictMode) -> String { +fn insert_sql( + table: &str, + bindings: &[ColumnBinding], + rows: usize, + conflict: ConflictMode, +) -> String { let columns: Vec = bindings.iter().map(|b| quote(&b.target_column)).collect(); let tuple = format!("({})", vec!["?"; bindings.len()].join(", ")); let mut sql = format!( @@ -67,7 +72,11 @@ pub(super) async fn write_batch( TransferValue::Bytes(v) => query.bind(v.clone()), }; } - written += query.execute(&mut *tx).await.map_err(describe_error)?.rows_affected(); + written += query + .execute(&mut *tx) + .await + .map_err(describe_error)? + .rows_affected(); } tx.commit().await.map_err(describe_error)?; Ok((written, rows.len() as u64 - written)) diff --git a/src-tauri/src/application/table_row_transfers_tests.rs b/src-tauri/src/application/table_row_transfers_tests.rs index e90908659..8bfc469d5 100644 --- a/src-tauri/src/application/table_row_transfers_tests.rs +++ b/src-tauri/src/application/table_row_transfers_tests.rs @@ -45,704 +45,957 @@ fn dropping_the_registration_cancels_and_unregisters() { let state = state(); let flag = Arc::new(AtomicBool::new(false)); let key = transfer_key(None, "x"); - state.table_transfers.lock().unwrap().insert(key.clone(), flag.clone()); - drop(Registration { state: state.table_transfers.clone(), key, flag: flag.clone() }); + state + .table_transfers + .lock() + .unwrap() + .insert(key.clone(), flag.clone()); + drop(Registration { + state: state.table_transfers.clone(), + key, + flag: flag.clone(), + }); assert!(flag.load(Ordering::SeqCst)); assert!(state.table_transfers.lock().unwrap().is_empty()); } -fn binding(name: &str, kind: crate::table_transfer::SourceKind) -> ColumnBinding { - use crate::table_transfer::*; - let target = TargetType::Pg(PgTarget::Int(32)); - ColumnBinding { - source_column: name.into(), - source_kind: kind, - target_column: name.into(), - conversion: types_plan(kind, &target), - target_type: target, +fn sqlite_params(path: &std::path::Path) -> ConnectionParams { + ConnectionParams { + driver: "sqlite".into(), + database: DatabaseSelection::Single(path.to_string_lossy().into()), + ..Default::default() } } -fn types_plan( - kind: crate::table_transfer::SourceKind, - target: &crate::table_transfer::TargetType, -) -> crate::table_transfer::Conversion { - let _ = (kind, target); - crate::table_transfer::Conversion { - op: crate::table_transfer::Op::Copy, - out: crate::table_transfer::OutKind::Int, - rule: crate::table_transfer::ConversionRule::Exact, +async fn sqlite_endpoint(path: &std::path::Path) -> Endpoint { + std::fs::File::create(path).unwrap(); + let pool = get_sqlite_pool(&sqlite_params(path)).await.unwrap(); + for table in ["a", "b", "dst"] { + sqlx::query(&format!("CREATE TABLE IF NOT EXISTS {table} (id INTEGER)")) + .execute(&pool) + .await + .unwrap(); + } + Endpoint { + driver: "sqlite".into(), + dialect: TransferDialect::Sqlite, + params: sqlite_params(path), + schema: String::new(), + drv: Arc::new(crate::drivers::sqlite::SqliteDriver::new()), } } -#[test] -fn generated_sql_quotes_identifiers_and_never_truncates_or_upserts() { - use crate::table_transfer::SourceKind; - let bindings = [binding("id", SourceKind::Int), binding("we\"ird", SourceKind::Int)]; - let sql = postgres::insert_sql("public", "t", &bindings, 2, ConflictMode::Fail); - assert_eq!( - sql, - "INSERT INTO \"public\".\"t\" (\"id\", \"we\"\"ird\") VALUES \ - (CAST($1 AS integer), CAST($2 AS integer)), (CAST($3 AS integer), CAST($4 AS integer))" - ); - let skip = postgres::insert_sql("public", "t", &bindings, 1, ConflictMode::Skip); - assert!(skip.ends_with("ON CONFLICT DO NOTHING")); - assert!(!skip.contains("UPDATE") && !skip.to_uppercase().contains("TRUNCATE")); - let select = postgres::select_sql("s", "t", &[binding("n", SourceKind::Decimal)]); - assert_eq!(select, "SELECT \"n\"::text FROM \"s\".\"t\""); +fn pick(source: &str, target: &str) -> TableSelection { + TableSelection { + source_table: source.into(), + target_table: target.into(), + columns: vec![], + } } -// --- Real PostgreSQL / SQLite transfers ------------------------------------- -// -// Same fixture as `tests/postgres_integration` (127.0.0.1:54320, testdb). The -// tests skip when PostgreSQL is not reachable. Each test works in its own -// uniquely named schema / temp file and removes it afterwards. +#[tokio::test] +async fn targets_differing_only_by_ascii_case_are_duplicates() { + let dir = tempfile::tempdir().unwrap(); + let source = sqlite_endpoint(&dir.path().join("src.db")).await; + let target = sqlite_endpoint(&dir.path().join("dst.db")).await; -use crate::table_transfer::TableSelection; -use std::sync::Mutex as StdMutex; + let (_, issues) = plan_tables(&source, &target, &[pick("a", "dst"), pick("b", "DST")]) + .await + .unwrap(); -struct Events { - cancel_when_written: Option<(Arc, u64)>, - progress: StdMutex>, + assert!(issues.iter().any(|i| i.code == "duplicateTargetTable")); } -impl crate::runtime::events::RuntimeEvents for Events { - fn emit(&self, _event: &str, payload: serde_json::Value) -> Result<(), String> { - if let Some((flag, threshold)) = &self.cancel_when_written { - if payload["rows_written"].as_u64().unwrap_or(0) >= *threshold { - flag.store(true, Ordering::SeqCst); - } - } - self.progress.lock().unwrap().push(payload); - Ok(()) - } - - fn emit_to(&self, _: Uuid, event: &str, payload: serde_json::Value) -> Result<(), String> { - self.emit(event, payload) - } -} +#[tokio::test] +async fn distinct_targets_are_not_flagged_as_duplicates() { + let dir = tempfile::tempdir().unwrap(); + let source = sqlite_endpoint(&dir.path().join("src.db")).await; + let target = sqlite_endpoint(&dir.path().join("dst.db")).await; -fn pg_params() -> ConnectionParams { - ConnectionParams { - driver: "postgres".into(), - host: Some("127.0.0.1".into()), - port: Some(54320), - username: Some("postgres".into()), - password: Some("password".into()), - database: DatabaseSelection::Single("testdb".into()), - ..Default::default() - } -} + let (_, issues) = plan_tables(&source, &target, &[pick("a", "dst"), pick("b", "a")]) + .await + .unwrap(); -async fn endpoint(params: ConnectionParams, schema: &str) -> Endpoint { - crate::drivers::registry::register_driver(crate::drivers::postgres::PostgresDriver::new()).await; - crate::drivers::registry::register_driver(crate::drivers::sqlite::SqliteDriver::new()).await; - let driver = params.driver.clone(); - Endpoint { - dialect: dialect_for_driver(&driver).unwrap(), - drv: crate::drivers::registry::get_connection_driver(¶ms).await.unwrap(), - schema: schema.to_string(), - driver, - params, - } + assert!(issues.iter().all(|i| i.code != "duplicateTargetTable")); } -async fn pg_exec(sql: &str) { - let pool = get_postgres_pool(&pg_params()).await.unwrap(); - let client = pool.get().await.unwrap(); - client.batch_execute(sql).await.unwrap(); -} +#[tokio::test] +async fn copying_a_table_onto_its_own_case_variant_is_a_self_copy() { + let dir = tempfile::tempdir().unwrap(); + let endpoint = sqlite_endpoint(&dir.path().join("one.db")).await; -async fn pg_scalar(sql: &str) -> String { - let pool = get_postgres_pool(&pg_params()).await.unwrap(); - let client = pool.get().await.unwrap(); - client.query_one(sql, &[]).await.unwrap().get::<_, String>(0) + assert_eq!( + same_table(&endpoint, &endpoint, &pick("a", "A")).await, + SameTable::Yes + ); + assert_eq!( + same_table(&endpoint, &endpoint, &pick("a", "b")).await, + SameTable::No + ); } -const SOURCE_ROWS: i64 = 1_250; +struct NoSecrets; -/// Pooled connections belong to the runtime that opened them, so tests that -/// share the PostgreSQL fixture run one at a time. -static FIXTURE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +impl crate::runtime::secrets::RuntimeSecrets for NoSecrets { + fn get(&self, _account: &str) -> Result, String> { + Ok(None) + } -async fn seed_source(schema: &str) -> Option> { - let guard = FIXTURE_LOCK.lock().await; - crate::pool_manager::close_pool(&pg_params()).await; - let available = match get_postgres_pool(&pg_params()).await { - Ok(pool) => pool.get().await.is_ok(), - Err(_) => false, - }; - if !available { - eprintln!("SKIPPING: PostgreSQL not available on port 54320"); - return None; + fn set(&self, _account: &str, _secret: &str) -> Result<(), String> { + Ok(()) } - pg_exec(&format!( - "DROP SCHEMA IF EXISTS {schema} CASCADE; CREATE SCHEMA {schema}; - CREATE TABLE {schema}.src ( - id integer PRIMARY KEY, name text, amount numeric(12,2), big numeric(30,10), - payload bytea, note text, created timestamptz, flag boolean, meta jsonb, uid uuid); - INSERT INTO {schema}.src - SELECT g, 'Zoë 日本語 ' || g, g * 1.25, 12345678901234567890.1234567891 + g, - '\\x00ff00'::bytea || int4send(g), CASE WHEN g % 2 = 0 THEN NULL ELSE 'n' END, - timestamptz '2024-01-02 03:04:05.123456+00' + g * interval '1 second', - g % 2 = 0, jsonb_build_object('n', g), gen_random_uuid() - FROM generate_series(1, {SOURCE_ROWS}) g;" - )) - .await; - Some(guard) -} -fn selection() -> TableSelection { - TableSelection { - source_table: "src".into(), - target_table: "dst".into(), - columns: vec![], + fn delete(&self, _account: &str) -> Result<(), String> { + Ok(()) } } -async fn job( - schema: &str, - target: Endpoint, - conflict: ConflictMode, - cancel: Arc, - cancel_after: Option, -) -> (TableTransferResult, Arc, Vec) { - let source = endpoint(pg_params(), schema).await; - let (tables, issues) = plan_tables(&source, &target, &[selection()]).await.unwrap(); - assert!(issues.is_empty()); - let dir = tempfile::tempdir().unwrap(); - let events = Arc::new(Events { - cancel_when_written: cancel_after.map(|n| (cancel.clone(), n)), - progress: StdMutex::default(), - }); - let runtime = RuntimeContext::new( +fn runtime(dir: &std::path::Path) -> RuntimeContext { + RuntimeContext::new( Arc::new(crate::runtime::paths::FixedRuntimePaths::new( - dir.path().to_path_buf(), - dir.path().to_path_buf(), + dir.to_path_buf(), + dir.to_path_buf(), )), - events.clone(), - Arc::new(crate::runtime::secrets::KeyringRuntimeSecrets), - ); + Arc::new(crate::runtime::events::NoopRuntimeEvents), + Arc::new(NoSecrets), + ) +} + +/// Source and target SQLite files, each with an empty `big(id, name)` table; +/// the source gets `rows` rows (`name` is NULL on every 7th). +async fn copy_fixture(dir: &std::path::Path, rows: i64) -> (Endpoint, Endpoint) { + let source = sqlite_endpoint(&dir.join("src.db")).await; + let target = sqlite_endpoint(&dir.join("dst.db")).await; + for endpoint in [&source, &target] { + let pool = get_sqlite_pool(&endpoint.params).await.unwrap(); + sqlx::query("CREATE TABLE big (id INTEGER PRIMARY KEY, name TEXT)") + .execute(&pool) + .await + .unwrap(); + } + let pool = get_sqlite_pool(&source.params).await.unwrap(); + sqlx::query( + "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?) \ + INSERT INTO big SELECT i, CASE WHEN i % 7 = 0 THEN NULL ELSE 'row-' || i END \ + FROM n WHERE i <= ?", + ) + .bind(rows) + .bind(rows) + .execute(&pool) + .await + .unwrap(); + (source, target) +} + +async fn big_job( + dir: &std::path::Path, + source: Endpoint, + target: Endpoint, + batch_rows: usize, + cancel: bool, +) -> (Job, Vec) { + let (tables, issues) = plan_tables(&source, &target, &[pick("big", "big")]) + .await + .unwrap(); + assert!(issues.is_empty()); + assert!(!tables[0].plan.blocking); let job = Job { - runtime, + runtime: runtime(dir), session_id: None, - transfer_id: "t1".into(), - cancel, + transfer_id: "copy-test".into(), + cancel: Arc::new(AtomicBool::new(cancel)), source, target, - conflict, - batch_rows: 500, + conflict: ConflictMode::default(), + batch_rows, total_tables: 1, }; - let result = run_job(job, tables.clone()).await; - (result, events, tables) + (job, tables) } -fn sqlite_params(path: &std::path::Path) -> ConnectionParams { - ConnectionParams { - driver: "sqlite".into(), - database: DatabaseSelection::Single(path.to_string_lossy().into()), - ..Default::default() - } +async fn copy_big( + dir: &std::path::Path, + source: Endpoint, + target: Endpoint, + batch_rows: usize, +) -> TableTransferTableResult { + let (job, tables) = big_job(dir, source, target, batch_rows, false).await; + run_job(job, tables).await.tables.remove(0) +} + +async fn assert_copied_exactly(source: &Endpoint, target: &Endpoint, rows: i64) { + let source_pool = get_sqlite_pool(&source.params).await.unwrap(); + let target_pool = get_sqlite_pool(&target.params).await.unwrap(); + let read = |pool: sqlx::Pool| async move { + sqlx::query_as::<_, (i64, Option)>("SELECT id, name FROM big ORDER BY id") + .fetch_all(&pool) + .await + .unwrap() + }; + let copied = read(target_pool).await; + assert_eq!(copied.len() as i64, rows); + assert_eq!(copied, read(source_pool).await); } -async fn sqlite_target(path: &std::path::Path, ddl: &str) -> Endpoint { - let params = sqlite_params(path); - std::fs::File::create(path).unwrap(); - let pool = get_sqlite_pool(¶ms).await.unwrap(); - sqlx::query(ddl).execute(&pool).await.unwrap(); - endpoint(params, "").await -} +#[tokio::test] +async fn a_multi_batch_copy_moves_every_row_once_in_order() { + let dir = tempfile::tempdir().unwrap(); + // 2,300 rows at 500 per batch: four full batches and a partial one. + let (source, target) = copy_fixture(dir.path(), 2_300).await; -const SQLITE_DDL: &str = "CREATE TABLE dst (id INTEGER PRIMARY KEY, name TEXT, amount NUMERIC, \ - big TEXT, payload BLOB, note TEXT, created TEXT, flag INTEGER, meta TEXT, uid TEXT)"; + let result = copy_big(dir.path(), source.clone(), target.clone(), 500).await; -async fn sqlite_count(path: &std::path::Path) -> i64 { - let pool = get_sqlite_pool(&sqlite_params(path)).await.unwrap(); - sqlx::query_scalar("SELECT count(*) FROM dst").fetch_one(&pool).await.unwrap() + assert_eq!(result.status, TransferStatus::Completed); + assert_eq!(result.rows_read, 2_300); + assert_eq!(result.rows_written, 2_300); + assert_copied_exactly(&source, &target, 2_300).await; } #[tokio::test] -async fn postgres_to_sqlite_copies_every_row_exactly() { - let schema = "tt_sqlite_ok"; - let Some(_fixture) = seed_source(schema).await else { - return; - }; +async fn a_row_count_that_is_an_exact_multiple_of_the_batch_copies_cleanly() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("target.db"); - let target = sqlite_target(&path, SQLITE_DDL).await; - let (result, events, _) = - job(schema, target, ConflictMode::Fail, Arc::new(AtomicBool::new(false)), None).await; - - assert_eq!(result.status, TransferStatus::Completed, "{:?}", result.tables[0].error); - assert_eq!(result.tables[0].rows_read, SOURCE_ROWS as u64); - assert_eq!(result.tables[0].rows_written, SOURCE_ROWS as u64); - assert_eq!(sqlite_count(&path).await, SOURCE_ROWS); - assert!(events.progress.lock().unwrap().len() >= 4, "per-batch progress"); - let progress = events.progress.lock().unwrap().last().unwrap().to_string(); - assert!(!progress.contains("Zoë"), "progress events carry no row data"); - - let pool = get_sqlite_pool(&sqlite_params(&path)).await.unwrap(); - let row = sqlx::query("SELECT name, big, payload, note, flag, meta, amount FROM dst WHERE id = 2") - .fetch_one(&pool) - .await - .unwrap(); - use sqlx::Row; - assert_eq!(row.get::("name"), "Zoë 日本語 2"); - assert_eq!(row.get::("big"), "12345678901234567892.1234567891"); - assert_eq!(row.get::, _>("payload"), vec![0, 255, 0, 0, 0, 0, 2]); - assert_eq!(row.get::, _>("note"), None); - assert_eq!(row.get::("flag"), 1); - assert_eq!(row.get::("meta"), "{\"n\": 2}"); - assert_eq!(row.get::("amount"), 2.5); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; -} + let (source, target) = copy_fixture(dir.path(), 1_000).await; -#[tokio::test] -async fn postgres_to_postgres_preserves_precision_and_timestamps() { - let schema = "tt_pg_ok"; - let Some(_fixture) = seed_source(schema).await else { - return; - }; - pg_exec(&format!( - "CREATE TABLE {schema}.dst (LIKE {schema}.src INCLUDING ALL)" - )) - .await; - let target = endpoint(pg_params(), schema).await; - let (result, _, _) = - job(schema, target, ConflictMode::Fail, Arc::new(AtomicBool::new(false)), None).await; - assert_eq!(result.status, TransferStatus::Completed, "{:?}", result.tables[0].error); - let diff = pg_scalar(&format!( - "SELECT count(*)::text FROM {schema}.src s FULL JOIN {schema}.dst d USING (id) - WHERE s.* IS DISTINCT FROM d.*" - )) - .await; - assert_eq!(diff, "0", "source and target rows must be identical"); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; + let result = copy_big(dir.path(), source.clone(), target.clone(), 500).await; + + assert_eq!(result.status, TransferStatus::Completed); + assert_eq!(result.rows_written, 1_000); + assert_copied_exactly(&source, &target, 1_000).await; } #[tokio::test] -async fn failing_batch_rolls_back_only_that_batch() { - let schema = "tt_fail"; - let Some(_fixture) = seed_source(schema).await else { - return; - }; +async fn an_empty_source_table_completes_with_nothing_written() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("target.db"); - let target = sqlite_target(&path, SQLITE_DDL).await; - let pool = get_sqlite_pool(&sqlite_params(&path)).await.unwrap(); - sqlx::query("INSERT INTO dst (id) VALUES (1100)").execute(&pool).await.unwrap(); - - let (result, _, _) = - job(schema, target, ConflictMode::Fail, Arc::new(AtomicBool::new(false)), None).await; - let table = &result.tables[0]; - assert_eq!(result.status, TransferStatus::Failed); - assert_eq!(table.rows_written, 1000, "two earlier batches stay committed"); - assert_eq!(table.rows_failed, 250); - assert_eq!(sqlite_count(&path).await, 1001); - let error = table.error.clone().unwrap(); - assert!(error.contains("UNIQUE"), "{error}"); - assert!(!error.contains("Zoë")); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; + let (source, target) = copy_fixture(dir.path(), 0).await; + + let result = copy_big(dir.path(), source.clone(), target.clone(), 500).await; + + assert_eq!(result.status, TransferStatus::Completed); + assert_eq!((result.rows_read, result.rows_written), (0, 0)); } #[tokio::test] -async fn skip_mode_ignores_only_duplicates() { - let schema = "tt_skip"; - let Some(_fixture) = seed_source(schema).await else { - return; - }; +async fn a_batch_of_one_row_still_streams_every_row() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("target.db"); - let target = sqlite_target(&path, SQLITE_DDL).await; - let pool = get_sqlite_pool(&sqlite_params(&path)).await.unwrap(); - sqlx::query("INSERT INTO dst (id) VALUES (7), (1100)").execute(&pool).await.unwrap(); + let (source, target) = copy_fixture(dir.path(), 25).await; + + let result = copy_big(dir.path(), source.clone(), target.clone(), 1).await; - let (result, _, _) = - job(schema, target, ConflictMode::Skip, Arc::new(AtomicBool::new(false)), None).await; assert_eq!(result.status, TransferStatus::Completed); - assert_eq!(result.tables[0].rows_skipped, 2); - assert_eq!(result.tables[0].rows_written, SOURCE_ROWS as u64 - 2); - assert_eq!(sqlite_count(&path).await, SOURCE_ROWS); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; + assert_copied_exactly(&source, &target, 25).await; } #[tokio::test] -async fn lossy_values_are_rejected_instead_of_coerced() { - let schema = "tt_lossy"; - let Some(_fixture) = seed_source(schema).await else { - return; - }; +async fn a_cancel_raised_before_the_first_batch_stops_the_stream_without_writing() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("target.db"); - let ddl = SQLITE_DDL.replace("amount NUMERIC", "amount INTEGER"); - let target = sqlite_target(&path, &ddl).await; - let (result, _, _) = - job(schema, target, ConflictMode::Fail, Arc::new(AtomicBool::new(false)), None).await; - let table = &result.tables[0]; - assert_eq!(result.status, TransferStatus::Failed); - assert_eq!(table.rows_written, 0); - assert_eq!(sqlite_count(&path).await, 0); - let error = table.error.clone().unwrap(); - assert!(error.contains("column \"amount\"") && error.contains("lossy"), "{error}"); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; -} + let (source, target) = copy_fixture(dir.path(), 2_300).await; + let (job, tables) = big_job(dir.path(), source, target.clone(), 500, true).await; + let mut result = TableTransferTableResult { + source_table: "big".into(), + target_table: "big".into(), + status: TransferStatus::Running, + rows_read: 0, + rows_written: 0, + rows_skipped: 0, + rows_failed: 0, + error: None, + }; -#[tokio::test] -async fn cancellation_keeps_committed_batches_and_reports_them() { - let schema = "tt_cancel"; - let Some(_fixture) = seed_source(schema).await else { - return; + let status = copy_table(&job, 0, &tables[0], &mut result).await.unwrap(); + + assert_eq!(status, TransferStatus::Cancelled); + assert_eq!((result.rows_read, result.rows_written), (0, 0)); + let pool = get_sqlite_pool(&target.params).await.unwrap(); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM big") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(count, 0); +} + +/// Copies `big(id, v )` between two SQLite files, seeding the source +/// with `values` (SQL literals, so each keeps its own storage class), and +/// returns `(id, typeof(v), hex(v))` for source and target. +async fn copy_typed_column( + dir: &std::path::Path, + declared: &str, + values: &[&str], +) -> ( + TableTransferTableResult, + Vec<(i64, String, String)>, + Vec<(i64, String, String)>, +) { + let source = sqlite_endpoint(&dir.join("typed-src.db")).await; + let target = sqlite_endpoint(&dir.join("typed-dst.db")).await; + for endpoint in [&source, &target] { + let pool = get_sqlite_pool(&endpoint.params).await.unwrap(); + sqlx::query(&format!( + "CREATE TABLE big (id INTEGER PRIMARY KEY, v {declared})" + )) + .execute(&pool) + .await + .unwrap(); + } + let pool = get_sqlite_pool(&source.params).await.unwrap(); + for (id, value) in values.iter().enumerate() { + sqlx::query(&format!("INSERT INTO big VALUES ({}, {value})", id + 1)) + .execute(&pool) + .await + .unwrap(); + } + let result = copy_big(dir, source.clone(), target.clone(), 2).await; + let read = |endpoint: Endpoint| async move { + let pool = get_sqlite_pool(&endpoint.params).await.unwrap(); + sqlx::query_as::<_, (i64, String, String)>( + "SELECT id, typeof(v), hex(v) FROM big ORDER BY id", + ) + .fetch_all(&pool) + .await + .unwrap() }; - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("target.db"); - let target = sqlite_target(&path, SQLITE_DDL).await; - let cancel = Arc::new(AtomicBool::new(false)); - let (result, _, _) = job(schema, target, ConflictMode::Fail, cancel, Some(500)).await; - let table = &result.tables[0]; - assert_eq!(result.status, TransferStatus::Cancelled); - assert_eq!(table.rows_written, 500); - assert_eq!(sqlite_count(&path).await, 500, "committed work remains in the target"); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; + (result, read(source).await, read(target).await) } #[tokio::test] -async fn plan_blocks_a_missing_target_table_and_never_creates_it() { - let schema = "tt_plan"; - let Some(_fixture) = seed_source(schema).await else { - return; - }; +async fn a_blob_column_keeps_the_storage_class_of_every_value() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("target.db"); - let params = sqlite_params(&path); - std::fs::File::create(&path).unwrap(); - get_sqlite_pool(¶ms).await.unwrap(); - let target = endpoint(params, "").await; - let source = endpoint(pg_params(), schema).await; - let (tables, _) = plan_tables(&source, &target, &[selection()]).await.unwrap(); - assert!(tables[0].plan.blocking); - assert_eq!(tables[0].plan.issues[0].code, "targetTableNotFound"); - assert!(target.drv.get_columns(&target.params, "dst", None).await.unwrap().is_empty()); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; + + // A BLOB column has no affinity, so it can hold a blob, text, an integer + // or a real. `typeof` and the bytes must survive the copy. + let (result, source, target) = copy_typed_column( + dir.path(), + "BLOB", + &["x'00ff10'", "'abc'", "NULL", "7", "2.5", "x''"], + ) + .await; + + assert_eq!(result.error, None); + assert_eq!(result.status, TransferStatus::Completed); + assert_eq!(target, source); + assert_eq!( + target.iter().map(|r| r.1.as_str()).collect::>(), + ["blob", "text", "null", "integer", "real", "blob"] + ); } #[tokio::test] -async fn a_transfer_cancelled_before_it_starts_copies_nothing() { - let schema = "tt_precancel"; - let Some(_fixture) = seed_source(schema).await else { - return; - }; +async fn text_stored_in_a_blob_column_stays_text() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("target.db"); - let target = sqlite_target(&path, SQLITE_DDL).await; - let (result, _, _) = - job(schema, target, ConflictMode::Fail, Arc::new(AtomicBool::new(true)), None).await; - assert_eq!(result.status, TransferStatus::Cancelled); - assert_eq!(result.tables[0].status, TransferStatus::NotStarted); - assert_eq!(sqlite_count(&path).await, 0); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; -} + let (result, source, target) = + copy_typed_column(dir.path(), "BLOB", &["'abc'", "x'616263'"]).await; + + assert_eq!(result.error, None); + assert_eq!(source[0].1, "text"); + assert_eq!(target, source); +} #[tokio::test] -async fn detects_strict_sqlite_tables() { +async fn a_numeric_column_copies_integer_and_real_values_unchanged() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("strict.db"); - std::fs::File::create(&path).unwrap(); - let pool = get_sqlite_pool(&sqlite_params(&path)).await.unwrap(); - sqlx::query("CREATE TABLE plain_any (v ANY)").execute(&pool).await.unwrap(); - sqlx::query("CREATE TABLE strict_any (v ANY) STRICT").execute(&pool).await.unwrap(); - assert!(sqlite::is_strict_table(&pool, "strict_any").await); - assert!(sqlite::is_strict_table(&pool, "STRICT_ANY").await); - assert!(!sqlite::is_strict_table(&pool, "plain_any").await); - assert!(!sqlite::is_strict_table(&pool, "missing").await); -} + let (result, source, target) = + copy_typed_column(dir.path(), "NUMERIC", &["42", "1.5", "NULL", "-7", "2.25"]).await; -fn saved_pg(host: &str, port: Option, database: &str) -> ConnectionParams { - ConnectionParams { - driver: "postgres".into(), - host: Some(host.into()), - port, - database: DatabaseSelection::Single(database.into()), - ..Default::default() - } + assert_eq!(result.error, None); + assert_eq!(result.status, TransferStatus::Completed); + assert_eq!(target, source); } -#[test] -fn string_identity_matches_aliases_that_are_provably_one_server() { - let a = saved_pg("db.example.com", Some(5432), "app"); - let mut b = saved_pg("DB.example.com", None, "app"); - b.username = Some("someone_else".into()); - assert!(reaches_same_database(&a, &b)); - assert!(reaches_same_database( - &saved_pg("localhost", Some(5432), "app"), - &saved_pg("127.0.0.1", Some(5432), "app"), - )); - assert!(!reaches_same_database(&a, &saved_pg("db.example.com", Some(5432), "other"))); - assert!(!reaches_same_database(&a, &saved_pg("db2", Some(5432), "app"))); - assert!(!reaches_same_database(&a, &saved_pg("db.example.com", Some(6543), "app"))); -} +#[tokio::test] +async fn numeric_values_copy_into_other_column_types_or_fail_loudly() { + // A NUMERIC source column holds integers, reals and text natively. Each + // target type either stores the value exactly or the copy reports an error; + // nothing is rounded or reclassified silently. + for (target_type, values, expect_ok) in [ + ("TEXT", &["42", "1.5"][..], true), + ("INTEGER", &["42", "-7"][..], true), + ("INTEGER", &["1.5"][..], false), + ("REAL", &["42", "1.5", "0.1"][..], true), + ] { + let dir = tempfile::tempdir().unwrap(); + let source = sqlite_endpoint(&dir.path().join("s.db")).await; + let target = sqlite_endpoint(&dir.path().join("t.db")).await; + for (endpoint, declared) in [(&source, "NUMERIC"), (&target, target_type)] { + let pool = get_sqlite_pool(&endpoint.params).await.unwrap(); + sqlx::query(&format!( + "CREATE TABLE big (id INTEGER PRIMARY KEY, v {declared})" + )) + .execute(&pool) + .await + .unwrap(); + } + let pool = get_sqlite_pool(&source.params).await.unwrap(); + for (id, value) in values.iter().enumerate() { + sqlx::query(&format!("INSERT INTO big VALUES ({}, {value})", id + 1)) + .execute(&pool) + .await + .unwrap(); + } -#[test] -fn tunnels_only_match_when_provably_the_same_route() { - let mut a = saved_pg("db", Some(5432), "app"); - let mut b = a.clone(); - a.ssh_enabled = Some(true); - a.ssh_connection_id = Some("bastion-1".into()); - assert!(!reaches_same_database(&a, &b), "tunnel vs direct"); - b.ssh_enabled = Some(true); - b.ssh_connection_id = Some("bastion-2".into()); - assert!(!reaches_same_database(&a, &b), "different bastions"); - b.ssh_connection_id = Some("bastion-1".into()); - assert!(reaches_same_database(&a, &b)); + let result = copy_big(dir.path(), source, target.clone(), 500).await; + + if expect_ok { + assert_eq!(result.error, None, "NUMERIC -> {target_type}"); + assert_eq!(result.rows_written, values.len() as u64); + } else { + assert_eq!( + result.status, + TransferStatus::Failed, + "NUMERIC -> {target_type}" + ); + let pool = get_sqlite_pool(&target.params).await.unwrap(); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM big") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(count, 0, "a rejected batch must write nothing"); + } + } } -#[test] -fn sqlite_aliases_of_one_file_are_one_database() { +#[tokio::test] +async fn a_real_in_a_numeric_column_round_trips_exactly_into_a_text_column() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("a.db"); - std::fs::File::create(&path).unwrap(); - let a = sqlite_params(&path); - assert!(reaches_same_database(&a, &sqlite_params(&dir.path().join(".").join("a.db")))); - let other = dir.path().join("b.db"); - std::fs::File::create(&other).unwrap(); - assert!(!reaches_same_database(&a, &sqlite_params(&other))); -} - -fn identity(system_id: Option<&str>, address: Option<(&str, i32)>, database: &str) -> ServerIdentity { - ServerIdentity { - system_id: system_id.map(str::to_string), - address: address.map(|(host, port)| (host.to_string(), port)), - database: database.to_string(), + let source = sqlite_endpoint(&dir.path().join("s.db")).await; + let target = sqlite_endpoint(&dir.path().join("t.db")).await; + for (endpoint, declared) in [(&source, "NUMERIC"), (&target, "TEXT")] { + let pool = get_sqlite_pool(&endpoint.params).await.unwrap(); + sqlx::query(&format!( + "CREATE TABLE big (id INTEGER PRIMARY KEY, v {declared})" + )) + .execute(&pool) + .await + .unwrap(); + } + let pool = get_sqlite_pool(&source.params).await.unwrap(); + // Values whose shortest text needs 16-17 significant digits: a copy that + // rendered a real with 15 would store a different number. + sqlx::query( + "INSERT INTO big VALUES (1, 1.2345678901234567), (2, 42), (3, 0.1), \ + (4, 0.30000000000000004), (5, 3.141592653589793), (6, NULL)", + ) + .execute(&pool) + .await + .unwrap(); + + let result = copy_big(dir.path(), source.clone(), target.clone(), 500).await; + + assert_eq!(result.error, None); + let read = |endpoint: Endpoint| async move { + let pool = get_sqlite_pool(&endpoint.params).await.unwrap(); + sqlx::query_as::<_, (i64, Option)>("SELECT id, CAST(v AS REAL) FROM big ORDER BY id") + .fetch_all(&pool) + .await + .unwrap() + }; + let target_pool = get_sqlite_pool(&target.params).await.unwrap(); + let texts: Vec<(i64, Option, String)> = + sqlx::query_as("SELECT id, v, typeof(v) FROM big ORDER BY id") + .fetch_all(&target_pool) + .await + .unwrap(); + assert!(texts + .iter() + .all(|(_, v, kind)| v.is_none() == (kind == "null"))); + assert!(texts + .iter() + .filter(|(_, v, _)| v.is_some()) + .all(|(_, _, kind)| kind == "text")); + // The stored text must parse back to the exact source number. + let source_values = read(source).await; + for ((id, original), (_, stored, _)) in source_values.iter().zip(&texts) { + let parsed = stored.as_deref().map(|text| text.parse::().unwrap()); + assert_eq!(parsed, *original, "row {id}: stored {stored:?}"); } } -#[test] -fn server_identity_ignores_the_name_used_to_reach_it() { - // `localhost.` reaches the server over ::1, `127.0.0.1` over IPv4. - let v6 = identity(Some("77"), Some(("::1", 54320)), "testdb"); - let v4 = identity(Some("77"), Some(("127.0.0.1", 54320)), "testdb"); - assert_eq!(compare_identities(&v6, &v4), Some(true)); - // Another cluster is a different database even with the same name and address. - let other = identity(Some("88"), Some(("127.0.0.1", 54320)), "testdb"); - assert_eq!(compare_identities(&v4, &other), Some(false)); - assert_eq!(compare_identities(&v4, &identity(Some("77"), None, "other")), Some(false)); +#[tokio::test] +async fn a_numeric_column_copied_into_an_untyped_column_keeps_its_storage_class() { + let dir = tempfile::tempdir().unwrap(); + let source = sqlite_endpoint(&dir.path().join("s.db")).await; + let target = sqlite_endpoint(&dir.path().join("t.db")).await; + for (endpoint, declared) in [(&source, "NUMERIC"), (&target, "")] { + let pool = get_sqlite_pool(&endpoint.params).await.unwrap(); + sqlx::query(&format!( + "CREATE TABLE big (id INTEGER PRIMARY KEY, v {declared})" + )) + .execute(&pool) + .await + .unwrap(); + } + let pool = get_sqlite_pool(&source.params).await.unwrap(); + sqlx::query("INSERT INTO big VALUES (1, 1.2345678901234567), (2, 42)") + .execute(&pool) + .await + .unwrap(); + + let result = copy_big(dir.path(), source, target.clone(), 500).await; + + assert_eq!(result.error, None); + let pool = get_sqlite_pool(&target.params).await.unwrap(); + let stored: Vec<(String, f64)> = + sqlx::query_as("SELECT typeof(v), CAST(v AS REAL) FROM big ORDER BY id") + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(stored[0], ("real".into(), 1.2345678901234567)); + assert_eq!(stored[1].0, "integer"); +} + +// --- Plugin-backed copy (fake plugin process) --- + +use serde_json::json; +use std::sync::Mutex; + +/// What a fake PostgreSQL plugin saw and how it answers. +#[derive(Default)] +struct FakePlugin { + /// Pages `read_rows` serves in order; the last repeats forever. + pages: Vec, + calls: Vec, + inserted: Vec, + /// `on_conflict` of each `insert_records`. + conflicts: Vec, + /// `read_rows` returns this error on its n-th call (1-based). + fail_read_on: Option, + reads: usize, + skipped_per_batch: u64, +} + +fn pg_manifest(version: &str) -> crate::drivers::driver_trait::PluginManifest { + let mut manifest = crate::plugins::driver::test_manifest(); + manifest.id = "postgresql".into(); + manifest.version = version.into(); + manifest.capabilities.table_copy = true; + manifest.capabilities.sql_dialect = Some(crate::drivers::driver_trait::SqlDialect::Postgres); + manifest +} + +fn fake_driver(version: &str, plugin: Arc>) -> Arc { + Arc::new(crate::plugins::driver::test_driver_with_manifest( + pg_manifest(version), + move |request| { + let mut state = plugin.lock().unwrap(); + state.calls.push(request.method.clone()); + match request.method.as_str() { + "read_rows" => { + state.reads += 1; + if state.fail_read_on == Some(state.reads) { + return Err("read_rows: the source went away".into()); + } + let index = (state.reads - 1).min(state.pages.len() - 1); + Ok(state.pages[index].clone()) + } + "insert_records" => { + state.conflicts.push( + request.params["on_conflict"] + .as_str() + .unwrap_or("") + .to_string(), + ); + let rows = request.params["rows"].clone(); + let skipped = state.skipped_per_batch; + let count = rows.as_array().map_or(0, |r| r.len()) as u64; + state.inserted.push(rows); + Ok(json!({"affected_rows": count - skipped, "skipped": skipped})) + } + "release_session" => Ok(json!({"released": true})), + other => Err(format!("unexpected {other}")), + } + }, + )) } -#[test] -fn without_a_cluster_id_only_the_same_address_proves_identity() { - let a = identity(None, Some(("10.0.0.5", 5432)), "app"); - assert_eq!(compare_identities(&a, &identity(None, Some(("10.0.0.5", 5432)), "app")), Some(true)); - let v6 = identity(None, Some(("::1", 5432)), "app"); - let v4 = identity(None, Some(("127.0.0.1", 5432)), "app"); - assert_eq!(compare_identities(&v6, &v4), Some(true)); - // Different addresses might still be one server, so nothing is proven. - assert_eq!(compare_identities(&a, &identity(None, Some(("10.0.0.6", 5432)), "app")), None); - assert_eq!(compare_identities(&a, &identity(None, None, "app")), None); - // One unreadable cluster id cannot be settled by the other side. - assert_eq!(compare_identities(&a, &identity(Some("1"), Some(("10.0.0.5", 5432)), "app")), None); +fn pg_endpoint(version: &str, plugin: Arc>) -> Endpoint { + Endpoint { + driver: "postgresql".into(), + dialect: TransferDialect::Postgres, + params: ConnectionParams { + driver: "postgresql".into(), + database: DatabaseSelection::Single("db".into()), + ..Default::default() + }, + schema: "public".into(), + drv: fake_driver(version, plugin), + } } -// --- Plan / run through two saved connections ------------------------------- +fn int_text_planned() -> PlannedTable { + use crate::table_transfer::*; + let columns = [("id", "bigint"), ("name", "text")]; + let source: Vec<_> = columns.iter().map(|(n, t)| table_column(n, t)).collect(); + build_table_plan(&PlanInputs { + selection: &pick("src", "dst"), + source_columns: &source, + target_columns: &source, + target_dialect: TransferDialect::Postgres, + target_strict: false, + estimated_rows: None, + same_table: false, + }) +} + +fn table_column(name: &str, data_type: &str) -> crate::models::TableColumn { + serde_json::from_value(json!({ + "name": name, "data_type": data_type, "is_pk": false, "is_nullable": true, + "is_auto_increment": false, + })) + .unwrap() +} + +fn page_of(ids: std::ops::RangeInclusive, has_more: bool) -> serde_json::Value { + json!({ + "columns": [{"name": "id", "type": "int8"}, {"name": "name", "type": "text"}], + "rows": ids.map(|i| json!([i, format!("n{i}")])).collect::>(), + "has_more": has_more, "page": 1, "page_size": 2, + }) +} + +async fn run_plugin_copy( + dir: &std::path::Path, + version: &str, + plugin: Arc>, + conflict: ConflictMode, + cancel: bool, +) -> TableTransferTableResult { + let planned = int_text_planned(); + assert!(!planned.plan.blocking, "{:?}", planned.plan.issues); + let job = Job { + runtime: runtime(dir), + session_id: None, + transfer_id: "plugin-copy".into(), + cancel: Arc::new(AtomicBool::new(cancel)), + source: pg_endpoint(version, plugin.clone()), + target: pg_endpoint(version, plugin), + conflict, + batch_rows: 2, + total_tables: 1, + }; + run_job(job, vec![planned]).await.tables.remove(0) +} -struct SavedPair { - _dir: tempfile::TempDir, - runtime: RuntimeContext, +fn count(plugin: &Mutex, method: &str) -> usize { + plugin + .lock() + .unwrap() + .calls + .iter() + .filter(|c| *c == method) + .count() } -/// A runtime whose connections file holds saved connections `a` and `b`. -fn runtime_with(a: ConnectionParams, b: ConnectionParams) -> SavedPair { +#[tokio::test] +async fn a_plugin_copy_pages_until_has_more_is_false_and_releases_the_session() { let dir = tempfile::tempdir().unwrap(); - let runtime = RuntimeContext::new( - Arc::new(crate::runtime::paths::FixedRuntimePaths::new( - dir.path().to_path_buf(), - dir.path().to_path_buf(), - )), - Arc::new(Events { cancel_when_written: None, progress: StdMutex::default() }), - Arc::new(crate::runtime::secrets::KeyringRuntimeSecrets), - ); - let saved = |id: &str, params: ConnectionParams| crate::models::SavedConnection { - id: id.into(), - name: id.into(), - params, - plugin_secret_keys: vec![], - group_id: None, - sort_order: None, - detect_json_in_text_columns: None, - appearance: None, - tag_ids: None, - environment: None, - managed: false, - }; - let file = crate::models::ConnectionsFile { - connections: vec![saved("conn-a", a), saved("conn-b", b)], + let plugin = Arc::new(Mutex::new(FakePlugin { + pages: vec![ + page_of(1..=2, true), + page_of(3..=4, true), + page_of(5..=5, false), + ], ..Default::default() - }; - crate::persistence::save_connections_file(&runtime.paths.connections_file(), &file).unwrap(); - SavedPair { _dir: dir, runtime } -} - -fn self_copy_request(schema: &str, table: &str) -> TableTransferRequest { - TableTransferRequest { - source_connection_id: "conn-a".into(), - target_connection_id: "conn-b".into(), - source_schema: Some(schema.into()), - target_schema: Some(schema.into()), - tables: vec![TableSelection { - source_table: table.into(), - target_table: table.into(), - columns: vec![], - }], - source_database: None, - target_database: None, - conflict: ConflictMode::Fail, - batch_rows: None, - transfer_id: Some("self-copy".into()), - } -} - -async fn alias_copy_fixture(schema: &str) -> Option> { - let guard = FIXTURE_LOCK.lock().await; - crate::pool_manager::close_pool(&pg_params()).await; - if get_postgres_pool(&pg_params()).await.ok()?.get().await.is_err() { - eprintln!("SKIPPING: PostgreSQL not available on port 54320"); - return None; - } - pg_exec(&format!( - "DROP SCHEMA IF EXISTS {schema} CASCADE; CREATE SCHEMA {schema}; - CREATE TABLE {schema}.alias_copy_test(id integer, note text); - INSERT INTO {schema}.alias_copy_test VALUES (1, 'first'), (2, 'second');" - )) + })); + let result = run_plugin_copy( + dir.path(), + "1.0.0-rc.15", + plugin.clone(), + ConflictMode::Fail, + false, + ) .await; - Some(guard) + assert_eq!(result.error, None); + assert_eq!(result.status, TransferStatus::Completed); + assert_eq!( + (result.rows_read, result.rows_written, result.rows_skipped), + (5, 5, 0) + ); + assert_eq!(count(&plugin, "read_rows"), 3); + assert_eq!(count(&plugin, "insert_records"), 3); + assert_eq!(count(&plugin, "release_session"), 1); + let state = plugin.lock().unwrap(); + assert_eq!(state.conflicts, vec!["fail"; 3]); + assert_eq!(state.inserted[0][0], json!({"id": 1, "name": "n1"})); } -/// Two saved connections to the same server, one spelled `localhost.` (which -/// resolves over ::1 here) and one `127.0.0.1`, must not copy a table into itself. -async fn assert_self_copy_is_rejected(host_a: &str, host_b: &str, schema: &str) { - let Some(_fixture) = alias_copy_fixture(schema).await else { - return; - }; - let mut a = pg_params(); - a.host = Some(host_a.into()); - let mut b = pg_params(); - b.host = Some(host_b.into()); - crate::drivers::registry::register_driver(crate::drivers::postgres::PostgresDriver::new()).await; - let reachable = match get_postgres_pool(&a).await { - Ok(pool) => pool.get().await.is_ok(), - Err(_) => false, - }; - if !reachable { - eprintln!("SKIPPING: {host_a} is not reachable"); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; - return; - } - let pair = runtime_with(a, b); - let request = self_copy_request(schema, "alias_copy_test"); - - let plan = plan(&pair.runtime, None, request.clone()).await.unwrap(); - assert!(plan.blocking); - assert_eq!(plan.tables[0].issues[0].code, "sourceEqualsTarget"); - - let state = state(); - let error = run(&pair.runtime, &state, None, request).await.unwrap_err(); - assert!(error.contains("blocking issues"), "{error}"); +#[tokio::test] +async fn skip_mode_asks_for_skip_and_reports_the_skipped_rows() { + let dir = tempfile::tempdir().unwrap(); + let plugin = Arc::new(Mutex::new(FakePlugin { + pages: vec![page_of(1..=2, false)], + skipped_per_batch: 1, + ..Default::default() + })); + let result = run_plugin_copy( + dir.path(), + "1.0.0-rc.15", + plugin.clone(), + ConflictMode::Skip, + false, + ) + .await; assert_eq!( - pg_scalar(&format!("SELECT count(*)::text FROM {schema}.alias_copy_test")).await, - "2", - "nothing is written back into the source" + (result.rows_read, result.rows_written, result.rows_skipped), + (2, 1, 1) ); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; + assert_eq!(plugin.lock().unwrap().conflicts, vec!["skip"]); } #[tokio::test] -async fn two_saved_connections_through_dns_dot_and_ip_cannot_copy_a_table_into_itself() { - assert_self_copy_is_rejected("localhost.", "127.0.0.1", "tt_alias_dot").await; +async fn an_empty_plugin_source_completes_and_still_releases_the_session() { + let dir = tempfile::tempdir().unwrap(); + let plugin = Arc::new(Mutex::new(FakePlugin { + pages: vec![json!({"columns": [], "rows": [], "has_more": false})], + ..Default::default() + })); + let result = run_plugin_copy( + dir.path(), + "1.0.0-rc.15", + plugin.clone(), + ConflictMode::Fail, + false, + ) + .await; + assert_eq!(result.status, TransferStatus::Completed); + assert_eq!(count(&plugin, "insert_records"), 0); + assert_eq!(count(&plugin, "release_session"), 1); } #[tokio::test] -async fn two_saved_connections_with_loopback_spellings_cannot_copy_a_table_into_itself() { - assert_self_copy_is_rejected("localhost", "127.0.0.1", "tt_alias_loop").await; +async fn a_read_failure_keeps_earlier_batches_and_releases_the_session() { + let dir = tempfile::tempdir().unwrap(); + let plugin = Arc::new(Mutex::new(FakePlugin { + pages: vec![page_of(1..=2, true), page_of(3..=4, true)], + fail_read_on: Some(2), + ..Default::default() + })); + let result = run_plugin_copy( + dir.path(), + "1.0.0-rc.15", + plugin.clone(), + ConflictMode::Fail, + false, + ) + .await; + assert_eq!(result.status, TransferStatus::Failed); + assert_eq!(result.rows_written, 2); + assert!(result.error.unwrap().contains("source went away")); + assert_eq!(count(&plugin, "release_session"), 1); } -#[test] -fn a_table_with_the_same_name_on_another_server_is_still_allowed() { - // Same database, schema and table names, but a different cluster: a legitimate copy. - let a = identity(Some("1"), Some(("10.0.0.5", 5432)), "app"); - let b = identity(Some("2"), Some(("10.0.0.6", 5432)), "app"); - assert_eq!(compare_identities(&a, &b), Some(false)); +#[tokio::test] +async fn a_transfer_cancelled_before_the_first_page_reads_nothing_but_still_releases() { + let dir = tempfile::tempdir().unwrap(); + let plugin = Arc::new(Mutex::new(FakePlugin { + pages: vec![page_of(1..=2, true)], + ..Default::default() + })); + let result = run_plugin_copy( + dir.path(), + "1.0.0-rc.15", + plugin.clone(), + ConflictMode::Fail, + true, + ) + .await; + assert_eq!(result.status, TransferStatus::NotStarted); + assert_eq!(count(&plugin, "read_rows"), 0); } -fn read_only(mut params: ConnectionParams) -> ConnectionParams { - params.read_only = true; - params -} +#[tokio::test] +async fn an_unfixed_plugin_page_cut_by_the_size_budget_stops_before_writing_it() { + let dir = tempfile::tempdir().unwrap(); + // limit 2, one row returned, more to come: the size budget cut the page. + let plugin = Arc::new(Mutex::new(FakePlugin { + pages: vec![page_of(1..=1, true), page_of(1..=2, false)], + ..Default::default() + })); + let result = run_plugin_copy( + dir.path(), + "1.0.0-rc.15", + plugin.clone(), + ConflictMode::Fail, + false, + ) + .await; + assert_eq!(result.status, TransferStatus::Failed); + assert!(result.error.unwrap().contains("rc.16")); + assert_eq!(count(&plugin, "insert_records"), 0); + assert_eq!(count(&plugin, "release_session"), 1); -fn copy_request(schema: &str, target_schema: Option<&str>) -> TableTransferRequest { - TableTransferRequest { - source_schema: Some(schema.into()), - target_schema: target_schema.map(Into::into), - tables: vec![selection()], - transfer_id: Some("read-only-target".into()), - ..self_copy_request(schema, "src") - } + let fixed = Arc::new(Mutex::new(FakePlugin { + pages: vec![page_of(1..=1, true), page_of(2..=2, false)], + ..Default::default() + })); + let result = run_plugin_copy( + dir.path(), + "1.0.0-rc.16", + fixed.clone(), + ConflictMode::Fail, + false, + ) + .await; + assert_eq!(result.status, TransferStatus::Completed); + assert_eq!(result.rows_written, 2); } -async fn assert_read_only_target_is_rejected(pair: &SavedPair, request: TableTransferRequest) { - let plan = plan(&pair.runtime, None, request.clone()).await.unwrap(); - assert!(plan.blocking); - assert!(plan.issues.iter().any(|i| i.code == "targetReadOnly"), "{:?}", plan.issues); - - let error = run(&pair.runtime, &state(), None, request).await.unwrap_err(); - assert!(error.contains("blocking issues"), "{error}"); +#[tokio::test] +async fn a_value_the_plugin_cannot_write_exactly_fails_the_batch_before_any_write() { + let dir = tempfile::tempdir().unwrap(); + let blob_text = json!({ + "columns": [{"name": "id", "type": "int8"}, {"name": "name", "type": "text"}], + "rows": [[1, "fine"], [2, "BLOB:1:a:Zg=="]], + "has_more": false, + }); + let plugin = Arc::new(Mutex::new(FakePlugin { + pages: vec![blob_text], + ..Default::default() + })); + let result = run_plugin_copy( + dir.path(), + "1.0.0-rc.15", + plugin.clone(), + ConflictMode::Fail, + false, + ) + .await; + assert_eq!(result.status, TransferStatus::Failed); + let error = result.error.unwrap(); + assert!( + error.contains("row 2") && error.contains("\"name\""), + "{error}" + ); + assert!(!error.contains("Zg==")); + assert_eq!(count(&plugin, "insert_records"), 0); + assert_eq!(count(&plugin, "release_session"), 1); } #[tokio::test] -async fn a_saved_read_only_postgres_target_is_rejected_by_plan_and_run() { - let schema = "tt_ro_pg"; - let Some(_fixture) = seed_source(schema).await else { - return; +async fn a_plugin_source_can_write_into_sqlite() { + let dir = tempfile::tempdir().unwrap(); + let plugin = Arc::new(Mutex::new(FakePlugin { + pages: vec![page_of(1..=2, true), page_of(3..=3, false)], + ..Default::default() + })); + let target = sqlite_endpoint(&dir.path().join("t.db")).await; + let pool = get_sqlite_pool(&target.params).await.unwrap(); + sqlx::query("DROP TABLE dst").execute(&pool).await.unwrap(); + sqlx::query("CREATE TABLE dst (id INTEGER PRIMARY KEY, name TEXT)") + .execute(&pool) + .await + .unwrap(); + let source = pg_endpoint("1.0.0-rc.15", plugin.clone()); + let source_columns = [table_column("id", "bigint"), table_column("name", "text")]; + let target_columns = target + .drv + .get_columns(&target.params, "dst", None) + .await + .unwrap(); + let planned = build_table_plan(&PlanInputs { + selection: &pick("src", "dst"), + source_columns: &source_columns, + target_columns: &target_columns, + target_dialect: TransferDialect::Sqlite, + target_strict: false, + estimated_rows: None, + same_table: false, + }); + assert!(!planned.plan.blocking, "{:?}", planned.plan.issues); + let job = Job { + runtime: runtime(dir.path()), + session_id: None, + transfer_id: "pg-to-sqlite".into(), + cancel: Arc::new(AtomicBool::new(false)), + source, + target, + conflict: ConflictMode::Fail, + batch_rows: 2, + total_tables: 1, }; - pg_exec(&format!( - "CREATE TABLE {schema}.dst (id integer PRIMARY KEY, name text, amount numeric(12,2), big numeric(30,10), - payload bytea, note text, created timestamptz, flag boolean, meta jsonb, uid uuid);" - )) - .await; - crate::drivers::registry::register_driver(crate::drivers::postgres::PostgresDriver::new()).await; - let pair = runtime_with(pg_params(), read_only(pg_params())); - assert_read_only_target_is_rejected(&pair, copy_request(schema, Some(schema))).await; - assert_eq!(pg_scalar(&format!("SELECT count(*)::text FROM {schema}.dst")).await, "0"); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; + let result = run_job(job, vec![planned]).await.tables.remove(0); + assert_eq!(result.error, None); + assert_eq!(result.rows_written, 3); + let rows: Vec<(i64, String)> = sqlx::query_as("SELECT id, name FROM dst ORDER BY id") + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!( + rows, + vec![(1, "n1".into()), (2, "n2".into()), (3, "n3".into())] + ); + assert_eq!(count(&plugin, "release_session"), 1); } #[tokio::test] -async fn a_saved_read_only_sqlite_target_is_rejected_by_plan_and_run() { - let schema = "tt_ro_sqlite"; - let Some(_fixture) = seed_source(schema).await else { - return; - }; - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("target.db"); - sqlite_target(&path, SQLITE_DDL).await; - let pair = runtime_with(pg_params(), read_only(sqlite_params(&path))); - let mut request = copy_request(schema, None); - request.target_connection_id = "conn-b".into(); - assert_read_only_target_is_rejected(&pair, request).await; - assert_eq!(sqlite_count(&path).await, 0); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; +async fn the_postgres_side_of_a_copy_is_never_the_same_table_when_the_servers_differ() { + let a = pg_endpoint("1.0.0-rc.15", Arc::default()); + let mut b = pg_endpoint("1.0.0-rc.15", Arc::default()); + let mut a = a; + a.params.host = Some("db-one".into()); + b.params.host = Some("db-two".into()); + assert!(!reaches_same_database( + &a.params, + &b.params, + TransferDialect::Postgres + )); + b.params.host = Some("DB-ONE".into()); + assert!(reaches_same_database( + &a.params, + &b.params, + TransferDialect::Postgres + )); + // Sockets are never provable from the names alone. + a.params.unix_socket_path = Some("/tmp".into()); + assert!(!reaches_same_database( + &a.params, + &b.params, + TransferDialect::Postgres + )); } #[tokio::test] -async fn a_saved_read_only_source_stays_usable() { - let schema = "tt_ro_source"; - let Some(_fixture) = seed_source(schema).await else { - return; - }; +async fn a_cancel_that_lands_mid_copy_stops_after_the_batch_and_releases_the_session() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("target.db"); - sqlite_target(&path, SQLITE_DDL).await; - let pair = runtime_with(read_only(pg_params()), sqlite_params(&path)); - let plan = plan(&pair.runtime, None, copy_request(schema, None)).await.unwrap(); - assert!(!plan.blocking, "{:?}", plan.issues); - pg_exec(&format!("DROP SCHEMA {schema} CASCADE")).await; + let plugin = Arc::new(Mutex::new(FakePlugin { + pages: vec![ + page_of(1..=2, true), + page_of(3..=4, true), + page_of(5..=6, false), + ], + ..Default::default() + })); + let planned = int_text_planned(); + let cancel = Arc::new(AtomicBool::new(false)); + let job = Job { + runtime: runtime(dir.path()), + session_id: None, + transfer_id: "cancel-mid".into(), + cancel: cancel.clone(), + source: pg_endpoint("1.0.0-rc.16", plugin.clone()), + target: pg_endpoint("1.0.0-rc.16", plugin.clone()), + conflict: ConflictMode::Fail, + batch_rows: 2, + total_tables: 1, + }; + // Raise the flag once the first batch has been written. + let watcher = { + let plugin = plugin.clone(); + tokio::spawn(async move { + loop { + if !plugin.lock().unwrap().inserted.is_empty() { + cancel.store(true, Ordering::SeqCst); + return; + } + tokio::task::yield_now().await; + } + }) + }; + let result = run_job(job, vec![planned]).await.tables.remove(0); + watcher.await.unwrap(); + assert_eq!(result.status, TransferStatus::Cancelled); + assert!( + result.rows_written >= 2 && result.rows_written < 6, + "{}", + result.rows_written + ); + assert_eq!(count(&plugin, "release_session"), 1); } diff --git a/src-tauri/src/application/table_transfers.rs b/src-tauri/src/application/table_transfers.rs index ac2f194c4..84f9b52f2 100644 --- a/src-tauri/src/application/table_transfers.rs +++ b/src-tauri/src/application/table_transfers.rs @@ -214,7 +214,6 @@ pub(crate) fn column_reads(driver: &str, columns: &[TableColumn]) -> Vec ColumnRead::Text, "sqlite" => ColumnRead::Quoted, "mysql" if is_binary_type(&column.data_type) => ColumnRead::Hex, "mysql" if is_text_read_type(&column.data_type) => ColumnRead::Text, @@ -1425,7 +1424,7 @@ impl ImportReporter<'_> { // --- Helpers ----------------------------------------------------------------- fn is_builtin_driver(driver: &str) -> bool { - matches!(driver, "mysql" | "postgres" | "sqlite") + matches!(driver, "mysql" | "sqlite") } fn scope_database(params: &mut ConnectionParams, database: Option<&str>) { diff --git a/src-tauri/src/application/table_transfers_tests.rs b/src-tauri/src/application/table_transfers_tests.rs index 29108acca..e41824012 100644 --- a/src-tauri/src/application/table_transfers_tests.rs +++ b/src-tauri/src/application/table_transfers_tests.rs @@ -237,22 +237,7 @@ mod select { } #[test] - fn reads_postgres_columns_as_text_and_binary_columns_as_hex() { - let columns = [ - typed("id", "integer"), - typed("raw", "bytea"), - TableColumn { - is_generated: true, - ..typed("doubled", "integer") - }, - ]; - let reads = column_reads("postgres", &columns); - assert_eq!(reads, [ColumnRead::Text, ColumnRead::Text]); - assert_eq!( - export_select(&dialect("\"", true), Some("public"), "t", &columns, &reads), - "SELECT \"id\"::text AS \"id\", \"raw\"::text AS \"raw\" FROM \"public\".\"t\"" - ); - + fn reads_mysql_binary_columns_as_hex_and_text_columns_as_text() { let columns = [ typed("id", "int"), typed("raw", "BLOB"), diff --git a/src-tauri/src/clipboard_import_tests.rs b/src-tauri/src/clipboard_import_tests.rs index 93bf0cefe..242754719 100644 --- a/src-tauri/src/clipboard_import_tests.rs +++ b/src-tauri/src/clipboard_import_tests.rs @@ -22,10 +22,6 @@ fn import_uses_the_identifier_quote_each_builtin_driver_declares() { ), "`tabularis_demo`.`new_arrivals`" ); - assert_eq!( - import_identifier_quote(&crate::drivers::postgres::PostgresDriver::new()), - "\"" - ); assert_eq!( import_identifier_quote(&crate::drivers::sqlite::SqliteDriver::new()), "\"" @@ -135,7 +131,7 @@ fn import_keeps_quoted_values_for_columns_it_did_not_create() { ); assert_eq!(added, [false, false, false, true, false]); // Other drivers keep today's quoted values (PostgreSQL casts them to boolean). - for driver in ["postgres", "sqlite"] { + for driver in ["postgresql", "sqlite"] { assert_eq!( boolean_literal_columns( &new_arrivals_import(Vec::new()), @@ -179,7 +175,7 @@ fn mysql_appends_send_booleans_into_existing_tinyint_columns_as_literals() { assert_eq!( boolean_literal_columns( &new_arrivals_import(Vec::new()), - "postgres", + "postgresql", false, &existing ), @@ -205,12 +201,12 @@ fn existing_tinyint_columns_are_found_by_type() { fn string_literals_follow_the_resolved_literal_style() { let value = "O'Brien \\ a\nb"; let style_of = |caps: &DriverCapabilities| SqlSyntax::resolve(caps).string_escape; - let postgres = crate::drivers::postgres::PostgresDriver::new(); let mysql = crate::drivers::mysql::MysqlDriver::new(); + let sqlite = crate::drivers::sqlite::SqliteDriver::new(); // Built-in drivers keep the doubled quote, MySQL included. for caps in [ DriverCapabilities::default(), - postgres.manifest().capabilities.clone(), + sqlite.manifest().capabilities.clone(), mysql.manifest().capabilities.clone(), ] { assert_eq!( diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 886cc2d47..5e53b3a0c 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -16,11 +16,10 @@ async fn driver_for( ) -> Result, String> { crate::drivers::registry::get_driver(id) .await - .ok_or_else(|| format!("Unsupported driver: {}", id)) + .ok_or_else(|| crate::drivers::registry::unsupported_driver_message(id)) } const DEFAULT_MYSQL_PORT: u16 = 3306; -const DEFAULT_POSTGRES_PORT: u16 = 5432; /// Per-slot collection of abort handles for in-flight cancellable tasks. /// Used by `QueryCancellationState`, `ExportCancellationState`, and @@ -438,20 +437,6 @@ mod tests { assert_eq!(url, "mysql://root:secret@localhost:3306/testdb"); } - #[tokio::test] - async fn test_postgres_url_basic() { - let params = create_params( - "postgres", - "localhost", - Some(5432), - "postgres", - Some("secret"), - "testdb", - ); - let url = build_connection_url(¶ms).await.unwrap(); - assert_eq!(url, "postgres://postgres:secret@localhost:5432/testdb"); - } - #[tokio::test] async fn test_sqlite_url() { let params = create_params("sqlite", "", None, "", None, "/path/to/db.sqlite"); @@ -477,14 +462,8 @@ mod tests { #[tokio::test] async fn test_default_ports() { let mysql_params = create_params("mysql", "localhost", None, "root", None, "testdb"); - let pg_params = - create_params("postgres", "localhost", None, "postgres", None, "testdb"); - let mysql_url = build_connection_url(&mysql_params).await.unwrap(); - let pg_url = build_connection_url(&pg_params).await.unwrap(); - assert!(mysql_url.contains(":3306/")); - assert!(pg_url.contains(":5432/")); } #[tokio::test] @@ -505,9 +484,9 @@ mod tests { #[tokio::test] async fn test_remote_host() { let params = create_params( - "postgres", + "mysql", "db.example.com", - Some(5432), + Some(3306), "admin", Some("pass"), "production", @@ -1593,6 +1572,48 @@ pub(crate) async fn read_in_open_transaction( } } +/// Run a statement that may write on the connection pinned to `session_id`, +/// inside its open transaction. Unlike [`read_in_open_transaction`] the +/// savepoint is released on success, so the statement's effect stays in the +/// user's transaction; only a failed statement is rolled back to it, which +/// keeps the failure from aborting that transaction. +pub(crate) async fn write_in_open_transaction( + drv: &dyn crate::drivers::driver_trait::DatabaseDriver, + params: &ConnectionParams, + query: &str, + limit: Option, + page: u32, + schema: Option<&str>, + session_id: &str, +) -> Result { + let batch = [ + "SAVEPOINT tabularis_write".to_string(), + query.to_string(), + "RELEASE SAVEPOINT tabularis_write".to_string(), + ]; + let (results, _) = drv + .execute_batch_in_session(params, &batch, limit, page, schema, Some(session_id), None) + .await?; + match results.into_iter().nth(1) { + Some(BatchStatementResult { + result: Some(result), + .. + }) => Ok(result), + Some(BatchStatementResult { error: Some(e), .. }) => { + // The failed statement left the transaction aborted: undo to the savepoint. + let undo = [ + "ROLLBACK TO SAVEPOINT tabularis_write".to_string(), + "RELEASE SAVEPOINT tabularis_write".to_string(), + ]; + let _ = drv + .execute_batch_in_session(params, &undo, None, 1, schema, Some(session_id), None) + .await; + Err(e) + } + _ => Err("The statement produced no result".to_string()), + } +} + // --- Count Query --- // --- Window Title Management --- @@ -1610,13 +1631,6 @@ pub async fn build_connection_url(params: &ConnectionParams) -> Result Ok(format!("sqlite://{}", params.database)), - "postgres" => Ok(format!( - "postgres://{}@{}:{}/{}", - credentials, - host, - params.port.unwrap_or(DEFAULT_POSTGRES_PORT), - params.database - )), "mysql" => Ok(format!( "mysql://{}@{}:{}/{}", credentials, diff --git a/src-tauri/src/connection_import/analyzer.rs b/src-tauri/src/connection_import/analyzer.rs index 1d9dd8a92..c4536c229 100644 --- a/src-tauri/src/connection_import/analyzer.rs +++ b/src-tauri/src/connection_import/analyzer.rs @@ -244,7 +244,7 @@ mod tests { fn marks_duplicates() { let env = envelope(vec![conn("A", "Host", 5432, "DB", "User", "PostgreSQL")]); let existing = vec![saved("x", "Existing", "host", 5432, "db", "user")]; - let preview = analyze(&env, &existing, &["postgres".into()], &|_| true); + let preview = analyze(&env, &existing, &["postgresql".into()], &|_| true); assert!(matches!( preview.items[0].status, ImportItemStatus::Duplicate { .. } @@ -254,7 +254,7 @@ mod tests { #[test] fn warns_on_uninstalled_driver() { let env = envelope(vec![conn("A", "h", 27017, "db", "u", "MongoDB")]); - let preview = analyze(&env, &[], &["postgres".into()], &|_| true); + let preview = analyze(&env, &[], &["postgresql".into()], &|_| true); match &preview.items[0].status { ImportItemStatus::Warnings { warnings } => { assert!(warnings.iter().any(|w| w.contains("not installed"))); @@ -268,7 +268,7 @@ mod tests { #[test] fn ready_when_known_and_unique() { let env = envelope(vec![conn("A", "h", 5432, "db", "u", "PostgreSQL")]); - let preview = analyze(&env, &[], &["postgres".into()], &|_| true); + let preview = analyze(&env, &[], &["postgresql".into()], &|_| true); assert!(matches!(preview.items[0].status, ImportItemStatus::Ready)); } @@ -278,7 +278,7 @@ mod tests { // here surfaces as `Duplicate of ""` in the UI (see analyzer note). let env = envelope(vec![conn("A", "Host", 5432, "DB", "User", "PostgreSQL")]); let existing = vec![saved("x", "Existing Name", "host", 5432, "db", "user")]; - let preview = analyze(&env, &existing, &["postgres".into()], &|_| true); + let preview = analyze(&env, &existing, &["postgresql".into()], &|_| true); let json = serde_json::to_value(&preview.items[0].status).unwrap(); assert_eq!(json["kind"], "duplicate"); assert_eq!(json["existingId"], "x"); diff --git a/src-tauri/src/connection_import/convert.rs b/src-tauri/src/connection_import/convert.rs index e201e4c1e..9c925d770 100644 --- a/src-tauri/src/connection_import/convert.rs +++ b/src-tauri/src/connection_import/convert.rs @@ -296,7 +296,7 @@ mod tests { assert_eq!(payload.connections.len(), 1); assert_eq!(payload.groups.len(), 1); let c = &payload.connections[0]; - assert_eq!(c.params.driver, "postgres"); + assert_eq!(c.params.driver, "postgresql"); assert_eq!(c.group_id.as_deref(), Some(payload.groups[0].id.as_str())); assert_eq!(c.params.save_in_keychain, Some(false)); } diff --git a/src-tauri/src/connection_import/driver_map.rs b/src-tauri/src/connection_import/driver_map.rs index 85aff2aff..a37b6486a 100644 --- a/src-tauri/src/connection_import/driver_map.rs +++ b/src-tauri/src/connection_import/driver_map.rs @@ -19,7 +19,7 @@ pub fn map_driver_label(label: &str, registered_ids: &[String]) -> (String, bool /// at a plugin id (e.g. "MongoDB" -> "mongodb"). pub fn canonical_id(label: &str) -> String { match label.trim().to_ascii_lowercase().as_str() { - "postgresql" | "postgres" | "postgre" => "postgres".to_string(), + "postgresql" | "postgres" | "postgre" => "postgresql".to_string(), "mysql" | "mariadb" => "mysql".to_string(), "sqlite" | "sqlite3" => "sqlite".to_string(), "sql server" | "sqlserver" | "mssql" | "jtds" => "mssql".to_string(), @@ -41,7 +41,7 @@ pub fn canonical_id(label: &str) -> String { /// 0 means "no port" (file-based drivers such as SQLite). pub fn default_port(driver_id: &str) -> u16 { match driver_id { - "postgres" | "redshift" => 5432, + "postgres" | "postgresql" | "redshift" => 5432, "mysql" => 3306, "cockroachdb" => 26257, "mssql" => 1433, @@ -60,7 +60,7 @@ mod tests { #[test] fn maps_builtin_labels() { - assert_eq!(canonical_id("PostgreSQL"), "postgres"); + assert_eq!(canonical_id("PostgreSQL"), "postgresql"); assert_eq!(canonical_id("MySQL"), "mysql"); assert_eq!(canonical_id("MariaDB"), "mysql"); assert_eq!(canonical_id("SQLite"), "sqlite"); @@ -75,10 +75,10 @@ mod tests { #[test] fn installed_flag_reflects_registry() { - let registered = vec!["postgres".to_string(), "mysql".to_string()]; + let registered = vec!["postgresql".to_string(), "mysql".to_string()]; assert_eq!( map_driver_label("PostgreSQL", ®istered), - ("postgres".to_string(), true) + ("postgresql".to_string(), true) ); assert_eq!( map_driver_label("MongoDB", ®istered), @@ -89,6 +89,7 @@ mod tests { #[test] fn default_ports() { assert_eq!(default_port("postgres"), 5432); + assert_eq!(default_port("postgresql"), 5432); assert_eq!(default_port("mysql"), 3306); assert_eq!(default_port("sqlite"), 0); assert_eq!(default_port("mssql"), 1433); diff --git a/src-tauri/src/connection_migrations.rs b/src-tauri/src/connection_migrations.rs index 298cd18cd..0d3313799 100644 --- a/src-tauri/src/connection_migrations.rs +++ b/src-tauri/src/connection_migrations.rs @@ -13,7 +13,6 @@ use crate::drivers::driver_trait::SqlDialect; use crate::drivers::registry as driver_registry; use crate::models::SavedConnection; use crate::persistence; - /// The SSL mode dropdown used to branch on `driver === "postgres"` literally /// (issue #614), so a postgres-dialect driver with a different id (e.g. the /// standalone PostgreSQL plugin, id `"postgresql"`) offered MySQL-style @@ -41,23 +40,18 @@ pub(crate) fn stale_postgres_ssl_mode_replacement(value: &str) -> Option<&'stati /// Rewrites `conn.params.ssl_mode` in place if `conn`'s driver resolves (via /// `dialects`) to the postgres SQL dialect and its stored value is a stale -/// MySQL-style spelling. Builtin `"postgres"` connections are excluded — -/// their own dropdown was always correct, so nothing there needs migrating. -/// A driver whose manifest doesn't declare `sql_dialect` (`None`, or absent -/// from the map because it never resolved) is treated as NOT postgres — -/// deliberately not defaulted, unlike the splitter's own historical -/// postgres-default, because this migration must distinguish "explicitly -/// postgres" from "unspecified" to avoid rewriting a driver's SSL value -/// based on a guess. +/// MySQL-style spelling. A driver whose manifest doesn't declare +/// `sql_dialect` (`None`, or absent from the map because it never resolved) +/// is treated as NOT postgres — deliberately not defaulted, unlike the +/// splitter's own historical postgres-default, because this migration must +/// distinguish "explicitly postgres" from "unspecified" to avoid rewriting a +/// driver's SSL value based on a guess. /// Pure and synchronous so it can be exercised directly in tests without a /// live driver registry. Returns whether a rewrite happened. pub(crate) fn migrate_connection_ssl_mode_in_place( conn: &mut SavedConnection, dialects: &HashMap>, ) -> bool { - if conn.params.driver == "postgres" { - return false; - } let is_postgres_dialect = dialects .get(&conn.params.driver) .copied() @@ -93,10 +87,9 @@ pub(crate) fn connections_file_changed_concurrently( } /// Migrates already-persisted `ssl_mode` values on postgres-dialect -/// connections (driver id other than the builtin `"postgres"`) from the -/// stale MySQL-style spelling to the Postgres-style spelling the plugin -/// actually understands. Idempotent — a no-op once every affected -/// connection has been rewritten. +/// connections from the stale MySQL-style spelling to the Postgres-style +/// spelling the plugin actually understands. Idempotent — a no-op once +/// every affected connection has been rewritten. /// /// Path-based, no `AppHandle` — callable from both the GUI process (wrapped /// by `commands::migrate_postgres_ssl_mode_spelling`, which additionally @@ -139,8 +132,8 @@ pub async fn migrate_postgres_ssl_mode_spelling_at_path(conn_path: &Path) -> Res let mut dialects: HashMap> = HashMap::new(); for conn in &conn_file.connections { let driver_id = &conn.params.driver; - if driver_id == "postgres" || dialects.contains_key(driver_id) { - continue; // builtin driver's own dropdown was always correct + if dialects.contains_key(driver_id) { + continue; } if let Some(driver) = driver_registry::get_driver(driver_id).await { dialects.insert( @@ -177,3 +170,112 @@ pub async fn migrate_postgres_ssl_mode_spelling_at_path(conn_path: &Path) -> Res Ok(true) }) } + +/// The built-in driver id being removed and the plugin id that replaces it. +/// Once the built-in driver is deleted from the codebase, any saved +/// connection still on `"postgres"` can no longer open (`registry::get_driver` +/// returns `None`), so every such connection is force-flipped to +/// `"postgresql"` at launch — no dismissible nudge, no `undoMigration`, no +/// live fallback. This is the one-directional rewrite that makes removal safe. +const FORCE_MIGRATABLE_PAIRS: &[(&str, &str)] = &[("postgres", "postgresql")]; + +/// Rewrites `conn.params.driver` in place from a built-in id slated for +/// removal to its replacement plugin id. Pure and synchronous so it can be +/// exercised directly in tests without a live driver registry. Returns +/// whether a rewrite happened. +pub(crate) fn migrate_connection_driver_id_in_place( + conn: &mut SavedConnection, + pairs: &[(&str, &str)], +) -> bool { + for &(from, to) in pairs { + if conn.params.driver == from { + conn.params.driver = to.to_string(); + return true; + } + } + false +} + +/// Force-migrates already-persisted `driver` ids on saved connections from a +/// built-in driver that is being removed to its replacement plugin. Unlike +/// the opt-in `useBuiltinDriverMigration` flow, this runs automatically at +/// launch (no user click, no dismissible banner). There is no +/// `undoMigration` — the built-in driver is gone, so flipping back is not +/// possible. +/// +/// Path-based, no `AppHandle` — callable from both the GUI process (wrapped +/// by `commands::migrate_builtin_driver_ids`, which invalidates the +/// connection cache) and the standalone `--mcp` server process. Idempotent — +/// a no-op once every affected connection has been rewritten. Uses the same +/// concurrency guard as [`migrate_postgres_ssl_mode_spelling_at_path`]. +/// +/// Returns `Ok(true)` only once the rewrite has been committed to disk; +/// `Ok(false)` covers "nothing needed migrating" and "skipped because the +/// file changed concurrently" (see the concurrency note on +/// [`migrate_postgres_ssl_mode_spelling_at_path`]). +/// +/// # Known limitation +/// +/// The concurrent-edit check narrows the race with another writer but does not +/// close it. The read, the re-read that compares against it, and the save are +/// three separate steps. The in-process file lock covers only the save, and it +/// cannot reach a second process (the GUI and `--mcp` do not share it). An edit +/// that another process commits between the re-read and the save is replaced +/// by the migrated snapshot. The window is short (the `eprintln!` between the +/// check and the save is its main cost), only opens on a launch where a +/// `postgres` connection still needs rewriting, and needs a simultaneous edit +/// from another process, so it is accepted rather than closed. Closing it +/// would take a cross-process file lock (or a compare-and-swap commit) held by +/// every `connections.json` writer. +pub async fn migrate_builtin_driver_ids_at_path(conn_path: &Path) -> Result { + migrate_builtin_driver_ids_when(conn_path, |_| true).await +} + +/// [`migrate_builtin_driver_ids_at_path`], moving a connection only when +/// `can_move` accepts the plugin id it would move to. A connection that stays +/// is left on its built-in id, so nothing is rewritten to a plugin that cannot +/// serve it yet; the move happens on a later launch once it can. +pub async fn migrate_builtin_driver_ids_when( + conn_path: &Path, + can_move: impl Fn(&str) -> bool, +) -> Result { + if !conn_path.exists() { + return Ok(false); // Nothing to migrate + } + + let content_before = fs::read_to_string(conn_path).map_err(|e| e.to_string())?; + let mut conn_file = persistence::parse_connections_file(&content_before)?; + + let mut migrated_count = 0usize; + let ready: Vec<(&str, &str)> = FORCE_MIGRATABLE_PAIRS + .iter() + .copied() + .filter(|(_, to)| can_move(to)) + .collect(); + for conn in conn_file.connections.iter_mut() { + if migrate_connection_driver_id_in_place(conn, &ready) { + migrated_count += 1; + } + } + + if migrated_count == 0 { + return Ok(false); // No migration needed + } + + // Bail if another process (e.g. the GUI) saved a concurrent edit while + // we were computing the migration above — don't blindly overwrite it. + let content_now = fs::read_to_string(conn_path).map_err(|e| e.to_string())?; + if connections_file_changed_concurrently(&content_before, &content_now) { + eprintln!( + "[Migration] connections.json changed concurrently — skipping this run, will retry next launch" + ); + return Ok(false); + } + + eprintln!( + "[Migration] Force-migrating {} connection(s) from built-in postgres driver to postgresql plugin", + migrated_count + ); + persistence::save_connections_file(conn_path, &conn_file)?; + Ok(true) +} diff --git a/src-tauri/src/connection_migrations_tests.rs b/src-tauri/src/connection_migrations_tests.rs index 3b5cf46c3..7d3b9ebbc 100644 --- a/src-tauri/src/connection_migrations_tests.rs +++ b/src-tauri/src/connection_migrations_tests.rs @@ -5,8 +5,10 @@ mod tests { use tempfile::TempDir; use crate::connection_migrations::{ - connections_file_changed_concurrently, migrate_connection_ssl_mode_in_place, - migrate_postgres_ssl_mode_spelling_at_path, stale_postgres_ssl_mode_replacement, + connections_file_changed_concurrently, migrate_builtin_driver_ids_at_path, + migrate_builtin_driver_ids_when, migrate_connection_driver_id_in_place, + migrate_connection_ssl_mode_in_place, migrate_postgres_ssl_mode_spelling_at_path, + stale_postgres_ssl_mode_replacement, }; use crate::drivers::driver_trait::SqlDialect; use crate::models::{ConnectionParams, ConnectionsFile, DatabaseSelection, SavedConnection}; @@ -120,21 +122,6 @@ mod tests { assert_eq!(conn.params.ssl_mode.as_deref(), Some("required")); } - #[test] - fn migrate_connection_ssl_mode_leaves_the_builtin_postgres_driver_alone() { - // The builtin driver's own dropdown was always correct — even if it - // somehow ended up with a stale value, this migration is scoped to - // plugin-driven connections only (driver id != "postgres"). - let mut dialects = HashMap::new(); - dialects.insert("postgres".to_string(), Some(SqlDialect::Postgres)); - let mut conn = saved_connection("postgres", Some("required")); - - let rewrote = migrate_connection_ssl_mode_in_place(&mut conn, &dialects); - - assert!(!rewrote); - assert_eq!(conn.params.ssl_mode.as_deref(), Some("required")); - } - #[test] fn migrate_connection_ssl_mode_leaves_an_unresolved_driver_alone() { // No entry in `dialects` (e.g. the driver failed to resolve from the @@ -223,6 +210,7 @@ mod tests { let file = ConnectionsFile { groups: Vec::new(), // Builtin "postgres" is always skipped, regardless of ssl_mode. + credential_profiles: Vec::new(), connections: vec![saved_connection("postgres", Some("required"))], tags: Vec::new(), ..Default::default() @@ -241,4 +229,174 @@ mod tests { "a no-op run must not rewrite the file at all" ); } + + #[test] + fn migrate_connection_driver_id_flips_postgres_to_postgresql() { + let mut conn = saved_connection("postgres", None); + assert!(migrate_connection_driver_id_in_place( + &mut conn, + &[("postgres", "postgresql")] + )); + assert_eq!(conn.params.driver, "postgresql"); + } + + #[test] + fn migrate_connection_driver_id_leaves_non_migratable_drivers_alone() { + let mut conn = saved_connection("mysql", None); + assert!(!migrate_connection_driver_id_in_place( + &mut conn, + &[("postgres", "postgresql")] + )); + assert_eq!(conn.params.driver, "mysql"); + } + + #[test] + fn migrate_connection_driver_id_leaves_already_migrated_connections_alone() { + let mut conn = saved_connection("postgresql", None); + assert!(!migrate_connection_driver_id_in_place( + &mut conn, + &[("postgres", "postgresql")] + )); + assert_eq!(conn.params.driver, "postgresql"); + } + + #[test] + fn migrate_connection_driver_id_is_idempotent() { + let mut conn = saved_connection("postgres", None); + assert!(migrate_connection_driver_id_in_place( + &mut conn, + &[("postgres", "postgresql")] + )); + // A second pass finds no `"postgres"` connection to flip. + assert!(!migrate_connection_driver_id_in_place( + &mut conn, + &[("postgres", "postgresql")] + )); + assert_eq!(conn.params.driver, "postgresql"); + } + + #[tokio::test] + async fn migrate_builtin_driver_ids_at_path_is_a_noop_for_a_missing_file() { + let dir = TempDir::new().expect("create temp dir"); + let path = dir.path().join("connections.json"); + + let migrated = migrate_builtin_driver_ids_at_path(&path) + .await + .expect("missing file is not an error"); + + assert!(!migrated); + } + + #[tokio::test] + async fn migrate_builtin_driver_ids_at_path_flips_postgres_to_postgresql() { + let dir = TempDir::new().expect("create temp dir"); + let path = dir.path().join("connections.json"); + let file = ConnectionsFile { + groups: Vec::new(), + credential_profiles: Vec::new(), + connections: vec![ + saved_connection("postgres", None), + saved_connection("mysql", None), + ], + tags: Vec::new(), + }; + persistence::save_connections_file(&path, &file).expect("seed fixture"); + + let migrated = migrate_builtin_driver_ids_at_path(&path) + .await + .expect("a successful migration is not an error"); + + assert!(migrated); + let after = persistence::parse_connections_file( + &std::fs::read_to_string(&path).expect("read after"), + ) + .expect("parse after"); + let drivers: Vec<&str> = after + .connections + .iter() + .map(|c| c.params.driver.as_str()) + .collect(); + assert_eq!(drivers, vec!["postgresql", "mysql"]); + } + + #[tokio::test] + async fn migrate_builtin_driver_ids_at_path_is_a_noop_when_nothing_needs_migrating() { + let dir = TempDir::new().expect("create temp dir"); + let path = dir.path().join("connections.json"); + let file = ConnectionsFile { + groups: Vec::new(), + credential_profiles: Vec::new(), + connections: vec![ + saved_connection("postgresql", None), + saved_connection("mysql", None), + ], + tags: Vec::new(), + }; + persistence::save_connections_file(&path, &file).expect("seed fixture"); + let content_before = std::fs::read_to_string(&path).expect("read fixture"); + + let migrated = migrate_builtin_driver_ids_at_path(&path) + .await + .expect("no migration needed is not an error"); + + assert!(!migrated); + let content_after = std::fs::read_to_string(&path).expect("read after"); + assert_eq!( + content_before, content_after, + "a no-op run must not rewrite the file at all" + ); + } + + #[tokio::test] + async fn migrate_builtin_driver_ids_at_path_is_idempotent() { + let dir = TempDir::new().expect("create temp dir"); + let path = dir.path().join("connections.json"); + let file = ConnectionsFile { + groups: Vec::new(), + credential_profiles: Vec::new(), + connections: vec![saved_connection("postgres", None)], + tags: Vec::new(), + }; + persistence::save_connections_file(&path, &file).expect("seed fixture"); + + let first = migrate_builtin_driver_ids_at_path(&path) + .await + .expect("first run"); + assert!(first, "first run should flip the connection"); + + let second = migrate_builtin_driver_ids_at_path(&path) + .await + .expect("second run"); + assert!(!second, "second run is a no-op — nothing left to flip"); + } + + #[tokio::test] + async fn a_connection_waits_on_the_builtin_id_until_the_plugin_can_serve_it() { + let dir = TempDir::new().expect("create temp dir"); + let path = dir.path().join("connections.json"); + let file = ConnectionsFile { + groups: Vec::new(), + credential_profiles: Vec::new(), + connections: vec![saved_connection("postgres", None)], + tags: Vec::new(), + }; + persistence::save_connections_file(&path, &file).expect("seed fixture"); + let before = std::fs::read_to_string(&path).expect("read fixture"); + + let moved = migrate_builtin_driver_ids_when(&path, |_| false) + .await + .expect("a refused move is not an error"); + + assert!(!moved); + assert_eq!( + std::fs::read_to_string(&path).expect("read after"), + before, + "a connection the plugin cannot serve yet must not be rewritten" + ); + + let moved = migrate_builtin_driver_ids_when(&path, |plugin| plugin == "postgresql") + .await + .expect("the move once the plugin is ready"); + assert!(moved); + } } diff --git a/src-tauri/src/credential_profiles.rs b/src-tauri/src/credential_profiles.rs index 3eab1e098..71806df3b 100644 --- a/src-tauri/src/credential_profiles.rs +++ b/src-tauri/src/credential_profiles.rs @@ -110,7 +110,9 @@ pub fn create_profile_impl( .iter() .any(|profile| profile.name.eq_ignore_ascii_case(name)) { - return Err(format!("A credential profile named \"{name}\" already exists")); + return Err(format!( + "A credential profile named \"{name}\" already exists" + )); } let id = Uuid::new_v4().to_string(); validate_profile_keychain_namespace(file, &id)?; @@ -136,7 +138,9 @@ pub fn update_profile_impl( .iter() .any(|profile| profile.id != id && profile.name.eq_ignore_ascii_case(name)) { - return Err(format!("A credential profile named \"{name}\" already exists")); + return Err(format!( + "A credential profile named \"{name}\" already exists" + )); } let profile = file .credential_profiles diff --git a/src-tauri/src/drivers/driver_trait.rs b/src-tauri/src/drivers/driver_trait.rs index 486c9bda8..d020c638d 100644 --- a/src-tauri/src/drivers/driver_trait.rs +++ b/src-tauri/src/drivers/driver_trait.rs @@ -12,6 +12,35 @@ use crate::models::{ RoutineParameter, TableColumn, TableInfo, TableSchema, TriggerInfo, ViewInfo, }; +/// One column of a [`CopyRows`] page: its name and the driver's own type name +/// (`int8`, `timestamptz`), which the host maps to a conversion. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +pub struct CopyColumn { + pub name: String, + #[serde(rename = "type")] + pub type_name: String, +} + +/// A page of a lossless `read_rows` response. +#[derive(Clone, Debug, Deserialize)] +pub struct CopyRows { + #[serde(default)] + pub columns: Vec, + #[serde(default)] + pub rows: Vec>, + #[serde(default)] + pub has_more: bool, +} + +/// Result of one `insert_records` batch. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +pub struct CopyInsertOutcome { + #[serde(default)] + pub affected_rows: u64, + #[serde(default)] + pub skipped: u64, +} + /// Plugin-declared native whole-file backup. The host echoes `format` and /// takes the file extension and UI labels from the plugin. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] @@ -296,6 +325,11 @@ pub struct DriverCapabilities { /// this allows users to switch a writable connection into read-only mode. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub read_only_queries: bool, + /// Implements the lossless `read_rows`, `insert_records` and + /// `release_session` RPCs, so the host can copy a table row by row to or + /// from this driver. Only meaningful with `sql_dialect: "postgres"`. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub table_copy: bool, /// Offers "Export table to SQL" on table nodes (#709). `None` (the /// manifest omits it) means enabled; non-SQL plugins set `false`. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -428,13 +462,8 @@ pub struct DeprecationInfo { /// (see the design doc's "Measuring adoption" section). pub fn deprecation_for_builtin(builtin_id: &str) -> Option { match builtin_id { - "postgres" => Some(DeprecationInfo { - replacement_id: Some("postgresql".to_string()), - removal_date: Some("2026-10-05".to_string()), - removal_version: None, - }), - // mysql and sqlite are expected to follow the same path later; not - // deprecated yet, so they return `None` and get no badge. + // mysql and sqlite are expected to follow the same deprecation path + // later; not deprecated yet, so they return `None` and get no badge. _ => None, } } @@ -1051,6 +1080,35 @@ pub trait DatabaseDriver: Send + Sync { /// connections have nothing to do. async fn release_session(&self, _session_id: &str) {} + /// Lossless page of a `SELECT`, for table-to-table copy. Only called when + /// `capabilities.table_copy` is set. `session_id` pins one snapshot (and + /// one cursor) across pages; the caller releases it with + /// [`Self::release_session`] on every exit path. + async fn read_rows( + &self, + _params: &ConnectionParams, + _query: &str, + _limit: u32, + _page: u32, + _schema: Option<&str>, + _session_id: &str, + ) -> Result { + Err("This driver does not support table copy".to_string()) + } + + /// Writes one batch of typed rows into `table` in a single transaction. + /// Only called when `capabilities.table_copy` is set. + async fn insert_records( + &self, + _params: &ConnectionParams, + _table: &str, + _schema: Option<&str>, + _rows: Vec>, + _skip_conflicts: bool, + ) -> Result { + Err("This driver does not support table copy".to_string()) + } + /// Whether `session_id` is still inside a transaction, asked after a /// failed or cancelled run, which returns no flag. A driver that pins only /// while a transaction is open can answer with whether it holds a pinned diff --git a/src-tauri/src/drivers/driver_trait_tests.rs b/src-tauri/src/drivers/driver_trait_tests.rs index e417519db..49c46b7d8 100644 --- a/src-tauri/src/drivers/driver_trait_tests.rs +++ b/src-tauri/src/drivers/driver_trait_tests.rs @@ -36,14 +36,6 @@ fn manifest_accepts_both_connection_string_example_spellings() { } } -#[test] -fn postgres_is_deprecated_in_favour_of_the_postgresql_plugin() { - let info = deprecation_for_builtin("postgres").expect("postgres is deprecated"); - assert_eq!(info.replacement_id, Some("postgresql".to_string())); - assert_eq!(info.removal_date, Some("2026-10-05".to_string())); - assert_eq!(info.removal_version, None); -} - #[test] fn drivers_without_a_wired_deprecation_return_none() { // mysql/sqlite are expected to follow the same path later, but aren't diff --git a/src-tauri/src/drivers/mysql/mod.rs b/src-tauri/src/drivers/mysql/mod.rs index df5617830..4d5cfea1a 100644 --- a/src-tauri/src/drivers/mysql/mod.rs +++ b/src-tauri/src/drivers/mysql/mod.rs @@ -2097,6 +2097,7 @@ impl MysqlDriver { explain: true, readonly: false, read_only_queries: true, + table_copy: false, table_export: None, table_import: None, triggers: true, diff --git a/src-tauri/src/drivers/postgres/README.md b/src-tauri/src/drivers/postgres/README.md new file mode 100644 index 000000000..4214d931a --- /dev/null +++ b/src-tauri/src/drivers/postgres/README.md @@ -0,0 +1,17 @@ +# PostgreSQL Driver + +The built-in PostgreSQL driver has been removed from Tabularis core. + +PostgreSQL connections are now handled exclusively by the standalone +[`tabularis-postgresql-plugin`](https://github.com/TabularisDB/tabularis-postgresql-plugin). + +Changes to the PostgreSQL driver implementation, and the tests that cover it, +belong in that plugin repository, not here. Tabularis core still owns the +host-side integration with plugin drivers, including the force-migration of +saved `postgres` connections to `postgresql`, the host-to-plugin contract +tests (for example `src-tauri/tests/socket_integration.rs`) and the PostgreSQL +server fixtures they use. + +If you are looking for the driver implementation that used to live in this +directory, see the git history +(`git log --all -- src-tauri/src/drivers/postgres/`) or the plugin repo above. diff --git a/src-tauri/src/drivers/postgres/binding.rs b/src-tauri/src/drivers/postgres/binding.rs deleted file mode 100644 index 2f4f7f0a0..000000000 --- a/src-tauri/src/drivers/postgres/binding.rs +++ /dev/null @@ -1,656 +0,0 @@ -use super::helpers::{ - escape_identifier, extract_base_type, is_raw_sql_function, is_wkt_geometry, - json_array_to_pg_literal, try_parse_pg_array, -}; -use crate::drivers::common::parse_unsafe_bigint_string; -use std::collections::HashMap; -use tokio_postgres::types::{ToSql, Type}; - -pub(super) type PgParam = Box; - -/// A boxed parameter plus the PostgreSQL wire type it must be declared as. -/// -/// `tokio-postgres` lets a caller pin a parameter's type via `prepare_typed` -/// instead of having the server infer it from query context. Pinning matters -/// whenever the bound Rust value's natural type does not match what the SQL -/// expression around the placeholder implies — most commonly a `String` bound -/// into `CAST($N AS uuid)` / `CAST($N AS timestamptz)` etc., where the column's -/// real type would otherwise be inferred for the placeholder and the bind is -/// rejected client-side with "error serializing parameter N" (#392, #401) -/// before the value ever reaches PostgreSQL's own (perfectly capable) text-to- -/// temporal/uuid parsing. Declaring the placeholder as `TEXT` instead makes the -/// `CAST` do the actual conversion server-side, exactly like a literal in a -/// plain SQL statement. -pub(super) type TypedPgParam = (PgParam, Type); - -pub(super) struct BoundValue { - pub sql: String, - pub param: Option, -} - -pub(super) struct PgValueOptions<'a> { - pub column_type: Option<&'a str>, - /// Schema-qualified, already-quoted enum type name (e.g. `"public"."plan_type"`) - /// when the target column is a PostgreSQL enum; `None` otherwise. Drives the - /// `CAST($N AS )` coercion in [`bind_pg_enum_string`] (#465). - pub enum_type: Option<&'a str>, - pub max_blob_size: u64, - pub allow_default: bool, - pub hstore_oid: Option, -} - -/// Build a parameterized " = $N" predicate plus the boxed parameter for the -/// given JSON pk_val. Numeric values are cast through bigint/double precision so the -/// bind succeeds against int2/int4/int8/real columns; UUID strings are bound as the -/// `Uuid` type so PostgreSQL receives the matching OID. -/// -/// `pk_type` is the PK column's declared type (e.g. `"uuid"`, `"character -/// varying"`); `None` when column metadata could not be loaded. It decides how a -/// uuid-/integer-shaped string binds: a uuid-shaped value goes out as the native -/// `Uuid` type only for an actual `uuid` column — a `varchar`/`text` PK that merely -/// holds a uuid-shaped string (e.g. `guid varchar(36)`) must bind as text, or -/// tokio-postgres rejects the param with "error serializing parameter N" (#392). -/// When the type is unknown we fall back to the shape heuristic. -pub(super) fn build_pk_predicate( - pk_col: &str, - pk_val: serde_json::Value, - placeholder_idx: usize, - pk_type: Option<&str>, -) -> Result<(String, Option), String> { - let col = format!("\"{}\"", escape_identifier(pk_col)); - let base_type = pk_type.map(extract_base_type); - let is_real = matches!(base_type.as_deref(), Some("REAL" | "FLOAT4")); - // Numeric and numeric-string float4 values must compare at column precision. - let row_value_sql = |sql: String| { - if is_real { - format!("CAST({sql} AS real)") - } else { - sql - } - }; - match pk_val { - serde_json::Value::Number(n) => { - let bound = bind_pg_number(&n, placeholder_idx)?; - let sql = row_value_sql(bound.sql); - let param = bound - .param - .ok_or_else(|| "Internal PostgreSQL numeric binding error".to_string())?; - Ok((format!("{} = {}", col, sql), Some(param))) - } - serde_json::Value::String(s) => { - let base = base_type.as_deref().map(str::to_lowercase); - - if matches!(base.as_deref(), Some("uuid") | None) { - if let Ok(uuid) = s.parse::() { - return Ok(( - format!("{} = ${}", col, placeholder_idx), - Some((Box::new(uuid), Type::UUID)), - )); - } - } - - // Keyless tables (#598) identify rows by every column, so the - // predicate can target numeric/temporal columns whose values reach - // the driver as JSON strings (numeric serializes as string to - // preserve arbitrary precision). Route them through the same - // coercions as SET binding — a plain TEXT bind trips SQLSTATE - // 42883, e.g. "operator does not exist: numeric = text". - if let Some(pk_type) = pk_type { - if let Some(bound) = bind_pg_numeric_string(&s, pk_type, placeholder_idx) - .or_else(|| bind_pg_temporal_string(&s, pk_type, placeholder_idx)) - { - let bound = bound?; - let param = bound - .param - .ok_or_else(|| "Internal PostgreSQL numeric binding error".to_string())?; - return Ok(( - format!("{} = {}", col, row_value_sql(bound.sql)), - Some(param), - )); - } - } - - // Bigint PK values outside JS safe range arrive from the UI as - // strings. Cast through bigint so the equality test against an int8 - // column does not trip a type mismatch — but skip for known text - // columns, which would reject `varchar = bigint`. - let integerish = matches!( - base.as_deref(), - Some("smallint" | "integer" | "bigint" | "int2" | "int4" | "int8") | None - ); - if integerish { - if let Some(n) = parse_unsafe_bigint_string(&s) { - return Ok(( - format!("{} = CAST(${} AS bigint)", col, placeholder_idx), - Some((Box::new(n), Type::INT8)), - )); - } - } - - Ok(( - format!("{} = ${}", col, placeholder_idx), - Some((Box::new(s), Type::TEXT)), - )) - } - serde_json::Value::Bool(b) => Ok(( - format!("{} = ${}", col, placeholder_idx), - Some((Box::new(b), Type::BOOL)), - )), - // Keyless tables identify rows by all comparable columns, so the map - // may legitimately carry NULLs — `= NULL` never matches, use IS NULL. - // No parameter is bound, so the placeholder index is not consumed. - serde_json::Value::Null => Ok((format!("{} IS NULL", col), None)), - _ => Err("Unsupported PK type".into()), - } -} - -/// Build a compound WHERE predicate from all entries of a pk_map. -/// Keys are sorted for determinism. Returns the predicate string and all boxed params. -/// E.g. `"col1" = $2 AND "col2" = $3` with params starting at placeholder_idx. -/// -/// `pk_types` maps each PK column to its declared type (e.g. `"uuid"`, `"character -/// varying"`); a column missing from the map binds via the shape heuristic. The type -/// is threaded per column into [`build_pk_predicate`] so each member of a composite PK -/// binds correctly — including a uuid-shaped value in a `varchar`/`text` column (#392). -pub(super) fn build_pk_map_predicate( - pk_map: &HashMap, - pk_types: &HashMap, - placeholder_idx: usize, -) -> Result<(String, Vec), String> { - if pk_map.is_empty() { - return Err("pk_map must not be empty".into()); - } - let mut keys: Vec<&String> = pk_map.keys().collect(); - keys.sort(); - let mut predicates = Vec::new(); - let mut params: Vec = Vec::new(); - for key in keys { - let val = pk_map[key].clone(); - let (pred, param) = build_pk_predicate( - key, - val, - placeholder_idx + params.len(), - pk_types.get(key).map(|s| s.as_str()), - )?; - predicates.push(pred); - // IS NULL predicates bind no parameter, so they don't advance the - // placeholder index. - if let Some(param) = param { - params.push(param); - } - } - Ok((predicates.join(" AND "), params)) -} - -pub(super) fn bind_pg_value( - value: serde_json::Value, - placeholder_idx: usize, - options: PgValueOptions<'_>, -) -> Result { - // The driver unfolds information_schema's generic 'USER-DEFINED' to the real - // udt_name, so an hstore column reports its type as plain "hstore" here. - if options.column_type == Some("hstore") { - return bind_pg_hstore(value, placeholder_idx, options.hstore_oid); - } - // Bind serde_json::Value directly for json/jsonb — serialize-and-cast trips an OID mismatch. - if let Some(ct) = options.column_type { - let normalized = extract_base_type(ct); - if matches!(normalized.as_str(), "JSON" | "JSONB") { - match &value { - serde_json::Value::String(_) | serde_json::Value::Null => {} - _ => { - let pg_type = if normalized == "JSONB" { - Type::JSONB - } else { - Type::JSON - }; - return Ok(BoundValue { - sql: format!("${}", placeholder_idx), - param: Some((Box::new(value), pg_type)), - }); - } - } - } - } - - match value { - serde_json::Value::Number(n) => bind_pg_number(&n, placeholder_idx), - serde_json::Value::String(s) => bind_pg_string(&s, placeholder_idx, options), - serde_json::Value::Bool(b) => Ok(BoundValue { - sql: format!("${}", placeholder_idx), - param: Some((Box::new(b), Type::BOOL)), - }), - serde_json::Value::Null => Ok(BoundValue { - sql: "NULL".to_string(), - param: None, - }), - serde_json::Value::Array(arr) => Ok(BoundValue { - sql: json_array_to_pg_literal(&arr)?, - param: None, - }), - serde_json::Value::Object(_) => { - Err("Cannot bind a JSON object to a non-JSON column".into()) - } - } -} - -/// Binds a JSON object to an hstore column as `HashMap>`, -/// which `tokio-postgres` encodes natively via its built-in hstore `ToSql` impl. -/// Requires the real OID of the `hstore` type in this database (extension-defined, -/// not a well-known Postgres OID) so `prepare_typed` pins the placeholder correctly. -fn bind_pg_hstore( - value: serde_json::Value, - placeholder_idx: usize, - hstore_oid: Option, -) -> Result { - let map = match value { - serde_json::Value::Null => { - return Ok(BoundValue { - sql: "NULL".to_string(), - param: None, - }); - } - serde_json::Value::Object(map) => map, - - // The grid's plain-text cell editor doesn't yet know about hstore, so it - // round-trips the value as a JSON-encoded string rather than an object. - // Accept that shape here so editing still works until the editor is - // taught to treat hstore columns like JSON (issue #395). - serde_json::Value::String(s) => match serde_json::from_str::(&s) { - Ok(serde_json::Value::Object(map)) => map, - _ => { - return Err(format!( - "hstore column requires a JSON object value, got a string that is not valid JSON: {:?}", - s - )); - } - }, - other => { - return Err(format!( - "hstore column requires a JSON object value, got {:?}", - other - )); - } - }; - - let oid = hstore_oid.ok_or_else(|| { - "Could not resolve the hstore type OID; is the hstore extension installed?".to_string() - })?; - let hmap = hstore_map_from_json_object(map)?; - let pg_type = Type::new( - "hstore".to_string(), - oid, - tokio_postgres::types::Kind::Simple, - "public".to_string(), - ); - Ok(BoundValue { - sql: format!("${}", placeholder_idx), - param: Some((Box::new(hmap), pg_type)), - }) -} - -/// Converts a JSON object into the `HashMap>` shape that -/// `tokio-postgres` encodes natively as hstore. Every value must be a string or -/// null — hstore itself only stores text, so numbers/bools/nested objects have no -/// unambiguous representation and are rejected with a message naming the offending key. -fn hstore_map_from_json_object( - map: serde_json::Map, -) -> Result>, String> { - let mut hmap = HashMap::with_capacity(map.len()); - for (k, v) in map { - let val = match v { - serde_json::Value::String(s) => Some(s), - serde_json::Value::Null => None, - other => { - return Err(format!( - "hstore value for key '{}' must be a string or null, got {:?}", - k, other - )); - } - }; - hmap.insert(k, val); - } - Ok(hmap) -} - -/// SQL fragment + boxed parameter for a JSON Number bound to PostgreSQL. -/// -/// tokio-postgres binds Rust `i64` as INT8 and `f64` as FLOAT8, and rejects the -/// bind when the column is INT2/INT4/REAL with "error serializing parameter X". -/// Wrapping the placeholder in `CAST($N AS bigint)` / `CAST($N AS double precision)` -/// lets PostgreSQL convert to the actual column width via its assignment / implicit -/// comparison casts. -pub(super) fn bind_pg_number( - n: &serde_json::Number, - placeholder_idx: usize, -) -> Result { - if let Some(v) = n.as_i64() { - Ok(BoundValue { - sql: format!("CAST(${} AS bigint)", placeholder_idx), - param: Some((Box::new(v), Type::INT8)), - }) - } else if let Some(v) = n.as_f64() { - Ok(BoundValue { - sql: format!("CAST(${} AS double precision)", placeholder_idx), - param: Some((Box::new(v), Type::FLOAT8)), - }) - } else { - Err(format!("Unsupported numeric value: {}", n)) - } -} - -/// Coerce a string value into a Rust `bool` for PostgreSQL `boolean` columns. -/// -/// `tokio-postgres` rejects a string bound to a `bool` column with -/// "error serializing parameter X". The data grid editor sends every cell as -/// a JSON string, so a "true"/"false" string never reaches `bind_pg_value`'s -/// `Bool` arm. This helper mirrors the literal forms PostgreSQL accepts for -/// `boolean` (case-insensitive, surrounding whitespace tolerated). -/// -/// Returns `None` if the column is not boolean, so callers can fall through -/// to the next coercion path. -pub(super) fn bind_pg_boolean_string( - s: &str, - column_type: &str, - placeholder_idx: usize, -) -> Option> { - let normalized = extract_base_type(column_type).to_lowercase(); - if !matches!(normalized.as_str(), "boolean" | "bool") { - return None; - } - - let parsed = match s.trim().to_lowercase().as_str() { - "true" | "t" | "yes" | "y" | "on" | "1" => Some(true), - "false" | "f" | "no" | "n" | "off" | "0" => Some(false), - _ => None, - }; - - Some(parsed.map_or_else( - || { - Err(format!( - "Cannot convert value {:?} to PostgreSQL boolean column type {}", - s, column_type - )) - }, - |b| { - Ok(BoundValue { - sql: format!("${}", placeholder_idx), - param: Some((Box::new(b) as PgParam, Type::BOOL)), - }) - }, - )) -} - -pub(super) fn bind_pg_numeric_string( - s: &str, - column_type: &str, - placeholder_idx: usize, -) -> Option> { - let trimmed = s.trim(); - let normalized = extract_base_type(column_type).to_lowercase(); - - if matches!( - normalized.as_str(), - "smallint" | "integer" | "bigint" | "int2" | "int4" | "int8" | "serial" | "bigserial" - ) { - return Some(trimmed.parse::().map_or_else( - |e| { - Err(format!( - "Cannot convert value {:?} to PostgreSQL numeric column type {}: {}", - s, column_type, e - )) - }, - |v| { - Ok(BoundValue { - sql: format!("CAST(${} AS bigint)", placeholder_idx), - param: Some((Box::new(v) as PgParam, Type::INT8)), - }) - }, - )); - } - - if matches!(normalized.as_str(), "numeric" | "decimal") { - return Some(trimmed.parse::().map_or_else( - |e| { - Err(format!( - "Cannot convert value {:?} to PostgreSQL numeric column type {}: {}", - s, column_type, e - )) - }, - |v| { - Ok(BoundValue { - sql: format!("CAST(${} AS numeric)", placeholder_idx), - param: Some((Box::new(v) as PgParam, Type::NUMERIC)), - }) - }, - )); - } - - if matches!( - normalized.as_str(), - "real" | "double precision" | "float4" | "float8" - ) { - return Some(trimmed.parse::().map_or_else( - |e| { - Err(format!( - "Cannot convert value {:?} to PostgreSQL numeric column type {}: {}", - s, column_type, e - )) - }, - |v| { - Ok(BoundValue { - sql: format!("CAST(${} AS double precision)", placeholder_idx), - param: Some((Box::new(v) as PgParam, Type::FLOAT8)), - }) - }, - )); - } - - None -} - -/// Coerce a string value into a temporal PostgreSQL column (`timestamp`, -/// `timestamptz`, `date`, `time`, `timetz`, `interval`). -/// -/// The data grid editor sends every edited cell as a JSON string. `tokio-postgres` -/// infers an unannotated placeholder's wire type from the temporal OID it sits -/// next to — even inside `CAST($N AS timestamptz)`, where PostgreSQL resolves -/// the parameter's *effective* type to `timestamptz` for the purposes of the -/// client-side `Describe` response. Binding a Rust `String` against that -/// inferred type is then rejected client-side with "error serializing -/// parameter X" before the value ever reaches PostgreSQL's own (perfectly -/// capable) text-to-temporal parsing (#401). The fix is therefore two-part: -/// the `CAST(...)` text (so the *value* parses correctly) plus pinning the -/// placeholder's wire type to `TEXT` via [`TypedPgParam`] when the statement is -/// prepared, so the client-side type check matches what we're actually -/// sending and PostgreSQL performs the real conversion server-side. The cast -/// target is always one of the fixed canonical names below — never the raw -/// column-type string — so this can't be turned into a SQL-injection vector -/// via a crafted column type. -/// -/// Returns `None` if the column is not a temporal type, so callers can fall -/// through to the next coercion path. -pub(super) fn bind_pg_temporal_string( - s: &str, - column_type: &str, - placeholder_idx: usize, -) -> Option> { - let normalized = extract_base_type(column_type); - - let cast_type = match normalized.as_str() { - "TIMESTAMP" | "TIMESTAMP WITHOUT TIME ZONE" => "timestamp", - "TIMESTAMPTZ" | "TIMESTAMP WITH TIME ZONE" => "timestamptz", - "DATE" => "date", - "TIME" | "TIME WITHOUT TIME ZONE" => "time", - "TIMETZ" | "TIME WITH TIME ZONE" => "timetz", - "INTERVAL" => "interval", - _ => return None, - }; - - Some(Ok(BoundValue { - sql: format!("CAST(${} AS {})", placeholder_idx, cast_type), - param: Some((Box::new(s.to_string()) as PgParam, Type::TEXT)), - })) -} - -/// Coerce a string value into a PostgreSQL enum column. -/// -/// The data grid editor sends every edited cell as a JSON string, which binds as -/// `TEXT`. PostgreSQL has no implicit text-to-enum assignment cast, so the server -/// rejects the statement with SQLSTATE 42804 — `column "x" is of type but -/// expression is of type text` (#465). Same two-part fix as the temporal/uuid -/// coercions above: wrap the placeholder in `CAST($N AS )` so the -/// server converts through the enum's own input function, and pin the wire type -/// to `TEXT` so tokio-postgres does not reject the bound `String` client-side. -/// `qualified_enum` comes from `pg_catalog` and is quoted via -/// `quote_qualified_type`, so it cannot be turned into a SQL-injection vector. -pub(super) fn bind_pg_enum_string( - s: &str, - qualified_enum: &str, - placeholder_idx: usize, -) -> BoundValue { - BoundValue { - sql: format!("CAST(${} AS {})", placeholder_idx, qualified_enum), - param: Some((Box::new(s.to_string()) as PgParam, Type::TEXT)), - } -} - -fn bind_pg_string( - s: &str, - placeholder_idx: usize, - options: PgValueOptions<'_>, -) -> Result { - if options.allow_default && s == "__USE_DEFAULT__" { - return Ok(BoundValue { - sql: "DEFAULT".to_string(), - param: None, - }); - } - - // pgvector types must be handled before the generic array/text paths below: - // "[1,2,3]" would otherwise be turned into a PostgreSQL array literal by - // `try_parse_pg_array`, and there is no text->vector cast for a bound param. - if let Some(binding) = options - .column_type - .and_then(|column_type| bind_pg_vector_string(s, column_type)) - { - return binding; - } - - if let Some(bytes) = crate::drivers::common::decode_blob_wire_format(s, options.max_blob_size) { - return Ok(BoundValue { - sql: format!("${}", placeholder_idx), - param: Some((Box::new(bytes), Type::BYTEA)), - }); - } - - // An enum column always coerces through its own type: any of the later - // shape-based heuristics (uuid-shaped, function-shaped, array-shaped - // strings) would misinterpret a label that merely looks like one of those. - if let Some(enum_type) = options.enum_type { - return Ok(bind_pg_enum_string(s, enum_type, placeholder_idx)); - } - - if let Some(binding) = options - .column_type - .and_then(|data_type| bind_pg_boolean_string(s, data_type, placeholder_idx)) - { - return binding; - } - - if let Some(binding) = options - .column_type - .and_then(|data_type| bind_pg_numeric_string(s, data_type, placeholder_idx)) - { - return binding; - } - - if let Some(binding) = options - .column_type - .and_then(|data_type| bind_pg_temporal_string(s, data_type, placeholder_idx)) - { - return binding; - } - - if is_raw_sql_function(s) { - return Ok(BoundValue { - sql: s.to_string(), - param: None, - }); - } - - if is_wkt_geometry(s) { - return Ok(BoundValue { - sql: format!("ST_GeomFromText(${})", placeholder_idx), - param: Some((Box::new(s.to_string()), Type::TEXT)), - }); - } - - // A uuid-shaped string CAST into a `uuid` column has the same client-side - // type-pinning requirement as the temporal coercion above: PostgreSQL - // resolves $N's effective type to `uuid` through the CAST, so the - // placeholder must be pinned to TEXT or tokio-postgres rejects the bound - // `String` before it reaches PostgreSQL's own uuid parser (#392, #401). - if s.parse::().is_ok() { - return Ok(BoundValue { - sql: format!("CAST(${} AS uuid)", placeholder_idx), - param: Some((Box::new(s.to_string()), Type::TEXT)), - }); - } - - if let Some(pg_arr) = try_parse_pg_array(s) { - return Ok(BoundValue { - sql: pg_arr?, - param: None, - }); - } - - Ok(BoundValue { - sql: format!("${}", placeholder_idx), - param: Some((Box::new(s.to_string()), Type::TEXT)), - }) -} - -/// Bind a value into a pgvector column (`vector`, `halfvec`, `sparsevec`). -/// -/// pgvector registers no `text -> vector` cast, so a bound TEXT parameter — even -/// via `CAST($N AS vector)` — is rejected by PostgreSQL. The literal only reaches -/// the type's input function when it arrives as an *unknown*-typed literal, so we -/// inline it as `''::`. To keep that safe, the value is validated -/// against a strict allow-list of characters that make up a vector literal; a -/// non-pgvector column returns `None` so the caller falls through to its normal -/// binding logic. -fn bind_pg_vector_string(s: &str, column_type: &str) -> Option> { - let pg_type = match extract_base_type(column_type).as_str() { - "VECTOR" => "vector", - "HALFVEC" => "halfvec", - "SPARSEVEC" => "sparsevec", - _ => return None, - }; - - let trimmed = s.trim(); - - // Characters that can legitimately appear in a vector / halfvec / sparsevec - // literal: digits, sign, decimal point, exponent marker, the bracket/brace - // delimiters, element separators, the sparsevec index (':') and dimension - // ('/') separators, and whitespace. Anything else cannot be inlined safely. - let is_vector_literal = !trimmed.is_empty() - && trimmed.chars().all(|c| { - c.is_ascii_digit() - || matches!( - c, - '+' | '-' | '.' | 'e' | 'E' | '[' | ']' | '{' | '}' | ',' | ':' | '/' | ' ' - ) - }); - - if !is_vector_literal { - return Some(Err(format!( - "Invalid {pg_type} value: expected a numeric vector literal such as [1,2,3]" - ))); - } - - Some(Ok(BoundValue { - sql: format!("'{trimmed}'::{pg_type}"), - param: None, - })) -} diff --git a/src-tauri/src/drivers/postgres/client.rs b/src-tauri/src/drivers/postgres/client.rs deleted file mode 100644 index 83d6bb7d5..000000000 --- a/src-tauri/src/drivers/postgres/client.rs +++ /dev/null @@ -1,125 +0,0 @@ -use deadpool_postgres::{Object as PgObject, Pool as PgPool}; -use tokio_postgres::Row as PgRow; - -pub(super) fn format_pg_error(e: &tokio_postgres::Error) -> String { - if let Some(db) = e.as_db_error() { - let brief = format!("{}: {}", db.severity(), db.message()); - let detail = format!("{:#?}", e); - format!("{}\n\n{}", brief, detail) - } else { - e.to_string() - } -} - -#[inline(always)] -fn map_pg_err(e: E) -> String { - let brief = e.to_string(); - let detail = format!("{:#?}", e); - if detail.len() > brief.len() + 20 { - format!("{}\n\n{}", brief, detail) - } else { - brief - } -} - -#[inline(always)] -pub(super) async fn get_client(pool: &PgPool) -> Result { - pool.get().await.map_err(map_pg_err) -} - -#[inline] -pub(super) async fn query_all( - pool: &PgPool, - sql: &str, - params: &[&(dyn tokio_postgres::types::ToSql + Sync)], -) -> Result, String> { - let client = get_client(pool).await?; - client - .query(sql, params) - .await - .map_err(|e| format_pg_error(&e)) -} - -#[inline] -pub(super) async fn query_one( - pool: &PgPool, - sql: &str, - params: &[&(dyn tokio_postgres::types::ToSql + Sync)], -) -> Result { - let client = get_client(pool).await?; - client - .query_one(sql, params) - .await - .map_err(|e| format_pg_error(&e)) -} - -#[inline] -pub(super) async fn execute( - pool: &PgPool, - sql: &str, - params: &[&(dyn tokio_postgres::types::ToSql + Sync)], -) -> Result { - let client = get_client(pool).await?; - client - .execute(sql, params) - .await - .map_err(|e| format_pg_error(&e)) -} - -/// Like [`execute`], but pins every placeholder's wire type via `prepare_typed` -/// instead of letting the server infer it from query context. -/// -/// Inference breaks for a `CAST($N AS uuid)` / `CAST($N AS timestamptz)`-style -/// placeholder: PostgreSQL resolves the parameter's *effective* type to the -/// cast's target for the client-side `Describe` response, so a bound `String` -/// is rejected before it ever reaches PostgreSQL's own text-to-uuid/temporal -/// parsing (#392, #401). Declaring the placeholder's type explicitly (e.g. -/// `TEXT`) sidesteps that client-side check and lets the `CAST` perform the -/// real conversion server-side, exactly like a literal in plain SQL. -#[inline] -pub(super) async fn execute_typed( - pool: &PgPool, - sql: &str, - params: &[( - &(dyn tokio_postgres::types::ToSql + Sync), - tokio_postgres::types::Type, - )], -) -> Result { - let client = get_client(pool).await?; - let types: Vec = params.iter().map(|(_, t)| t.clone()).collect(); - let stmt = client - .prepare_typed(sql, &types) - .await - .map_err(|e| format_pg_error(&e))?; - let values: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> = - params.iter().map(|(v, _)| *v).collect(); - client - .execute(&stmt, &values) - .await - .map_err(|e| format_pg_error(&e)) -} - -/// Like [`query_one`], but pins placeholder types via `prepare_typed`. See -/// [`execute_typed`] for why this matters. -#[inline] -pub(super) async fn query_one_typed( - pool: &PgPool, - sql: &str, - params: &[( - &(dyn tokio_postgres::types::ToSql + Sync), - tokio_postgres::types::Type, - )], -) -> Result { - let client = get_client(pool).await?; - let types: Vec = params.iter().map(|(_, t)| t.clone()).collect(); - let stmt = client - .prepare_typed(sql, &types) - .await - .map_err(|e| format_pg_error(&e))?; - let values: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> = - params.iter().map(|(v, _)| *v).collect(); - client - .query_one(&stmt, &values) - .await - .map_err(|e| format_pg_error(&e)) -} diff --git a/src-tauri/src/drivers/postgres/column_comments.rs b/src-tauri/src/drivers/postgres/column_comments.rs deleted file mode 100644 index 10f2eae6a..000000000 --- a/src-tauri/src/drivers/postgres/column_comments.rs +++ /dev/null @@ -1,17 +0,0 @@ -pub(super) fn comment_sql(table_ref: &str, column: &str, comment: Option<&str>) -> String { - let value = match comment.filter(|value| !value.is_empty()) { - // Explicit escape strings also work when standard_conforming_strings is off. - Some(value) => format!("E'{}'", value.replace('\\', "\\\\").replace('\'', "''")), - None => "NULL".to_string(), - }; - format!( - "COMMENT ON COLUMN {}.\"{}\" IS {}", - table_ref, - column.replace('"', "\"\""), - value - ) -} - -#[cfg(test)] -#[path = "column_comments_tests.rs"] -mod tests; diff --git a/src-tauri/src/drivers/postgres/column_comments_tests.rs b/src-tauri/src/drivers/postgres/column_comments_tests.rs deleted file mode 100644 index 4550a878e..000000000 --- a/src-tauri/src/drivers/postgres/column_comments_tests.rs +++ /dev/null @@ -1,19 +0,0 @@ -use super::comment_sql; - -#[test] -fn quotes_identifiers_and_preserves_comment_text() { - assert_eq!( - comment_sql("\"s\".\"t\"", "col\"umn", Some(" O'Brien\\path\n日本語 ")), - "COMMENT ON COLUMN \"s\".\"t\".\"col\"\"umn\" IS E' O''Brien\\\\path\n日本語 '" - ); -} - -#[test] -fn clearing_a_comment_uses_null() { - for comment in [None, Some("")] { - assert_eq!( - comment_sql("\"public\".\"t\"", "c", comment), - "COMMENT ON COLUMN \"public\".\"t\".\"c\" IS NULL" - ); - } -} diff --git a/src-tauri/src/drivers/postgres/column_ddl_tests.rs b/src-tauri/src/drivers/postgres/column_ddl_tests.rs deleted file mode 100644 index 5f44b2bf5..000000000 --- a/src-tauri/src/drivers/postgres/column_ddl_tests.rs +++ /dev/null @@ -1,132 +0,0 @@ -use super::PostgresDriver; -use crate::drivers::driver_trait::DatabaseDriver; -use crate::models::ColumnDefinition; - -#[tokio::test] -async fn connection_aware_defaults_preserve_the_existing_builder_contract() { - let driver = PostgresDriver::new(); - let params = crate::models::ConnectionParams::default(); - let new = column(Some("note")); - assert_eq!( - driver - .get_add_column_sql_for_connection(¶ms, "t", new.clone(), Some("s")) - .await - .unwrap(), - driver - .get_add_column_sql("t", new.clone(), Some("s")) - .await - .unwrap() - ); - assert_eq!( - driver - .get_alter_column_sql_for_connection(¶ms, "t", column(None), new.clone(), Some("s")) - .await - .unwrap(), - driver - .get_alter_column_sql("t", column(None), new, Some("s")) - .await - .unwrap() - ); -} - -fn column(comment: Option<&str>) -> ColumnDefinition { - ColumnDefinition { - name: "email".into(), - data_type: "VARCHAR(255)".into(), - is_nullable: false, - is_pk: false, - is_auto_increment: false, - default_value: Some("'unknown'::character varying".into()), - comment: comment.map(str::to_string), - on_update: None, - } -} - -#[test] -fn advertises_column_comments() { - assert!( - PostgresDriver::new() - .manifest() - .capabilities - .column_comments - ); -} - -#[tokio::test] -async fn comment_only_edits_do_not_restate_the_column() { - for (old, new, literal) in [ - (None, Some("new"), "E'new'"), - (Some("old"), Some("new"), "E'new'"), - (Some("old"), None, "NULL"), - (Some("old"), Some(""), "NULL"), - ] { - let sql = PostgresDriver::new() - .get_alter_column_sql("customers", column(old), column(new), Some("sales")) - .await - .unwrap(); - assert_eq!( - sql, - [format!( - "COMMENT ON COLUMN \"sales\".\"customers\".\"email\" IS {literal}" - )] - ); - } -} - -#[tokio::test] -async fn unchanged_comments_produce_no_comment_statement() { - for comment in [None, Some(""), Some("existing")] { - let old = column(comment); - let mut new = old.clone(); - new.name = "renamed".into(); - let sql = PostgresDriver::new() - .get_alter_column_sql("customers", old, new, None) - .await - .unwrap(); - assert_eq!(sql.len(), 1); - assert!(sql[0].contains("RENAME COLUMN")); - } - assert!(PostgresDriver::new() - .get_alter_column_sql( - "customers", - column(Some("same")), - column(Some("same")), - None - ) - .await - .is_err()); -} - -#[tokio::test] -async fn rename_and_comment_use_the_new_quoted_name() { - let mut new = column(Some("O'Brien\n日本語")); - new.name = "new\"name".into(); - let sql = PostgresDriver::new() - .get_alter_column_sql("cust\"omers", column(None), new, Some("sa\"les")) - .await - .unwrap(); - assert_eq!(sql.len(), 2); - assert_eq!( - sql[1], - "COMMENT ON COLUMN \"sa\"\"les\".\"cust\"\"omers\".\"new\"\"name\" IS E'O''Brien\n日本語'" - ); -} - -#[tokio::test] -async fn add_column_emits_the_comment_after_adding_the_column() { - let driver = PostgresDriver::new(); - let with_comment = driver - .get_add_column_sql("customers", column(Some("note")), None) - .await - .unwrap(); - let without_comment = driver - .get_add_column_sql("customers", column(None), None) - .await - .unwrap(); - assert_eq!(with_comment[0], without_comment[0]); - assert_eq!(without_comment.len(), 1); - assert_eq!( - with_comment[1], - "COMMENT ON COLUMN \"public\".\"customers\".\"email\" IS E'note'" - ); -} diff --git a/src-tauri/src/drivers/postgres/explain.rs b/src-tauri/src/drivers/postgres/explain.rs deleted file mode 100644 index 2c0c53b52..000000000 --- a/src-tauri/src/drivers/postgres/explain.rs +++ /dev/null @@ -1,52 +0,0 @@ -use super::client::{format_pg_error, query_all}; -use super::helpers::escape_identifier; -use crate::models::{ConnectionParams, ExplainQueryOutput, RawExplainOutput}; -use crate::pool_manager::get_postgres_pool; - -pub async fn explain_query( - params: &ConnectionParams, - query: &str, - analyze: bool, - schema: Option<&str>, -) -> Result { - let pool = get_postgres_pool(params).await?; - - if let Some(s) = schema { - let search_path = format!("SET search_path TO \"{}\"", escape_identifier(s)); - query_all(&pool, &search_path, &[]).await?; - } - - let explain_sql = if analyze { - format!("EXPLAIN (FORMAT JSON, ANALYZE, BUFFERS) {}", query) - } else { - format!("EXPLAIN (FORMAT JSON) {}", query) - }; - - let rows = query_all(&pool, &explain_sql, &[]).await?; - - if rows.is_empty() { - return Err("EXPLAIN returned no output".into()); - } - - // `EXPLAIN (FORMAT JSON)` on real PostgreSQL returns a column of type - // `json` (not `text`), so reading it as `String` fails with - // "error deserializing column 0". Read it as a `serde_json::Value` and - // re-serialize. Some Postgres-compatible engines hand back a plain `text` - // column instead, so fall back to reading the raw string in that case. - let plan_json_str = match rows[0].try_get::<_, serde_json::Value>(0) { - Ok(value) => value.to_string(), - Err(json_err) => rows[0].try_get::<_, String>(0).map_err(|e| { - log::debug!("EXPLAIN json read failed ({json_err}); text read also failed"); - format_pg_error(&e) - })?, - }; - - Ok(ExplainQueryOutput::Raw { - raw: RawExplainOutput { - engine: "postgres".to_string(), - format: "postgres-json".to_string(), - payload: plan_json_str, - original_query: query.to_string(), - }, - }) -} diff --git a/src-tauri/src/drivers/postgres/export.rs b/src-tauri/src/drivers/postgres/export.rs deleted file mode 100644 index 0fd79ca7c..000000000 --- a/src-tauri/src/drivers/postgres/export.rs +++ /dev/null @@ -1,92 +0,0 @@ -use futures::StreamExt; -use serde_json::Value; - -use crate::models::ConnectionParams; -use crate::pool_manager::get_postgres_pool; - -use super::extract::extract_value; - -/// Streams the rows produced by `query` against a PostgreSQL connection. See -/// the MySQL counterpart for the contract of `on_row`. -/// -/// With the `session_id` of a tab inside a transaction, the query runs as one -/// cursor on that tab's pinned connection, so the export sees its uncommitted -/// changes. The connection stays pinned throughout, so cancelling the export -/// leaves the transaction open. -pub async fn stream_query( - params: &ConnectionParams, - query: &str, - session_id: Option<&str>, - mut on_row: F, -) -> Result<(), String> -where - F: FnMut(&[String], &[Value]) -> Result<(), String> + Send, -{ - if let Some(id) = session_id { - let mut slot = super::session::lock(id).await; - // A pinned connection belongs to one transaction on one database. If the - // tab has switched databases since opening it, exporting on the pinned - // connection would silently stream rows from the old database. Reject - // before borrowing the client so the pinned session (and its open - // transaction) is left intact — the user can switch back or end the - // transaction and retry. Mirrors the guard in `execute_batch_in_session`. - let requested_db = params.database.primary(); - super::session::check_pinned_database(slot.database(), requested_db, "export")?; - if let Some(client) = slot.client() { - // A savepoint keeps a failing export from aborting the user's transaction. - client - .batch_execute("SAVEPOINT tabularis_read") - .await - .map_err(|e| e.to_string())?; - let streamed = stream_rows(client, query, &mut on_row).await; - let end = match streamed { - Ok(()) => "RELEASE SAVEPOINT tabularis_read", - Err(_) => "ROLLBACK TO SAVEPOINT tabularis_read; RELEASE SAVEPOINT tabularis_read", - }; - let ended = client.batch_execute(end).await.map_err(|e| e.to_string()); - slot.touch(); - return streamed.and(ended); - } - } - - let pool = get_postgres_pool(params).await?; - let client = pool - .get() - .await - .map_err(|e| format!("failed to get postgres client: {:?}", e))?; - stream_rows(&client, query, &mut on_row).await -} - -async fn stream_rows( - client: &tokio_postgres::Client, - query: &str, - on_row: &mut F, -) -> Result<(), String> -where - F: FnMut(&[String], &[Value]) -> Result<(), String> + Send, -{ - let bind_params: Vec = vec![]; - let mut rows = std::pin::pin!(client - .query_raw(query, &bind_params) - .await - .map_err(|e| format!("failed to execute postgres query: {:?}", e))?); - - let mut headers: Option> = None; - - while let Some(row_res) = rows.next().await { - let row = row_res.map_err(|e| e.to_string())?; - - if headers.is_none() { - headers = Some(row.columns().iter().map(|c| c.name().to_string()).collect()); - } - let h = headers.as_ref().expect("headers initialized"); - - let values: Vec = (0..row.columns().len()) - .map(|i| extract_value(&row, i, None)) - .collect(); - - on_row(h, &values)?; - } - - Ok(()) -} diff --git a/src-tauri/src/drivers/postgres/extract/advanced_types.rs b/src-tauri/src/drivers/postgres/extract/advanced_types.rs deleted file mode 100644 index e65eb4cda..000000000 --- a/src-tauri/src/drivers/postgres/extract/advanced_types.rs +++ /dev/null @@ -1,1742 +0,0 @@ -use std::net::IpAddr; - -use serde_json::{Number as JsonNumber, Value as JsonValue}; -use tokio_postgres::types::{FromSql, Type}; - -use crate::drivers::common::{encode_blob, i64_to_json, u64_to_json}; - -// System Identifiers & Object References (The "Reg" Types) - -macro_rules! u32_wrapper { - ($name: ident, $pg_type: ident) => { - pub struct $name(u32); - - impl<'a> FromSql<'a> for $name { - fn from_sql( - ty: &Type, - raw: &[u8], - ) -> Result> { - Ok(Self(::from_sql(ty, raw)?)) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::$pg_type => true, - _ => false, - } - } - } - - impl From<$name> for JsonValue { - #[inline(always)] - fn from(value: $name) -> Self { - JsonValue::Number(JsonNumber::from(value.0)) - } - } - }; -} - -u32_wrapper!(Xid, XID); -u32_wrapper!(Cid, CID); - -// NOTE: -// These are all literally just Oids under the hood and we should get the name of the object -// from the database but we can't do that from here so instead we just return the Oid (u32) -u32_wrapper!(RegClass, REGCLASS); -u32_wrapper!(RegProc, REGPROC); -u32_wrapper!(RegProcedure, REGPROCEDURE); -u32_wrapper!(RegOper, REGOPER); -u32_wrapper!(RegOperator, REGOPERATOR); -u32_wrapper!(RegType, REGTYPE); -u32_wrapper!(RegConfig, REGCONFIG); -u32_wrapper!(RegDictionary, REGDICTIONARY); -u32_wrapper!(RegNamespace, REGNAMESPACE); -u32_wrapper!(RegRole, REGROLE); -u32_wrapper!(RegCollation, REGCOLLATION); - -pub struct Xid8(u64); - -impl<'a> FromSql<'a> for Xid8 { - fn from_sql( - ty: &Type, - raw: &'a [u8], - ) -> Result> { - Ok(Self(::from_sql(ty, raw)? as u64)) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::XID8 => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: Xid8) -> Self { - u64_to_json(value.0) - } -} - -pub struct Tid { - block_num: u32, - offset: u16, -} - -impl<'a> FromSql<'a> for Tid { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() != 6 { - return Err(format!("expected 6 bytes for TID, got {}", raw.len()).into()); - }; - - Ok(Self { - block_num: ::from_sql(&Type::OID, &raw[..4])?, - offset: ::from_sql(&Type::INT2, &raw[4..])? as u16, - }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::TID => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: Tid) -> Self { - JsonValue::String(format!("({}, {})", value.block_num, value.offset)) - } -} - -// Geometric Types - -pub struct Point { - pub x: f64, - pub y: f64, -} - -impl Point { - #[inline] - fn extract(raw: &[u8]) -> Result> { - if raw.len() != 16 { - return Err(format!("expected 16 bytes for Point, got {}", raw.len()).into()); - }; - - Ok(Self { - x: ::from_sql(&Type::FLOAT8, &raw[..8])?, - y: ::from_sql(&Type::FLOAT8, &raw[8..])?, - }) - } -} - -impl<'a> FromSql<'a> for Point { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - Point::extract(raw) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::POINT => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: Point) -> Self { - JsonValue::String(format!("({}, {})", value.x, value.y)) - } -} - -pub struct Lseg { - pub p1: Point, - pub p2: Point, -} - -impl<'a> FromSql<'a> for Lseg { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() != 32 { - return Err(format!("expected 32 bytes for Lseg, got {}", raw.len()).into()); - }; - - Ok(Self { - p1: Point::extract(&raw[..16])?, - p2: Point::extract(&raw[16..])?, - }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::LSEG => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: Lseg) -> Self { - JsonValue::String(format!( - "[({}, {}), ({}, {})]", - value.p1.x, value.p1.y, value.p2.x, value.p2.y - )) - } -} - -pub struct PgBox { - pub upper_right_p: Point, - pub lower_left_p: Point, -} - -impl<'a> FromSql<'a> for PgBox { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() != 32 { - return Err(format!("expected 32 bytes for Box, got {}", raw.len()).into()); - }; - - Ok(Self { - upper_right_p: Point::extract(&raw[..16])?, - lower_left_p: Point::extract(&raw[16..])?, - }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::BOX => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: PgBox) -> Self { - JsonValue::String(format!( - "(({}, {}), ({}, {}))", - value.upper_right_p.x, - value.upper_right_p.y, - value.lower_left_p.x, - value.lower_left_p.y - )) - } -} - -pub struct Polygon { - pub points: Vec, -} - -impl<'a> FromSql<'a> for Polygon { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() < 4 { - return Err(format!("expected at least 4 bytes for Polygon, got {}", raw.len()).into()); - }; - - let num_points = i32::from_be_bytes(raw[..4].try_into().unwrap()); - - if num_points < 0 { - return Err(format!( - "expected non-negative number of points for Polygon, got {}", - num_points - ) - .into()); - }; - - if num_points == 0 { - return Ok(Self { points: Vec::new() }); - }; - - let num_points = num_points as usize; - - if raw.len() < 4 + num_points * 16 { - return Err(format!( - "expected at least {} bytes for Polygon, got {}", - 4 + num_points * 16, - raw.len() - ) - .into()); - } - - let mut points = Vec::with_capacity(num_points); - let mut buf = raw[4..].chunks_exact(16); - - while let Some(chunk) = buf.next() { - points.push(Point::extract(chunk)?); - } - - Ok(Self { points }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::POLYGON => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline] - fn from(value: Polygon) -> Self { - let mut s = String::with_capacity(5 + value.points.len() * 16); - - s.push('('); - if value.points.is_empty() { - s.push(')'); - return JsonValue::String(s); - }; - - s.push_str(&format!("({}, {})", value.points[0].x, value.points[0].y)); - for p in value.points[1..].iter() { - s.push_str(&format!(", ({}, {})", p.x, p.y)); - } - - s.push(')'); - - JsonValue::String(s) - } -} - -pub struct Path { - pub flag: u8, - pub points: Vec, -} - -impl<'a> FromSql<'a> for Path { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() < 5 { - return Err(format!("expected at least 5 bytes for Path, got {}", raw.len()).into()); - }; - - let flag = raw[0]; - - let num_points = i32::from_be_bytes(raw[1..5].try_into().unwrap()); - - if num_points < 0 { - return Err(format!( - "expected non-negative number of points for Path, got {}", - num_points - ) - .into()); - } - - if num_points == 0 { - return Ok(Self { - flag, - points: Vec::new(), - }); - } - - let num_points = num_points as usize; - - if raw.len() < 5 + num_points * 16 { - return Err(format!( - "expected at least {} bytes for Path, got {}", - 5 + num_points * 16, - raw.len() - ) - .into()); - } - - let mut points = Vec::with_capacity(num_points); - let mut buf = raw[5..].chunks_exact(16); - while let Some(chunk) = buf.next() { - points.push(Point::extract(chunk)?); - } - - Ok(Self { flag, points }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::PATH => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline] - fn from(value: Path) -> Self { - let (opening, closing) = if value.flag & 0x01 == 1 { - ('(', ')') - } else { - ('[', ']') - }; - - let mut s = String::with_capacity(6 + value.points.len() * 16); - - s.push(opening); - - if value.points.is_empty() { - s.push(closing); - return JsonValue::String(s); - }; - - s.push_str(&format!("({}, {})", value.points[0].x, value.points[0].y)); - for p in value.points[1..].iter() { - s.push_str(&format!(", ({}, {})", p.x, p.y)); - } - - s.push(closing); - - JsonValue::String(s) - } -} - -pub struct Line { - pub a: f64, - pub b: f64, - pub c: f64, -} - -impl<'a> FromSql<'a> for Line { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() != 24 { - return Err(format!("expected 24 bytes for Line, got {}", raw.len()).into()); - }; - - let a = f64::from_sql(&Type::FLOAT8, &raw[..8])?; - let b = f64::from_sql(&Type::FLOAT8, &raw[8..16])?; - let c = f64::from_sql(&Type::FLOAT8, &raw[16..])?; - Ok(Self { a, b, c }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::LINE => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: Line) -> Self { - JsonValue::String(format!("{{{}, {}, {}}}", value.a, value.b, value.c)) - } -} - -pub struct Circle { - pub point: Point, - pub radius: f64, -} - -impl<'a> FromSql<'a> for Circle { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() != 24 { - return Err(format!("expected 24 bytes for Circle, got {}", raw.len()).into()); - }; - - let point = Point::extract(&raw[..16])?; - let radius = f64::from_sql(&Type::FLOAT8, &raw[16..])?; - Ok(Self { point, radius }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::CIRCLE => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: Circle) -> Self { - JsonValue::String(format!( - "<({}, {}), {}>", - value.point.x, value.point.y, value.radius - )) - } -} - -// Network types - -pub struct MacAddr { - bytes: [u8; 6], -} - -impl<'a> FromSql<'a> for MacAddr { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() != 6 { - return Err(format!("expected 6 bytes for MacAddr, got {}", raw.len()).into()); - } - let mut bytes = [0u8; 6]; - bytes.copy_from_slice(raw); - Ok(Self { bytes }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::MACADDR => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: MacAddr) -> Self { - JsonValue::String(format!( - "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", - value.bytes[0], - value.bytes[1], - value.bytes[2], - value.bytes[3], - value.bytes[4], - value.bytes[5] - )) - } -} - -pub struct MacAddr8 { - bytes: [u8; 8], -} - -impl<'a> FromSql<'a> for MacAddr8 { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() != 8 { - return Err(format!("expected 8 bytes for MacAddr8, got {}", raw.len()).into()); - } - let mut bytes = [0u8; 8]; - bytes.copy_from_slice(raw); - Ok(Self { bytes }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::MACADDR8 => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: MacAddr8) -> Self { - JsonValue::String(format!( - "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", - value.bytes[0], - value.bytes[1], - value.bytes[2], - value.bytes[3], - value.bytes[4], - value.bytes[5], - value.bytes[6], - value.bytes[7] - )) - } -} - -pub struct CidrOrInet { - pub addr: IpAddr, - pub netmask: u8, -} - -impl<'a> FromSql<'a> for CidrOrInet { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() < 8 { - return Err("invalid buffer size".into()); - } - - let family = raw[0]; - let netmask = raw[1]; - // let _is_cidr = raw[2]; - let len = raw[3]; - - match family { - 2 => { - if netmask > 32 { - return Err( - format!("expected IPv4 netmask to be <= 32, got {}", netmask).into(), - ); - } - if len != 4 { - return Err(format!("expected IP4v address length to be 4, got {}", len).into()); - } - - let octets: [u8; 4] = raw[4..8].try_into().unwrap(); - let addr = IpAddr::from(octets); - Ok(Self { addr, netmask }) - } - 3 => { - if netmask > 128 { - return Err( - format!("expected IPv6 netmask to be <= 128, got {}", netmask).into(), - ); - } - if len != 16 { - return Err( - format!("expected IP6v address length to be 16, got {}", len).into(), - ); - }; - if raw.len() < 20 { - return Err(format!( - "expected IP6v address buffer length to be 20, got {}", - raw.len() - ) - .into()); - } - - let bytes: [u8; 16] = raw[4..20].try_into().unwrap(); - let addr = IpAddr::from(bytes); - Ok(Self { addr, netmask }) - } - - _ => { - return Err(format!( - "expected IP family to be 2 (IPv4) or 3 (IPv6) got {}", - family - ) - .into()) - } - } - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::CIDR | Type::INET => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: CidrOrInet) -> Self { - JsonValue::String(format!("{}/{}", value.addr, value.netmask)) - } -} - -pub struct BitOrVarBit { - pub bits: String, -} - -impl<'a> FromSql<'a> for BitOrVarBit { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() < 4 { - return Err(format!( - "expected at least 4 bytes for BIT/VARBIT, got {}", - raw.len() - ) - .into()); - }; - - let bits_num = i32::from_be_bytes(raw[..4].try_into().unwrap()) as usize; - - let mut bits_len = bits_num / 8; - let remainder = bits_num % 8; - - if remainder > 0 { - bits_len += 1; - }; - - if raw.len() < 4 + bits_len { - return Err(format!( - "expected at least {} bytes for BIT/VARBIT, got {}", - 4 + bits_len, - raw.len() - ) - .into()); - }; - - if bits_len == 0 { - return Ok(Self { - bits: String::new(), - }); - } - - let mut bits = String::with_capacity(bits_num); - - for b in raw[4..4 + bits_len - 1].iter() { - bits.push_str(&format!("{:08b}", b)); - } - - let last_byte = format!("{:08b}", raw[4 + bits_len - 1]); - if remainder > 0 { - // remove padded zeros - bits.push_str(&last_byte[..remainder]); - } else { - bits.push_str(&last_byte); - } - - Ok(Self { bits }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::BIT | Type::VARBIT => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: BitOrVarBit) -> Self { - JsonValue::String(value.bits) - } -} - -// Time types - -pub struct TimeTz { - hrs: u8, - mins: u8, - secs: u8, - microseconds: u32, - offset_sign: char, - offset_hrs: u8, - offset_mins: u8, - offset_secs: u8, -} - -impl<'a> FromSql<'a> for TimeTz { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() < 12 { - return Err(format!("expected at least 12 bytes for TIMETZ, got {}", raw.len()).into()); - } - - let mut microseconds = i64::from_be_bytes([ - raw[0], raw[1], raw[2], raw[3], raw[4], raw[5], raw[6], raw[7], - ]); - - if microseconds < 0 { - return Err(format!( - "microseconds must not be negative for TIMETZ: {}", - microseconds - ) - .into()); - }; - - // it is important to check for this because we need to convert to hours `u8` safely - if microseconds > 1000 * 1000 * 60 * 60 * 24 { - return Err(format!( - "microseconds must not exceed 24 hours for TIMETZ: {}", - microseconds - ) - .into()); - }; - - let hrs = (microseconds / (1000 * 1000 * 60 * 60)) as u8; - microseconds %= 1000 * 1000 * 60 * 60; - let mins = (microseconds / (1000 * 1000 * 60)) as u8; - microseconds %= 1000 * 1000 * 60; - let secs = (microseconds / (1000 * 1000)) as u8; - let microseconds = (microseconds % (1000 * 1000)) as u32; - - let mut timezone_offset = i32::from_be_bytes([raw[8], raw[9], raw[10], raw[11]]); - - let offset_sign = if timezone_offset.is_positive() { - '-' - } else { - timezone_offset = -timezone_offset; - '+' - }; - - let offset_hrs = (timezone_offset / (60 * 60)) as u8; - let remainder = timezone_offset % (60 * 60); - let offset_mins = (remainder / 60) as u8; - let offset_secs = (remainder % 60) as u8; - - Ok(Self { - hrs, - mins, - secs, - microseconds, - offset_sign, - offset_hrs, - offset_mins, - offset_secs, - }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::TIMETZ => true, - _ => false, - } - } -} - -impl From for JsonValue { - fn from(value: TimeTz) -> Self { - let mut time = format!("{:02}:{:02}:{:02}", value.hrs, value.mins, value.secs,); - - if value.microseconds > 0 { - time.push('.'); - time.push_str(&value.microseconds.to_string().trim_end_matches('0')); - }; - - time.push_str(&format!("{}{:02}", value.offset_sign, value.offset_hrs)); - - if value.offset_mins > 0 { - time.push_str(&format!(":{:02}", value.offset_mins)); - } - - if value.offset_secs > 0 { - time.push_str(&format!(":{:02}", value.offset_secs)); - }; - - JsonValue::String(time) - } -} - -pub struct Interval { - pub years: i32, - pub months: i8, - pub days: i32, - pub sign: char, - pub hours: u8, - pub minutes: u8, - pub seconds: u8, - pub microseconds: u32, -} - -impl<'a> FromSql<'a> for Interval { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() < 16 { - return Err(format!("expected 16 bytes for Interval, got {}", raw.len()).into()); - }; - - let mut microseconds = i64::from_be_bytes(raw[..8].try_into().unwrap()); - let mut days = i32::from_be_bytes(raw[8..12].try_into().unwrap()); - let mut months = i32::from_be_bytes(raw[12..].try_into().unwrap()); - let mut years = 0; - - if months > 11 || months < -11 { - years = (months / 12) as i32; - months %= 12; - }; - - let sign; - - if microseconds < 0 { - sign = '-'; - microseconds = -microseconds; - } else { - sign = '+'; - } - - let mut hrs = microseconds / (1000 * 1000 * 60 * 60); - microseconds %= 1000 * 1000 * 60 * 60; - let mins = (microseconds / (1000 * 1000 * 60)) as u8; - microseconds %= 1000 * 1000 * 60; - let secs = (microseconds / (1000 * 1000)) as u8; - - let microseconds = (microseconds % (1000 * 1000)) as u32; - - if hrs > 23 || hrs < -23 { - days += (hrs / 24) as i32; - hrs %= 24; - }; - - Ok(Interval { - years, - months: months as i8, - days, - sign, - hours: hrs as u8, - minutes: mins, - seconds: secs, - microseconds, - }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::INTERVAL => true, - _ => false, - } - } -} - -impl From for JsonValue { - fn from(value: Interval) -> Self { - let mut s = String::new(); - - if value.years != 0 { - let years_str = if value.years == 1 || value.years == -1 { - "year" - } else { - "years" - }; - s.push_str(&format!("{} {} ", value.years, years_str)); - }; - - if value.months != 0 { - let months_str = if value.months == 1 || value.months == -1 { - "month" - } else { - "months" - }; - s.push_str(&format!("{} {} ", value.months, months_str)); - }; - - if value.days != 0 { - let days_str = if value.days == 1 || value.days == -1 { - "day" - } else { - "days" - }; - s.push_str(&format!("{} {} ", value.days, days_str)); - }; - - if value.hours != 0 || value.minutes != 0 || value.seconds != 0 || value.microseconds != 0 { - if value.sign != '+' { - s.push(value.sign); - }; - - s.push_str(&format!( - "{:02}:{:02}:{:02}", - value.hours, value.minutes, value.seconds - )); - if value.microseconds != 0 { - s.push_str(&format!( - ".{}", - value.microseconds.to_string().trim_end_matches('0') - )); - } - }; - - JsonValue::String(s) - } -} - -/// Represents the total value in "cents" or the fractional unit of the database's locale. -pub struct Money(i64); - -impl<'a> FromSql<'a> for Money { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - Ok(Self(::from_sql(&Type::INT8, raw)?)) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::MONEY => true, - _ => false, - } - } -} - -impl From for JsonValue { - fn from(value: Money) -> Self { - i64_to_json(value.0) - } -} - -macro_rules! utf8_wrapper { - ($name: ident, $pg_type: ident) => { - pub struct $name(String); - - impl<'a> FromSql<'a> for $name { - fn from_sql( - _ty: &Type, - raw: &[u8], - ) -> Result> { - Ok(Self(String::from_utf8(raw.to_vec())?)) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::$pg_type => true, - _ => false, - } - } - } - - impl From<$name> for JsonValue { - #[inline(always)] - fn from(value: $name) -> Self { - JsonValue::String(value.0) - } - } - }; -} - -utf8_wrapper!(Xml, XML); -utf8_wrapper!(RefCursor, REFCURSOR); - -pub struct JsonPath { - _version: u8, - path: String, -} - -impl<'a> FromSql<'a> for JsonPath { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() < 1 { - return Err("invalid JSON path".into()); - } - - let version = raw[0]; - let path = String::from_utf8(raw[1..].to_vec())?; - Ok(Self { - _version: version, - path, - }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::JSONPATH => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: JsonPath) -> Self { - JsonValue::String(value.path) - } -} - -// Full Text Search types - -pub struct Lexeme { - pub text: String, - pub positions_weights: Vec<(u16, char)>, // char: A, B, C, D (default: D and it is implict) -} - -impl Lexeme { - pub fn try_extract_from( - buf: &mut &[u8], - ) -> Result> { - let text = try_extract_lexeme_text(buf)?; - - let position_count = i16::from_be_bytes(match buf[..2].try_into() { - Ok(arr) => arr, - Err(e) => return Err(format!("buf too short for position count: {}", e).into()), - }); - - if position_count < 0 { - return Err(format!( - "expected non-negative position count, got: {}", - position_count - ) - .into()); - }; - - if position_count == 0 { - return Ok(Self { - text, - positions_weights: Vec::new(), - }); - }; - - *buf = &buf[2..]; - - if buf.len() < (position_count as usize) * 2 { - return Err(format!( - "buf too short for positions and weights: expected {} bytes, got {}", - (position_count as usize) * 2, - buf.len() - ) - .into()); - }; - - let mut positions_weights = Vec::with_capacity(position_count as usize); - for _ in 0..position_count { - let position_weight = u16::from_be_bytes(buf[..2].try_into().unwrap()); - - let weight = match position_weight >> 14 { - 0 => 'D', - 1 => 'C', - 2 => 'B', - 3 => 'A', - _ => unreachable!(), - }; - - let position = position_weight & 0x3FFF; - - *buf = &buf[2..]; - positions_weights.push((position, weight)); - } - - Ok(Self { - text, - positions_weights, - }) - } -} - -pub struct TsVector { - lexemes: Vec, -} - -impl<'a> FromSql<'a> for TsVector { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() < 4 { - return Err(format!( - "raw buffer too short for TsVector: expected at least 4 bytes, got {}", - raw.len() - ) - .into()); - }; - - let count = i32::from_be_bytes(raw[..4].try_into().unwrap()); - - if count == 0 { - return Ok(Self { - lexemes: Vec::new(), - }); - } - - let mut buf = &raw[4..]; - - let mut lexemes = Vec::with_capacity(count as usize); - for _ in 0..count { - let lexeme = Lexeme::try_extract_from(&mut buf)?; - lexemes.push(lexeme); - } - - Ok(Self { lexemes }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::TS_VECTOR => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline] - fn from(value: TsVector) -> Self { - let mut ss = Vec::with_capacity(value.lexemes.len()); - - for lexeme in value.lexemes { - let mut s = String::new(); - s.push_str(&format!("'{}':", lexeme.text)); - - let mut positions_weights = lexeme.positions_weights.into_iter(); - - if let Some((position, weight)) = positions_weights.next() { - s.push_str(&format!("{}", position)); - if weight != 'D' { - s.push(weight); - }; - }; - - while let Some((position, weight)) = positions_weights.next() { - s.push_str(&format!(",{}", position)); - if weight != 'D' { - s.push(weight); - }; - } - ss.push(s); - } - - JsonValue::String(ss.join(" ")) - } -} - -// NOTE: the structure of this type is very complex so it will be converted to a string representation directly -// instead of parsing the raw bytes -pub struct TsQuery { - pub query: String, -} - -impl<'a> FromSql<'a> for TsQuery { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() < 4 { - return Err(format!( - "error extracting TsQuery: expected at least 4 bytes, got {}", - raw.len() - ) - .into()); - }; - - // ignore length prefix - let mut buf = &raw[4..]; - match try_extract_ts_query(&mut buf, 4) { - Ok(query) => Ok(TsQuery { query }), - Err(e) => Err(e.into()), - } - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::TSQUERY => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: TsQuery) -> Self { - JsonValue::String(value.query) - } -} - -pub struct GtsVector { - pub header: [u8; 4], - pub signature: u8, -} - -impl<'a> FromSql<'a> for GtsVector { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() < 5 { - return Err(format!( - "fail to extract gts_vector: expected at least 5 bytes, got {}", - raw.len() - ) - .into()); - }; - - let header = [raw[0], raw[1], raw[2], raw[3]]; - let signature = raw[4]; - - Ok(Self { header, signature }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::GTS_VECTOR => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: GtsVector) -> Self { - JsonValue::String(encode_blob(&[ - value.header[0], - value.header[1], - value.header[2], - value.header[3], - value.signature, - ])) - } -} - -fn try_extract_ts_query(buf: &mut &[u8], pre_lvl: u8) -> Result { - if buf.len() == 0 { - return Err("fail to extract ts_query: buffer is empty".into()); - }; - - match buf[0] { - 1 => { - if buf.len() < 3 { - return Err("fail to extract ts_query operand: buffer is too short".into()); - }; - - let weight = match buf[1] { - 0 => None, - 1 => Some('D'), - 2 => Some('C'), - 4 => Some('B'), - 8 => Some('A'), - _ => { - return Err( - "fail to extract ts_query operand weight: invalid weight value".into(), - ); - } - }; - - let prefixed = buf[2] == 1; - - *buf = &buf[3..]; - - let lexeme = try_extract_lexeme_text(buf)?; - - let mut s = String::new(); - - s.push('\''); - s.push_str(&lexeme); - s.push('\''); - if prefixed { - s.push_str(":*"); - }; - - if let Some(weight) = weight { - if prefixed { - s.push_str(&format!("{}", weight)); - } else { - s.push_str(&format!(":{}", weight)); - } - }; - - Ok(s) - } - - 2 => { - let operator = match buf.get(1) { - Some(b) => *b, - None => { - return Err("fail to extract ts_query operator: buffer is too short".into()); - } - }; - - *buf = &buf[2..]; - - let (cur_lvl, operator) = match operator { - 1 => { - let operand = try_extract_ts_query(buf, 1)?; - return Ok(format!("!{}", operand)); - } - - 2 => (3, "&".into()), - 3 => (4, "|".into()), - 4 => { - if buf.len() < 2 { - return Err( - "fail to extract ts_query phrase operator distance: buffer is to short" - .into(), - ); - }; - - let distance = i16::from_be_bytes(buf[..2].try_into().unwrap()); - - *buf = &buf[2..]; - - if distance == 1 { - (2, "<->".into()) - } else { - (2, format!("<{}>", distance)) - } - } - - _ => { - return Err(format!("fail to extract ts_query operator: invalid operator expected 1, 2, 3, or 4, got: {}", operator)); - } - }; - - let right_operand = try_extract_ts_query(buf, cur_lvl)?; - let left_operand = try_extract_ts_query(buf, cur_lvl)?; - - if pre_lvl < cur_lvl { - Ok(format!("({} {} {})", left_operand, operator, right_operand)) - } else { - Ok(format!("{} {} {}", left_operand, operator, right_operand)) - } - } - - _ => { - return Err(format!( - "fail to extract ts_query: expected 1 or 2 got: {}", - buf[0] - )); - } - } -} - -#[inline] -fn try_extract_lexeme_text(buf: &mut &[u8]) -> Result { - let Some(nul_pos) = buf.iter().position(|b| *b == 0) else { - return Err("lexeme string not terminated".into()); - }; - - let text = match String::from_utf8(buf[..nul_pos].to_vec()) { - Ok(s) => s, - Err(e) => return Err(format!("invalid UTF-8 in lexeme string: {}", e)), - }; - - *buf = &buf[nul_pos + 1..]; - - Ok(text) -} - -// Internal System, Snapshots & Statistics postgres types - -pub struct PgLsn { - pub upper: u32, - pub lower: u32, -} - -impl<'a> FromSql<'a> for PgLsn { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() != 8 { - return Err( - format!("fail to extract PgLsn: expected 8 bytes, got {}", raw.len()).into(), - ); - }; - - Ok(Self { - upper: u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]), - lower: u32::from_be_bytes([raw[4], raw[5], raw[6], raw[7]]), - }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::PG_LSN => true, - _ => false, - } - } -} - -impl From for JsonValue { - #[inline(always)] - fn from(value: PgLsn) -> Self { - JsonValue::String(format!("{:X}/{:X}", value.upper, value.lower)) - } -} - -pub struct TxidSnapshotOrPgSnapshot { - xmin: i64, - xmax: i64, - active_xids: Vec, -} - -impl<'a> FromSql<'a> for TxidSnapshotOrPgSnapshot { - fn from_sql( - _ty: &Type, - raw: &'a [u8], - ) -> Result> { - if raw.len() < 20 { - return Err(format!( - "fail to extract TxidSnapshotOrPgSnapshot: expected at least 20 bytes, got {}", - raw.len() - ) - .into()); - }; - - let count = i32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]); - - if count < 0 { - return Err(format!( - "fail to extract TxidSnapshot/PgSnapshot: count is negative: {}", - count - ) - .into()); - }; - - let xmin = i64::from_be_bytes(raw[4..12].try_into().unwrap()); - let xmax = i64::from_be_bytes(raw[12..20].try_into().unwrap()); - - if count == 0 { - return Ok(Self { - xmin, - xmax, - active_xids: Vec::new(), - }); - }; - - let count = count as usize; - - let mut chunks = (&raw[20..]).chunks_exact(8); - - if chunks.len() < count { - return Err(format!( - "fail to extract TxidSnapshot/PgSnapshot: expected {} 8-byte chunks, got {}", - count, - chunks.len() - ) - .into()); - }; - - let mut active_xids = Vec::with_capacity(count as usize); - - while let Some(chunk) = chunks.next() { - let xid = i64::from_be_bytes(chunk.try_into().unwrap()); - active_xids.push(xid); - } - - Ok(Self { - xmin, - xmax, - active_xids, - }) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::TXID_SNAPSHOT | Type::PG_SNAPSHOT => true, - _ => false, - } - } -} - -impl From for JsonValue { - fn from(value: TxidSnapshotOrPgSnapshot) -> Self { - JsonValue::String(format!( - "{}:{}:{}", - value.xmin, - value.xmax, - value - .active_xids - .into_iter() - .map(|xid| xid.to_string()) - .collect::>() - .join(",") - )) - } -} - -// FIXME: Postgres Wire Protocol has two formats for sending data - text and binary. -// The current format is binary (it is either set by `tokio-postgres` or by postgres -// because it is the default). anyway binary format doesn't support sending `AclItem` -utf8_wrapper!(AclItem, ACLITEM); -utf8_wrapper!(PgNodeTree, PG_NODE_TREE); - -macro_rules! binary_wrapper { - ($name: ident, $pg_type: ident) => { - pub struct $name(pub Vec); - - impl<'a> FromSql<'a> for $name { - fn from_sql( - _ty: &Type, - raw: &[u8], - ) -> Result> { - Ok(Self(raw.to_vec())) - } - - fn accepts(ty: &Type) -> bool { - match *ty { - Type::$pg_type => true, - _ => false, - } - } - } - - impl From<$name> for JsonValue { - #[inline(always)] - fn from(value: $name) -> Self { - JsonValue::String(encode_blob(&value.0)) - } - } - }; -} - -// Some of the following types have a complex binary structure but since -// they are very rarly used, we send them as blobs. anyway if someone requests, -// we should implement a proper text representation - -binary_wrapper!(PgMcvList, PG_MCV_LIST); -binary_wrapper!(PgDependencies, PG_DEPENDENCIES); -binary_wrapper!(PgNdistinct, PG_NDISTINCT); -binary_wrapper!(PgBrinBloomSummary, PG_BRIN_BLOOM_SUMMARY); -binary_wrapper!(PgBrinMinmaxMultiSummary, PG_BRIN_MINMAX_MULTI_SUMMARY); - -// pgvector extension types (vector, halfvec, sparsevec). -// -// These are extension-defined base types, so they have dynamic OIDs and are NOT -// available as `Type::*` constants — `accepts` matches on the type name instead. -// Values are rendered as their canonical pgvector text representation so they show -// up verbatim in the grid and can be edited/round-tripped as text (pgvector accepts -// the same text form on input). Binary layouts follow pgvector's `*_send` functions. - -/// Format an `f32` the way pgvector's text output does: shortest round-trippable -/// decimal, e.g. `1.0 -> "1"`, `1.5 -> "1.5"`. Rust's default formatter already -/// produces the shortest round-trip representation. -#[inline] -fn format_vector_float(value: f32) -> String { - value.to_string() -} - -/// pgvector `vector`: `int16 dim`, `int16 unused`, then `dim` big-endian `float4`. -pub struct PgVector(Vec); - -impl<'a> FromSql<'a> for PgVector { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() < 4 { - return Err(format!("expected at least 4 bytes for vector, got {}", raw.len()).into()); - } - let dim = u16::from_be_bytes([raw[0], raw[1]]) as usize; - let expected = 4 + dim * 4; - if raw.len() < expected { - return Err(format!( - "vector of dim {dim} expects {expected} bytes, got {}", - raw.len() - ) - .into()); - } - let mut values = Vec::with_capacity(dim); - for i in 0..dim { - let off = 4 + i * 4; - values.push(f32::from_be_bytes([ - raw[off], - raw[off + 1], - raw[off + 2], - raw[off + 3], - ])); - } - Ok(Self(values)) - } - - fn accepts(ty: &Type) -> bool { - ty.name() == "vector" - } -} - -impl From for JsonValue { - fn from(value: PgVector) -> Self { - let body = value - .0 - .iter() - .map(|v| format_vector_float(*v)) - .collect::>() - .join(","); - JsonValue::String(format!("[{body}]")) - } -} - -/// Decode an IEEE 754 half-precision (`binary16`) value into `f32`. -#[inline] -fn f16_bits_to_f32(bits: u16) -> f32 { - let sign = if (bits >> 15) & 1 == 1 { - -1.0f32 - } else { - 1.0f32 - }; - let exp = (bits >> 10) & 0x1f; - let mant = bits & 0x3ff; - match exp { - 0 => sign * (mant as f32) * 2f32.powi(-24), // zero / subnormal - 0x1f if mant == 0 => sign * f32::INFINITY, - 0x1f => f32::NAN, - _ => sign * (1.0 + (mant as f32) / 1024.0) * 2f32.powi(exp as i32 - 15), - } -} - -/// pgvector `halfvec`: `int16 dim`, `int16 unused`, then `dim` big-endian `float2` -/// (half-precision) values. -pub struct PgHalfVector(Vec); - -impl<'a> FromSql<'a> for PgHalfVector { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() < 4 { - return Err(format!("expected at least 4 bytes for halfvec, got {}", raw.len()).into()); - } - let dim = u16::from_be_bytes([raw[0], raw[1]]) as usize; - let expected = 4 + dim * 2; - if raw.len() < expected { - return Err(format!( - "halfvec of dim {dim} expects {expected} bytes, got {}", - raw.len() - ) - .into()); - } - let mut values = Vec::with_capacity(dim); - for i in 0..dim { - let off = 4 + i * 2; - values.push(f16_bits_to_f32(u16::from_be_bytes([ - raw[off], - raw[off + 1], - ]))); - } - Ok(Self(values)) - } - - fn accepts(ty: &Type) -> bool { - ty.name() == "halfvec" - } -} - -impl From for JsonValue { - fn from(value: PgHalfVector) -> Self { - let body = value - .0 - .iter() - .map(|v| format_vector_float(*v)) - .collect::>() - .join(","); - JsonValue::String(format!("[{body}]")) - } -} - -/// pgvector `sparsevec`: `int32 dim`, `int32 nnz`, `int32 unused`, then `nnz` -/// big-endian `int32` indices (0-based on the wire), then `nnz` big-endian -/// `float4` values. Text form is `{i1:v1,i2:v2}/dim` with 1-based indices. -pub struct PgSparseVector { - dim: i32, - entries: Vec<(i32, f32)>, -} - -impl<'a> FromSql<'a> for PgSparseVector { - fn from_sql(_ty: &Type, raw: &[u8]) -> Result> { - if raw.len() < 12 { - return Err(format!( - "expected at least 12 bytes for sparsevec, got {}", - raw.len() - ) - .into()); - } - let dim = i32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]); - let nnz = i32::from_be_bytes([raw[4], raw[5], raw[6], raw[7]]) as usize; - // raw[8..12] is the unused/reserved header field. - let expected = 12 + nnz * 4 + nnz * 4; - if raw.len() < expected { - return Err(format!( - "sparsevec with {nnz} entries expects {expected} bytes, got {}", - raw.len() - ) - .into()); - } - let mut entries = Vec::with_capacity(nnz); - let values_off = 12 + nnz * 4; - for i in 0..nnz { - let idx_off = 12 + i * 4; - let index = i32::from_be_bytes([ - raw[idx_off], - raw[idx_off + 1], - raw[idx_off + 2], - raw[idx_off + 3], - ]); - let val_off = values_off + i * 4; - let value = f32::from_be_bytes([ - raw[val_off], - raw[val_off + 1], - raw[val_off + 2], - raw[val_off + 3], - ]); - entries.push((index, value)); - } - Ok(Self { dim, entries }) - } - - fn accepts(ty: &Type) -> bool { - ty.name() == "sparsevec" - } -} - -impl From for JsonValue { - fn from(value: PgSparseVector) -> Self { - let body = value - .entries - .iter() - // pgvector prints indices 1-based; the wire format stores them 0-based. - .map(|(idx, v)| format!("{}:{}", idx + 1, format_vector_float(*v))) - .collect::>() - .join(","); - JsonValue::String(format!("{{{body}}}/{}", value.dim)) - } -} diff --git a/src-tauri/src/drivers/postgres/extract/array.rs b/src-tauri/src/drivers/postgres/extract/array.rs deleted file mode 100644 index df8428e11..000000000 --- a/src-tauri/src/drivers/postgres/extract/array.rs +++ /dev/null @@ -1,465 +0,0 @@ -use serde_json::Value as JsonValue; -use tokio_postgres::types::{Kind, Type}; - -use super::common::split_at_value_len; - -pub fn extract_or_null(ty: &Type, buf: &mut &[u8]) -> JsonValue { - // array must be at least 12 bytes (header) except if it is `NULL` - if buf.len() == 0 { - return JsonValue::Null; - }; - - if buf.len() < 12 { - log::error!("array buffer too short: {}", buf.len()); - return JsonValue::Null; - }; - - let dimensions = i32::from_be_bytes(buf[..4].try_into().unwrap()); - - // this means empty array - if dimensions < 1 { - return JsonValue::Array(vec![]); - }; - - // max dimensions is 64 and just for safety - if dimensions > 64 { - log::error!("too many dimensions: {}", dimensions); - return JsonValue::Null; - } - - // ignore `has nulls` 4 bytes - // ignore `element type` 4 bytes because we already have it - *buf = &buf[12..]; - - let dimensions = dimensions as usize; - - // each dimension must have at least 8 bytes info - if buf.len() < 8 * dimensions { - log::error!("array buffer too short: {}", buf.len()); - return JsonValue::Null; - }; - - let mut total_vecs: usize = 1; - let mut arr_lengths = Vec::with_capacity(dimensions); - - for i in 0..dimensions { - let length = i32::from_be_bytes(buf[..4].try_into().unwrap()); - - // i don't think this is possible but just in case - if length < 0 { - log::error!("invalid length: {}", length); - return JsonValue::Null; - }; - - let length = length as usize; - - arr_lengths.push(length); - - *buf = &buf[8..]; // skip `lower bound` 4 bytes - - if dimensions - i == 1 { - continue; - }; - - let all_vecs_in_this_lvl = match total_vecs.checked_mul(length) { - Some(v) => v, - None => { - log::error!("overflow: total_vecs={} length={}", total_vecs, length); - return JsonValue::Null; - } - }; - - total_vecs = match total_vecs.checked_add(all_vecs_in_this_lvl) { - Some(v) => v, - None => { - log::error!( - "overflow: total_vecs={} all_vecs_in_this_lvl={}", - total_vecs, - all_vecs_in_this_lvl - ); - return JsonValue::Null; - } - }; - } - - // SAFETY: i think this number should be discussed - if total_vecs > 1024 { - log::error!("too many vectors: total_vecs={}", total_vecs); - return JsonValue::Null; - }; - - let mut vec = Vec::with_capacity(arr_lengths[0]); - - let _ = extract_recursively_or_fill_nulls_into(&mut vec, &arr_lengths, 1, &ty, buf); - - JsonValue::Array(vec) -} - -/// the idea of returning a `Result` is to stop extracting further if error occurs -/// because it is most likely to fail anyway -fn extract_recursively_or_fill_nulls_into( - vec: &mut Vec, - arr_lengths: &[usize], - depth: usize, - ty: &Type, - buf: &mut &[u8], -) -> Result<(), ()> { - match depth == arr_lengths.len() { - true => { - let len = arr_lengths[depth - 1]; - for i in 0..len { - match try_extract_elem(ty, buf) { - Ok(value) => vec.push(value), - Err(_) => { - fill_nulls(vec, len - i); - return Err(()); - } - } - } - } - - false => { - let len = arr_lengths[depth - 1]; - for i in 0..len { - let mut sub_vec = Vec::with_capacity(len); - if let Err(_) = extract_recursively_or_fill_nulls_into( - &mut sub_vec, - arr_lengths, - depth + 1, - ty, - buf, - ) { - vec.push(JsonValue::Array(sub_vec)); - fill_nulls(vec, len - 1 - i); - return Err(()); - } - vec.push(JsonValue::Array(sub_vec)); - } - } - }; - - Ok(()) -} - -#[inline(always)] -fn fill_nulls(vec: &mut Vec, count: usize) { - for _ in 0..count { - vec.push(JsonValue::Null); - } -} - -#[inline] -fn try_extract_elem(ty: &Type, buf: &mut &[u8]) -> Result { - let mut value_buf = match split_at_value_len(buf)? { - Some(buf) => buf, - None => return Ok(JsonValue::Null), - }; - - Ok(match ty.kind() { - Kind::Simple => super::simple::extract_or_null(ty, value_buf), - Kind::Enum(_variants) => super::r#enum::extract_or_null(value_buf), - Kind::Array(_) => JsonValue::Null, // impossible case - Kind::Range(ty) => super::range::extract_or_null(ty, &mut value_buf), - Kind::Multirange(ty) => super::multi_range::extract_or_null(ty, &mut value_buf), - Kind::Domain(inner) => super::simple::extract_or_null(inner, value_buf), - Kind::Composite(fields) => super::composite::extract_or_null(fields, &mut value_buf), - _ => JsonValue::Null, - }) -} - -mod tests { - #[allow(unused_imports)] - use super::*; - - #[test] - fn test_simple_1d_pg_array_extraction() { - let arr = [ - 0, 0, 0, 1, // dimenstions 1 - 0, 0, 0, 0, // has nulls 0: false, 1: true - 0, 0, 0, 17, // oid 17 = INT4 - 0, 0, 0, 3, // array length - 0, 0, 0, 1, // lower bound - // the following is a sequance of element length and element bytes - 0, 0, 0, 4, // length 4 bytes - 0, 0, 0, 1, // element - 0, 0, 0, 4, // length - 0, 0, 0, 2, // element - 0, 0, 0, 4, // length - 0, 0, 0, 3, // element - ]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::INT4, &mut buf); - assert_eq!( - json, - JsonValue::Array(vec![ - JsonValue::Number(1.into()), - JsonValue::Number(2.into()), - JsonValue::Number(3.into()) - ]) - ); - } - - #[test] - fn test_simple_2dim_pg_array_extraction() { - let arr = [ - 0, 0, 0, 2, // dimensions 2 - 0, 0, 0, 0, // has nulls 0: false, 1: true - 0, 0, 0, 17, // oid 17 = INT4 - 0, 0, 0, 2, // outer array length: we have 2 sub arrays - 0, 0, 0, 1, // lower bound - 0, 0, 0, 2, // inner array lengths: each sub array has 2 elements - 0, 0, 0, 1, // lower bound - // the following is a sequance of element length and element bytes for each array - // beginning of first array - 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 2, - // end of first array - // beginning of second array - 0, 0, 0, 4, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 4, - ]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::INT4, &mut buf); - assert_eq!( - json, - JsonValue::Array(vec![ - JsonValue::Array(vec![ - JsonValue::Number(1.into()), - JsonValue::Number(2.into()), - ]), - JsonValue::Array(vec![ - JsonValue::Number(3.into()), - JsonValue::Number(4.into()), - ]), - ]) - ); - } - - #[test] - fn test_simple_3dim_pg_array_extraction() { - let arr = [ - 0, 0, 0, 3, // dimensions: 3 dimensions - 0, 0, 0, 0, // has nulls 0: false, 1: true - 0, 0, 0, 17, // oid 17 = INT4 - 0, 0, 0, 2, // main array length: we have 2 sub arrays - 0, 0, 0, 1, // lower bound - 0, 0, 0, 2, // level 1 array lengths: each level 1 array has 2 elements - 0, 0, 0, 1, // lower bound - 0, 0, 0, 2, // level 2 array lengths: each level 2 array has 2 elements - 0, 0, 0, 1, // lower bound - // beginning of (level 1 first array -> level 2 first array) - 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 2, - // end - // beginning of (level 1 first array -> level 2 second array) - 0, 0, 0, 4, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 4, - // beginning of (level 1 second array -> level 2 first array) - 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 2, - // end - // beginning of (level 1 second array -> level 2 second array) - 0, 0, 0, 4, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 4, - ]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::INT4, &mut buf); - assert_eq!( - json, - JsonValue::Array(vec![ - JsonValue::Array(vec![ - JsonValue::Array(vec![ - JsonValue::Number(1.into()), - JsonValue::Number(2.into()), - ]), - JsonValue::Array(vec![ - JsonValue::Number(3.into()), - JsonValue::Number(4.into()), - ]), - ]), - JsonValue::Array(vec![ - JsonValue::Array(vec![ - JsonValue::Number(1.into()), - JsonValue::Number(2.into()), - ]), - JsonValue::Array(vec![ - JsonValue::Number(3.into()), - JsonValue::Number(4.into()), - ]), - ]) - ]) - ); - } - - #[test] - fn test_empty_1d_array() { - // 1 dimension, INT4, length 0 - let arr = [ - 0, 0, 0, 1, // dimensions 1 - 0, 0, 0, 0, // has nulls false - 0, 0, 0, 17, // oid INT4 - 0, 0, 0, 0, // array length 0 - 0, 0, 0, 1, // lower bound - ]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::INT4, &mut buf); - assert_eq!(json, JsonValue::Array(vec![])); - } - - #[test] - fn test_single_element_array() { - let arr = [ - 0, 0, 0, 1, // dimensions 1 - 0, 0, 0, 0, // has nulls false - 0, 0, 0, 17, // oid INT4 - 0, 0, 0, 1, // array length 1 - 0, 0, 0, 1, // lower bound - 0, 0, 0, 4, // value length 4 - 0, 0, 0, 99, // element 99 - ]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::INT4, &mut buf); - assert_eq!(json, JsonValue::Array(vec![JsonValue::Number(99.into())])); - } - - #[test] - fn test_1d_text_array() { - // 1D array of TEXT (oid 25) with 2 elements: "hello", "world" - let arr = [ - 0, 0, 0, 1, // dimensions 1 - 0, 0, 0, 0, // has nulls false - 0, 0, 0, 25, // oid TEXT - 0, 0, 0, 2, // array length 2 - 0, 0, 0, 1, // lower bound - // element 1: "hello" - 0, 0, 0, 5, // length 5 - b'h', b'e', b'l', b'l', b'o', // element 2: "world" - 0, 0, 0, 5, // length 5 - b'w', b'o', b'r', b'l', b'd', - ]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::TEXT, &mut buf); - assert_eq!( - json, - JsonValue::Array(vec![ - JsonValue::String("hello".to_string()), - JsonValue::String("world".to_string()), - ]) - ); - } - - #[test] - fn test_empty_buffer_returns_null() { - let mut buf = &[][..]; - let json = extract_or_null(&Type::INT4, &mut buf); - assert_eq!(json, JsonValue::Null); - } - - #[test] - fn test_truncated_header_returns_null() { - // only 4 bytes — not enough for the 12-byte header - let arr = [0, 0, 0, 1]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::INT4, &mut buf); - assert_eq!(json, JsonValue::Null); - } - - #[test] - fn test_zero_dimensions_returns_empty_array() { - let arr = [ - 0, 0, 0, 0, // dimensions 0 — invalid - 0, 0, 0, 0, 0, 0, 0, 17, - ]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::INT4, &mut buf); - assert_eq!(json, JsonValue::Array(vec![])); - } - - #[test] - fn test_negative_length_returns_null_with_partial_fill() { - // 1D array with 2 elements where first has invalid (negative) length - let arr = [ - 0, 0, 0, 1, // dimensions 1 - 0, 0, 0, 0, // has nulls false - 0, 0, 0, 17, // oid INT4 - 0, 0, 0, 2, // array length 2 - 0, 0, 0, 1, // lower bound - // element 1: negative length = NULL - 0xff, 0xff, 0xff, 0xff, // length -1 (NULL marker) - // element 2: normal - 0, 0, 0, 4, 0, 0, 0, 42, - ]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::INT4, &mut buf); - assert_eq!( - json, - JsonValue::Array(vec![JsonValue::Null, JsonValue::Number(42.into()),]) - ); - } - - #[test] - fn test_2d_empty_inner_arrays() { - // 2 dimensions, outer length 2, each inner length 0 - let arr = [ - 0, 0, 0, 2, // dimensions 2 - 0, 0, 0, 0, // has nulls false - 0, 0, 0, 17, // oid INT4 - 0, 0, 0, 2, // outer length 2 - 0, 0, 0, 1, // lower bound - 0, 0, 0, 0, // inner length 0 (each sub-array has 0 elements) - 0, 0, 0, 1, // lower bound - ]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::INT4, &mut buf); - assert_eq!( - json, - JsonValue::Array(vec![JsonValue::Array(vec![]), JsonValue::Array(vec![]),]) - ); - } - - #[test] - fn test_truncated_elements_fill_with_nulls() { - // 1D array length 3, but only 1 complete element provided - let arr = [ - 0, 0, 0, 1, // dimensions 1 - 0, 0, 0, 0, // has nulls false - 0, 0, 0, 17, // oid INT4 - 0, 0, 0, 3, // array length 3 - 0, 0, 0, 1, // lower bound - // element 1: valid - 0, 0, 0, 4, 0, 0, 0, 10, - // element 2: truncated — only 2 bytes of value instead of 4 - 0, 0, 0, 4, // length says 4... - 0, 0, // ...but only 2 bytes available - ]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::INT4, &mut buf); - assert_eq!( - json, - JsonValue::Array(vec![ - JsonValue::Number(10.into()), - JsonValue::Null, - JsonValue::Null, - ]) - ); - } - - #[test] - fn test_bool_array() { - // 1D array of BOOL (oid 16) with 3 elements: true, false, true - let arr = [ - 0, 0, 0, 1, // dimensions 1 - 0, 0, 0, 0, // has nulls false - 0, 0, 0, 16, // oid BOOL - 0, 0, 0, 3, // array length 3 - 0, 0, 0, 1, // lower bound - 0, 0, 0, 1, 1, // length 1, value true - 0, 0, 0, 1, 0, // length 1, value false - 0, 0, 0, 1, 1, // length 1, value true - ]; - let mut buf = &arr[..]; - let json = extract_or_null(&Type::BOOL, &mut buf); - assert_eq!( - json, - JsonValue::Array(vec![ - JsonValue::Bool(true), - JsonValue::Bool(false), - JsonValue::Bool(true), - ]) - ); - } -} diff --git a/src-tauri/src/drivers/postgres/extract/common.rs b/src-tauri/src/drivers/postgres/extract/common.rs deleted file mode 100644 index 191083dcb..000000000 --- a/src-tauri/src/drivers/postgres/extract/common.rs +++ /dev/null @@ -1,42 +0,0 @@ -#[inline] -pub fn advance_buf(buf: &mut &[u8], n: usize) -> Result<(), ()> { - if buf.len() < n { - log::error!("Buffer too short: {} < {}", buf.len(), n); - return Err(()); - } - *buf = &buf[n..]; - Ok(()) -} - -pub fn split_at_value_len<'a>(buf: &mut &'a [u8]) -> Result, ()> { - if buf.len() < 4 { - log::error!("Buffer too short to read value length"); - return Err(()); - }; - - let len = i32::from_be_bytes(match buf[..4].try_into() { - Ok(bytes) => bytes, - Err(e) => { - log::error!("Failed to parse value length: {:?}", e); - return Err(()); - } - }); - - *buf = &buf[4..]; - - if len < 0 { - return Ok(None); - }; - - match buf.split_at_checked(len as usize) { - Some((value_buf, rest)) => { - *buf = rest; - Ok(Some(value_buf)) - } - - None => { - log::error!("Failed to split buffer at value length"); - return Err(()); - } - } -} diff --git a/src-tauri/src/drivers/postgres/extract/composite.rs b/src-tauri/src/drivers/postgres/extract/composite.rs deleted file mode 100644 index 8f8fe3143..000000000 --- a/src-tauri/src/drivers/postgres/extract/composite.rs +++ /dev/null @@ -1,253 +0,0 @@ -use serde_json::{Map, Value as JsonValue}; -use tokio_postgres::types::{Field, Kind}; - -use super::common::split_at_value_len; - -#[inline] -pub fn extract_or_null(fields: &Vec, buf: &mut &[u8]) -> JsonValue { - if buf.len() == 0 { - // receiving an empty buffer is an error but it indicates a null value - // log::error!("received empty buffer"); - return JsonValue::Null; - }; - - let mut map = serde_json::Map::with_capacity(fields.len()); - // ignore the error and return only the successfully extracted elements - // and fill the map with nulls for any remaining fields - extract_or_fill_nulls_into(fields, buf, &mut map); - JsonValue::Object(map) -} - -fn extract_or_fill_nulls_into( - fields: &Vec, - buf: &mut &[u8], - map: &mut Map, -) { - // skip the composite length we already have fields - if let Err(_) = super::common::advance_buf(buf, 4) { - fill_nulls(fields, map); - return; - }; - - let mut field; - for i in 0..fields.len() { - field = &fields[i]; - - // skip the field type OID - if let Err(_) = super::common::advance_buf(buf, 4) { - fill_nulls(&fields[i..], map); - return; - } - - match try_extract_field(field, buf) { - Ok(value) => { - map.insert(field.name().to_string(), value); - } - Err(_) => { - map.insert(field.name().to_string(), JsonValue::Null); - - if i + 1 < fields.len() { - // insert the rest of the fields with null values - fill_nulls(&fields[i + 1..], map); - return; - } - } - } - } -} - -#[inline(always)] -fn fill_nulls(fields: &[Field], map: &mut Map) { - fields.iter().for_each(|f| { - map.insert(f.name().to_string(), JsonValue::Null); - }); -} - -#[inline] -/// the idea of returning a `Result` is to stop extracting further if error occurs -/// because it is most likely to fail anyway -fn try_extract_field(field: &Field, buf: &mut &[u8]) -> Result { - let mut value_buf = match split_at_value_len(buf)? { - Some(buf) => buf, - None => return Ok(JsonValue::Null), - }; - - let ty = field.type_(); - - Ok(match ty.kind() { - Kind::Simple => super::simple::extract_or_null(ty, value_buf), - Kind::Enum(_variants) => super::r#enum::extract_or_null(value_buf), - Kind::Array(of) => super::array::extract_or_null(of, &mut value_buf), - Kind::Range(ty) => super::range::extract_or_null(ty, &mut value_buf), - Kind::Multirange(ty) => super::multi_range::extract_or_null(ty, &mut value_buf), - Kind::Domain(ty) => super::simple::extract_or_null(ty, value_buf), - Kind::Composite(fields) => extract_or_null(fields, buf), - _ => JsonValue::Null, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use tokio_postgres::types::Type; - - fn build_composite_buf(field_values: &[(u32, Option)]) -> Vec { - let mut payload = Vec::new(); - for &(oid, val) in field_values { - payload.extend_from_slice(&oid.to_be_bytes()); - match val { - Some(v) => { - payload.extend_from_slice(&4i32.to_be_bytes()); - payload.extend_from_slice(&v.to_be_bytes()); - } - None => { - payload.extend_from_slice(&(-1i32).to_be_bytes()); - } - } - } - let composite_len = payload.len() as i32; - let mut buf = Vec::with_capacity(4 + payload.len()); - buf.extend_from_slice(&composite_len.to_be_bytes()); - buf.extend_from_slice(&payload); - buf - } - - #[test] - fn test_empty_buffer_returns_null() { - let fields = vec![Field::new("id".to_string(), Type::INT4)]; - let mut buf = &[][..]; - assert_eq!(extract_or_null(&fields, &mut buf), JsonValue::Null); - } - - #[test] - fn test_single_int4_field() { - let fields = vec![Field::new("id".to_string(), Type::INT4)]; - let buf = build_composite_buf(&[(Type::INT4.oid(), Some(42))]); - let mut slice = &buf[..]; - let result = extract_or_null(&fields, &mut slice); - let obj = result.as_object().unwrap(); - assert_eq!(obj.get("id").unwrap(), &JsonValue::Number(42.into())); - } - - #[test] - fn test_multiple_int4_fields() { - let fields = vec![ - Field::new("a".to_string(), Type::INT4), - Field::new("b".to_string(), Type::INT4), - Field::new("c".to_string(), Type::INT4), - ]; - let buf = build_composite_buf(&[ - (Type::INT4.oid(), Some(10)), - (Type::INT4.oid(), Some(20)), - (Type::INT4.oid(), Some(30)), - ]); - let mut slice = &buf[..]; - let result = extract_or_null(&fields, &mut slice); - let obj = result.as_object().unwrap(); - assert_eq!(obj.get("a").unwrap(), &JsonValue::Number(10.into())); - assert_eq!(obj.get("b").unwrap(), &JsonValue::Number(20.into())); - assert_eq!(obj.get("c").unwrap(), &JsonValue::Number(30.into())); - } - - #[test] - fn test_null_field_value() { - let fields = vec![ - Field::new("x".to_string(), Type::INT4), - Field::new("y".to_string(), Type::INT4), - ]; - let buf = build_composite_buf(&[(Type::INT4.oid(), Some(99)), (Type::INT4.oid(), None)]); - let mut slice = &buf[..]; - let result = extract_or_null(&fields, &mut slice); - let obj = result.as_object().unwrap(); - assert_eq!(obj.get("x").unwrap(), &JsonValue::Number(99.into())); - assert_eq!(obj.get("y").unwrap(), &JsonValue::Null); - } - - #[test] - fn test_all_null_fields() { - let fields = vec![ - Field::new("a".to_string(), Type::TEXT), - Field::new("b".to_string(), Type::INT4), - ]; - let buf = build_composite_buf(&[(Type::TEXT.oid(), None), (Type::INT4.oid(), None)]); - let mut slice = &buf[..]; - let result = extract_or_null(&fields, &mut slice); - let obj = result.as_object().unwrap(); - assert_eq!(obj.get("a").unwrap(), &JsonValue::Null); - assert_eq!(obj.get("b").unwrap(), &JsonValue::Null); - } - - #[test] - fn test_truncated_composite_fills_remaining_with_nulls() { - let fields = vec![ - Field::new("first".to_string(), Type::INT4), - Field::new("second".to_string(), Type::INT4), - ]; - let full_buf = - build_composite_buf(&[(Type::INT4.oid(), Some(1)), (Type::INT4.oid(), Some(2))]); - let truncated = &full_buf[..16]; - let mut slice = truncated; - let result = extract_or_null(&fields, &mut slice); - let obj = result.as_object().unwrap(); - assert_eq!(obj.get("first").unwrap(), &JsonValue::Number(1.into())); - assert_eq!(obj.get("second").unwrap(), &JsonValue::Null); - } - - #[test] - fn test_composite_with_text_field() { - let fields = vec![Field::new("name".to_string(), Type::TEXT)]; - let name_bytes = b"alice"; - let mut payload = Vec::new(); - payload.extend_from_slice(&Type::TEXT.oid().to_be_bytes()); - payload.extend_from_slice(&(name_bytes.len() as i32).to_be_bytes()); - payload.extend_from_slice(name_bytes); - let composite_len = payload.len() as i32; - let mut buf = Vec::new(); - buf.extend_from_slice(&composite_len.to_be_bytes()); - buf.extend_from_slice(&payload); - let mut slice = &buf[..]; - let result = extract_or_null(&fields, &mut slice); - let obj = result.as_object().unwrap(); - assert_eq!( - obj.get("name").unwrap(), - &JsonValue::String("alice".to_string()) - ); - } - - #[test] - fn test_composite_with_bool_field() { - let fields = vec![Field::new("active".to_string(), Type::BOOL)]; - let mut payload = Vec::new(); - payload.extend_from_slice(&Type::BOOL.oid().to_be_bytes()); - payload.extend_from_slice(&1i32.to_be_bytes()); - payload.push(1u8); - let composite_len = payload.len() as i32; - let mut buf = Vec::new(); - buf.extend_from_slice(&composite_len.to_be_bytes()); - buf.extend_from_slice(&payload); - let mut slice = &buf[..]; - let result = extract_or_null(&fields, &mut slice); - let obj = result.as_object().unwrap(); - assert_eq!(obj.get("active").unwrap(), &JsonValue::Bool(true)); - } - - // `serde_json::Map` does not preserve field order, so this test is not applicable - // #[test] - // fn test_composite_preserves_field_order() { - // let fields = vec![ - // Field::new("z_last".to_string(), Type::INT4), - // Field::new("a_first".to_string(), Type::INT4), - // Field::new("m_middle".to_string(), Type::INT4), - // ]; - // let buf = build_composite_buf(&[ - // (Type::INT4.oid(), Some(1)), - // (Type::INT4.oid(), Some(2)), - // (Type::INT4.oid(), Some(3)), - // ]); - // let mut slice = &buf[..]; - // let result = extract_or_null(&fields, &mut slice); - // let obj = result.as_object().unwrap(); - // let keys: Vec<&str> = obj.keys().map(|s| s.as_str()).collect(); - // assert_eq!(keys, vec!["z_last", "a_first", "m_middle"]); - // } -} diff --git a/src-tauri/src/drivers/postgres/extract/enum.rs b/src-tauri/src/drivers/postgres/extract/enum.rs deleted file mode 100644 index bd3698d41..000000000 --- a/src-tauri/src/drivers/postgres/extract/enum.rs +++ /dev/null @@ -1,54 +0,0 @@ -use serde_json::Value as JsonValue; - -#[inline(always)] -pub fn extract_or_null(buf: &[u8]) -> JsonValue { - match std::str::from_utf8(buf) { - Ok(s) => JsonValue::String(s.to_string()), - Err(_) => JsonValue::Null, - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_valid_utf8() { - let buf = b"active"; - assert_eq!( - extract_or_null(buf), - JsonValue::String("active".to_string()) - ); - } - - #[test] - fn test_empty_buffer() { - let buf = b""; - assert_eq!(extract_or_null(buf), JsonValue::String("".to_string())); - } - - #[test] - fn test_invalid_utf8_returns_null() { - let buf = [0xff, 0xfe, 0xfd]; - assert_eq!(extract_or_null(&buf), JsonValue::Null); - } - - #[test] - fn test_single_char() { - let buf = b"A"; - assert_eq!(extract_or_null(buf), JsonValue::String("A".to_string())); - } - - #[test] - fn test_unicode() { - let buf = "héllo".as_bytes(); - assert_eq!(extract_or_null(buf), JsonValue::String("héllo".to_string())); - } - - #[test] - fn test_truncated_utf8_returns_null() { - // 0xC3 is a valid UTF-8 lead byte but incomplete without continuation - let buf = [0xC3]; - assert_eq!(extract_or_null(&buf), JsonValue::Null); - } -} diff --git a/src-tauri/src/drivers/postgres/extract/mod.rs b/src-tauri/src/drivers/postgres/extract/mod.rs deleted file mode 100644 index eaf321cdc..000000000 --- a/src-tauri/src/drivers/postgres/extract/mod.rs +++ /dev/null @@ -1,73 +0,0 @@ -mod advanced_types; -mod array; -mod common; -mod composite; -mod r#enum; -mod multi_range; -mod range; -mod simple; - -use serde_json::Value as JsonValue; -use tokio_postgres::{ - types::{FromSql, Kind, Type}, - Row, -}; - -pub fn extract_value(row: &Row, index: usize, _known_type: Option<&str>) -> JsonValue { - match row.try_get::<_, Extractor>(index) { - Ok(extractor) => extractor.value, - Err(_) => JsonValue::Null, - } -} - -/// used to get the raw value from postgres `Row`, before converting to `JsonValue`. -struct Extractor { - value: JsonValue, -} - -impl Extractor { - #[inline(always)] - const fn new() -> Self { - Self { - value: JsonValue::Null, - } - } -} - -impl<'a> FromSql<'a> for Extractor { - fn from_sql( - ty: &Type, - raw: &'a [u8], - ) -> Result> { - let mut extractor = Extractor::new(); - extractor.value = match ty.kind() { - Kind::Simple => simple::extract_or_null(ty, raw), - Kind::Enum(_variants) => r#enum::extract_or_null(raw), // we don't need _variants - Kind::Array(ty) => { - let mut buf = raw; - array::extract_or_null(ty, &mut buf) - } - Kind::Range(ty) => { - let mut buf = raw; - range::extract_or_null(ty, &mut buf) - } - Kind::Multirange(ty) => { - let mut buf = raw; - multi_range::extract_or_null(ty, &mut buf) - } - Kind::Domain(ty) => simple::extract_or_null(ty, raw), - Kind::Composite(fields) => { - let mut buf = raw; - composite::extract_or_null(fields, &mut buf) - } - _ => JsonValue::Null, // unsupported - }; - - Ok(extractor) - } - - #[inline(always)] - fn accepts(_ty: &Type) -> bool { - true - } -} diff --git a/src-tauri/src/drivers/postgres/extract/multi_range.rs b/src-tauri/src/drivers/postgres/extract/multi_range.rs deleted file mode 100644 index 21608af8d..000000000 --- a/src-tauri/src/drivers/postgres/extract/multi_range.rs +++ /dev/null @@ -1,161 +0,0 @@ -use serde_json::Value as JsonValue; -use tokio_postgres::types::Type; - -use crate::drivers::postgres::extract::common::advance_buf; - -#[inline] -pub fn extract_or_null(ty: &Type, buf: &mut &[u8]) -> JsonValue { - if buf.len() < 4 { - return JsonValue::Null; - }; - - let count = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]); - - *buf = &buf[4..]; - - if count == 0 { - return JsonValue::from("{}"); - }; - - let mut ranges = String::from('{'); - - for _ in 0..count - 1 { - // skip range length - if let Err(_) = advance_buf(buf, 4) { - ranges.push('}'); - return JsonValue::String(ranges); - }; - - match super::range::extract_or_null(ty, buf) { - JsonValue::String(r) => ranges.push_str(&r), - r @ _ => { - log::error!("range::extract_or_null must return a string or null"); - ranges.push_str(&r.to_string()) - } - } - - ranges.push(','); - } - - // skip range length - if let Err(_) = advance_buf(buf, 4) { - ranges.push('}'); - return JsonValue::String(ranges); - }; - - match super::range::extract_or_null(ty, buf) { - JsonValue::String(r) => ranges.push_str(&r), - r @ _ => { - log::error!("range::extract_or_null must return a string or null"); - ranges.push_str(&r.to_string()) - } - }; - - ranges.push('}'); - - JsonValue::String(ranges) -} - -#[cfg(test)] -mod tests { - use super::*; - - const RANGE_LB_INC: u8 = 1 << 1; - const RANGE_UB_INC: u8 = 1 << 2; - - fn build_int4_range(flag: u8, lower: Option, upper: Option) -> Vec { - let mut buf = vec![flag]; - if let Some(v) = lower { - buf.extend_from_slice(&4i32.to_be_bytes()); - buf.extend_from_slice(&v.to_be_bytes()); - } - if let Some(v) = upper { - buf.extend_from_slice(&4i32.to_be_bytes()); - buf.extend_from_slice(&v.to_be_bytes()); - } - buf - } - - fn build_multirange(count: u32, ranges: &[Vec]) -> Vec { - let mut buf = Vec::new(); - buf.extend_from_slice(&count.to_be_bytes()); - for r in ranges { - buf.extend_from_slice(&(r.len() as i32).to_be_bytes()); // range length prefix - buf.extend_from_slice(r); - } - buf - } - - #[test] - fn test_empty_multirange() { - let buf = build_multirange(0, &[]); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::from("{}") - ); - } - - #[test] - fn test_single_range_multirange() { - let range = build_int4_range(RANGE_LB_INC, Some(1), Some(5)); - let buf = build_multirange(1, &[range]); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::from("{[1, 5)}") - ); - } - - #[test] - fn test_two_ranges_multirange() { - let r1 = build_int4_range(RANGE_LB_INC, Some(1), Some(5)); - let r2 = build_int4_range(RANGE_LB_INC, Some(10), Some(20)); - let buf = build_multirange(2, &[r1, r2]); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::from("{[1, 5),[10, 20)}") - ); - } - - #[test] - fn test_three_ranges_multirange() { - let r1 = build_int4_range(RANGE_LB_INC, Some(1), Some(5)); - let r2 = build_int4_range(RANGE_LB_INC | RANGE_UB_INC, Some(10), Some(20)); - let r3 = build_int4_range(RANGE_LB_INC, Some(100), Some(200)); - let buf = build_multirange(3, &[r1, r2, r3]); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::from("{[1, 5),[10, 20],[100, 200)}") - ); - } - - #[test] - fn test_empty_buffer_returns_null() { - let buf = []; - let mut slice = &buf[..]; - assert_eq!(extract_or_null(&Type::INT4, &mut slice), JsonValue::Null); - } - - #[test] - fn test_truncated_count_returns_null() { - let buf = [0x00, 0x00]; // only 2 bytes, need 4 - let mut slice = &buf[..]; - assert_eq!(extract_or_null(&Type::INT4, &mut slice), JsonValue::Null); - } - - #[test] - fn test_mixed_bounds() { - let r1 = build_int4_range(RANGE_LB_INC, Some(1), Some(5)); // [1, 5) - let r2 = build_int4_range(0x00, Some(10), Some(20)); // (10, 20) - let r3 = build_int4_range(RANGE_UB_INC, Some(100), Some(200)); // (100, 200] - let buf = build_multirange(3, &[r1, r2, r3]); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::from("{[1, 5),(10, 20),(100, 200]}") - ); - } -} diff --git a/src-tauri/src/drivers/postgres/extract/range.rs b/src-tauri/src/drivers/postgres/extract/range.rs deleted file mode 100644 index a02168bf6..000000000 --- a/src-tauri/src/drivers/postgres/extract/range.rs +++ /dev/null @@ -1,268 +0,0 @@ -use serde_json::Value as JsonValue; -use tokio_postgres::types::{Kind, Type}; - -use crate::drivers::postgres::extract::common::split_at_value_len; - -#[inline] -pub fn extract_or_null(ty: &Type, buf: &mut &[u8]) -> JsonValue { - if buf.len() < 1 { - return JsonValue::Null; - }; - - let flag = buf[0]; - *buf = &buf[1..]; - - if (flag & 1) == 1 { - return JsonValue::String(String::from("empty")); - }; - - let mut range = String::new(); - - range.push(get_lower_bound(flag)); - - if flag & (1 << 3) == 0 { - if let Err(_) = try_extract_bound_into(ty, buf, &mut range) { - range.push_str("null, null"); - range.push(get_upper_bound(flag)); - return JsonValue::String(range); - }; - }; - - range.push_str(", "); - - if flag & (1 << 4) == 0 { - if let Err(_) = try_extract_bound_into(ty, buf, &mut range) { - range.push_str("null"); - }; - } - - range.push(get_upper_bound(flag)); - - JsonValue::String(range) -} - -#[inline(always)] -fn get_lower_bound(flag: u8) -> char { - if (flag & (1 << 1)) == 0 { - '(' - } else { - '[' - } -} - -fn try_extract_bound_into(ty: &Type, buf: &mut &[u8], range: &mut String) -> Result<(), ()> { - let mut value_buf = match split_at_value_len(buf)? { - Some(buf) => buf, - _ => { - return Err(()); - } - }; - - let val = match ty.kind() { - Kind::Simple => super::simple::extract_or_null(ty, value_buf), - Kind::Enum(_variants) => super::r#enum::extract_or_null(value_buf), - Kind::Array(ty) => super::array::extract_or_null(ty, &mut value_buf), - Kind::Range(_) => JsonValue::Null, // impossible - Kind::Multirange(_) => JsonValue::Null, // not allowed by postgres - Kind::Domain(ty) => super::simple::extract_or_null(ty, value_buf), - Kind::Composite(fields) => super::composite::extract_or_null(fields, &mut value_buf), - _ => JsonValue::Null, // unsupported - }; - - range.push_str(&val.to_string()); - Ok(()) -} - -#[inline(always)] -fn get_upper_bound(flag: u8) -> char { - if (flag & (1 << 2)) == 0 { - ')' - } else { - ']' - } -} - -#[cfg(test)] -mod tests { - use super::*; - - // postgres range flags - const RANGE_EMPTY: u8 = 1 << 0; - const RANGE_LB_INC: u8 = 1 << 1; - const RANGE_UB_INC: u8 = 1 << 2; - const RANGE_LB_INF: u8 = 1 << 3; - const RANGE_UB_INF: u8 = 1 << 4; - - fn build_int4_range(flag: u8, lower: Option, upper: Option) -> Vec { - let mut buf = vec![flag]; - if let Some(v) = lower { - buf.extend_from_slice(&4i32.to_be_bytes()); - buf.extend_from_slice(&v.to_be_bytes()); - } - if let Some(v) = upper { - buf.extend_from_slice(&4i32.to_be_bytes()); - buf.extend_from_slice(&v.to_be_bytes()); - } - buf - } - - #[test] - fn test_empty_range() { - let buf = [RANGE_EMPTY]; - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("empty".to_string()) - ); - } - - #[test] - fn test_inclusive_exclusive() { - // [1, 5) - let buf = build_int4_range(RANGE_LB_INC, Some(1), Some(5)); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("[1, 5)".to_string()) - ); - } - - #[test] - fn test_inclusive_inclusive() { - // [1, 5] - let buf = build_int4_range(RANGE_LB_INC | RANGE_UB_INC, Some(1), Some(5)); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("[1, 5]".to_string()) - ); - } - - #[test] - fn test_exclusive_exclusive() { - // (1, 5) - let buf = build_int4_range(0x00, Some(1), Some(5)); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("(1, 5)".to_string()) - ); - } - - #[test] - fn test_exclusive_inclusive() { - // (1, 5] - let buf = build_int4_range(RANGE_UB_INC, Some(1), Some(5)); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("(1, 5]".to_string()) - ); - } - - #[test] - fn test_unbounded_lower_inclusive_upper() { - // (, 5] - let buf = build_int4_range(RANGE_LB_INF | RANGE_UB_INC, None, Some(5)); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("(, 5]".to_string()) - ); - } - - #[test] - fn test_unbounded_lower_exclusive_upper() { - // (, 5) - let buf = build_int4_range(RANGE_LB_INF, None, Some(5)); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("(, 5)".to_string()) - ); - } - - #[test] - fn test_inclusive_lower_unbounded_upper() { - // [5, ) - let buf = build_int4_range(RANGE_LB_INC | RANGE_UB_INF, Some(5), None); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("[5, )".to_string()) - ); - } - - #[test] - fn test_exclusive_lower_unbounded_upper() { - // (5, ) - let buf = build_int4_range(RANGE_UB_INF, Some(5), None); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("(5, )".to_string()) - ); - } - - #[test] - fn test_both_unbounded() { - // (, ) - let buf = build_int4_range(RANGE_LB_INF | RANGE_UB_INF, None, None); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("(, )".to_string()) - ); - } - - #[test] - fn test_empty_buffer_returns_null() { - let buf = []; - let mut slice = &buf[..]; - assert_eq!(extract_or_null(&Type::INT4, &mut slice), JsonValue::Null); - } - - #[test] - fn test_negative_values() { - // [-10, 0) - let buf = build_int4_range(RANGE_LB_INC, Some(-10), Some(0)); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("[-10, 0)".to_string()) - ); - } - - #[test] - fn test_point_range() { - // [42, 42] - let buf = build_int4_range(RANGE_LB_INC | RANGE_UB_INC, Some(42), Some(42)); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("[42, 42]".to_string()) - ); - } - - #[test] - fn test_truncated_upper_returns_null_upper() { - // valid lower but no upper data - let buf = build_int4_range(RANGE_LB_INC, Some(1), None); - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("[1, null)".to_string()) - ); - } - - #[test] - fn test_truncated_lower_returns_null_both() { - // flag + lower len says 4 bytes but only 2 available - let buf = [RANGE_LB_INC, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00]; - let mut slice = &buf[..]; - assert_eq!( - extract_or_null(&Type::INT4, &mut slice), - JsonValue::String("[null, null)".to_string()) - ); - } -} diff --git a/src-tauri/src/drivers/postgres/extract/simple.rs b/src-tauri/src/drivers/postgres/extract/simple.rs deleted file mode 100644 index 0c5bdab8b..000000000 --- a/src-tauri/src/drivers/postgres/extract/simple.rs +++ /dev/null @@ -1,1659 +0,0 @@ -use std::collections::HashMap; - -use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc}; -use rust_decimal::Decimal; -use serde_json::Value as JsonValue; -use tokio_postgres::types::{FromSql, Type}; -use uuid::Uuid; - -use crate::drivers::common::{encode_blob, float4_to_json_f64, i64_to_json}; - -use super::advanced_types; - -#[cfg(test)] -#[path = "simple_tests.rs"] -mod simple_tests; - -#[inline] -pub fn extract_or_null(ty: &Type, buf: &[u8]) -> JsonValue { - match *ty { - Type::BOOL => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::BYTEA => { - JsonValue::from(from_sql_or_none::>(ty, buf).map(|b| encode_blob(&b))) - } - - // numeric - Type::CHAR => JsonValue::from(from_sql_or_none::(ty, buf)), // this mapped to `i8` - Type::INT2 => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::INT4 => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::INT8 => from_sql_or_none::(ty, buf) - .map(i64_to_json) - .unwrap_or(JsonValue::Null), - Type::FLOAT4 => { - JsonValue::from(from_sql_or_none::(ty, buf).and_then(float4_to_json_f64)) - } - Type::FLOAT8 => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::NUMERIC => { - JsonValue::from(from_sql_or_none::(ty, buf).map(|d| d.to_string())) - } - Type::OID => JsonValue::from(from_sql_or_none::(ty, buf)), - - // text - Type::TEXT => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::VARCHAR => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::BPCHAR => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::UNKNOWN => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::NAME => JsonValue::from(from_sql_or_none::(ty, buf)), - ref ty if ["citext", "ltree", "lquery", "ltxtquery"].contains(&ty.name()) => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - - // uuid - Type::UUID => JsonValue::from(from_sql_or_none::(ty, buf).map(|u| u.to_string())), - - // date/time - Type::DATE => JsonValue::from( - from_sql_or_none::(ty, buf).map(|d| d.format("%Y-%m-%d").to_string()), - ), - Type::TIME => JsonValue::from( - from_sql_or_none::(ty, buf).map(|t| t.format("%H:%M:%S").to_string()), - ), - Type::TIMESTAMP => JsonValue::from( - from_sql_or_none::(ty, buf) - .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string()), - ), - Type::TIMESTAMPTZ => JsonValue::from( - from_sql_or_none::>(ty, buf) - .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string()), - ), - Type::INTERVAL => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::TIMETZ => JsonValue::from(from_sql_or_none::(ty, buf)), - - // json - Type::JSON => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::JSONB => JsonValue::from(from_sql_or_none::(ty, buf)), - - // HashMap - ref ty if ty.name() == "hstore" => { - serde_json::to_value(from_sql_or_none::>>(ty, buf)) - .unwrap_or_default() - } - - // Network types - Type::MACADDR => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::MACADDR8 => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::INET => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::CIDR => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::BIT => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::VARBIT => JsonValue::from(from_sql_or_none::(ty, buf)), - - // System Identifiers - Type::XID => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::CID => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::TID => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::XID8 => JsonValue::from(from_sql_or_none::(ty, buf)), - - // Object References (The "Reg" Types) - Type::REGPROC => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::REGPROCEDURE => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - Type::REGOPER => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::REGOPERATOR => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - Type::REGCLASS => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::REGTYPE => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::REGCONFIG => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::REGDICTIONARY => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - Type::REGNAMESPACE => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - Type::REGROLE => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::REGCOLLATION => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - - // Geometric Types - Type::POINT => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::LSEG => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::BOX => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::POLYGON => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::PATH => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::LINE => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::CIRCLE => JsonValue::from(from_sql_or_none::(ty, buf)), - - // uft8 text - Type::JSONPATH => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::XML => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::REFCURSOR => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::ACLITEM => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::PG_NODE_TREE => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - - Type::MONEY => JsonValue::from(from_sql_or_none::(ty, buf)), - - // Full Text Search types - Type::TS_VECTOR => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::TSQUERY => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::GTS_VECTOR => JsonValue::from(from_sql_or_none::(ty, buf)), - - // Internal System, Snapshots & Statistics postgres types - Type::PG_LSN => JsonValue::from(from_sql_or_none::(ty, buf)), - Type::PG_SNAPSHOT => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - Type::TXID_SNAPSHOT => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - Type::PG_NDISTINCT => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - Type::PG_DEPENDENCIES => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - Type::PG_BRIN_BLOOM_SUMMARY => JsonValue::from(from_sql_or_none::< - advanced_types::PgBrinBloomSummary, - >(ty, buf)), - Type::PG_BRIN_MINMAX_MULTI_SUMMARY => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - Type::PG_MCV_LIST => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - - // pgvector extension types (dynamic OIDs, matched by name) - ref ty if ty.name() == "vector" => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - ref ty if ty.name() == "halfvec" => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - ref ty if ty.name() == "sparsevec" => { - JsonValue::from(from_sql_or_none::(ty, buf)) - } - - _ => JsonValue::Null, - } -} - -#[inline] -fn from_sql_or_none<'a, T>(ty: &Type, buf: &'a [u8]) -> Option -where - T: FromSql<'a>, -{ - match as FromSql>::from_sql(ty, buf) { - Ok(value) => value, - Err(e) => { - log::error!("Failed to read value from sql: {:?}", e); - None - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use tokio_postgres::types::Kind; - - #[test] - fn test_bool_true() { - let buf = [1u8]; - assert_eq!(extract_or_null(&Type::BOOL, &buf), JsonValue::Bool(true)); - } - - #[test] - fn test_bool_false() { - let buf = [0u8]; - assert_eq!(extract_or_null(&Type::BOOL, &buf), JsonValue::Bool(false)); - } - - #[test] - fn test_int2_positive() { - let buf = 42i16.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::INT2, &buf), - JsonValue::Number(42.into()) - ); - } - - #[test] - fn test_int2_negative() { - let buf = (-100i16).to_be_bytes(); - assert_eq!( - extract_or_null(&Type::INT2, &buf), - JsonValue::Number((-100).into()) - ); - } - - #[test] - fn test_int4_positive() { - let buf = 123456i32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::INT4, &buf), - JsonValue::Number(123456.into()) - ); - } - - #[test] - fn test_int4_zero() { - let buf = 0i32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::INT4, &buf), - JsonValue::Number(0.into()) - ); - } - - #[test] - fn test_int4_negative() { - let buf = (-999i32).to_be_bytes(); - assert_eq!( - extract_or_null(&Type::INT4, &buf), - JsonValue::Number((-999).into()) - ); - } - - #[test] - fn test_int8_positive() { - let buf = 9876543210i64.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::INT8, &buf), - JsonValue::Number(9876543210i64.into()) - ); - } - - #[test] - fn test_int8_negative() { - let buf = (-42i64).to_be_bytes(); - assert_eq!( - extract_or_null(&Type::INT8, &buf), - JsonValue::Number((-42).into()) - ); - } - - #[test] - fn test_int8_above_js_safe_becomes_string() { - // Snowflake id from issue #210 — must survive without precision loss. - let buf = 844_197_938_335_842_304i64.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::INT8, &buf), - JsonValue::String("844197938335842304".to_string()) - ); - } - - #[test] - fn test_int8_below_js_safe_becomes_string() { - let buf = (-9_007_199_254_740_992i64).to_be_bytes(); - assert_eq!( - extract_or_null(&Type::INT8, &buf), - JsonValue::String("-9007199254740992".to_string()) - ); - } - - #[test] - #[allow(clippy::approx_constant)] - fn test_float4() { - let buf = 3.14f32.to_be_bytes(); - let result = extract_or_null(&Type::FLOAT4, &buf); - match result { - JsonValue::Number(n) => { - let val = n.as_f64().unwrap(); - assert!((val - 3.14).abs() < 0.001); - } - _ => panic!("expected number"), - } - } - - #[test] - #[allow(clippy::approx_constant)] - fn test_float8() { - let buf = 2.718281828f64.to_be_bytes(); - let result = extract_or_null(&Type::FLOAT8, &buf); - match result { - JsonValue::Number(n) => { - let val = n.as_f64().unwrap(); - assert!((val - 2.718281828).abs() < 1e-9); - } - _ => panic!("expected number"), - } - } - - #[test] - fn test_text() { - let buf = b"hello world"; - assert_eq!( - extract_or_null(&Type::TEXT, buf), - JsonValue::String("hello world".to_string()) - ); - } - - #[test] - fn test_text_empty() { - let buf = b""; - assert_eq!( - extract_or_null(&Type::TEXT, buf), - JsonValue::String("".to_string()) - ); - } - - #[test] - fn test_varchar() { - let buf = b"test varchar"; - assert_eq!( - extract_or_null(&Type::VARCHAR, buf), - JsonValue::String("test varchar".to_string()) - ); - } - - #[test] - fn test_bpchar() { - let buf = b"padded "; - assert_eq!( - extract_or_null(&Type::BPCHAR, buf), - JsonValue::String("padded ".to_string()) - ); - } - - #[test] - fn test_name() { - let buf = b"pg_type"; - assert_eq!( - extract_or_null(&Type::NAME, buf), - JsonValue::String("pg_type".to_string()) - ); - } - - #[test] - fn test_unknown_type() { - let buf = b"unknown_val"; - assert_eq!( - extract_or_null(&Type::UNKNOWN, buf), - JsonValue::String("unknown_val".to_string()) - ); - } - - #[test] - fn test_char_as_i8() { - let buf = (-5i8).to_be_bytes(); - assert_eq!( - extract_or_null(&Type::CHAR, &buf), - JsonValue::Number((-5).into()) - ); - } - - #[test] - fn test_oid() { - let buf = 23u32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::OID, &buf), - JsonValue::Number(23.into()) - ); - } - - #[test] - fn test_uuid() { - let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(); - let buf = *uuid.as_bytes(); - assert_eq!( - extract_or_null(&Type::UUID, &buf), - JsonValue::String("550e8400-e29b-41d4-a716-446655440000".to_string()) - ); - } - - #[test] - fn test_date() { - // 2024-01-15 = 8780 days since 2000-01-01 - let days: i32 = 8780; - let buf = days.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::DATE, &buf), - JsonValue::String("2024-01-15".to_string()) - ); - } - - #[test] - fn test_time() { - // 14:30:00 = 52200000000 microseconds - let micros: i64 = 14 * 3_600_000_000 + 30 * 60_000_000; - let buf = micros.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::TIME, &buf), - JsonValue::String("14:30:00".to_string()) - ); - } - - #[test] - fn test_json() { - let json_bytes = br#"{"key":"value","num":42}"#; - let result = extract_or_null(&Type::JSON, json_bytes); - assert_eq!(result["key"], "value"); - assert_eq!(result["num"], 42); - } - - #[test] - fn test_jsonb() { - // JSONB format: 1 byte version (1) + JSON bytes - let mut buf = vec![1u8]; // version 1 - buf.extend_from_slice(br#"{"a":true}"#); - let result = extract_or_null(&Type::JSONB, &buf); - assert_eq!(result["a"], true); - } - - #[test] - fn test_bytea() { - let buf = b"\x00\x01\x02\x03"; - let result = extract_or_null(&Type::BYTEA, buf); - match result { - JsonValue::String(s) => { - assert!(s.starts_with("BLOB:4:application/octet-stream:")); - } - _ => panic!("expected string for BYTEA"), - } - } - - #[test] - fn test_inet_ipv4() { - // postgres INET binary for IPv4: - // 1byte: family(2) = ipv4, - // 1byte: net mask, - // 1byte: is_cidr(0), - // 1byte: addr_len, must be 4 - // 4bytes: addr bytes - let buf = [2u8, 32, 0, 4, 192, 168, 1, 1]; - assert_eq!( - extract_or_null(&Type::INET, &buf), - JsonValue::String("192.168.1.1/32".to_string()) - ); - } - - #[test] - fn test_inet_ipv6() { - // postgres INET binary for IPv6: - // 1byte: family(3) = ipv6, - // 1byte: net mask, - // 1byte: is_cidr(0), - // 1byte: addr_len, must be 16 - // 16bytes: addr bytes - let mut buf = vec![3u8, 128, 0, 16]; - buf.extend_from_slice(&[0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); - assert_eq!( - extract_or_null(&Type::INET, &buf), - JsonValue::String("2001:db8::1/128".to_string()) - ); - } - - #[test] - fn test_cidr_ipv4() { - // postgres CIDR binary for IPv4 with /24 netmask - let buf = [2u8, 24, 1, 4, 10, 0, 0, 0]; - assert_eq!( - extract_or_null(&Type::CIDR, &buf), - JsonValue::String("10.0.0.0/24".to_string()) - ); - } - - #[test] - fn test_macaddr() { - // MACADDR is 6 bytes - let buf = [0x08u8, 0x00, 0x2b, 0x01, 0x02, 0x03]; - assert_eq!( - extract_or_null(&Type::MACADDR, &buf), - JsonValue::String("08:00:2b:01:02:03".to_string()) - ); - } - - #[test] - fn test_macaddr8() { - // MACADDR8 is 8 bytes - let buf = [0x08u8, 0x00, 0x2b, 0x01, 0x02, 0x03, 0x04, 0x05]; - assert_eq!( - extract_or_null(&Type::MACADDR8, &buf), - JsonValue::String("08:00:2b:01:02:03:04:05".to_string()) - ); - } - - #[test] - fn test_bit_varbit() { - // BIT/VARBIT: 4 bytes for bit count + bit bytes - // 8 bits = 1 byte, value 0b10101010 - let mut buf = Vec::new(); - buf.extend_from_slice(&8i32.to_be_bytes()); // 8 bits - buf.push(0b10101010); - assert_eq!( - extract_or_null(&Type::BIT, &buf), - JsonValue::String("10101010".to_string()) - ); - } - - #[test] - fn test_varbit_partial_byte() { - // VARBIT with 13 bits = 2 bytes - let mut buf = Vec::new(); - buf.extend_from_slice(&13i32.to_be_bytes()); // 13 bits - buf.push(0b11110000); // first 8 bits - buf.push(0b10100000); // remaining 5 bits (13-8=5) - assert_eq!( - extract_or_null(&Type::VARBIT, &buf), - JsonValue::String("1111000010100".to_string()) - ); - } - - #[test] - fn test_xid() { - let buf = 12345u32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::XID, &buf), - JsonValue::Number(12345.into()) - ); - } - - #[test] - fn test_cid() { - let buf = 67890u32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::CID, &buf), - JsonValue::Number(67890.into()) - ); - } - - #[test] - fn test_tid() { - // TID: 4 bytes block_num + 2 bytes offset - let buf = [0x00, 0x01, 0x00, 0x00, 0x00, 0x05]; // block=65536, offset=5 - assert_eq!( - extract_or_null(&Type::TID, &buf), - JsonValue::String("(65536, 5)".to_string()) - ); - } - - #[test] - fn test_xid8() { - let buf = 9876543210i64.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::XID8, &buf), - JsonValue::Number(9876543210i64.into()) - ); - } - - #[test] - fn test_xid8_above_js_safe_becomes_string() { - // Large u64 transaction id beyond JS_MAX_SAFE_INTEGER. - let large: u64 = u64::MAX; - let buf = (large as i64).to_be_bytes(); - assert_eq!( - extract_or_null(&Type::XID8, &buf), - JsonValue::String(large.to_string()) - ); - } - - #[test] - fn test_regclass() { - let buf = 12345u32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::REGCLASS, &buf), - JsonValue::Number(12345.into()) - ); - } - - #[test] - fn test_regtype() { - let buf = 23u32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::REGTYPE, &buf), - JsonValue::Number(23.into()) - ); - } - - #[test] - fn test_point() { - // Point: 16 bytes (2 x f64) - let mut buf = Vec::new(); - buf.extend_from_slice(&1.5f64.to_be_bytes()); - buf.extend_from_slice(&(-2.5f64).to_be_bytes()); - assert_eq!( - extract_or_null(&Type::POINT, &buf), - JsonValue::String("(1.5, -2.5)".to_string()) - ); - } - - #[test] - fn test_lseg() { - // Lseg: 32 bytes (2 x Point) - let mut buf = Vec::new(); - buf.extend_from_slice(&0.0f64.to_be_bytes()); - buf.extend_from_slice(&0.0f64.to_be_bytes()); - buf.extend_from_slice(&3.0f64.to_be_bytes()); - buf.extend_from_slice(&4.0f64.to_be_bytes()); - assert_eq!( - extract_or_null(&Type::LSEG, &buf), - JsonValue::String("[(0, 0), (3, 4)]".to_string()) - ); - } - - #[test] - fn test_box() { - // Box: 32 bytes (2 x Point: upper_right, lower_left) - let mut buf = Vec::new(); - buf.extend_from_slice(&5.0f64.to_be_bytes()); - buf.extend_from_slice(&5.0f64.to_be_bytes()); - buf.extend_from_slice(&1.0f64.to_be_bytes()); - buf.extend_from_slice(&1.0f64.to_be_bytes()); - assert_eq!( - extract_or_null(&Type::BOX, &buf), - JsonValue::String("((5, 5), (1, 1))".to_string()) - ); - } - - #[test] - fn test_line() { - // Line: 24 bytes (3 x f64: a, b, c) - let mut buf = Vec::new(); - buf.extend_from_slice(&1.0f64.to_be_bytes()); - buf.extend_from_slice(&2.0f64.to_be_bytes()); - buf.extend_from_slice(&3.0f64.to_be_bytes()); - assert_eq!( - extract_or_null(&Type::LINE, &buf), - JsonValue::String("{1, 2, 3}".to_string()) - ); - } - - #[test] - fn test_circle() { - // Circle: 24 bytes (Point + radius) - let mut buf = Vec::new(); - buf.extend_from_slice(&0.0f64.to_be_bytes()); - buf.extend_from_slice(&0.0f64.to_be_bytes()); - buf.extend_from_slice(&5.0f64.to_be_bytes()); - assert_eq!( - extract_or_null(&Type::CIRCLE, &buf), - JsonValue::String("<(0, 0), 5>".to_string()) - ); - } - - #[test] - fn test_polygon() { - // Polygon: 4 bytes num_points + points - let mut buf = Vec::new(); - buf.extend_from_slice(&2i32.to_be_bytes()); // 2 points - buf.extend_from_slice(&0.0f64.to_be_bytes()); - buf.extend_from_slice(&0.0f64.to_be_bytes()); - buf.extend_from_slice(&1.0f64.to_be_bytes()); - buf.extend_from_slice(&1.0f64.to_be_bytes()); - assert_eq!( - extract_or_null(&Type::POLYGON, &buf), - JsonValue::String("((0, 0), (1, 1))".to_string()) - ); - } - - #[test] - fn test_path_closed() { - // Path: 1 byte flag + 4 bytes num_points + points - // flag=0 means closed path - let mut buf = Vec::new(); - buf.push(0u8); // closed - buf.extend_from_slice(&2i32.to_be_bytes()); // 2 points - buf.extend_from_slice(&0.0f64.to_be_bytes()); - buf.extend_from_slice(&0.0f64.to_be_bytes()); - buf.extend_from_slice(&1.0f64.to_be_bytes()); - buf.extend_from_slice(&1.0f64.to_be_bytes()); - assert_eq!( - extract_or_null(&Type::PATH, &buf), - JsonValue::String("[(0, 0), (1, 1)]".to_string()) - ); - } - - #[test] - fn test_path_open() { - // Path: 1 byte flag + 4 bytes num_points + points - // flag=1 means open path - let mut buf = Vec::new(); - buf.push(1u8); // open - buf.extend_from_slice(&2i32.to_be_bytes()); // 2 points - buf.extend_from_slice(&0.0f64.to_be_bytes()); - buf.extend_from_slice(&0.0f64.to_be_bytes()); - buf.extend_from_slice(&1.0f64.to_be_bytes()); - buf.extend_from_slice(&1.0f64.to_be_bytes()); - assert_eq!( - extract_or_null(&Type::PATH, &buf), - JsonValue::String("((0, 0), (1, 1))".to_string()) - ); - } - - #[test] - fn test_money() { - let buf = 12345i64.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::MONEY, &buf), - JsonValue::Number(12345.into()) - ); - } - - #[test] - fn test_money_above_js_safe_becomes_string() { - // Money is stored as an i64 of fractional units — a real value, but a - // valid postgres value still has to round-trip without precision loss. - let buf = 9_007_199_254_740_993i64.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::MONEY, &buf), - JsonValue::String("9007199254740993".to_string()) - ); - } - - #[test] - fn test_xml() { - let buf = b"test"; - assert_eq!( - extract_or_null(&Type::XML, buf), - JsonValue::String("test".to_string()) - ); - } - - #[test] - fn test_refcursor() { - let buf = b"my_cursor"; - assert_eq!( - extract_or_null(&Type::REFCURSOR, buf), - JsonValue::String("my_cursor".to_string()) - ); - } - - #[test] - fn test_pg_lsn() { - // PgLsn: 8 bytes (upper u32 + lower u32) - let buf = [0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2A]; - assert_eq!( - extract_or_null(&Type::PG_LSN, &buf), - JsonValue::String("1/2A".to_string()) - ); - } - - #[test] - fn test_txid_snapshot() { - // TxidSnapshot: 4 bytes count + 8 bytes xmin + 8 bytes xmax + count*8 bytes active_xids - let mut buf = Vec::new(); - buf.extend_from_slice(&0i32.to_be_bytes()); // 0 active xids - buf.extend_from_slice(&100i64.to_be_bytes()); // xmin - buf.extend_from_slice(&200i64.to_be_bytes()); // xmax - assert_eq!( - extract_or_null(&Type::TXID_SNAPSHOT, &buf), - JsonValue::String("100:200:".to_string()) - ); - } - - #[test] - fn test_pg_snapshot_with_active_xids() { - let mut buf = Vec::new(); - buf.extend_from_slice(&2i32.to_be_bytes()); // 2 active xids - buf.extend_from_slice(&100i64.to_be_bytes()); // xmin - buf.extend_from_slice(&200i64.to_be_bytes()); // xmax - buf.extend_from_slice(&150i64.to_be_bytes()); // active xid 1 - buf.extend_from_slice(&175i64.to_be_bytes()); // active xid 2 - assert_eq!( - extract_or_null(&Type::PG_SNAPSHOT, &buf), - JsonValue::String("100:200:150,175".to_string()) - ); - } - - #[test] - fn test_aclitem() { - let buf = b"postgres=arwdDxt/postgres"; - assert_eq!( - extract_or_null(&Type::ACLITEM, buf), - JsonValue::String("postgres=arwdDxt/postgres".to_string()) - ); - } - - #[test] - fn test_pg_node_tree() { - let buf = b"12345 12346 12347"; - assert_eq!( - extract_or_null(&Type::PG_NODE_TREE, buf), - JsonValue::String("12345 12346 12347".to_string()) - ); - } - - #[test] - fn test_int2_zero() { - let buf = 0i16.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::INT2, &buf), - JsonValue::Number(0.into()) - ); - } - - #[test] - fn test_char_positive() { - let buf = 65i8.to_be_bytes(); // 'A' - assert_eq!( - extract_or_null(&Type::CHAR, &buf), - JsonValue::Number(65.into()) - ); - } - - #[test] - fn test_unsupported_type_returns_null() { - let buf = [0u8; 8]; - assert_eq!(extract_or_null(&Type::TIMETZ, &buf), JsonValue::Null); - } - - #[test] - fn test_empty_buffer_returns_null() { - let buf = []; - let result = extract_or_null(&Type::INT4, &buf); - assert_eq!(result, JsonValue::Null); - } - - #[test] - fn test_truncated_buffer_returns_null() { - // INT4 needs 4 bytes, give only 2 - let buf = [0u8; 2]; - assert_eq!(extract_or_null(&Type::INT4, &buf), JsonValue::Null); - } - - #[test] - fn test_timestamp() { - // 2024-01-15 10:30:00 = 8781 days + 10h30m since 2000-01-01 00:00:00 - let days: i64 = 8780; - let micros: i64 = days * 86_400_000_000 + 10 * 3_600_000_000 + 30 * 60_000_000; - let buf = micros.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::TIMESTAMP, &buf), - JsonValue::String("2024-01-15 10:30:00".to_string()) - ); - } - - #[test] - fn test_timestamptz() { - // Same value for TIMESTAMPTZ — postgres stores as UTC microseconds since 2000-01-01 - let days: i64 = 8780; - let micros: i64 = days * 86_400_000_000 + 10 * 3_600_000_000 + 30 * 60_000_000; - let buf = micros.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::TIMESTAMPTZ, &buf), - JsonValue::String("2024-01-15 10:30:00".to_string()) - ); - } - - #[test] - fn test_float4_negative() { - let buf = (-0.5f32).to_be_bytes(); - let result = extract_or_null(&Type::FLOAT4, &buf); - match result { - JsonValue::Number(n) => { - let val = n.as_f64().unwrap(); - assert!((val - (-0.5)).abs() < 0.001); - } - _ => panic!("expected number"), - } - } - - #[test] - fn test_float8_negative() { - let buf = (-999.999f64).to_be_bytes(); - let result = extract_or_null(&Type::FLOAT8, &buf); - match result { - JsonValue::Number(n) => { - let val = n.as_f64().unwrap(); - assert!((val - (-999.999)).abs() < 1e-6); - } - _ => panic!("expected number"), - } - } - - #[test] - fn test_numeric_zero() { - // postgres numeric for 0: ndigits=0, weight=0, sign=0x0000 (positive), dscale=0 - let buf: [u8; 8] = [ - 0x00, 0x00, // ndigits = 0 - 0x00, 0x00, // weight = 0 - 0x00, 0x00, // sign = NUMERIC_POS (0) - 0x00, 0x00, // dscale = 0 - // no digit groups - ]; - assert_eq!( - extract_or_null(&Type::NUMERIC, &buf), - JsonValue::String("0".to_string()) - ); - } - - #[test] - fn test_numeric_integer() { - // postgres numeric for 12345: - // ndigits=2, weight=1, sign=0x0000, dscale=0 - // digit groups: 1, 2345 (each is a base-10000 digit) - let buf: [u8; 12] = [ - 0x00, 0x02, // ndigits = 2 - 0x00, 0x01, // weight = 1 - 0x00, 0x00, // sign = NUMERIC_POS - 0x00, 0x00, // dscale = 0 - 0x00, 0x01, // digit 1 - 0x09, 0x29, // digit 2345 (0x0929) - ]; - assert_eq!( - extract_or_null(&Type::NUMERIC, &buf), - JsonValue::String("12345".to_string()) - ); - } - - #[test] - fn test_regproc() { - let buf = 12345u32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::REGPROC, &buf), - JsonValue::Number(12345.into()) - ); - } - - #[test] - fn test_regprocedure() { - let buf = 67890u32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::REGPROCEDURE, &buf), - JsonValue::Number(67890.into()) - ); - } - - #[test] - fn test_regoper() { - let buf = 11111u32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::REGOPER, &buf), - JsonValue::Number(11111.into()) - ); - } - - #[test] - fn test_regoperator() { - let buf = 22222u32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::REGOPERATOR, &buf), - JsonValue::Number(22222.into()) - ); - } - - #[test] - fn test_regconfig() { - let buf = 3748u32.to_be_bytes(); // default OID for 'english' - assert_eq!( - extract_or_null(&Type::REGCONFIG, &buf), - JsonValue::Number(3748.into()) - ); - } - - #[test] - fn test_regdictionary() { - let buf = 3380u32.to_be_bytes(); // default OID for 'simple' - assert_eq!( - extract_or_null(&Type::REGDICTIONARY, &buf), - JsonValue::Number(3380.into()) - ); - } - - #[test] - fn test_regnamespace() { - let buf = 11u32.to_be_bytes(); // default OID for 'pg_catalog' - assert_eq!( - extract_or_null(&Type::REGNAMESPACE, &buf), - JsonValue::Number(11.into()) - ); - } - - #[test] - fn test_regrole() { - let buf = 10u32.to_be_bytes(); // default OID for 'pg_role' - assert_eq!( - extract_or_null(&Type::REGROLE, &buf), - JsonValue::Number(10.into()) - ); - } - - #[test] - fn test_regcollation() { - let buf = 100u32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::REGCOLLATION, &buf), - JsonValue::Number(100.into()) - ); - } - - #[test] - fn test_timetz() { - // TIMETZ: 8 bytes microseconds + 4 bytes timezone offset (seconds) - // 14:30:05.37 = 52205370000 microseconds - let mut buf = Vec::new(); - buf.extend_from_slice(&52205370000i64.to_be_bytes()); - buf.extend_from_slice(&(-18347i32).to_be_bytes()); // +5:05:47 (EST) - assert_eq!( - extract_or_null(&Type::TIMETZ, &buf), - JsonValue::String("14:30:05.37+05:05:47".to_string()) - ); - } - - #[test] - fn test_interval() { - // INTERVAL: 8 bytes microseconds + 4 bytes days + 4 bytes months - // 1 year 2 months 3 days 04:05:06.007 - let mut buf = Vec::new(); - // microseconds: 4*3600*1000000 + 5*60*1000000 + 6*1000000 + 7000 = 14706007000 - buf.extend_from_slice(&14706007000i64.to_be_bytes()); - buf.extend_from_slice(&3i32.to_be_bytes()); // 3 days - buf.extend_from_slice(&14i32.to_be_bytes()); // 14 months (1 year + 2 months) - assert_eq!( - extract_or_null(&Type::INTERVAL, &buf), - JsonValue::String("1 year 2 months 3 days 04:05:06.7".to_string()) - ); - } - - fn pgvector_type(name: &str, oid: u32) -> Type { - Type::new(name.to_string(), oid, Kind::Simple, "public".to_string()) - } - - #[test] - fn test_pgvector_vector() { - // vector [1, 2, 3.5]: int16 dim, int16 unused, then dim x float4 (big-endian) - let mut buf = Vec::new(); - buf.extend_from_slice(&3u16.to_be_bytes()); // dim - buf.extend_from_slice(&0u16.to_be_bytes()); // unused - buf.extend_from_slice(&1.0f32.to_be_bytes()); - buf.extend_from_slice(&2.0f32.to_be_bytes()); - buf.extend_from_slice(&3.5f32.to_be_bytes()); - assert_eq!( - extract_or_null(&pgvector_type("vector", 20000), &buf), - JsonValue::String("[1,2,3.5]".to_string()) - ); - } - - #[test] - fn test_pgvector_vector_empty() { - let mut buf = Vec::new(); - buf.extend_from_slice(&0u16.to_be_bytes()); // dim - buf.extend_from_slice(&0u16.to_be_bytes()); // unused - assert_eq!( - extract_or_null(&pgvector_type("vector", 20000), &buf), - JsonValue::String("[]".to_string()) - ); - } - - #[test] - fn test_pgvector_halfvec() { - // halfvec [1, 2]: int16 dim, int16 unused, then dim x float2 (half-precision) - // 1.0 = 0x3C00, 2.0 = 0x4000 - let mut buf = Vec::new(); - buf.extend_from_slice(&2u16.to_be_bytes()); // dim - buf.extend_from_slice(&0u16.to_be_bytes()); // unused - buf.extend_from_slice(&0x3C00u16.to_be_bytes()); // 1.0 - buf.extend_from_slice(&0x4000u16.to_be_bytes()); // 2.0 - assert_eq!( - extract_or_null(&pgvector_type("halfvec", 20001), &buf), - JsonValue::String("[1,2]".to_string()) - ); - } - - #[test] - fn test_pgvector_sparsevec() { - // sparsevec {1:1.5,3:2}/5: int32 dim, int32 nnz, int32 unused, - // then nnz x int32 indices (0-based), then nnz x float4 values. - let mut buf = Vec::new(); - buf.extend_from_slice(&5i32.to_be_bytes()); // dim - buf.extend_from_slice(&2i32.to_be_bytes()); // nnz - buf.extend_from_slice(&0i32.to_be_bytes()); // unused - buf.extend_from_slice(&0i32.to_be_bytes()); // index 0 (-> printed as 1) - buf.extend_from_slice(&2i32.to_be_bytes()); // index 2 (-> printed as 3) - buf.extend_from_slice(&1.5f32.to_be_bytes()); - buf.extend_from_slice(&2.0f32.to_be_bytes()); - assert_eq!( - extract_or_null(&pgvector_type("sparsevec", 20002), &buf), - JsonValue::String("{1:1.5,3:2}/5".to_string()) - ); - } - - #[test] - fn test_citext() { - let buf = b"CaseInsensitiveText"; - // Create a custom Type for citext - let citext_type = Type::new( - "citext".to_string(), - 10000, - Kind::Simple, - "public".to_string(), - ); - assert_eq!( - extract_or_null(&citext_type, buf), - JsonValue::String("CaseInsensitiveText".to_string()) - ); - } - - #[test] - fn test_ltree() { - let buf = b"\x01Top.Science.Astronomy"; - let ltree_type = Type::new( - "ltree".to_string(), - 10001, - Kind::Simple, - "public".to_string(), - ); - assert_eq!( - extract_or_null(<ree_type, buf), - JsonValue::String("Top.Science.Astronomy".to_string()) - ); - } - - #[test] - fn test_lquery() { - let buf = b"\x01Top.*{1,2}"; - let lquery_type = Type::new( - "lquery".to_string(), - 10002, - Kind::Simple, - "public".to_string(), - ); - assert_eq!( - extract_or_null(&lquery_type, buf), - JsonValue::String("Top.*{1,2}".to_string()) - ); - } - - #[test] - fn test_ltxtquery() { - let buf = b"\x01Top & Science"; - let ltxtquery_type = Type::new( - "ltxtquery".to_string(), - 10003, - Kind::Simple, - "public".to_string(), - ); - assert_eq!( - extract_or_null(<xtquery_type, buf), - JsonValue::String("Top & Science".to_string()) - ); - } - - #[test] - fn test_tsvector() { - // TsVector: 4 bytes count + lexemes - // Each lexeme: null-terminated text + 2 bytes position count + positions - let mut buf = Vec::new(); - buf.extend_from_slice(&1i32.to_be_bytes()); // 1 lexeme - buf.extend_from_slice(b"hello\0"); // lexeme text - buf.extend_from_slice(&1i16.to_be_bytes()); // 1 position - buf.extend_from_slice(&1u16.to_be_bytes()); // position 1, weight D (0) - assert_eq!( - extract_or_null(&Type::TS_VECTOR, &buf), - JsonValue::String("'hello':1".to_string()) - ); - } - - #[test] - fn test_tsvector_empty() { - let buf = 0i32.to_be_bytes(); - assert_eq!( - extract_or_null(&Type::TS_VECTOR, &buf), - JsonValue::String("".to_string()) - ); - } - - #[test] - fn test_tsvector_with_weights() { - let mut buf = Vec::new(); - buf.extend_from_slice(&1i32.to_be_bytes()); // 1 lexeme - buf.extend_from_slice(b"world\0"); // lexeme text - buf.extend_from_slice(&2i16.to_be_bytes()); // 2 positions - // position 5, weight A (3 << 14 = 0xC000 | 5 = 0xC005) - buf.extend_from_slice(&0xC005u16.to_be_bytes()); - // position 10, weight B (2 << 14 = 0x8000 | 10 = 0x800A) - buf.extend_from_slice(&0x800Au16.to_be_bytes()); - assert_eq!( - extract_or_null(&Type::TS_VECTOR, &buf), - JsonValue::String("'world':5A,10B".to_string()) - ); - } - - #[test] - fn test_tsquery() { - // TsQuery binary: type byte + data - // length, type=1 (operand): weight(0) + prefixed(1) + null-terminated text - let buf = [0u8, 0, 0, 1, 1, 0, 0, b'f', b'o', b'o', 0]; // operand 'foo', weight D, not prefixed - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'foo'".to_string()) - ); - } - - #[test] - fn test_tsquery_and() { - // AND query: type=2, operator=2 (&), then two operands - let buf = [ - 0u8, 0, 0, 3, // length prefix - 2u8, 2, // type=2, operator=AND - 1u8, 0, 0, b'f', b'o', b'o', 0, // operand 'foo' - 1u8, 0, 0, b'b', b'a', b'r', 0, // operand 'bar' - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'bar' & 'foo'".to_string()) - ); - } - - #[test] - fn test_tsquery_simple_operand() { - // Simple operand: 'hello' (weight D, not prefixed) - let buf = [ - 0u8, 0, 0, 1, // length prefix - 1u8, 0, 0, b'h', b'e', b'l', b'l', b'o', 0, - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'hello'".to_string()) - ); - } - - #[test] - fn test_tsquery_all_weights() { - // Weight A - let buf_a = [ - 0u8, 0, 0, 1, // length prefix - 1u8, 8, 0, b'a', 0, - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf_a), - JsonValue::String("'a':A".to_string()) - ); - - // Weight B - let buf_b = [ - 0u8, 0, 0, 1, // length prefix - 1u8, 4, 0, b'b', 0, - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf_b), - JsonValue::String("'b':B".to_string()) - ); - - // Weight C - let buf_c = [ - 0u8, 0, 0, 1, // length prefix - 1u8, 2, 0, b'c', 0, - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf_c), - JsonValue::String("'c':C".to_string()) - ); - - // Weight D - let buf_d = [ - 0u8, 0, 0, 1, // length prefix - 1u8, 1, 0, b'd', 0, - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf_d), - JsonValue::String("'d':D".to_string()) - ); - - // no Weight (default) - let buf_d = [ - 0u8, 0, 0, 1, // length prefix - 1u8, 0, 0, b'd', 0, - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf_d), - JsonValue::String("'d'".to_string()) - ); - } - - #[test] - fn test_tsquery_prefixed() { - // 'foo':* (weight D, prefixed) - let buf = [ - 0u8, 0, 0, 1, // length prefix - 1u8, 0, 1, b'f', b'o', b'o', 0, - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'foo':*".to_string()) - ); - } - - #[test] - fn test_tsquery_prefixed_with_weight() { - // 'bar':*A (weight A, prefixed) — code outputs weight after :* - let buf = [ - 0u8, 0, 0, 1, // length prefix - 1u8, 8, 1, b'b', b'a', b'r', 0, - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'bar':*A".to_string()) - ); - } - - #[test] - fn test_tsquery_not() { - // !'foo':* - // Tree: - // NOT(1) - // | - // 'foo':* - let buf = [ - 0u8, 0, 0, 2, // length prefix - 2, 1, // NOT operator - 1, 0, 1, b'f', b'o', b'o', 0, // operand: weight D, prefixed, "foo" - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("!'foo':*".to_string()) - ); - } - - #[test] - fn test_tsquery_or() { - // 'cat' | 'dog' - let buf = [ - 0u8, 0, 0, 3, // length prefix - 2, 3, // OR operator - 1, 0, 0, b'd', b'o', b'g', 0, // right: 'dog' - 1, 0, 0, b'c', b'a', b't', 0, // left: 'cat' - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'cat' | 'dog'".to_string()) - ); - } - - #[test] - fn test_tsquery_phrase_default_distance() { - // 'hello' <-> 'world' (distance=1) - let buf = [ - 0u8, 0, 0, 3, // length prefix - 2, 4, 0x00, 0x01, // PHRASE operator, distance=1 - 1, 0, 0, b'w', b'o', b'r', b'l', b'd', 0, // right: 'world' - 1, 0, 0, b'h', b'e', b'l', b'l', b'o', 0, // left: 'hello' - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'hello' <-> 'world'".to_string()) - ); - } - - #[test] - fn test_tsquery_phrase_custom_distance() { - // 'hello' <5> 'world' - let buf = [ - 0u8, 0, 0, 3, // length prefix - 2, 4, 0x00, 0x05, // PHRASE operator, distance=5 - 1, 0, 0, b'w', b'o', b'r', b'l', b'd', 0, // right: 'world' - 1, 0, 0, b'h', b'e', b'l', b'l', b'o', 0, // left: 'hello' - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'hello' <5> 'world'".to_string()) - ); - } - - #[test] - fn test_tsquery_and_or_nesting() { - // 'fat':A & 'rat':B | ('cat':C <-> 'mat':A) - // Tree: - // OR(3) - // / \ - // AND(2) PHRASE(4,d=1) - // / \ / \ - // 'fat':A 'rat':B 'cat':C 'mat':A - let buf = [ - 0u8, 0, 0, 7, // length prefix - 2, 3, // OR - 2, 4, 0x00, 0x01, // PHRASE d=1 - 1, 8, 0, b'm', b'a', b't', 0, // right: 'mat':A - 1, 2, 0, b'c', b'a', b't', 0, // left: 'cat':C - 2, 2, // AND - 1, 4, 0, b'r', b'a', b't', 0, // right: 'rat':B - 1, 8, 0, b'f', b'a', b't', 0, // left: 'fat':A - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'fat':A & 'rat':B | 'cat':C <-> 'mat':A".to_string()) - ); - } - - #[test] - fn test_tsquery_deeply_nested() { - // 'a':A & 'b':B & ('c':C | ('d':A <-> 'e':B)) - // Tree: - // AND(2) - // / \ - // AND(2) OR(3) - // / \ / \ - // 'a':A 'b':B 'c':C PHRASE(4,d=1) - // / \ - // 'd':A 'e':B - let buf = [ - 0u8, 0, 0, 9, // length prefix - 2, 2, // top AND - 2, 3, // right: OR - 2, 4, 0x00, 0x01, // right of OR: PHRASE d=1 - 1, 4, 0, b'e', 0, // right: 'e':B - 1, 8, 0, b'd', 0, // left: 'd':A - 1, 2, 0, b'c', 0, // left of OR: 'c':C - 2, 2, // left: AND - 1, 4, 0, b'b', 0, // right: 'b':B - 1, 8, 0, b'a', 0, // left: 'a':A - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'a':A & 'b':B & ('c':C | 'd':A <-> 'e':B)".to_string()) - ); - } - - #[test] - fn test_tsquery_not_with_or() { - // !'foo' | 'bar' - // Tree: - // OR(3) - // / \ - // 'bar' NOT(1) - // | - // 'foo' - let buf = [ - 0u8, 0, 0, 4, // length prefix - 2, 3, // OR - 1, 0, 0, b'b', b'a', b'r', 0, // right: 'bar' - 2, 1, // left: NOT - 1, 0, 0, b'f', b'o', b'o', 0, // operand: 'foo' - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("!'foo' | 'bar'".to_string()) - ); - } - - #[test] - fn test_tsquery_complex_search_query() { - // Represents a realistic full-text search: - // 'quick':A & 'brown':B & ('fox':C | 'dog') & !'cat':* - // Tree: - // AND(2) - // / \ - // AND(2) AND(2) - // / \ / \ - // 'quick':A 'brown':B OR(3) NOT(1) - // / \ | - // 'fox':C 'dog' 'cat':* - let buf = [ - 0u8, 0, 0, 10, // length prefix - 2, 2, // top AND - 2, 2, // right: AND - 2, 3, // right: OR - 1, 0, 0, b'd', b'o', b'g', 0, // right: 'dog' - 1, 2, 0, b'f', b'o', b'x', 0, // left: 'fox':C - 2, 1, // left: NOT - 1, 0, 1, b'c', b'a', b't', 0, // operand: 'cat':* - 2, 2, // left: AND - 1, 4, 0, b'b', b'r', b'o', b'w', b'n', 0, // right: 'brown':B - 1, 8, 0, b'q', b'u', b'i', b'c', b'k', 0, // left: 'quick':A - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'quick':A & 'brown':B & !'cat':* & ('fox':C | 'dog')".to_string()) - ); - } - - #[test] - fn test_tsquery_multiple_phrases() { - // 'the' <-> 'quick' & 'brown' <-> 'fox' - // Tree: - // AND(2) - // / \ - // PHRASE(4) PHRASE(4) - // / \ / \ - // 'the' 'quick' 'brown' 'fox' - - let buf = [ - 0, 0, 0, 7, // length prefix - 2, 2, // AND - 2, 4, 0x00, 0x01, // right: PHRASE - 1, 0, 0, b'f', b'o', b'x', 0, // right: 'fox' - 1, 0, 0, b'b', b'r', b'o', b'w', b'n', 0, // left: 'brown' - 2, 4, 0x00, 0x01, // left: PHRASE - 1, 0, 0, b'q', b'u', b'i', b'c', b'k', 0, // right: 'quick' - 1, 0, 0, b't', b'h', b'e', 0, // left: 'the' - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'the' <-> 'quick' & 'brown' <-> 'fox'".to_string()) - ); - } - - #[test] - fn test_tsquery_not_not() { - // !!'foo' (double negation) - let buf = [ - 0u8, 0, 0, 3, // length prefix - 2, 1, // outer NOT - 2, 1, // inner NOT - 1, 0, 0, b'f', b'o', b'o', 0, // operand: 'foo' - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("!!'foo'".to_string()) - ); - } - - #[test] - fn test_tsquery_large_phrase_distance() { - // 'start' <100> 'end' - let buf = [ - 0u8, 0, 0, 3, // length prefix - 2, 4, 0x00, 0x64, // PHRASE distance=100 (0x64) - 1, 0, 0, b'e', b'n', b'd', 0, // right: 'end' - 1, 0, 0, b's', b't', b'a', b'r', b't', 0, // left: 'start' - ]; - assert_eq!( - extract_or_null(&Type::TSQUERY, &buf), - JsonValue::String("'start' <100> 'end'".to_string()) - ); - } - - #[test] - fn test_gts_vector() { - // GtsVector: 4 bytes header + 1 byte signature - let buf = [0x01, 0x02, 0x03, 0x04, 0xAB]; - let result = extract_or_null(&Type::GTS_VECTOR, &buf); - match result { - JsonValue::String(s) => { - assert!(s.starts_with("BLOB:5:")); - } - _ => panic!("expected blob string for GTS_VECTOR"), - } - } - - #[test] - fn test_pg_ndistinct() { - let buf = [0xDE, 0xAD, 0xBE, 0xEF]; - let result = extract_or_null(&Type::PG_NDISTINCT, &buf); - match result { - JsonValue::String(s) => { - assert!(s.starts_with("BLOB:4:")); - } - _ => panic!("expected blob string for PG_NDISTINCT"), - } - } - - #[test] - fn test_pg_dependencies() { - let buf = [0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x01]; - let result = extract_or_null(&Type::PG_DEPENDENCIES, &buf); - match result { - JsonValue::String(s) => { - assert!(s.starts_with("BLOB:6:")); - } - _ => panic!("expected blob string for PG_DEPENDENCIES"), - } - } - - #[test] - fn test_pg_brin_bloom_summary() { - let buf = [0x01, 0x02, 0x03]; - let result = extract_or_null(&Type::PG_BRIN_BLOOM_SUMMARY, &buf); - match result { - JsonValue::String(s) => { - assert!(s.starts_with("BLOB:3:")); - } - _ => panic!("expected blob string for PG_BRIN_BLOOM_SUMMARY"), - } - } - - #[test] - fn test_pg_brin_minmax_multi_summary() { - let buf = [0xAA, 0xBB]; - let result = extract_or_null(&Type::PG_BRIN_MINMAX_MULTI_SUMMARY, &buf); - match result { - JsonValue::String(s) => { - assert!(s.starts_with("BLOB:2:")); - } - _ => panic!("expected blob string for PG_BRIN_MINMAX_MULTI_SUMMARY"), - } - } - - #[test] - fn test_pg_mcv_list() { - let buf = [0x01, 0x02, 0x03, 0x04, 0x05]; - let result = extract_or_null(&Type::PG_MCV_LIST, &buf); - match result { - JsonValue::String(s) => { - assert!(s.starts_with("BLOB:5:")); - } - _ => panic!("expected blob string for PG_MCV_LIST"), - } - } - - #[test] - fn test_jsonpath() { - // JSONPATH: 1 byte version + path string - let mut buf = vec![1u8]; // version 1 - buf.extend_from_slice(b"$.store.book[*].author"); - assert_eq!( - extract_or_null(&Type::JSONPATH, &buf), - JsonValue::String("$.store.book[*].author".to_string()) - ); - } - - #[test] - fn test_hstore() { - // HSTORE uses HashMap> via tokio_postgres - // Binary format is complex; this test verifies the type mapping exists - // In practice, hstore binary parsing is handled by tokio_postgres - let hstore_type = Type::new( - "hstore".to_string(), - 10004, - Kind::Simple, - "public".to_string(), - ); - // Empty hstore would be handled by tokio_postgres internally - // We just verify the type match works - let result = extract_or_null(&hstore_type, &[]); - // Empty buffer should fail gracefully - assert_eq!(result, JsonValue::Null); - } -} diff --git a/src-tauri/src/drivers/postgres/extract/simple_tests.rs b/src-tauri/src/drivers/postgres/extract/simple_tests.rs deleted file mode 100644 index 16fb92c51..000000000 --- a/src-tauri/src/drivers/postgres/extract/simple_tests.rs +++ /dev/null @@ -1,97 +0,0 @@ -use super::extract_or_null; -use serde_json::Value; -use tokio_postgres::types::Type; - -#[test] -fn float4_preserves_short_decimal_values() { - for (value, expected) in [ - (89.9f32, 89.9f64), - (59.99, 59.99), - (29.5, 29.5), - (-89.9, -89.9), - (0.1, 0.1), - (1.2345678, 1.2345678), - ] { - let result = extract_or_null(&Type::FLOAT4, &value.to_be_bytes()); - assert_eq!(result, Value::from(expected), "input: {value}"); - } -} - -#[test] -fn float4_extremes_round_trip_without_losing_precision() { - for value in [ - f32::MAX, - f32::MIN, - f32::MIN_POSITIVE, - f32::from_bits(1), - f32::from_bits(0x15ae43fd), - -f32::from_bits(0x15ae43fd), - -0.0, - ] { - let result = extract_or_null(&Type::FLOAT4, &value.to_be_bytes()); - let decoded = result.as_f64().expect("finite float4 is a JSON number") as f32; - assert_eq!(decoded.to_bits(), value.to_bits(), "input: {value}"); - } -} - -#[test] -fn float4_non_finite_and_invalid_values_remain_null() { - for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - assert_eq!( - extract_or_null(&Type::FLOAT4, &value.to_be_bytes()), - Value::Null, - ); - } - assert_eq!(extract_or_null(&Type::FLOAT4, &[0, 0, 0]), Value::Null); -} - -#[test] -fn float8_retains_double_precision() { - let value = 89.9000015258789f64; - assert_eq!( - extract_or_null(&Type::FLOAT8, &value.to_be_bytes()), - Value::from(value), - ); -} - -#[test] -fn float4_arrays_and_composites_preserve_short_decimals_and_nulls() { - use super::super::{array, composite}; - use tokio_postgres::types::Field; - - let mut array_bytes = Vec::new(); - for header in [1i32, 1, Type::FLOAT4.oid() as i32, 3, 1] { - array_bytes.extend_from_slice(&header.to_be_bytes()); - } - for value in [Some(89.9f32), None, Some(59.99)] { - match value { - Some(value) => { - array_bytes.extend_from_slice(&4i32.to_be_bytes()); - array_bytes.extend_from_slice(&value.to_be_bytes()); - } - None => array_bytes.extend_from_slice(&(-1i32).to_be_bytes()), - } - } - assert_eq!( - array::extract_or_null(&Type::FLOAT4, &mut array_bytes.as_slice()), - serde_json::json!([89.9, null, 59.99]), - ); - - let mut composite_bytes = 2i32.to_be_bytes().to_vec(); - for (ty, bytes) in [ - (Type::FLOAT4, 89.9f32.to_be_bytes().to_vec()), - (Type::FLOAT4_ARRAY, array_bytes), - ] { - composite_bytes.extend_from_slice(&ty.oid().to_be_bytes()); - composite_bytes.extend_from_slice(&(bytes.len() as i32).to_be_bytes()); - composite_bytes.extend_from_slice(&bytes); - } - let fields = vec![ - Field::new("price".to_string(), Type::FLOAT4), - Field::new("prices".to_string(), Type::FLOAT4_ARRAY), - ]; - assert_eq!( - composite::extract_or_null(&fields, &mut composite_bytes.as_slice()), - serde_json::json!({"price": 89.9, "prices": [89.9, null, 59.99]}), - ); -} diff --git a/src-tauri/src/drivers/postgres/helpers.rs b/src-tauri/src/drivers/postgres/helpers.rs deleted file mode 100644 index f26d88cd3..000000000 --- a/src-tauri/src/drivers/postgres/helpers.rs +++ /dev/null @@ -1,157 +0,0 @@ -use crate::drivers::common::full_type_if_distinct; - -/// Extract base type name, e.g. "GEOMETRY(Point, 4326)" -> "GEOMETRY", "VARCHAR(255)" -> "VARCHAR" -pub(super) fn extract_base_type(data_type: &str) -> String { - if let Some(idx) = data_type.find('(') { - data_type[..idx].trim().to_uppercase() - } else { - data_type.trim().to_uppercase() - } -} - -/// Check if PostgreSQL can implicitly cast between these base types (no USING clause needed). -pub(super) fn is_implicit_cast_compatible(old_type: &str, new_type: &str) -> bool { - if old_type == new_type { - return true; - } - - let compatible_groups: &[&[&str]] = &[ - &[ - "SMALLINT", - "INTEGER", - "BIGINT", - "SERIAL", - "BIGSERIAL", - "SMALLSERIAL", - ], - &["REAL", "DOUBLE PRECISION", "NUMERIC", "DECIMAL", "MONEY"], - &["CHAR", "VARCHAR", "TEXT", "NAME", "CITEXT"], - &["TIMESTAMP", "TIMESTAMPTZ"], - &["TIME", "TIMETZ"], - &["JSON", "JSONB"], - &["BIT", "VARBIT"], - ]; - - for group in compatible_groups { - if group.contains(&old_type) && group.contains(&new_type) { - return true; - } - } - false -} - -// Helper function to escape double quotes in identifiers for PostgreSQL -pub(super) fn escape_identifier(name: &str) -> String { - name.replace('"', "\"\"") -} - -/// Quote a schema-qualified type name (e.g. `"public"."plan_type"`) so it can be -/// spliced into a `CAST($N AS ...)` without becoming an injection vector. -pub(super) fn quote_qualified_type(type_schema: &str, type_name: &str) -> String { - format!( - "\"{}\".\"{}\"", - escape_identifier(type_schema), - escape_identifier(type_name) - ) -} - -/// `information_schema.columns` reports enum columns only as `USER-DEFINED`. -/// When the allowed labels could be loaded from `pg_enum` (pre-quoted and -/// comma-joined, e.g. `'free','pro'`), surface the full definition in MySQL's -/// `column_type` shape — `enum('free','pro')` — so the UI can offer a dropdown -/// of the allowed values (#465). Falls back to the raw `data_type` otherwise. -pub(super) fn enum_data_type(data_type: String, enum_values: Option) -> String { - match enum_values { - Some(vals) if !vals.is_empty() => format!("enum({})", vals), - _ => data_type, - } -} - -/// Builds the `(data_type, full_type)` reported on a `TableColumn` from the -/// `information_schema` type, the enum labels and `format_type(atttypid, -/// atttypmod)`. -/// -/// `full_type` carries the declared type with its modifiers for display -/// (`character varying(255)`, `numeric(10,2)`, `integer[]`) when it says more -/// than `data_type` (#1277). Enum columns get none: `data_type` already lists -/// their values (`enum('free','pro')`), which says more than the bare type -/// name `format_type` returns. -pub(super) fn postgres_column_types( - data_type: String, - enum_values: Option, - formatted_type: Option, -) -> (String, Option) { - if enum_values.as_deref().is_some_and(|vals| !vals.is_empty()) { - return (enum_data_type(data_type, enum_values), None); - } - let full_type = full_type_if_distinct(&data_type, formatted_type); - (data_type, full_type) -} - -/// Checks if a string value looks like WKT (Well-Known Text) geometry format -pub(super) fn is_wkt_geometry(s: &str) -> bool { - let s_upper = s.trim().to_uppercase(); - s_upper.starts_with("POINT(") - || s_upper.starts_with("LINESTRING(") - || s_upper.starts_with("POLYGON(") - || s_upper.starts_with("MULTIPOINT(") - || s_upper.starts_with("MULTILINESTRING(") - || s_upper.starts_with("MULTIPOLYGON(") - || s_upper.starts_with("GEOMETRYCOLLECTION(") - || s_upper.starts_with("GEOMETRY(") -} - -/// Convert a JSON array to a PostgreSQL ARRAY[...] literal. -/// Elements are safely formatted to prevent SQL injection. -pub(super) fn json_array_to_pg_literal(arr: &[serde_json::Value]) -> Result { - if arr.is_empty() { - return Ok("'{}'".to_string()); - } - let mut parts = Vec::new(); - for val in arr { - match val { - serde_json::Value::Number(n) => parts.push(n.to_string()), - serde_json::Value::String(s) => { - let escaped = s.replace('\'', "''"); - parts.push(format!("'{}'", escaped)); - } - serde_json::Value::Bool(b) => parts.push(if *b { "TRUE" } else { "FALSE" }.to_string()), - serde_json::Value::Null => parts.push("NULL".to_string()), - serde_json::Value::Array(nested) => { - parts.push(json_array_to_pg_literal(nested)?); - } - _ => return Err("Unsupported array element type".to_string()), - } - } - Ok(format!("ARRAY[{}]", parts.join(", "))) -} - -/// Try to parse a string as a JSON array and convert to PostgreSQL array literal. -pub(super) fn try_parse_pg_array(s: &str) -> Option> { - let trimmed = s.trim(); - if trimmed.starts_with('[') && trimmed.ends_with(']') { - if let Ok(serde_json::Value::Array(arr)) = - serde_json::from_str::(trimmed) - { - return Some(json_array_to_pg_literal(&arr)); - } - } - None -} - -/// Checks if a string value is a raw SQL function call (e.g., ST_GeomFromText(...)) -/// This is used to detect when user has entered a complete SQL function that should -/// be inserted directly into the query without parameter binding -pub(super) fn is_raw_sql_function(s: &str) -> bool { - let trimmed = s.trim().to_uppercase(); - // Check for common SQL spatial function patterns - // Functions starting with ST_ followed by parenthesis - if trimmed.starts_with("ST_") { - return trimmed.contains('('); - } - // Legacy function names - trimmed.starts_with("GEOMFROMTEXT(") - || trimmed.starts_with("GEOMFROMWKB(") - || trimmed.starts_with("POINTFROMTEXT(") - || trimmed.starts_with("POINTFROMWKB(") -} diff --git a/src-tauri/src/drivers/postgres/mod.rs b/src-tauri/src/drivers/postgres/mod.rs deleted file mode 100644 index f016bb8db..000000000 --- a/src-tauri/src/drivers/postgres/mod.rs +++ /dev/null @@ -1,3284 +0,0 @@ -pub mod types; - -pub mod export; -pub mod extract; - -mod binding; -mod client; -mod column_comments; -mod explain; -mod helpers; -mod routines; -pub mod session; - -#[cfg(test)] -mod column_ddl_tests; -#[cfg(test)] -mod tests; - -use crate::models::{ - ConnectionParams, ForeignKey, Index, Pagination, QueryResult, RoutineInfo, RoutineParameter, - TableColumn, TableInfo, TriggerInfo, ViewInfo, -}; -use crate::pool_manager::get_postgres_pool; -use binding::{bind_pg_value, build_pk_map_predicate, PgValueOptions}; -use client::{ - execute, execute_typed, format_pg_error, get_client, query_all, query_one, query_one_typed, -}; -pub use explain::explain_query; -use extract::extract_value; -use helpers::{ - escape_identifier, extract_base_type, is_implicit_cast_compatible, postgres_column_types, - quote_qualified_type, -}; -use tokio_postgres::types::{ToSql, Type}; - -fn primary_key_exists_expression() -> &'static str { - r#" - EXISTS ( - SELECT 1 - FROM pg_constraint pk_con - JOIN pg_class pk_table ON pk_table.oid = pk_con.conrelid - JOIN pg_namespace pk_schema ON pk_schema.oid = pk_table.relnamespace - JOIN unnest(pk_con.conkey) AS pk_col(attnum) ON true - JOIN pg_attribute pk_att - ON pk_att.attrelid = pk_table.oid - AND pk_att.attnum = pk_col.attnum - AND NOT pk_att.attisdropped - WHERE pk_con.contype = 'p' - AND pk_schema.nspname = c.table_schema - AND pk_table.relname = c.table_name - AND pk_att.attname = c.column_name - ) AS is_pk"# -} - -pub async fn get_schemas(params: &ConnectionParams) -> Result, String> { - let pool = get_postgres_pool(params).await?; - let rows = query_all( - &pool, - "SELECT schema_name::text FROM information_schema.schemata \ -WHERE schema_name NOT IN ('pg_catalog', 'information_schema', 'pg_toast') \ -AND schema_name NOT LIKE 'pg_temp_%' \ -AND schema_name NOT LIKE 'pg_toast_temp_%' \ -ORDER BY schema_name", - &[], - ) - .await?; - - Ok(rows - .iter() - .map(|r| r.try_get("schema_name").unwrap_or_default()) - .collect()) -} - -pub async fn get_databases(params: &ConnectionParams) -> Result, String> { - let pool = get_postgres_pool(params).await?; - let rows = query_all( - &pool, - "SELECT datname::text FROM pg_database WHERE datistemplate = false ORDER BY datname", - &[], - ) - .await?; - Ok(rows - .iter() - .map(|r| r.try_get("datname").unwrap_or_default()) - .collect()) -} - -pub async fn get_tables(params: &ConnectionParams, schema: &str) -> Result, String> { - log::debug!( - "PostgreSQL: Fetching tables for database: {} schema: {}", - params.database, - schema - ); - let pool = get_postgres_pool(params).await?; - let rows = query_all( - &pool, - r#" - SELECT t.table_name::text AS name, d.description::text AS comment - FROM information_schema.tables t - JOIN pg_namespace n ON n.nspname = t.table_schema - JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = t.table_name - LEFT JOIN pg_description d - ON d.objoid = c.oid - AND d.classoid = 'pg_class'::regclass - AND d.objsubid = 0 - WHERE t.table_schema = $1 AND t.table_type = 'BASE TABLE' - ORDER BY t.table_name ASC - "#, - &[&schema], - ) - .await?; - let tables: Vec = rows - .iter() - .map(|r| TableInfo { - name: r.try_get("name").unwrap_or_default(), - comment: r.try_get("comment").ok(), - }) - .collect(); - log::debug!( - "PostgreSQL: Found {} tables in {}", - tables.len(), - params.database - ); - Ok(tables) -} - -pub async fn get_columns( - params: &ConnectionParams, - table_name: &str, - schema: &str, -) -> Result, String> { - let pool = get_postgres_pool(params).await?; - - // Postgres auto increment is usually sequences (nextval) or GENERATED BY DEFAULT/ALWAYS AS IDENTITY - let query = format!( - r#" - SELECT - c.column_name::text, - -- information_schema reports extension/composite/enum types as the - -- literal 'USER-DEFINED'; fall back to udt_name for the real type name - -- (e.g. pgvector's 'vector', 'halfvec', 'sparsevec'). - CASE - WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name::text - ELSE c.data_type::text - END AS data_type, - c.is_nullable::text, - c.column_default::text, - c.is_identity::text, - c.character_maximum_length, - c.numeric_precision, - c.numeric_scale, - d.description::text AS comment, - (SELECT string_agg('''' || replace(e.enumlabel, '''', '''''') || '''', ',' ORDER BY e.enumsortorder) - FROM pg_enum e - JOIN pg_type t ON t.oid = e.enumtypid - JOIN pg_namespace tn ON tn.oid = t.typnamespace - WHERE t.typname = c.udt_name AND tn.nspname = c.udt_schema) AS enum_values, - format_type(a.atttypid, a.atttypmod) AS full_type, - {} - FROM information_schema.columns c - JOIN pg_namespace n ON n.nspname = c.table_schema - JOIN pg_class pc ON pc.relnamespace = n.oid AND pc.relname = c.table_name - JOIN pg_attribute a ON a.attrelid = pc.oid AND a.attname = c.column_name - LEFT JOIN pg_description d - ON d.objoid = pc.oid - AND d.classoid = 'pg_class'::regclass - AND d.objsubid = a.attnum - WHERE c.table_schema = $1 AND c.table_name = $2 - ORDER BY c.ordinal_position - "#, - primary_key_exists_expression(), - ); - - let rows = query_all(&pool, query.as_str(), &[&schema, &table_name]).await?; - - Ok(rows - .iter() - .map(|r| { - let null_str: String = r.try_get("is_nullable").unwrap_or_default(); - let is_pk: bool = r.try_get("is_pk").unwrap_or(false); - let default_val: String = r.try_get("column_default").unwrap_or_default(); - let is_identity: String = r.try_get("is_identity").unwrap_or_default(); // YES/NO - let character_maximum_length: Option = r - .try_get::<_, Option>("character_maximum_length") - .ok() - .flatten() - .and_then(|v| u64::try_from(v).ok()); - - let numeric_precision: Option = r - .try_get::<_, Option>("numeric_precision") - .ok() - .flatten(); - let numeric_scale: Option = - r.try_get::<_, Option>("numeric_scale").ok().flatten(); - - let is_auto = is_identity == "YES" || default_val.contains("nextval"); - - // Only set default_value if not auto-increment, not empty, and not NULL - // Filter out NULL defaults (PostgreSQL represents nullable without default as NULL or NULL::type) - let default_value = if !is_auto - && !default_val.is_empty() - && !default_val.eq_ignore_ascii_case("null") - && !default_val.starts_with("NULL::") - { - Some(default_val) - } else { - None - }; - - let enum_values: Option = r.try_get("enum_values").ok().flatten(); - let (data_type, full_type) = postgres_column_types( - r.try_get("data_type").unwrap_or_default(), - enum_values, - r.try_get("full_type").ok().flatten(), - ); - - TableColumn { - name: r.try_get("column_name").unwrap_or_default(), - data_type, - is_pk, - is_nullable: null_str == "YES", - is_auto_increment: is_auto, - is_generated: false, - // PostgreSQL reports the default as SQL already. - default_sql: default_value.clone(), - default_value, - character_maximum_length, - numeric_precision, - numeric_scale, - comment: r.try_get("comment").ok(), - full_type, - on_update: None, - } - }) - .collect()) -} - -pub async fn get_foreign_keys( - params: &ConnectionParams, - table_name: &str, - schema: &str, -) -> Result, String> { - let pool = get_postgres_pool(params).await?; - - let query = r#" - SELECT - con.conname::text AS constraint_name, - src_att.attname::text AS column_name, - ref_nsp.nspname::text AS foreign_schema_name, - ref_cl.relname::text AS foreign_table_name, - ref_att.attname::text AS foreign_column_name, - CASE con.confupdtype - WHEN 'a' THEN 'NO ACTION' - WHEN 'r' THEN 'RESTRICT' - WHEN 'c' THEN 'CASCADE' - WHEN 'n' THEN 'SET NULL' - WHEN 'd' THEN 'SET DEFAULT' - END::text AS update_rule, - CASE con.confdeltype - WHEN 'a' THEN 'NO ACTION' - WHEN 'r' THEN 'RESTRICT' - WHEN 'c' THEN 'CASCADE' - WHEN 'n' THEN 'SET NULL' - WHEN 'd' THEN 'SET DEFAULT' - END::text AS delete_rule, - cols.key_seq - FROM pg_constraint con - JOIN pg_class src_cl ON src_cl.oid = con.conrelid - JOIN pg_namespace src_nsp ON src_nsp.oid = src_cl.relnamespace - JOIN pg_class ref_cl ON ref_cl.oid = con.confrelid - JOIN pg_namespace ref_nsp ON ref_nsp.oid = ref_cl.relnamespace - JOIN unnest(con.conkey, con.confkey) WITH ORDINALITY AS cols(src_attnum, ref_attnum, key_seq) ON true - JOIN pg_attribute src_att - ON src_att.attrelid = src_cl.oid - AND src_att.attnum = cols.src_attnum - AND NOT src_att.attisdropped - JOIN pg_attribute ref_att - ON ref_att.attrelid = ref_cl.oid - AND ref_att.attnum = cols.ref_attnum - AND NOT ref_att.attisdropped - WHERE con.contype = 'f' - AND con.conparentid = 0 - AND src_nsp.nspname = $1 - AND src_cl.relname = $2 - ORDER BY con.conname, cols.key_seq - "#; - - let rows = query_all(&pool, &query, &[&schema, &table_name]).await?; - - Ok(rows - .iter() - .map(|r| ForeignKey { - name: r.try_get("constraint_name").unwrap_or_default(), - column_name: r.try_get("column_name").unwrap_or_default(), - ref_table: r.try_get("foreign_table_name").unwrap_or_default(), - ref_column: r.try_get("foreign_column_name").unwrap_or_default(), - ref_schema: r.try_get("foreign_schema_name").ok(), - on_update: r.try_get("update_rule").ok(), - on_delete: r.try_get("delete_rule").ok(), - // WITH ORDINALITY yields the position within conkey/confkey — the - // true composite-key column order, independent of raw attnum (#840). - // The ordinal column is a Postgres bigint (i64); narrow to i32 for - // the struct field. A composite key's position is always small, so - // the cast is lossless, but try_get as i64 first to match the wire - // type (sqlx won't decode bigint into i32). - seq_in_fk: r - .try_get::<_, Option>("key_seq") - .ok() - .flatten() - .and_then(|v| i32::try_from(v).ok()), - }) - .collect()) -} - -// Batch function: Get all columns for all tables in one query -pub async fn get_all_columns_batch( - params: &ConnectionParams, - schema: &str, -) -> Result>, String> { - use std::collections::HashMap; - let pool = get_postgres_pool(params).await?; - - let query = format!( - r#" - SELECT - c.table_name, - c.column_name, - -- See get_columns: map extension/composite/enum types (reported as - -- 'USER-DEFINED') back to their real udt_name (e.g. pgvector 'vector'). - CASE - WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name::text - ELSE c.data_type::text - END AS data_type, - c.is_nullable, - c.column_default, - c.is_identity, - c.character_maximum_length, - c.numeric_precision, - c.numeric_scale, - d.description::text AS comment, - (SELECT string_agg('''' || replace(e.enumlabel, '''', '''''') || '''', ',' ORDER BY e.enumsortorder) - FROM pg_enum e - JOIN pg_type t ON t.oid = e.enumtypid - JOIN pg_namespace tn ON tn.oid = t.typnamespace - WHERE t.typname = c.udt_name AND tn.nspname = c.udt_schema) AS enum_values, - format_type(a.atttypid, a.atttypmod) AS full_type, - {} - FROM information_schema.columns c - JOIN pg_namespace n ON n.nspname = c.table_schema - JOIN pg_class pc ON pc.relnamespace = n.oid AND pc.relname = c.table_name - JOIN pg_attribute a ON a.attrelid = pc.oid AND a.attname = c.column_name - LEFT JOIN pg_description d - ON d.objoid = pc.oid - AND d.classoid = 'pg_class'::regclass - AND d.objsubid = a.attnum - WHERE c.table_schema = $1 - ORDER BY c.table_name, c.ordinal_position - "#, - primary_key_exists_expression(), - ); - - let rows = query_all(&pool, query.as_str(), &[&schema]).await?; - - let mut result: HashMap> = HashMap::new(); - - for row in rows { - let table_name: String = row.try_get("table_name").unwrap_or_default(); - let null_str: String = row.try_get("is_nullable").unwrap_or_default(); - let is_pk: bool = row.try_get("is_pk").unwrap_or(false); - let default_val: String = row.try_get("column_default").unwrap_or_default(); - let is_identity: String = row.try_get("is_identity").unwrap_or_default(); - let character_maximum_length: Option = row - .try_get::<_, Option>("character_maximum_length") - .ok() - .flatten() - .and_then(|v| u64::try_from(v).ok()); - let numeric_precision: Option = row - .try_get::<_, Option>("numeric_precision") - .ok() - .flatten(); - let numeric_scale: Option = row - .try_get::<_, Option>("numeric_scale") - .ok() - .flatten(); - - let is_auto = is_identity == "YES" || default_val.contains("nextval"); - - // Only set default_value if not auto-increment, not empty, and not NULL - // Filter out NULL defaults (PostgreSQL represents nullable without default as NULL or NULL::type) - let default_value = if !is_auto - && !default_val.is_empty() - && !default_val.eq_ignore_ascii_case("null") - && !default_val.starts_with("NULL::") - { - Some(default_val) - } else { - None - }; - - let enum_values: Option = row.try_get("enum_values").ok().flatten(); - let (data_type, full_type) = postgres_column_types( - row.try_get("data_type").unwrap_or_default(), - enum_values, - row.try_get("full_type").ok().flatten(), - ); - - let column = TableColumn { - name: row.try_get("column_name").unwrap_or_default(), - data_type, - is_pk, - is_nullable: null_str == "YES", - is_auto_increment: is_auto, - is_generated: false, - // PostgreSQL reports the default as SQL already. - default_sql: default_value.clone(), - default_value, - character_maximum_length, - numeric_precision, - numeric_scale, - comment: row.try_get("comment").ok(), - full_type, - on_update: None, - }; - - result - .entry(table_name) - .or_insert_with(Vec::new) - .push(column); - } - - Ok(result) -} - -// Batch function: Get all foreign keys for all tables in one query -pub async fn get_all_foreign_keys_batch( - params: &ConnectionParams, - schema: &str, -) -> Result>, String> { - use std::collections::HashMap; - let pool = get_postgres_pool(params).await?; - - let query = r#" - SELECT - src_cl.relname::text AS table_name, - con.conname::text AS constraint_name, - src_att.attname::text AS column_name, - ref_nsp.nspname::text AS foreign_schema_name, - ref_cl.relname::text AS foreign_table_name, - ref_att.attname::text AS foreign_column_name, - CASE con.confupdtype - WHEN 'a' THEN 'NO ACTION' - WHEN 'r' THEN 'RESTRICT' - WHEN 'c' THEN 'CASCADE' - WHEN 'n' THEN 'SET NULL' - WHEN 'd' THEN 'SET DEFAULT' - END::text AS update_rule, - CASE con.confdeltype - WHEN 'a' THEN 'NO ACTION' - WHEN 'r' THEN 'RESTRICT' - WHEN 'c' THEN 'CASCADE' - WHEN 'n' THEN 'SET NULL' - WHEN 'd' THEN 'SET DEFAULT' - END::text AS delete_rule, - cols.key_seq - FROM pg_constraint con - JOIN pg_class src_cl ON src_cl.oid = con.conrelid - JOIN pg_namespace src_nsp ON src_nsp.oid = src_cl.relnamespace - JOIN pg_class ref_cl ON ref_cl.oid = con.confrelid - JOIN pg_namespace ref_nsp ON ref_nsp.oid = ref_cl.relnamespace - JOIN unnest(con.conkey, con.confkey) WITH ORDINALITY AS cols(src_attnum, ref_attnum, key_seq) ON true - JOIN pg_attribute src_att - ON src_att.attrelid = src_cl.oid - AND src_att.attnum = cols.src_attnum - AND NOT src_att.attisdropped - JOIN pg_attribute ref_att - ON ref_att.attrelid = ref_cl.oid - AND ref_att.attnum = cols.ref_attnum - AND NOT ref_att.attisdropped - WHERE con.contype = 'f' - AND con.conparentid = 0 - AND src_nsp.nspname = $1 - ORDER BY src_cl.relname, con.conname, cols.key_seq - "#; - - let rows = query_all(&pool, &query, &[&schema]).await?; - - let mut result: HashMap> = HashMap::new(); - - for row in rows { - let table_name: String = row.try_get("table_name").unwrap_or_default(); - - let fk = ForeignKey { - name: row.try_get("constraint_name").unwrap_or_default(), - column_name: row.try_get("column_name").unwrap_or_default(), - ref_table: row.try_get("foreign_table_name").unwrap_or_default(), - ref_column: row.try_get("foreign_column_name").unwrap_or_default(), - ref_schema: row.try_get("foreign_schema_name").ok(), - on_update: row.try_get("update_rule").ok(), - on_delete: row.try_get("delete_rule").ok(), - seq_in_fk: row - .try_get::<_, Option>("key_seq") - .ok() - .flatten() - .and_then(|v| i32::try_from(v).ok()), - }; - - result.entry(table_name).or_insert_with(Vec::new).push(fk); - } - - Ok(result) -} - -pub async fn get_indexes( - params: &ConnectionParams, - table_name: &str, - schema: &str, -) -> Result, String> { - let pool = get_postgres_pool(params).await?; - - // Expression index columns have attnum = 0 and match no pg_attribute row, so - // walk indkey positionally and read their text from pg_get_indexdef; an inner - // join would drop them and hide all-expression indexes. - let query = r#" - SELECT - i.relname AS index_name, - COALESCE( - a.attname::text, - pg_get_indexdef(ix.indexrelid, k.n::int, true) - ) AS column_name, - ix.indisunique AS is_unique, - ix.indisprimary AS is_primary, - k.n::int AS seq_in_index, - (k.attnum = 0) AS is_expression - FROM - pg_class t - JOIN pg_namespace n ON t.relnamespace = n.oid - JOIN pg_index ix ON t.oid = ix.indrelid - JOIN pg_class i ON i.oid = ix.indexrelid - CROSS JOIN LATERAL unnest(string_to_array(ix.indkey::text, ' ')::int2[]) - WITH ORDINALITY AS k(attnum, n) - LEFT JOIN pg_attribute a - ON a.attrelid = t.oid - AND a.attnum = k.attnum - AND k.attnum <> 0 - WHERE - t.relkind IN ('r', 'm') - AND n.nspname = $1 - AND t.relname = $2 - ORDER BY - i.relname, - k.n - "#; - - let rows = query_all(&pool, &query, &[&schema, &table_name]).await?; - - Ok(rows - .iter() - .map(|r| Index { - name: r.try_get("index_name").unwrap_or_default(), - column_name: r.try_get("column_name").unwrap_or_default(), - is_unique: r.try_get("is_unique").unwrap_or(false), - is_primary: r.try_get("is_primary").unwrap_or(false), - seq_in_index: r.try_get("seq_in_index").unwrap_or(0), - is_expression: r.try_get("is_expression").unwrap_or(false), - }) - .collect()) -} - -pub async fn save_blob_column_to_file( - params: &ConnectionParams, - table: &str, - col_name: &str, - pk_map: &HashMap, - schema: &str, - file_path: &str, -) -> Result<(), String> { - let pool = get_postgres_pool(params).await?; - - let pk_types = get_pk_column_types(&pool, schema, table, pk_map).await; - let (predicate, pk_params) = build_pk_map_predicate(pk_map, &pk_types, 1)?; - let query = format!( - "SELECT \"{}\" FROM \"{}\".\"{}\" WHERE {}", - escape_identifier(col_name), - escape_identifier(schema), - escape_identifier(table), - predicate, - ); - - let params_ref: Vec<(&(dyn ToSql + Sync), Type)> = pk_params - .iter() - .map(|(b, t)| (b.as_ref() as &(dyn ToSql + Sync), t.clone())) - .collect(); - let row = query_one_typed(&pool, &query, ¶ms_ref).await?; - - let bytes: Vec = row.try_get(0).map_err(|e| format_pg_error(&e))?; - std::fs::write(file_path, bytes).map_err(|e| e.to_string()) -} - -pub async fn fetch_blob_column_as_data_url( - params: &ConnectionParams, - table: &str, - col_name: &str, - pk_map: &HashMap, - schema: &str, -) -> Result { - let pool = get_postgres_pool(params).await?; - - let pk_types = get_pk_column_types(&pool, schema, table, pk_map).await; - let (predicate, pk_params) = build_pk_map_predicate(pk_map, &pk_types, 1)?; - let query = format!( - "SELECT \"{}\" FROM \"{}\".\"{}\" WHERE {}", - escape_identifier(col_name), - escape_identifier(schema), - escape_identifier(table), - predicate, - ); - - let params_ref: Vec<(&(dyn ToSql + Sync), Type)> = pk_params - .iter() - .map(|(b, t)| (b.as_ref() as &(dyn ToSql + Sync), t.clone())) - .collect(); - let row = query_one_typed(&pool, &query, ¶ms_ref).await?; - - let bytes: Vec = row.try_get(0).map_err(|e| format_pg_error(&e))?; - Ok(crate::drivers::common::encode_blob_full(&bytes)) -} - -async fn get_column_data_type( - pool: &deadpool_postgres::Pool, - schema: &str, - table: &str, - col_name: &str, -) -> Result, String> { - let rows = query_all( - pool, - "SELECT data_type::text, udt_name::text \ -FROM information_schema.columns \ -WHERE table_schema = $1 AND table_name = $2 AND column_name = $3 \ -LIMIT 1", - &[&schema, &table, &col_name], - ) - .await?; - - Ok(rows.first().map(|row| { - // information_schema reports extension/composite/enum types as the - // literal 'USER-DEFINED'; fall back to udt_name for the real type name - // (e.g. pgvector's 'vector', 'halfvec', 'sparsevec') so the write path - // (update_record/insert_record) resolves the same type as get_columns. - let data_type = row - .try_get::<_, String>("data_type") - .unwrap_or_else(|_| "unknown".to_string()); - if data_type == "USER-DEFINED" { - row.try_get::<_, String>("udt_name").unwrap_or(data_type) - } else { - data_type - } - })) -} - -/// Resolves the real OID of the `hstore` type for a specific column, confirming in -/// the same query that the column actually is hstore. hstore is an extension type -/// (not a well-known Postgres OID), so its OID varies per installation and — unlike -/// `information_schema.columns.data_type`, which reports it only as the generic -/// "USER-DEFINED" — the concrete type name has to come from the catalog directly. -/// `None` means either the extension isn't installed or the column isn't hstore. -async fn get_hstore_oid_for_column( - pool: &deadpool_postgres::Pool, - schema: &str, - table: &str, - col_name: &str, -) -> Result, String> { - let rows = query_all( - pool, - "SELECT a.atttypid::oid \ - FROM pg_attribute a \ - JOIN pg_class c ON c.oid = a.attrelid \ - JOIN pg_namespace n ON n.oid = c.relnamespace \ - JOIN pg_type t ON t.oid = a.atttypid \ - WHERE n.nspname = $1 AND c.relname = $2 AND a.attname = $3 AND t.typname = 'hstore' \ - LIMIT 1", - &[&schema, &table, &col_name], - ) - .await?; - Ok(rows.first().map(|row| row.get::(0))) -} - -/// Resolve the declared type of every column in `pk_map`, so each PK member binds -/// against its real column type (uuid vs varchar etc. — #392). Columns whose type -/// cannot be loaded are simply omitted, leaving `build_pk_map_predicate` to fall back -/// to the shape heuristic for them. -async fn get_pk_column_types( - pool: &deadpool_postgres::Pool, - schema: &str, - table: &str, - pk_map: &HashMap, -) -> HashMap { - let mut types = HashMap::new(); - for col in pk_map.keys() { - match get_column_data_type(pool, schema, table, col).await { - Ok(Some(t)) => { - types.insert(col.clone(), t); - } - Ok(None) => log::warn!( - "No PostgreSQL column type found for {schema}.{table}.{col}; row matching may fail" - ), - Err(error) => log::warn!( - "Failed to load PostgreSQL column type for {schema}.{table}.{col}: {error}; row matching may fail" - ), - } - } - types -} - -/// Map every enum-typed column of the table to its schema-qualified, quoted enum -/// type name (e.g. `"public"."plan_type"`). PostgreSQL rejects a `TEXT`-bound -/// parameter assigned to an enum column with SQLSTATE 42804 (#465), so the -/// binding layer needs the real type to `CAST` through. On any catalog error the -/// map is simply empty and binding falls back to the plain TEXT path. -async fn get_enum_column_types( - pool: &deadpool_postgres::Pool, - schema: &str, - table: &str, -) -> HashMap { - let query = "SELECT a.attname::text AS column_name, \ -tn.nspname::text AS type_schema, t.typname::text AS type_name \ -FROM pg_attribute a \ -JOIN pg_class c ON c.oid = a.attrelid \ -JOIN pg_namespace n ON n.oid = c.relnamespace \ -JOIN pg_type t ON t.oid = a.atttypid \ -JOIN pg_namespace tn ON tn.oid = t.typnamespace \ -WHERE n.nspname = $1 AND c.relname = $2 \ -AND a.attnum > 0 AND NOT a.attisdropped AND t.typtype = 'e'"; - - match query_all(pool, query, &[&schema, &table]).await { - Ok(rows) => rows - .iter() - .filter_map(|row| { - let col: String = row.try_get("column_name").ok()?; - let type_schema: String = row.try_get("type_schema").ok()?; - let type_name: String = row.try_get("type_name").ok()?; - Some((col, quote_qualified_type(&type_schema, &type_name))) - }) - .collect(), - Err(err) => { - log::debug!( - "Could not load PostgreSQL enum column types for {}.{}: {}", - schema, - table, - err - ); - HashMap::new() - } - } -} - -fn json_value_kind(value: &serde_json::Value) -> &'static str { - match value { - serde_json::Value::Null => "null", - serde_json::Value::Bool(_) => "boolean", - serde_json::Value::Number(_) => "number", - serde_json::Value::String(_) => "string", - serde_json::Value::Array(_) => "array", - serde_json::Value::Object(_) => "object", - } -} - -fn update_record_error_context( - err: String, - schema: &str, - table: &str, - pk_col: &str, - pk_val: &serde_json::Value, - col_name: &str, - new_val: &serde_json::Value, - column_type: Option<&str>, - query: &str, -) -> String { - let column_type = column_type.unwrap_or("unknown"); - let hint = if matches!(new_val, serde_json::Value::String(_)) - && matches!( - column_type.to_ascii_lowercase().as_str(), - "smallint" - | "integer" - | "bigint" - | "int2" - | "int4" - | "int8" - | "serial" - | "bigserial" - | "numeric" - | "decimal" - | "real" - | "double precision" - | "float4" - | "float8" - ) { - "\nHint: the edited value arrived from the grid as a JSON string. For numeric PostgreSQL columns, Tabularis attempts to parse it before binding; check that the value is valid for the target column type." - } else { - "" - }; - - format!( - "{err}\n\nPostgreSQL update context:\n- table: \"{schema}\".\"{table}\"\n- column: \"{col_name}\" ({column_type})\n- new value JSON type: {new_val_kind}\n- primary key: \"{pk_col}\" JSON type {pk_val_kind}\n- SQL: {query}{hint}", - new_val_kind = json_value_kind(new_val), - pk_val_kind = json_value_kind(pk_val), - ) -} - -pub async fn delete_record( - params: &ConnectionParams, - table: &str, - pk_map: &HashMap, - schema: &str, -) -> Result { - let pool = get_postgres_pool(params).await?; - - let pk_types = get_pk_column_types(&pool, schema, table, pk_map).await; - let (predicate, pk_params) = build_pk_map_predicate(pk_map, &pk_types, 1)?; - let query = format!( - "DELETE FROM \"{}\".\"{}\" WHERE {}", - escape_identifier(schema), - escape_identifier(table), - predicate, - ); - - let params_ref: Vec<(&(dyn ToSql + Sync), Type)> = pk_params - .iter() - .map(|(b, t)| (b.as_ref() as &(dyn ToSql + Sync), t.clone())) - .collect(); - execute_typed(&pool, &query, ¶ms_ref).await -} - -pub async fn update_record( - params: &ConnectionParams, - table: &str, - pk_map: &HashMap, - col_name: &str, - new_val: serde_json::Value, - schema: &str, - max_blob_size: u64, -) -> Result { - let pool = get_postgres_pool(params).await?; - let column_data_type = match get_column_data_type(&pool, schema, table, col_name).await { - Ok(data_type) => data_type, - Err(err) => { - log::debug!( - "Could not load PostgreSQL column metadata for {}.{}.{}: {}", - schema, - table, - col_name, - err - ); - None - } - }; - // get_column_data_type already unfolds 'USER-DEFINED' to the real udt_name, - // so hstore columns report as plain "hstore" here. - let hstore_oid = if column_data_type.as_deref() == Some("hstore") { - get_hstore_oid_for_column(&pool, schema, table, col_name) - .await - .unwrap_or(None) - } else { - None - }; - - let enum_types = get_enum_column_types(&pool, schema, table).await; - let new_val_for_context = new_val.clone(); - let pk_map_for_context = pk_map.clone(); - - let mut query = format!( - "UPDATE \"{}\".\"{}\" SET \"{}\" = ", - escape_identifier(schema), - escape_identifier(table), - escape_identifier(col_name) - ); - - let mut bound_params: Vec<(Box, Type)> = - Vec::new(); - - let bound = bind_pg_value( - new_val, - bound_params.len() + 1, - PgValueOptions { - column_type: column_data_type.as_deref(), - enum_type: enum_types.get(col_name).map(|s| s.as_str()), - max_blob_size, - allow_default: true, - hstore_oid, - }, - )?; - query.push_str(&bound.sql); - if let Some(param) = bound.param { - bound_params.push(param); - } - - let pk_types = get_pk_column_types(&pool, schema, table, pk_map).await; - let (predicate, pk_params) = build_pk_map_predicate(pk_map, &pk_types, bound_params.len() + 1)?; - query.push_str(" WHERE "); - query.push_str(&predicate); - bound_params.extend(pk_params); - - let params_ref: Vec<(&(dyn ToSql + Sync), Type)> = bound_params - .iter() - .map(|(b, t)| (b.as_ref() as &(dyn ToSql + Sync), t.clone())) - .collect(); - - let first_pk_col = { - let mut keys: Vec<&String> = pk_map_for_context.keys().collect(); - keys.sort(); - keys.first().map(|k| k.as_str()).unwrap_or("") - }; - let first_pk_val = pk_map_for_context - .get(first_pk_col) - .cloned() - .unwrap_or(serde_json::Value::Null); - - execute_typed(&pool, &query, ¶ms_ref) - .await - .map_err(|err| { - update_record_error_context( - err, - schema, - table, - first_pk_col, - &first_pk_val, - col_name, - &new_val_for_context, - column_data_type.as_deref(), - &query, - ) - }) -} - -pub async fn insert_record( - params: &ConnectionParams, - table: &str, - data: std::collections::HashMap, - schema: &str, - max_blob_size: u64, -) -> Result { - let pool = get_postgres_pool(params).await?; - - // Preserve original column ordering for stable SQL (collect from HashMap once) - let mut entries: Vec<(String, serde_json::Value)> = data.into_iter().collect(); - - let mut cols = Vec::with_capacity(entries.len()); - for (name, _) in &entries { - cols.push(format!("\"{}\"", name)); - } - - // Allow empty inserts for auto-generated values (e.g., auto-increment PKs) - if cols.is_empty() { - return execute( - &pool, - &format!( - "INSERT INTO \"{}\".\"{}\" DEFAULT VALUES", - escape_identifier(schema), - escape_identifier(table) - ), - &[], - ) - .await; - }; - - // Fetch column types so json/jsonb columns get JSON-aware binding. - let col_types: std::collections::HashMap = - match get_columns(params, table, schema).await { - Ok(cols_meta) => cols_meta - .into_iter() - .map(|c| (c.name, c.data_type)) - .collect(), - Err(err) => { - log::debug!( - "Could not load PostgreSQL column metadata for {}.{}: {}", - schema, - table, - err - ); - std::collections::HashMap::new() - } - }; - - let enum_types = get_enum_column_types(&pool, schema, table).await; - - let mut params: Vec<(Box, Type)> = Vec::with_capacity(entries.len()); - let mut vals_set: Vec = Vec::with_capacity(entries.len()); - - for (col_name, val) in entries.drain(..) { - let column_type = col_types.get(&col_name).map(|s| s.as_str()); - // get_columns already unfolds 'USER-DEFINED' to the real udt_name, - // so hstore columns report as plain "hstore" here. - let hstore_oid = if column_type == Some("hstore") { - get_hstore_oid_for_column(&pool, schema, table, &col_name) - .await - .unwrap_or(None) - } else { - None - }; - let bound = bind_pg_value( - val, - params.len() + 1, - PgValueOptions { - column_type, - enum_type: enum_types.get(&col_name).map(|s| s.as_str()), - max_blob_size, - allow_default: false, - hstore_oid, - }, - )?; - vals_set.push(bound.sql); - if let Some(param) = bound.param { - params.push(param); - } - } - - let query = format!( - "INSERT INTO \"{}\".\"{}\" ({}) VALUES ({})", - escape_identifier(schema), - escape_identifier(table), - cols.join(", "), - vals_set.join(", ") - ); - - let params: Vec<(&(dyn ToSql + Sync), Type)> = params - .iter() - .map(|(b, t)| (b.as_ref() as &(dyn ToSql + Sync), t.clone())) - .collect(); - - execute_typed(&pool, &query, ¶ms).await -} - -pub async fn get_table_ddl( - params: &ConnectionParams, - table_name: &str, - schema: &str, -) -> Result { - let cols = get_columns(params, table_name, schema).await?; - if cols.is_empty() { - return Err(format!("Table {} not found or empty", table_name)); - } - - let mut defs = Vec::new(); - let mut pks = Vec::new(); - - for col in cols { - // `full_type` is `format_type()`: `text[]`, `numeric(10,2)`, ...; - // `data_type` alone says `ARRAY` or drops the precision. - let data_type = col.full_type.as_deref().unwrap_or(&col.data_type); - let mut def = format!("\"{}\" {}", col.name, data_type); - - if !col.is_nullable { - def.push_str(" NOT NULL"); - } - - if col.is_pk { - pks.push(format!("\"{}\"", col.name)); - } - defs.push(def); - } - - if !pks.is_empty() { - defs.push(format!("PRIMARY KEY ({})", pks.join(", "))); - } - - let mut ddl = format!( - "CREATE TABLE \"{}\".\"{}\" (\n {}\n);", - escape_identifier(schema), - escape_identifier(table_name), - defs.join(",\n ") - ); - // The table's other indexes, as PostgreSQL writes them; the primary key - // is part of the table above. An index behind a UNIQUE or EXCLUDE - // constraint is written as that constraint, so it keeps being one (with - // `DEFERRABLE` and the exclusion operators). - let pool = get_postgres_pool(params).await?; - let client = pool.get().await.map_err(|e| e.to_string())?; - let indexes = client - .query( - "SELECT CASE WHEN c.oid IS NULL THEN pg_catalog.pg_get_indexdef(ix.indexrelid) \ - ELSE 'ALTER TABLE ' || pg_catalog.quote_ident(n.nspname) || '.' \ - || pg_catalog.quote_ident(t.relname) || ' ADD CONSTRAINT ' \ - || pg_catalog.quote_ident(c.conname) || ' ' \ - || pg_catalog.pg_get_constraintdef(c.oid) END \ - FROM pg_catalog.pg_index ix \ - JOIN pg_catalog.pg_class t ON t.oid = ix.indrelid \ - JOIN pg_catalog.pg_class i ON i.oid = ix.indexrelid \ - JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace \ - LEFT JOIN pg_catalog.pg_constraint c ON c.conindid = ix.indexrelid \ - AND c.conrelid = t.oid AND c.contype IN ('u', 'x') \ - WHERE n.nspname = $1 AND t.relname = $2 AND NOT ix.indisprimary \ - ORDER BY i.relname", - &[&schema, &table_name], - ) - .await - .map_err(|e| format!("Failed to read the table's indexes: {}", e))?; - for index in indexes { - let definition: String = index.try_get(0).map_err(|e| e.to_string())?; - ddl.push_str(&format!("\n{definition};")); - } - Ok(ddl) -} - -/// Acquires a single PostgreSQL client from the pool and applies the -/// optional `search_path` once. Used by both `execute_query` and -/// `execute_batch`; the latter relies on the schema being set on the -/// shared connection so all statements in the batch see the same -/// search_path. -async fn acquire_pg_client( - params: &ConnectionParams, - schema: Option<&str>, -) -> Result { - let pool = get_postgres_pool(params).await?; - let client = get_client(&pool).await?; - if let Some(s) = schema { - let search_path = format!("SET search_path TO \"{}\"", escape_identifier(s)); - client - .execute(&search_path, &[]) - .await - .map_err(|e| format_pg_error(&e))?; - } - Ok(client) -} - -/// Runs one statement against an already-acquired client. Pulled out of -/// `execute_query` so `execute_batch` can reuse it while keeping a single -/// physical connection open for session-state continuity (`BEGIN`/`COMMIT`, -/// `SET LOCAL`, `CREATE TEMP TABLE`, `LASTVAL()`, `PREPARE`/`EXECUTE`). -async fn exec_on_pg_client( - client: &tokio_postgres::Client, - query: &str, - limit: Option, - page: u32, -) -> Result { - // Non-result-set statements (INSERT/UPDATE/DELETE/DDL) go through - // `client.execute()` so we can return the real affected-row count. - // The fetch path below is reserved for SELECT-like statements. - if !crate::drivers::common::returns_result_set(query) { - let affected = client - .execute(query, &[]) - .await - .map_err(|e| format_pg_error(&e))?; - return Ok(QueryResult { - columns: vec![], - rows: vec![], - affected_rows: affected, - truncated: false, - pagination: None, - additional_results: None, - server_time_ms: None, - fetch_time_ms: None, - }); - } - - let is_select = crate::drivers::common::is_select_query(query); - let mut manual_limit = limit; - let mut truncated = false; - - let (final_query, pagination_meta) = if is_select && limit.is_some() { - let l = limit.unwrap(); - // A failed probe fails the run: a cancel stops only the running - // command, so the user's query must not run after a cancelled probe. - let backslash_escapes = query.contains('\\') - && client - .query_one("SHOW standard_conforming_strings", &[]) - .await - .map_err(|e| format_pg_error(&e))? - .try_get::<_, String>(0) - .is_ok_and(|value| value.eq_ignore_ascii_case("off")); - let data_query = crate::drivers::common::build_paginated_query_for( - query, - l, - page, - crate::drivers::common::ScanRules { - hash_comments: false, - line_comment_requires_space: false, - backslash_escapes, - negative_limit_unbounded: false, - }, - ); - manual_limit = None; - (data_query, Some((l, page))) - } else { - (query.to_string(), None) - }; - - let start_instant = std::time::Instant::now(); - let mut server_time_ms: Option = None; - - let pg_params: Vec = vec![]; - let mut rows_stream = std::pin::pin!(client - .query_raw(&final_query, &pg_params) - .await - .map_err(|e| format_pg_error(&e))?); - - let mut columns: Vec = Vec::new(); - let mut json_rows = Vec::new(); - - use futures::stream::StreamExt; - - while let Some(result) = rows_stream.next().await { - if server_time_ms.is_none() { - server_time_ms = Some(start_instant.elapsed().as_secs_f64() * 1000.0); - } - match result { - Ok(row) => { - if columns.is_empty() { - columns = row.columns().iter().map(|c| c.name().to_string()).collect(); - } - - if let Some(l) = manual_limit { - if json_rows.len() >= l as usize { - truncated = true; - break; - } - } - - let mut json_row = Vec::new(); - for (i, _) in row.columns().iter().enumerate() { - let val = extract_value(&row, i, None); - json_row.push(val); - } - json_rows.push(json_row); - } - Err(e) => return Err(format_pg_error(&e)), - } - } - - let (server_time, fetch_time) = - crate::drivers::common::calculate_query_timing_from_start(start_instant, server_time_ms); - - let pagination = if let Some((page_size, p)) = pagination_meta { - let has_more = json_rows.len() > page_size as usize; - if has_more { - json_rows.truncate(page_size as usize); - } - truncated = has_more; - Some(Pagination { - page: p, - page_size, - total_rows: None, - has_more, - }) - } else { - None - }; - - Ok(QueryResult { - columns, - rows: json_rows, - affected_rows: 0, - truncated, - pagination, - additional_results: None, - server_time_ms: server_time, - fetch_time_ms: fetch_time, - }) -} - -pub async fn execute_query( - params: &ConnectionParams, - query: &str, - limit: Option, - page: u32, - schema: Option<&str>, -) -> Result { - let (result, _) = execute_query_in_session(params, query, limit, page, schema, None).await?; - Ok(result) -} - -/// Runs one statement inside `BEGIN READ ONLY` and always rolls it back, so -/// PostgreSQL rejects any write the statement attempts (`SELECT … INTO`, -/// `setval`, a volatile function that modifies data). -/// -/// If the rollback fails, or the run is dropped mid-flight, the connection is -/// closed instead of returned to the pool, so the read-only transaction never -/// leaks into another caller. -pub async fn execute_read_only_query( - params: &ConnectionParams, - query: &str, - limit: Option, - page: u32, - schema: Option<&str>, -) -> Result { - let mut in_flight = InFlight::new(acquire_pg_client(params, schema).await?, params); - let client = in_flight.client.as_ref().expect("set above"); - client - .batch_execute("BEGIN READ ONLY") - .await - .map_err(|e| format_pg_error(&e))?; - let outcome = exec_within_query_timeout(client, params, query, limit, page).await?; - match client.batch_execute("ROLLBACK").await { - // Back to the pool only once the transaction is closed. - Ok(()) => drop(in_flight.client.take()), - Err(e) => log::warn!("PostgreSQL: ROLLBACK after a read-only query failed: {e}"), - } - outcome -} - -/// `execute_query` with the tab's connection carried across calls. -/// -/// One statement at a time is how a transaction is actually driven — run -/// `BEGIN`, look, change, verify, `COMMIT` — so the single-statement path -/// needs the same pinning as a batch, or each run lands on a different -/// pooled connection and the transaction is stranded. -/// -/// Implemented as a one-statement batch so there is a single session -/// code path. -pub async fn execute_query_in_session( - params: &ConnectionParams, - query: &str, - limit: Option, - page: u32, - schema: Option<&str>, - session_id: Option<&str>, -) -> Result<(QueryResult, bool), String> { - let queries = [query.to_string()]; - let (mut results, in_transaction) = - execute_batch_in_session(params, &queries, limit, page, schema, session_id, None).await?; - - let statement = results - .pop() - .ok_or_else(|| "The statement produced no result".to_string())?; - match (statement.result, statement.error) { - (Some(result), _) => Ok((result, in_transaction)), - (None, Some(error)) => Err(error), - (None, None) => Err("The statement produced no result".to_string()), - } -} - -/// Runs a sequence of statements on a single pooled client so -/// session-local state survives across them. Per-statement errors are -/// reported in the slot but do not abort the batch — when the script -/// uses an explicit transaction, PostgreSQL rejects subsequent -/// statements with "current transaction is aborted" until `ROLLBACK`, -/// which surfaces the failure naturally in the per-statement result. -pub async fn execute_batch( - params: &ConnectionParams, - queries: &[String], - limit: Option, - page: u32, - schema: Option<&str>, - on_progress: Option<&crate::drivers::driver_trait::BatchProgressFn>, -) -> Result, String> { - let (results, _) = - execute_batch_in_session(params, queries, limit, page, schema, None, on_progress).await?; - Ok(results) -} - -/// `execute_batch` with the tab's connection carried across calls. -/// -/// When `session_id` is given and the batch leaves an explicit transaction -/// open, the connection is pinned to that session instead of returning to -/// the pool, so the next batch from the same tab continues the same -/// transaction — `BEGIN`, changes, verify, `COMMIT`, each as its own run. -/// The returned flag says whether the session is still inside one. -/// -/// A batch that leaves a transaction open with no session to pin it to is -/// rolled back rather than handed back to the pool: the pool recycles -/// connections without resetting them, so the next borrower would otherwise -/// inherit the transaction and its locks. -pub async fn execute_batch_in_session( - params: &ConnectionParams, - queries: &[String], - limit: Option, - page: u32, - schema: Option<&str>, - session_id: Option<&str>, - on_progress: Option<&crate::drivers::driver_trait::BatchProgressFn>, -) -> Result<(Vec, bool), String> { - // Held for the whole run, so an overlapping run from the same tab waits its turn. - let mut slot = match session_id { - Some(id) => Some(session::lock(id).await), - None => None, - }; - // A pinned connection belongs to one transaction, and a transaction is - // scoped to one database. If the tab has switched databases since opening - // the transaction, keeping running on the pinned connection would silently - // execute on the old database. Reject before taking the client so the - // pinned session (and its open transaction) is left intact. - let requested_db = params.database.primary(); - if let Some(slot) = slot.as_ref() { - session::check_pinned_database(slot.database(), requested_db, "run")?; - } - let pinned = slot.as_mut().and_then(|s| s.take()); - // A pinned connection only exists because its transaction is still open. - let mut in_transaction = pinned.is_some(); - let client = match pinned { - Some(client) => client, - None => acquire_pg_client(params, schema).await?, - }; - let mut in_flight = InFlight::new(client, params); - let client = in_flight.client.as_ref().expect("set above"); - - let mut results = Vec::with_capacity(queries.len()); - for (idx, q) in queries.iter().enumerate() { - let start = std::time::Instant::now(); - let outcome = exec_within_query_timeout(client, params, q, limit, page).await?; - in_transaction = crate::drivers::common::transaction_effect(q) - .in_transaction_after(outcome.is_ok(), in_transaction); - let res = crate::models::BatchStatementResult::from_outcome(start, outcome); - if let Some(cb) = on_progress { - cb(idx, &res); - } - results.push(res); - } - - let client = in_flight.client.take().expect("set above"); - match slot.as_mut() { - Some(slot) if in_transaction => { - slot.pin(client, requested_db.to_string()); - Ok((results, true)) - } - _ => { - if in_transaction { - session::rollback_and_release(client).await; - } - Ok((results, false)) - } - } -} - -/// A connection a run is using. If the run is dropped mid-flight (a cancelled -/// query), the server is asked to cancel the running statement and the -/// connection is closed rather than returned to the pool, so the server ends -/// any open transaction instead of the next borrower inheriting it. -struct InFlight<'a> { - client: Option, - params: &'a ConnectionParams, -} - -impl<'a> InFlight<'a> { - fn new(client: deadpool_postgres::Client, params: &'a ConnectionParams) -> Self { - Self { - client: Some(client), - params, - } - } -} - -impl Drop for InFlight<'_> { - fn drop(&mut self) { - let Some(client) = self.client.take() else { - return; - }; - // Closing the connection alone does not stop the statement: the - // server only notices the client is gone when it next writes to it. - match tokio::runtime::Handle::try_current() { - Ok(runtime) => { - runtime.spawn(cancel_on_server(client.cancel_token(), self.params)); - } - Err(_) => log::warn!("PostgreSQL: no runtime to send a cancel request from"), - } - drop(deadpool_postgres::Client::take(client)); - } -} - -/// How long a timed-out statement gets to stop after the cancel request -/// before its connection is closed. -const CANCEL_GRACE: std::time::Duration = std::time::Duration::from_secs(5); - -/// Runs one statement under the connection's query timeout. When it runs -/// over, the server is asked to cancel it and the statement fails with a -/// "stopped after N s" error. -/// -/// The outer `Err` means the statement was still running after -/// [`CANCEL_GRACE`]: the connection is busy and must be closed, not reused. -async fn exec_within_query_timeout( - client: &tokio_postgres::Client, - params: &ConnectionParams, - query: &str, - limit: Option, - page: u32, -) -> Result, String> { - let run = exec_on_pg_client(client, query, limit, page); - let Some(timeout) = crate::pool_manager::query_timeout(params) else { - return Ok(run.await); - }; - tokio::pin!(run); - if let Ok(outcome) = tokio::time::timeout(timeout, &mut run).await { - return Ok(outcome); - } - cancel_on_server(client.cancel_token(), params).await; - let stopped = format!( - "Query stopped after {} s by the connection's query timeout", - timeout.as_secs() - ); - match tokio::time::timeout(CANCEL_GRACE, run).await { - // Finished between the timeout and the cancel request. - Ok(Ok(result)) => Ok(Ok(result)), - Ok(Err(e)) if is_query_canceled(&e) => Ok(Err(stopped)), - // Failed for its own reason before the cancel landed. - Ok(Err(e)) => Ok(Err(e)), - Err(_) => Err(format!( - "{stopped}. The server did not confirm the cancel, so the connection was closed." - )), - } -} - -/// Whether a statement error from [`exec_on_pg_client`] is the server's -/// `query_canceled` (SQLSTATE 57014). The error arrives as text, and -/// `format_pg_error` appends the `DbError` debug output, which names the code -/// as `E57014`. -fn is_query_canceled(error: &str) -> bool { - error.contains("E57014") -} - -/// Asks the server to cancel whatever the connection behind `token` is -/// running. Built from `params` so it uses the same TLS settings as the -/// connection. Failures are logged: the caller closes the connection either -/// way. -fn cancel_on_server( - token: tokio_postgres::CancelToken, - params: &ConnectionParams, -) -> impl std::future::Future + Send + 'static { - let tls = crate::pool_manager::build_postgres_tls_connector(params); - async move { - let sent = match tls { - // The cancel opens its own connection, which ignores the - // connect timeout, so bound it here. - Ok(tls) => match tokio::time::timeout(CANCEL_GRACE, token.cancel_query(tls)).await { - Ok(sent) => sent.map_err(|e| e.to_string()), - Err(_) => Err(format!("no answer within {} s", CANCEL_GRACE.as_secs())), - }, - Err(e) => Err(e), - }; - if let Err(e) = sent { - log::warn!("PostgreSQL: cancel request failed: {e}"); - } - } -} - -pub async fn get_views(params: &ConnectionParams, schema: &str) -> Result, String> { - log::debug!( - "PostgreSQL: Fetching views for database: {} schema: {}", - params.database, - schema - ); - let pool = get_postgres_pool(params).await?; - let rows = query_all( - &pool, - "SELECT viewname as name FROM pg_views WHERE schemaname = $1 ORDER BY viewname ASC", - &[&schema], - ) - .await?; - - let views: Vec = rows - .iter() - .map(|r| ViewInfo { - name: r.try_get("name").unwrap_or_default(), - definition: None, - }) - .collect(); - log::debug!( - "PostgreSQL: Found {} views in {}", - views.len(), - params.database - ); - Ok(views) -} - -/// `pg_class.reltuples`, the planner's row estimate; `None` before the -/// table was first vacuumed or analyzed (-1 since PostgreSQL 14). -pub async fn get_approximate_row_count( - params: &ConnectionParams, - table_name: &str, - schema: &str, -) -> Result, String> { - let pool = get_postgres_pool(params).await?; - let client = pool.get().await.map_err(|e| e.to_string())?; - let row = client - .query_opt( - "SELECT c.reltuples::float8 FROM pg_catalog.pg_class c \ - JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \ - WHERE n.nspname = $1 AND c.relname = $2", - &[&schema, &table_name], - ) - .await - .map_err(|e| format!("Failed to read the row estimate: {}", e))?; - let estimate = row.and_then(|row| row.try_get::<_, f64>(0).ok()); - Ok(estimate - .filter(|rows| *rows >= 0.0) - .map(|rows| rows.round() as u64)) -} - -pub async fn get_view_definition( - params: &ConnectionParams, - view_name: &str, - schema: &str, -) -> Result { - let pool = get_postgres_pool(params).await?; - let qualified = format!( - "\"{}\".\"{}\"", - escape_identifier(schema), - escape_identifier(view_name) - ); - - let client = pool.get().await.map_err(|e| e.to_string())?; - - let row = client - .query_one( - "SELECT pg_get_viewdef(($1::text)::regclass, true) as definition", - &[&qualified], - ) - .await - .map_err(|e| format!("Failed to get view definition: {}", e))?; - - let definition: String = row.try_get("definition").unwrap_or_default(); - Ok(format!( - "CREATE OR REPLACE VIEW {} AS\n{}", - qualified, definition - )) -} - -pub async fn create_view( - params: &ConnectionParams, - view_name: &str, - definition: &str, - schema: &str, -) -> Result<(), String> { - let pool = get_postgres_pool(params).await?; - let query = format!( - "CREATE VIEW \"{}\".\"{}\" AS {}", - escape_identifier(schema), - escape_identifier(view_name), - definition - ); - - let client = pool.get().await.map_err(|e| e.to_string())?; - client - .execute(&query, &[]) - .await - .map_err(|e| format!("Failed to create view: {}", e))?; - - Ok(()) -} - -pub async fn alter_view( - params: &ConnectionParams, - view_name: &str, - definition: &str, - schema: &str, -) -> Result<(), String> { - let pool = get_postgres_pool(params).await?; - let query = format!( - "CREATE OR REPLACE VIEW \"{}\".\"{}\" AS {}", - escape_identifier(schema), - escape_identifier(view_name), - definition - ); - - let client = pool.get().await.map_err(|e| e.to_string())?; - client - .execute(&query, &[]) - .await - .map_err(|e| format!("Failed to alter view: {}", e))?; - - Ok(()) -} - -pub async fn drop_view( - params: &ConnectionParams, - view_name: &str, - schema: &str, -) -> Result<(), String> { - let pool = get_postgres_pool(params).await?; - let query = format!( - "DROP VIEW IF EXISTS \"{}\".\"{}\"", - escape_identifier(schema), - escape_identifier(view_name) - ); - - let client = pool.get().await.map_err(|e| e.to_string())?; - client - .execute(&query, &[]) - .await - .map_err(|e| format!("Failed to drop view: {}", e))?; - - Ok(()) -} - -pub async fn get_view_columns( - params: &ConnectionParams, - view_name: &str, - schema: &str, -) -> Result, String> { - let pool = get_postgres_pool(params).await?; - - let query = format!( - r#" - SELECT - c.column_name, - -- information_schema reports extension/composite/enum types as the - -- literal 'USER-DEFINED'; fall back to udt_name for the real type name - -- (e.g. pgvector's 'vector', 'halfvec', 'sparsevec'). - CASE - WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name::text - ELSE c.data_type::text - END AS data_type, - c.is_nullable, - c.column_default, - c.is_identity, - c.character_maximum_length, - c.numeric_precision, - c.numeric_scale, - (SELECT string_agg('''' || replace(e.enumlabel, '''', '''''') || '''', ',' ORDER BY e.enumsortorder) - FROM pg_enum e - JOIN pg_type t ON t.oid = e.enumtypid - JOIN pg_namespace tn ON tn.oid = t.typnamespace - WHERE t.typname = c.udt_name AND tn.nspname = c.udt_schema) AS enum_values, - format_type(a.atttypid, a.atttypmod) AS full_type, - {} - FROM information_schema.columns c - JOIN pg_namespace n ON n.nspname = c.table_schema - JOIN pg_class pc ON pc.relnamespace = n.oid AND pc.relname = c.table_name - JOIN pg_attribute a ON a.attrelid = pc.oid AND a.attname = c.column_name - WHERE c.table_schema = $1 AND c.table_name = $2 - ORDER BY c.ordinal_position - "#, - primary_key_exists_expression(), - ); - - let rows = query_all(&pool, query.as_str(), &[&schema, &view_name]).await?; - - Ok(rows - .iter() - .map(|r| { - let null_str: String = r.try_get("is_nullable").unwrap_or_default(); - let is_pk: bool = r.try_get("is_pk").unwrap_or(false); - let default_val: String = r.try_get("column_default").unwrap_or_default(); - let is_identity: String = r.try_get("is_identity").unwrap_or_default(); - let character_maximum_length: Option = r - .try_get::<_, Option>("character_maximum_length") - .ok() - .flatten() - .and_then(|v| u64::try_from(v).ok()); - let numeric_precision: Option = r - .try_get::<_, Option>("numeric_precision") - .ok() - .flatten(); - let numeric_scale: Option = - r.try_get::<_, Option>("numeric_scale").ok().flatten(); - - let is_auto = is_identity == "YES" || default_val.contains("nextval"); - - // Only set default_value if not auto-increment, not empty, and not NULL - // Filter out NULL defaults (PostgreSQL represents nullable without default as NULL or NULL::type) - let default_value = if !is_auto - && !default_val.is_empty() - && !default_val.eq_ignore_ascii_case("null") - && !default_val.starts_with("NULL::") - { - Some(default_val) - } else { - None - }; - - let enum_values: Option = r.try_get("enum_values").ok().flatten(); - let (data_type, full_type) = postgres_column_types( - r.try_get("data_type").unwrap_or_default(), - enum_values, - r.try_get("full_type").ok().flatten(), - ); - - TableColumn { - name: r.try_get("column_name").unwrap_or_default(), - data_type, - is_pk, - is_nullable: null_str == "YES", - is_auto_increment: is_auto, - is_generated: false, - // PostgreSQL reports the default as SQL already. - default_sql: default_value.clone(), - default_value, - character_maximum_length, - numeric_precision, - numeric_scale, - comment: None, - full_type, - on_update: None, - } - }) - .collect()) -} - -pub async fn get_materialized_views( - params: &ConnectionParams, - schema: &str, -) -> Result, String> { - log::debug!( - "PostgreSQL: Fetching materialized views for database: {} schema: {}", - params.database, - schema - ); - let pool = get_postgres_pool(params).await?; - let rows = query_all( - &pool, - "SELECT matviewname as name FROM pg_matviews WHERE schemaname = $1 ORDER BY matviewname ASC", - &[&schema], - ) - .await?; - - let views: Vec = rows - .iter() - .map(|r| ViewInfo { - name: r.try_get("name").unwrap_or_default(), - definition: None, - }) - .collect(); - Ok(views) -} - -/// Materialized views are not exposed via `information_schema.columns`, so their -/// columns must be read from the system catalog (`pg_attribute`/`pg_class`). -pub async fn get_materialized_view_columns( - params: &ConnectionParams, - view_name: &str, - schema: &str, -) -> Result, String> { - let pool = get_postgres_pool(params).await?; - let query = r#" - SELECT - a.attname AS column_name, - format_type(a.atttypid, a.atttypmod) AS data_type, - a.attnotnull AS not_null - FROM pg_attribute a - JOIN pg_class c ON c.oid = a.attrelid - JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind = 'm' - AND a.attnum > 0 AND NOT a.attisdropped - ORDER BY a.attnum - "#; - - let rows = query_all(&pool, query, &[&schema, &view_name]).await?; - - Ok(rows - .iter() - .map(|r| TableColumn { - name: r.try_get("column_name").unwrap_or_default(), - data_type: r.try_get("data_type").unwrap_or_default(), - is_pk: false, - is_nullable: !r.try_get::<_, bool>("not_null").unwrap_or(false), - is_auto_increment: false, - is_generated: false, - default_value: None, - character_maximum_length: None, - numeric_precision: None, - numeric_scale: None, - comment: None, - // `data_type` is already `format_type(...)` here. - full_type: None, - default_sql: None, - on_update: None, - }) - .collect()) -} - -pub async fn get_materialized_view_definition( - params: &ConnectionParams, - view_name: &str, - schema: &str, -) -> Result { - let pool = get_postgres_pool(params).await?; - let qualified = format!( - "\"{}\".\"{}\"", - escape_identifier(schema), - escape_identifier(view_name) - ); - - let client = pool.get().await.map_err(|e| e.to_string())?; - - // Resolve via pg_class/pg_namespace with a `relkind = 'm'` filter so only - // materialized views match — a regular view or table name returns no row - // (a clean "not found") instead of wrong DDL. `pg_get_viewdef` alone - // resolves any relation by name. Binding schema/name as separate text - // params also avoids the PG 16 "error serializing parameter 0" failure - // that a direct `regclass` bind triggers. - let row = client - .query_one( - "SELECT pg_get_viewdef(c.oid, true) AS definition \ - FROM pg_class c \ - JOIN pg_namespace n ON c.relnamespace = n.oid \ - WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind = 'm'", - &[&schema, &view_name], - ) - .await - .map_err(|e| format!("Failed to get materialized view definition: {}", e))?; - - let definition: String = row.try_get("definition").unwrap_or_default(); - Ok(format!( - "CREATE MATERIALIZED VIEW {} AS\n{}", - qualified, definition - )) -} - -pub async fn refresh_materialized_view( - params: &ConnectionParams, - view_name: &str, - schema: &str, -) -> Result<(), String> { - let pool = get_postgres_pool(params).await?; - let query = format!( - "REFRESH MATERIALIZED VIEW \"{}\".\"{}\"", - escape_identifier(schema), - escape_identifier(view_name) - ); - - let client = pool.get().await.map_err(|e| e.to_string())?; - client - .execute(&query, &[]) - .await - .map_err(|e| format!("Failed to refresh materialized view: {}", e))?; - - Ok(()) -} - -pub async fn get_routines( - params: &ConnectionParams, - schema: &str, -) -> Result, String> { - let pool = get_postgres_pool(params).await?; - - // `pg_proc.prokind` was introduced in PostgreSQL 11, replacing the boolean - // columns `proisagg` / `proiswindow`. On 9.x and 10 the column does not - // exist, so referencing it fails at parse time (SQLSTATE 42703). Pick the - // query based on the server version. - let server_version_num: i32 = query_one( - &pool, - "SELECT current_setting('server_version_num')::int4 AS v", - &[], - ) - .await? - .try_get("v") - .unwrap_or(0); - - // `pg_get_function_identity_arguments` comes along so the sidebar can tell - // overloads apart. Without it a name was the whole identity: four functions - // called `f` arrived as four identical rows, and every read that followed a - // click fell back to `LIMIT 1` (#893). The ORDER BY takes the signature as - // a second key so the order is stable rather than whatever the scan returns. - let query = if server_version_num >= 110000 { - r#" - SELECT - proname, - prokind, - pg_get_function_identity_arguments(oid) AS identity_args - FROM pg_proc - WHERE pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = $1) - AND prokind IN ('f', 'p') - ORDER BY proname, identity_args - "# - } else { - // Pre-11: procedures don't exist; exclude aggregates and window - // functions and report everything else as a plain function ('f'). - // Cast to the internal "char" type so it maps to i8 like prokind. - r#" - SELECT - proname, - 'f'::"char" AS prokind, - pg_get_function_identity_arguments(oid) AS identity_args - FROM pg_proc - WHERE pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = $1) - AND NOT proisagg - AND NOT proiswindow - ORDER BY proname, identity_args - "# - }; - - let rows = query_all(&pool, query, &[&schema]).await?; - - Ok(rows - .iter() - .map(|r| { - let prokind: i8 = r.try_get("prokind").unwrap_or(b'f' as i8); // f=function, p=procedure - let routine_type = match prokind as u8 as char { - 'p' => "PROCEDURE", - _ => "FUNCTION", - }; - - RoutineInfo { - name: r.try_get("proname").unwrap_or_default(), - routine_type: routine_type.to_string(), - definition: None, - // Always Some on this driver, including the empty string a - // no-argument routine has: that empty signature is what tells - // `f()` apart from `f(a integer)`, so it is a value and not an - // absence. `None` would mean "this dialect does not overload". - identity_args: Some(r.try_get("identity_args").unwrap_or_default()), - } - }) - .collect()) -} - -/// One routine's parameters, and its return type where it is a function. -/// -/// Both reads are keyed on `specific_name` when the caller passes a signature. -/// Filtered on schema and name alone, as they used to be, the return type came -/// from `LIMIT 1` over the overloads and the parameter join came back with ALL -/// of their parameters in one list: measured on PostgreSQL 18, three overloads -/// of `f` answered four rows, two of them at `ordinal_position` 1 with -/// different types. So the Run dialog could offer one overload's arguments -/// under another's name, and did (#893). -pub async fn get_routine_parameters( - params: &ConnectionParams, - routine_name: &str, - schema: &str, - identity_args: Option<&str>, -) -> Result, String> { - let pool = get_postgres_pool(params).await?; - let client = pool.get().await.map_err(|e| e.to_string())?; - - // `information_schema` cannot be reached from a signature, so the key it - // CAN be filtered by is derived from `pg_proc` first. A signature that - // names nothing leaves this None and both reads fall back to the old - // name-only form rather than answering about no routine at all. - // - // `nameconcatoid` is how the view itself builds that key, and it exists - // from PostgreSQL 12. Referencing it on an older server fails at parse - // time, so the expression is picked by version, exactly as the `prokind` - // read above is. - let specific_name: Option = match identity_args { - Some(identity) => { - let server_version_num: i32 = client - .query_one( - "SELECT current_setting('server_version_num')::int4 AS v", - &[], - ) - .await - .map_err(|e| format_pg_error(&e))? - .try_get("v") - .unwrap_or(0); - - client - .query_opt( - routines::routine_specific_name_sql(server_version_num >= 120000), - &[&schema, &routine_name, &identity], - ) - .await - .map_err(|e| format_pg_error(&e))? - .and_then(|row| row.try_get("specific_name").ok()) - } - None => None, - }; - - // 1. Get return type for functions - let routine_info = match specific_name.as_deref() { - Some(specific) => client - .query_opt( - routines::routine_return_type_sql(true), - &[&schema, &specific], - ) - .await - .map_err(|e| format_pg_error(&e))?, - None => client - .query_opt( - routines::routine_return_type_sql(false), - &[&schema, &routine_name], - ) - .await - .map_err(|e| format_pg_error(&e))?, - }; - - let mut parameters = Vec::new(); - - if let Some(info) = routine_info { - let routine_type: String = info.try_get("routine_type").unwrap_or_default(); - if routine_type == "FUNCTION" { - let data_type: String = info.try_get("data_type").unwrap_or_default(); - // Exclude void or trigger returns if not relevant - if !data_type.eq_ignore_ascii_case("void") && !data_type.eq_ignore_ascii_case("trigger") - { - parameters.push(RoutineParameter { - name: "".to_string(), // Empty name for return value - data_type, - mode: "OUT".to_string(), - ordinal_position: 0, - }); - } - } - } - - // 2. Get parameters - let rows = match specific_name.as_deref() { - Some(specific) => client - .query( - routines::routine_parameters_sql(true), - &[&schema, &specific], - ) - .await - .map_err(|e| format_pg_error(&e))?, - None => client - .query( - routines::routine_parameters_sql(false), - &[&schema, &routine_name], - ) - .await - .map_err(|e| format_pg_error(&e))?, - }; - - parameters.extend(rows.iter().map(|r| RoutineParameter { - name: r.try_get("parameter_name").unwrap_or_default(), - data_type: r.try_get("data_type").unwrap_or_default(), - mode: r.try_get("parameter_mode").unwrap_or_default(), - ordinal_position: r.try_get("ordinal_position").unwrap_or(0), - })); - - Ok(parameters) -} - -/// One routine's `CREATE OR REPLACE` statement. -/// -/// A schema and a name do not identify a routine in PostgreSQL, they identify -/// a set of overloads, so this used to take `LIMIT 1` out of that set and -/// answer about whichever row the scan returned: measured on 18, four -/// functions named `f` and View Definition showed `f()` for all of them (#893). -/// -/// `identity_args` is the signature `get_routines` reported for the row the -/// user clicked, and filtering on it picks exactly that routine. It is compared -/// as a string against the catalog's own rendering of the same thing, so the -/// two can only agree, and the empty string is the real signature of a -/// no-argument routine rather than a missing value. `None` keeps the old -/// lookup, for the callers that have no signature to pass. -pub async fn get_routine_definition( - params: &ConnectionParams, - routine_name: &str, - _routine_type: &str, - schema: &str, - identity_args: Option<&str>, -) -> Result { - let pool = get_postgres_pool(params).await?; - - let row = match identity_args { - Some(identity) => { - query_one( - &pool, - routines::routine_definition_sql(true), - &[&schema, &routine_name, &identity], - ) - .await? - } - None => { - query_one( - &pool, - routines::routine_definition_sql(false), - &[&schema, &routine_name], - ) - .await? - } - }; - - let definition: String = row.try_get("definition").unwrap_or_default(); - Ok(definition) -} - -/// Drops a routine, resolving its exact identity signature first: PostgreSQL -/// identifies routines by name *and* argument types, so a bare -/// `DROP FUNCTION name` fails as soon as overloads exist. -pub async fn drop_routine( - params: &ConnectionParams, - routine_name: &str, - routine_type: &str, - schema: &str, - identity_args: Option<&str>, -) -> Result<(), String> { - let pool = get_postgres_pool(params).await?; - - // The signature the caller clicked, where it has one. Before #893 nothing - // reached here but a name, so a name with overloads had no answer but to - // refuse and tell the reader to go and write the DROP themselves. - if let Some(identity) = identity_args { - let exists = query_all( - &pool, - routines::routine_exists_sql(), - &[&schema, &routine_name, &identity], - ) - .await?; - - if exists.is_empty() { - return Err(format!( - "Routine '{}({})' not found in schema '{}'", - routine_name, identity, schema - )); - } - - let sql = routines::drop_routine_sql(routine_name, routine_type, identity, Some(schema)); - return execute(&pool, &sql, &[]).await.map(|_| ()); - } - - let query = r#" - SELECT pg_get_function_identity_arguments(p.oid) AS args - FROM pg_proc p - JOIN pg_namespace n ON p.pronamespace = n.oid - WHERE n.nspname = $1 AND p.proname = $2 - "#; - let rows = query_all(&pool, query, &[&schema, &routine_name]).await?; - - match rows.len() { - 0 => Err(format!( - "Routine '{}' not found in schema '{}'", - routine_name, schema - )), - 1 => { - let identity_args: String = rows[0].try_get("args").unwrap_or_default(); - let sql = routines::drop_routine_sql( - routine_name, - routine_type, - &identity_args, - Some(schema), - ); - execute(&pool, &sql, &[]).await.map(|_| ()) - } - n => Err(format!( - "Routine '{}' has {} overloads; drop it manually specifying the argument types", - routine_name, n - )), - } -} - -pub async fn get_triggers( - params: &ConnectionParams, - schema: &str, -) -> Result, String> { - log::debug!( - "PostgreSQL: Fetching triggers for database: {} schema: {}", - params.database, - schema - ); - let pool = get_postgres_pool(params).await?; - let query = r#" - SELECT - t.trigger_name AS name, - t.event_object_table AS table_name, - string_agg(t.event_manipulation, ' OR ' ORDER BY t.event_manipulation) AS event, - t.action_timing AS timing - FROM information_schema.triggers t - WHERE t.trigger_schema = $1 - GROUP BY t.trigger_name, t.event_object_table, t.action_timing - ORDER BY t.trigger_name - "#; - let rows = query_all(&pool, query, &[&schema]).await?; - let triggers: Vec = rows - .iter() - .map(|r| TriggerInfo { - name: r.try_get("name").unwrap_or_default(), - table_name: r.try_get("table_name").unwrap_or_default(), - event: r.try_get("event").unwrap_or_default(), - timing: r.try_get("timing").unwrap_or_default(), - definition: None, - }) - .collect(); - log::debug!( - "PostgreSQL: Found {} triggers in {}", - triggers.len(), - schema - ); - Ok(triggers) -} - -pub async fn get_trigger_definition( - params: &ConnectionParams, - trigger_name: &str, - table_name: &str, - schema: &str, -) -> Result { - let pool = get_postgres_pool(params).await?; - let query = r#" - SELECT pg_get_triggerdef(t.oid, true) AS definition - FROM pg_trigger t - JOIN pg_class c ON t.tgrelid = c.oid - JOIN pg_namespace n ON c.relnamespace = n.oid - WHERE t.tgname = $1 - AND c.relname = $2 - AND n.nspname = $3 - AND NOT t.tgisinternal - LIMIT 1 - "#; - let row = query_one(&pool, query, &[&trigger_name, &table_name, &schema]).await?; - let definition: String = row - .try_get("definition") - .map_err(|e| format!("Failed to get trigger definition: {}", e))?; - Ok(definition) -} - -pub async fn create_trigger( - params: &ConnectionParams, - trigger_sql: &str, - _schema: &str, -) -> Result<(), String> { - let pool = get_postgres_pool(params).await?; - execute(&pool, trigger_sql, &[]) - .await - .map_err(|e| format!("Failed to create trigger: {}", e))?; - Ok(()) -} - -pub async fn drop_trigger( - params: &ConnectionParams, - trigger_name: &str, - table_name: &str, - schema: &str, -) -> Result<(), String> { - let pool = get_postgres_pool(params).await?; - let sql = format!( - "DROP TRIGGER IF EXISTS {} ON {}.{}", - escape_identifier(trigger_name), - escape_identifier(schema), - escape_identifier(table_name), - ); - execute(&pool, &sql, &[]) - .await - .map_err(|e| format!("Failed to drop trigger: {}", e))?; - Ok(()) -} - -// ============================================================ -// Plugin wrapper -// ============================================================ - -use crate::drivers::driver_trait::{ - deprecation_for_builtin, DatabaseDriver, DriverCapabilities, PluginManifest, - PluginSettingDefinition, SqlDialect, -}; -use async_trait::async_trait; -use std::collections::HashMap; - -pub struct PostgresDriver { - manifest: PluginManifest, -} - -impl PostgresDriver { - pub fn new() -> Self { - Self { - manifest: PluginManifest { - id: "postgres".to_string(), - name: "PostgreSQL".to_string(), - version: "1.0.0".to_string(), - description: "PostgreSQL databases".to_string(), - default_port: Some(5432), - capabilities: DriverCapabilities { - schemas: true, - single_database: false, - views: true, - materialized_views: true, - routines: true, - routine_management: true, - routine_debug: None, - file_based: false, - folder_based: false, - in_memory: false, - data_files: Vec::new(), - connection_string: true, - connection_string_example: "postgres://user:pass@localhost:5432/db".into(), - connection_string_examples: Vec::new(), - connection_uri: false, - connection_uri_schemes: Vec::new(), - socks5_proxy: false, - identifier_quote: "\"".into(), - alter_primary_key: true, - auto_increment_keyword: String::new(), - serial_type: "SERIAL".into(), - inline_pk: false, - table_query_templates: false, - column_comments: true, - drop_table_sql: false, - column_stats: false, - query_classification: false, - query_timeout: true, - alter_column: true, - create_foreign_keys: true, - no_connection_required: false, - manage_tables: true, - explain: true, - readonly: false, - read_only_queries: true, - table_export: None, - table_import: None, - triggers: true, - supports_ssl: true, - user_management: false, - unix_socket: true, - sql_dialect: Some(SqlDialect::Postgres), - sql_syntax: None, - }, - is_builtin: true, - engine: Some("postgres".to_string()), - paradigms: vec!["sql".to_string()], - default_username: "postgres".to_string(), - color: "#3b82f6".to_string(), - icon: "postgres".to_string(), - settings: vec![PluginSettingDefinition { - key: "poolMaxSize".to_string(), - label: "Pool Max Size".to_string(), - setting_type: "number".to_string(), - default: Some(serde_json::json!( - crate::pool_manager::DEFAULT_POSTGRES_POOL_MAX_SIZE - )), - description: Some( - "Maximum number of PostgreSQL connections kept in the pool.".to_string(), - ), - required: false, - options: vec![], - }], - ui_extensions: None, - explain_parsers: None, - connection_fields: None, - type_mappings: std::collections::HashMap::new(), - // The built-in postgres driver is deprecated in favour of the - // standalone `postgresql` plugin; the decision lives in the - // single `deprecation_for_builtin` table. - deprecated: deprecation_for_builtin("postgres"), - }, - } - } - - fn resolve_schema<'a>(&self, schema: Option<&'a str>) -> &'a str { - schema.unwrap_or("public") - } -} - -#[async_trait] -impl DatabaseDriver for PostgresDriver { - fn manifest(&self) -> &PluginManifest { - &self.manifest - } - - fn get_data_types(&self) -> Vec { - types::get_data_types() - } - - fn map_inferred_type(&self, kind: &str) -> String { - match kind { - "DATETIME" => "TIMESTAMP".to_string(), - "JSON" => "JSONB".to_string(), - other => other.to_string(), - } - } - - fn build_connection_url( - &self, - params: &crate::models::ConnectionParams, - ) -> Result { - use urlencoding::encode; - let user = encode(params.username.as_deref().unwrap_or_default()); - let pass = encode(params.password.as_deref().unwrap_or_default()); - let sslmode = match params.ssl_mode.as_deref() { - Some("disable") => "disable", - Some("allow") => "allow", - Some("prefer") => "prefer", - Some("require") => "require", - Some("verify-ca") => "verify-ca", - Some("verify-full") => "verify-full", - _ => "prefer", - }; - Ok(format!( - "postgres://{}:{}@{}:{}/{}?sslmode={}", - user, - pass, - params.host.as_deref().unwrap_or("localhost"), - params.port.unwrap_or(5432), - params.database, - sslmode - )) - } - - async fn ping(&self, params: &crate::models::ConnectionParams) -> Result<(), String> { - let conn_id = params.connection_id.as_deref(); - if !crate::pool_manager::has_pool(params, conn_id).await { - return Err("No active connection pool".into()); - } - let pool = crate::pool_manager::get_postgres_pool_with_id(params, conn_id).await?; - let client = pool - .get() - .await - .map_err(|e| crate::pool_manager::format_error_chain(&e))?; - client - .simple_query("SELECT 1") - .await - .map_err(|e| crate::pool_manager::format_error_chain(&e))?; - Ok(()) - } - - async fn test_connection( - &self, - params: &crate::models::ConnectionParams, - ) -> Result<(), String> { - let cfg = crate::pool_manager::build_postgres_configurations(params)?; - let tls_connector = crate::pool_manager::build_postgres_tls_connector(params)?; - crate::pool_manager::with_connect_timeout(params, async { - let (client, connection) = cfg - .connect(tls_connector) - .await - .map_err(|e| crate::pool_manager::format_error_chain(&e))?; - tokio::spawn(async move { - if let Err(e) = connection.await { - log::debug!("Postgres test_connection connection background task ended: {e}"); - } - }); - client - .simple_query("SELECT 1") - .await - .map_err(|e| crate::pool_manager::format_error_chain(&e))?; - Ok(()) - }) - .await - } - - async fn get_databases( - &self, - params: &crate::models::ConnectionParams, - ) -> Result, String> { - let mut p = params.clone(); - p.database = crate::models::DatabaseSelection::Single("postgres".to_string()); - get_databases(&p).await - } - - async fn get_schemas( - &self, - params: &crate::models::ConnectionParams, - ) -> Result, String> { - get_schemas(params).await - } - - async fn get_tables( - &self, - params: &crate::models::ConnectionParams, - schema: Option<&str>, - ) -> Result, String> { - get_tables(params, self.resolve_schema(schema)).await - } - - async fn get_columns( - &self, - params: &crate::models::ConnectionParams, - table: &str, - schema: Option<&str>, - ) -> Result, String> { - get_columns(params, table, self.resolve_schema(schema)).await - } - - async fn get_foreign_keys( - &self, - params: &crate::models::ConnectionParams, - table: &str, - schema: Option<&str>, - ) -> Result, String> { - get_foreign_keys(params, table, self.resolve_schema(schema)).await - } - - async fn get_indexes( - &self, - params: &crate::models::ConnectionParams, - table: &str, - schema: Option<&str>, - ) -> Result, String> { - get_indexes(params, table, self.resolve_schema(schema)).await - } - - async fn get_views( - &self, - params: &crate::models::ConnectionParams, - schema: Option<&str>, - ) -> Result, String> { - get_views(params, self.resolve_schema(schema)).await - } - - async fn get_view_definition( - &self, - params: &crate::models::ConnectionParams, - view_name: &str, - schema: Option<&str>, - ) -> Result { - get_view_definition(params, view_name, self.resolve_schema(schema)).await - } - - async fn get_view_columns( - &self, - params: &crate::models::ConnectionParams, - view_name: &str, - schema: Option<&str>, - ) -> Result, String> { - get_view_columns(params, view_name, self.resolve_schema(schema)).await - } - - async fn create_view( - &self, - params: &crate::models::ConnectionParams, - view_name: &str, - definition: &str, - schema: Option<&str>, - ) -> Result<(), String> { - create_view(params, view_name, definition, self.resolve_schema(schema)).await - } - - async fn alter_view( - &self, - params: &crate::models::ConnectionParams, - view_name: &str, - definition: &str, - schema: Option<&str>, - ) -> Result<(), String> { - alter_view(params, view_name, definition, self.resolve_schema(schema)).await - } - - async fn drop_view( - &self, - params: &crate::models::ConnectionParams, - view_name: &str, - schema: Option<&str>, - ) -> Result<(), String> { - drop_view(params, view_name, self.resolve_schema(schema)).await - } - - async fn get_materialized_views( - &self, - params: &crate::models::ConnectionParams, - schema: Option<&str>, - ) -> Result, String> { - get_materialized_views(params, self.resolve_schema(schema)).await - } - - async fn get_materialized_view_columns( - &self, - params: &crate::models::ConnectionParams, - view_name: &str, - schema: Option<&str>, - ) -> Result, String> { - get_materialized_view_columns(params, view_name, self.resolve_schema(schema)).await - } - - async fn get_materialized_view_definition( - &self, - params: &crate::models::ConnectionParams, - view_name: &str, - schema: Option<&str>, - ) -> Result { - get_materialized_view_definition(params, view_name, self.resolve_schema(schema)).await - } - - async fn refresh_materialized_view( - &self, - params: &crate::models::ConnectionParams, - view_name: &str, - schema: Option<&str>, - ) -> Result<(), String> { - refresh_materialized_view(params, view_name, self.resolve_schema(schema)).await - } - - async fn get_routines( - &self, - params: &crate::models::ConnectionParams, - schema: Option<&str>, - ) -> Result, String> { - get_routines(params, self.resolve_schema(schema)).await - } - - async fn get_routine_parameters( - &self, - params: &crate::models::ConnectionParams, - routine_name: &str, - schema: Option<&str>, - identity_args: Option<&str>, - ) -> Result, String> { - get_routine_parameters( - params, - routine_name, - self.resolve_schema(schema), - identity_args, - ) - .await - } - - async fn get_routine_definition( - &self, - params: &crate::models::ConnectionParams, - routine_name: &str, - routine_type: &str, - schema: Option<&str>, - identity_args: Option<&str>, - ) -> Result { - get_routine_definition( - params, - routine_name, - routine_type, - self.resolve_schema(schema), - identity_args, - ) - .await - } - - async fn build_routine_call_sql( - &self, - _params: &crate::models::ConnectionParams, - routine_name: &str, - routine_type: &str, - args: &[crate::models::RoutineCallArg], - schema: Option<&str>, - ) -> Result { - Ok(routines::routine_call_sql( - routine_name, - routine_type, - args, - Some(self.resolve_schema(schema)), - )) - } - - async fn routine_create_template( - &self, - routine_type: &str, - schema: Option<&str>, - ) -> Result { - Ok(routines::routine_create_template( - routine_type, - Some(self.resolve_schema(schema)), - )) - } - - // `get_routine_edit_script` keeps the trait default: `pg_get_functiondef` - // already returns a re-runnable `CREATE OR REPLACE` statement. - - async fn drop_routine( - &self, - params: &crate::models::ConnectionParams, - routine_name: &str, - routine_type: &str, - schema: Option<&str>, - identity_args: Option<&str>, - ) -> Result<(), String> { - drop_routine( - params, - routine_name, - routine_type, - self.resolve_schema(schema), - identity_args, - ) - .await - } - - async fn get_triggers( - &self, - params: &crate::models::ConnectionParams, - schema: Option<&str>, - ) -> Result, String> { - get_triggers(params, self.resolve_schema(schema)).await - } - - async fn get_trigger_definition( - &self, - params: &crate::models::ConnectionParams, - trigger_name: &str, - table_name: &str, - schema: Option<&str>, - ) -> Result { - get_trigger_definition( - params, - trigger_name, - table_name, - self.resolve_schema(schema), - ) - .await - } - - async fn create_trigger( - &self, - params: &crate::models::ConnectionParams, - trigger_sql: &str, - schema: Option<&str>, - ) -> Result<(), String> { - create_trigger(params, trigger_sql, self.resolve_schema(schema)).await - } - - async fn drop_trigger( - &self, - params: &crate::models::ConnectionParams, - trigger_name: &str, - table_name: &str, - schema: Option<&str>, - ) -> Result<(), String> { - drop_trigger( - params, - trigger_name, - table_name, - self.resolve_schema(schema), - ) - .await - } - - async fn execute_query( - &self, - params: &crate::models::ConnectionParams, - query: &str, - limit: Option, - page: u32, - schema: Option<&str>, - ) -> Result { - execute_query(params, query, limit, page, schema).await - } - - async fn execute_query_in_session( - &self, - params: &crate::models::ConnectionParams, - query: &str, - limit: Option, - page: u32, - schema: Option<&str>, - session_id: Option<&str>, - ) -> Result<(crate::models::QueryResult, bool), String> { - execute_query_in_session(params, query, limit, page, schema, session_id).await - } - - async fn execute_read_only_query( - &self, - params: &crate::models::ConnectionParams, - query: &str, - limit: Option, - page: u32, - schema: Option<&str>, - ) -> Result { - execute_read_only_query(params, query, limit, page, schema).await - } - - async fn execute_batch( - &self, - params: &crate::models::ConnectionParams, - queries: &[String], - limit: Option, - page: u32, - schema: Option<&str>, - on_progress: Option<&crate::drivers::driver_trait::BatchProgressFn>, - ) -> Result, String> { - execute_batch(params, queries, limit, page, schema, on_progress).await - } - - async fn execute_batch_in_session( - &self, - params: &crate::models::ConnectionParams, - queries: &[String], - limit: Option, - page: u32, - schema: Option<&str>, - session_id: Option<&str>, - on_progress: Option<&crate::drivers::driver_trait::BatchProgressFn>, - ) -> Result<(Vec, bool), String> { - execute_batch_in_session( - params, - queries, - limit, - page, - schema, - session_id, - on_progress, - ) - .await - } - - async fn release_session(&self, session_id: &str) { - session::release(session_id).await; - } - - async fn session_in_transaction(&self, session_id: &str) -> Option { - Some(session::is_pinned(session_id).await) - } - - async fn explain_query( - &self, - params: &crate::models::ConnectionParams, - query: &str, - analyze: bool, - schema: Option<&str>, - ) -> Result { - explain_query(params, query, analyze, schema).await - } - - async fn insert_record( - &self, - params: &crate::models::ConnectionParams, - table: &str, - data: std::collections::HashMap, - schema: Option<&str>, - max_blob_size: u64, - ) -> Result { - insert_record( - params, - table, - data, - self.resolve_schema(schema), - max_blob_size, - ) - .await - } - - async fn update_record( - &self, - params: &crate::models::ConnectionParams, - table: &str, - pk_map: &std::collections::HashMap, - col_name: &str, - new_val: serde_json::Value, - schema: Option<&str>, - max_blob_size: u64, - ) -> Result { - update_record( - params, - table, - pk_map, - col_name, - new_val, - self.resolve_schema(schema), - max_blob_size, - ) - .await - } - - async fn delete_record( - &self, - params: &crate::models::ConnectionParams, - table: &str, - pk_map: &std::collections::HashMap, - schema: Option<&str>, - ) -> Result { - delete_record(params, table, pk_map, self.resolve_schema(schema)).await - } - - async fn save_blob_to_file( - &self, - params: &crate::models::ConnectionParams, - table: &str, - col_name: &str, - pk_map: &std::collections::HashMap, - schema: Option<&str>, - file_path: &str, - ) -> Result<(), String> { - save_blob_column_to_file( - params, - table, - col_name, - pk_map, - self.resolve_schema(schema), - file_path, - ) - .await - } - - async fn fetch_blob_as_data_url( - &self, - params: &crate::models::ConnectionParams, - table: &str, - col_name: &str, - pk_map: &std::collections::HashMap, - schema: Option<&str>, - ) -> Result { - fetch_blob_column_as_data_url(params, table, col_name, pk_map, self.resolve_schema(schema)) - .await - } - - async fn get_create_table_sql( - &self, - table_name: &str, - columns: Vec, - schema: Option<&str>, - ) -> Result, String> { - let pg_schema = self.resolve_schema(schema); - let mut col_defs = Vec::new(); - let mut pk_cols = Vec::new(); - for col in &columns { - let type_str = if col.is_auto_increment { - let upper = col.data_type.to_uppercase(); - if upper.contains("BIGINT") || upper.contains("BIGSERIAL") { - "BIGSERIAL".to_string() - } else if upper.contains("SMALLINT") || upper.contains("SMALLSERIAL") { - "SMALLSERIAL".to_string() - } else { - "SERIAL".to_string() - } - } else { - col.data_type.clone() - }; - let mut def = format!("\"{}\" {}", col.name.replace('"', "\"\""), type_str); - if !col.is_nullable && !col.is_auto_increment { - def.push_str(" NOT NULL"); - } - if let Some(default) = &col.default_value { - if !col.is_auto_increment { - def.push_str(&format!(" DEFAULT {}", default)); - } - } - col_defs.push(def); - if col.is_pk { - pk_cols.push(format!("\"{}\"", col.name.replace('"', "\"\""))); - } - } - if !pk_cols.is_empty() { - col_defs.push(format!("PRIMARY KEY ({})", pk_cols.join(", "))); - } - Ok(vec![format!( - "CREATE TABLE \"{}\".\"{}\" (\n {}\n)", - pg_schema.replace('"', "\"\""), - table_name.replace('"', "\"\""), - col_defs.join(",\n ") - )]) - } - - async fn get_add_column_sql( - &self, - table: &str, - column: crate::models::ColumnDefinition, - schema: Option<&str>, - ) -> Result, String> { - let pg_schema = self.resolve_schema(schema); - let tbl = format!( - "\"{}\".\"{}\"", - pg_schema.replace('"', "\"\""), - table.replace('"', "\"\"") - ); - let type_str = if column.is_auto_increment { - let upper = column.data_type.to_uppercase(); - if upper.contains("BIGINT") || upper.contains("BIGSERIAL") { - "BIGSERIAL".to_string() - } else if upper.contains("SMALLINT") || upper.contains("SMALLSERIAL") { - "SMALLSERIAL".to_string() - } else { - "SERIAL".to_string() - } - } else { - column.data_type.clone() - }; - let mut def = format!( - "ALTER TABLE {} ADD COLUMN \"{}\" {}", - tbl, - column.name.replace('"', "\"\""), - type_str - ); - if !column.is_nullable && !column.is_auto_increment { - def.push_str(" NOT NULL"); - } - if let Some(default) = &column.default_value { - if !column.is_auto_increment { - def.push_str(&format!(" DEFAULT {}", default)); - } - } - let mut stmts = vec![def]; - if let Some(comment) = column.comment.as_deref().filter(|value| !value.is_empty()) { - stmts.push(column_comments::comment_sql( - &tbl, - &column.name, - Some(comment), - )); - } - Ok(stmts) - } - - async fn get_alter_column_sql( - &self, - table: &str, - old_column: crate::models::ColumnDefinition, - new_column: crate::models::ColumnDefinition, - schema: Option<&str>, - ) -> Result, String> { - let pg_schema = self.resolve_schema(schema); - let tbl = format!( - "\"{}\".\"{}\"", - pg_schema.replace('"', "\"\""), - table.replace('"', "\"\"") - ); - let old_name = format!("\"{}\"", old_column.name.replace('"', "\"\"")); - let new_name_quoted = format!("\"{}\"", new_column.name.replace('"', "\"\"")); - let mut stmts = Vec::new(); - - if old_column.name != new_column.name { - stmts.push(format!( - "ALTER TABLE {} RENAME COLUMN {} TO {}", - tbl, old_name, new_name_quoted - )); - } - - let col_ref = &new_name_quoted; - - if old_column.data_type != new_column.data_type { - let old_base = extract_base_type(&old_column.data_type); - let new_base = extract_base_type(&new_column.data_type); - - if is_implicit_cast_compatible(&old_base, &new_base) { - stmts.push(format!( - "ALTER TABLE {} ALTER COLUMN {} TYPE {}", - tbl, col_ref, new_column.data_type - )); - } else { - stmts.push(format!( - "ALTER TABLE {} ALTER COLUMN {} TYPE {} USING {}::{}", - tbl, col_ref, new_column.data_type, col_ref, new_column.data_type - )); - } - } - - if old_column.is_nullable != new_column.is_nullable { - if new_column.is_nullable { - stmts.push(format!( - "ALTER TABLE {} ALTER COLUMN {} DROP NOT NULL", - tbl, col_ref - )); - } else { - stmts.push(format!( - "ALTER TABLE {} ALTER COLUMN {} SET NOT NULL", - tbl, col_ref - )); - } - } - - if old_column.default_value != new_column.default_value { - if let Some(default) = &new_column.default_value { - stmts.push(format!( - "ALTER TABLE {} ALTER COLUMN {} SET DEFAULT {}", - tbl, col_ref, default - )); - } else { - stmts.push(format!( - "ALTER TABLE {} ALTER COLUMN {} DROP DEFAULT", - tbl, col_ref - )); - } - } - - if old_column.comment.as_deref().unwrap_or("") - != new_column.comment.as_deref().unwrap_or("") - { - stmts.push(column_comments::comment_sql( - &tbl, - &new_column.name, - new_column.comment.as_deref(), - )); - } - - if stmts.is_empty() { - return Err("No changes detected".into()); - } - Ok(stmts) - } - - async fn get_create_index_sql( - &self, - table: &str, - index_name: &str, - columns: Vec, - is_unique: bool, - schema: Option<&str>, - ) -> Result, String> { - let pg_schema = self.resolve_schema(schema); - let unique = if is_unique { "UNIQUE " } else { "" }; - let cols: Vec = columns - .iter() - .map(|c| format!("\"{}\"", c.replace('"', "\"\""))) - .collect(); - Ok(vec![format!( - "CREATE {}INDEX \"{}\" ON \"{}\".\"{}\" ({})", - unique, - index_name.replace('"', "\"\""), - pg_schema.replace('"', "\"\""), - table.replace('"', "\"\""), - cols.join(", ") - )]) - } - - async fn get_create_foreign_key_sql( - &self, - _params: &crate::models::ConnectionParams, - table: &str, - fk_name: &str, - column: &str, - ref_table: &str, - ref_column: &str, - on_delete: Option<&str>, - on_update: Option<&str>, - schema: Option<&str>, - ) -> Result, String> { - let pg_schema = self.resolve_schema(schema); - let tbl = format!( - "\"{}\".\"{}\"", - pg_schema.replace('"', "\"\""), - table.replace('"', "\"\"") - ); - let mut query = format!( - "ALTER TABLE {} ADD CONSTRAINT \"{}\" FOREIGN KEY (\"{}\") REFERENCES \"{}\".\"{}\" (\"{}\")", - tbl, - fk_name.replace('"', "\"\""), - column.replace('"', "\"\""), - pg_schema.replace('"', "\"\""), - ref_table.replace('"', "\"\""), - ref_column.replace('"', "\"\"") - ); - if let Some(action) = on_delete { - query.push_str(&format!(" ON DELETE {}", action)); - } - if let Some(action) = on_update { - query.push_str(&format!(" ON UPDATE {}", action)); - } - Ok(vec![query]) - } - - async fn get_table_ddl( - &self, - params: &crate::models::ConnectionParams, - table: &str, - schema: Option<&str>, - ) -> Result { - get_table_ddl(params, table, &self.resolve_schema(schema)).await - } - - async fn get_approximate_row_count( - &self, - params: &crate::models::ConnectionParams, - table: &str, - schema: Option<&str>, - ) -> Result, String> { - get_approximate_row_count(params, table, &self.resolve_schema(schema)).await - } - - async fn drop_index( - &self, - params: &crate::models::ConnectionParams, - _table: &str, - index_name: &str, - schema: Option<&str>, - ) -> Result<(), String> { - let pg_schema = self.resolve_schema(schema); - let query = format!( - "DROP INDEX \"{}\".\"{}\"", - pg_schema.replace('"', "\"\""), - index_name.replace('"', "\"\"") - ); - execute_query(params, &query, None, 1, schema).await?; - Ok(()) - } - - async fn drop_foreign_key( - &self, - params: &crate::models::ConnectionParams, - table: &str, - fk_name: &str, - schema: Option<&str>, - ) -> Result<(), String> { - let pg_schema = self.resolve_schema(schema); - let query = format!( - "ALTER TABLE \"{}\".\"{}\" DROP CONSTRAINT \"{}\"", - pg_schema.replace('"', "\"\""), - table.replace('"', "\"\""), - fk_name.replace('"', "\"\"") - ); - execute_query(params, &query, None, 1, schema).await?; - Ok(()) - } - - async fn get_all_columns_batch( - &self, - params: &crate::models::ConnectionParams, - schema: Option<&str>, - ) -> Result>, String> { - get_all_columns_batch(params, self.resolve_schema(schema)).await - } - - async fn get_all_foreign_keys_batch( - &self, - params: &crate::models::ConnectionParams, - schema: Option<&str>, - ) -> Result>, String> { - get_all_foreign_keys_batch(params, self.resolve_schema(schema)).await - } - - async fn get_schema_snapshot( - &self, - params: &crate::models::ConnectionParams, - schema: Option<&str>, - ) -> Result, String> { - let pg_schema = self.resolve_schema(schema); - let tables = get_tables(params, pg_schema).await?; - let mut columns_map = get_all_columns_batch(params, pg_schema).await?; - let mut fks_map = get_all_foreign_keys_batch(params, pg_schema).await?; - Ok(tables - .into_iter() - .map(|t| crate::models::TableSchema { - name: t.name.clone(), - columns: columns_map.remove(&t.name).unwrap_or_default(), - foreign_keys: fks_map.remove(&t.name).unwrap_or_default(), - }) - .collect()) - } -} diff --git a/src-tauri/src/drivers/postgres/routines.rs b/src-tauri/src/drivers/postgres/routines.rs deleted file mode 100644 index 069b10d73..000000000 --- a/src-tauri/src/drivers/postgres/routines.rs +++ /dev/null @@ -1,241 +0,0 @@ -//! PostgreSQL-dialect SQL builders for stored-routine management. -//! -//! Pure string builders; the trait overrides in `mod.rs` delegate here so -//! the generation logic stays unit-testable without a live server. - -use crate::drivers::common::{quote_qualified, render_sql_literal}; -use crate::models::RoutineCallArg; - -/// Builds the invocation script. Functions go through `SELECT * FROM` so -/// both scalar and set-returning functions come back as a result set; their -/// pure `OUT` parameters are NOT part of the call signature in PostgreSQL, so -/// they are excluded from the argument list (passing them raises -/// `function ... does not exist`). Procedures use `CALL`; there OUT parameters -/// ARE required in the argument list and are rendered as `NULL` placeholders, -/// with INOUT values echoed back by the server as the procedure's result row. -pub(super) fn routine_call_sql( - routine_name: &str, - routine_type: &str, - args: &[RoutineCallArg], - schema: Option<&str>, -) -> String { - let name = quote_qualified(routine_name, schema, "\""); - let is_function = routine_type.eq_ignore_ascii_case("FUNCTION"); - let rendered: Vec = args - .iter() - .filter(|arg| !(is_function && arg.mode.eq_ignore_ascii_case("OUT"))) - .map(render_sql_literal) - .collect(); - let arg_list = rendered.join(", "); - if is_function { - format!("SELECT * FROM {}({});", name, arg_list) - } else { - format!("CALL {}({});", name, arg_list) - } -} - -/// Starter script for a new routine. `CREATE OR REPLACE` keeps the script -/// re-runnable while iterating on the body. -pub(super) fn routine_create_template(routine_type: &str, schema: Option<&str>) -> String { - let prefix = match schema { - Some(s) if !s.is_empty() => format!("\"{}\".", s.replace('"', "\"\"")), - _ => String::new(), - }; - if routine_type.eq_ignore_ascii_case("FUNCTION") { - format!( - r#"CREATE OR REPLACE FUNCTION {prefix}my_function(p_value integer) -RETURNS integer -LANGUAGE plpgsql -AS $$ -BEGIN - RETURN p_value; -END; -$$; -"# - ) - } else { - format!( - r#"CREATE OR REPLACE PROCEDURE {prefix}my_procedure(p_value integer) -LANGUAGE plpgsql -AS $$ -BEGIN - RAISE NOTICE 'value: %', p_value; -END; -$$; -"# - ) - } -} - -/// `DROP` statement for a routine identified by its exact signature (the -/// output of `pg_get_function_identity_arguments`), which is how PostgreSQL -/// disambiguates overloads. -pub(super) fn drop_routine_sql( - routine_name: &str, - routine_type: &str, - identity_args: &str, - schema: Option<&str>, -) -> String { - let keyword = if routine_type.eq_ignore_ascii_case("PROCEDURE") { - "PROCEDURE" - } else { - "FUNCTION" - }; - format!( - "DROP {} {}({})", - keyword, - quote_qualified(routine_name, schema, "\""), - identity_args - ) -} - -/// The catalog lookup for one routine's definition. -/// -/// Two forms, because a schema and a name do not identify a routine in -/// PostgreSQL: they identify a set of overloads. With a signature the lookup -/// names one row and needs no `LIMIT`; without one it is the pre-#893 read, -/// which takes whichever row the scan returns and is kept for the callers that -/// have no signature to pass. -pub(super) fn routine_definition_sql(by_identity: bool) -> &'static str { - if by_identity { - r#" - SELECT pg_get_functiondef(p.oid) AS definition - FROM pg_proc p - JOIN pg_namespace n ON p.pronamespace = n.oid - WHERE n.nspname = $1 - AND p.proname = $2 - AND pg_get_function_identity_arguments(p.oid) = $3 - "# - } else { - r#" - SELECT pg_get_functiondef(p.oid) AS definition - FROM pg_proc p - JOIN pg_namespace n ON p.pronamespace = n.oid - WHERE n.nspname = $1 AND p.proname = $2 - LIMIT 1 - "# - } -} - -/// Whether one exact overload is there, for the `DROP` path to check before it -/// builds a statement naming a signature the server may not have. -pub(super) fn routine_exists_sql() -> &'static str { - r#" - SELECT 1 - FROM pg_proc p - JOIN pg_namespace n ON p.pronamespace = n.oid - WHERE n.nspname = $1 - AND p.proname = $2 - AND pg_get_function_identity_arguments(p.oid) = $3 - "# -} - -/// `information_schema.specific_name` for one overload, from its signature. -/// -/// That column is the only key `information_schema.parameters` can be filtered -/// by, and the two views offer no way to reach it from a signature, so it has -/// to be derived. The derivation uses the SAME function the view does rather -/// than reimplementing it, because the obvious reimplementation is wrong. -/// -/// `proname || '_' || oid` is what it looks like, and it does not fit in a -/// `name`. Since PostgreSQL 12 the view builds the column with -/// `nameconcatoid`, which truncates the NAME part so the OID survives inside 63 -/// bytes; the plain concatenation does not truncate at all. Measured on -/// PostgreSQL 18 with a 60-character routine name: -/// -/// ```text -/// proname || '_' || oid fn_with_a_really_long_name_to_hit_namedatalen_limit_abcdefgh_16385 -/// nameconcatoid fn_with_a_really_long_name_to_hit_namedatalen_limit_abcde_16385 -/// specific_name fn_with_a_really_long_name_to_hit_namedatalen_limit_abcde_16385 -/// ``` -/// -/// So the plain form matched nothing for a long-named routine, and the caller -/// answered with no parameters and no return type - for every long-named -/// routine on the server, overloaded or not, because the UI always sends a -/// signature on this driver (#926 review). -/// -/// Before 12 nothing is truncated at all, so the plain concatenation is right -/// there. `sql_identifier` was a domain over `character varying` until 12 turned -/// it into `name` and added `nameconcatoid` in the same release. Measured on -/// PostgreSQL 11.16, same routine: -/// -/// ```text -/// sql_identifier base type character varying -/// specific_name fn_..._abcdefgh_16385 (66 characters, untruncated) -/// (proname || '_' || oid)::text matches -/// (proname || '_' || oid)::name does NOT match - truncated to 63 -/// ``` -/// -/// So casting to `name` on an old server is the mirror of the first bug: it -/// truncates where the view does not, and a long-named routine would answer -/// with no parameters there too. Each version gets the expression its own -/// `information_schema` uses, and neither gets the other's. -pub(super) fn routine_specific_name_sql(has_nameconcatoid: bool) -> &'static str { - if has_nameconcatoid { - r#" - SELECT nameconcatoid(p.proname, p.oid)::text AS specific_name - FROM pg_proc p - JOIN pg_namespace n ON p.pronamespace = n.oid - WHERE n.nspname = $1 - AND p.proname = $2 - AND pg_get_function_identity_arguments(p.oid) = $3 - "# - } else { - r#" - SELECT (p.proname || '_' || p.oid)::text AS specific_name - FROM pg_proc p - JOIN pg_namespace n ON p.pronamespace = n.oid - WHERE n.nspname = $1 - AND p.proname = $2 - AND pg_get_function_identity_arguments(p.oid) = $3 - "# - } -} - -/// The return type of one routine, by `specific_name` where the caller has one. -/// -/// Without it this took `LIMIT 1` over every overload of the name, so the Run -/// dialog could show one overload's return type beside another's parameters. -pub(super) fn routine_return_type_sql(by_specific_name: bool) -> &'static str { - if by_specific_name { - r#" - SELECT r.data_type, r.routine_type - FROM information_schema.routines r - WHERE r.routine_schema = $1 - AND r.specific_name = $2 - "# - } else { - r#" - SELECT data_type, routine_type - FROM information_schema.routines - WHERE routine_schema = $1 AND routine_name = $2 - LIMIT 1 - "# - } -} - -/// One routine's parameters, by `specific_name` where the caller has one. -/// -/// Without it the join filtered on schema and name only, so every overload's -/// parameters came back in one list ordered by position: measured on -/// PostgreSQL 18, three overloads of `f` answered four rows, two of them -/// `ordinal_position` 1 with different types. -pub(super) fn routine_parameters_sql(by_specific_name: bool) -> &'static str { - if by_specific_name { - r#" - SELECT p.parameter_name, p.data_type, p.parameter_mode, p.ordinal_position - FROM information_schema.parameters p - WHERE p.specific_schema = $1 - AND p.specific_name = $2 - ORDER BY p.ordinal_position - "# - } else { - r#" - SELECT p.parameter_name, p.data_type, p.parameter_mode, p.ordinal_position - FROM information_schema.parameters p - JOIN information_schema.routines r ON p.specific_name = r.specific_name - WHERE r.routine_schema = $1 AND r.routine_name = $2 - ORDER BY p.ordinal_position - "# - } -} diff --git a/src-tauri/src/drivers/postgres/session.rs b/src-tauri/src/drivers/postgres/session.rs deleted file mode 100644 index f88e4b73f..000000000 --- a/src-tauri/src/drivers/postgres/session.rs +++ /dev/null @@ -1,251 +0,0 @@ -//! Per-editor-tab pinned PostgreSQL connections. -//! -//! A batch already runs every statement on one pooled connection, so a -//! script containing `BEGIN … COMMIT` works. What did not work is the -//! workflow the transaction exists for: run `BEGIN`, look at the result, -//! run the changes, verify them, and only then `COMMIT` — each as its own -//! run. Between runs the connection went back to the pool, so the next run -//! could land on a different one and the transaction was stranded. -//! -//! This module keeps the connection of a tab that left a transaction open, -//! keyed by the tab's session id, until it commits, rolls back, closes, or -//! goes idle for too long. A pinned connection is never handed back to the -//! pool without a `ROLLBACK` first, so an open transaction can never leak -//! into an unrelated query. -//! -//! Each session has its own lock, held for a whole run, so two overlapping -//! runs from one tab execute one after the other on the same connection -//! instead of each taking a fresh one. - -use std::collections::HashMap; -use std::sync::{Arc, OnceLock}; -use std::time::{Duration, Instant}; -use tokio::sync::{Mutex, OwnedMutexGuard}; - -type Client = deadpool_postgres::Client; - -/// A pooled client held across `execute_batch` calls because the tab that -/// owns it left an explicit transaction open. -struct PinnedSession { - client: Client, - /// The database the client is connected to. A pinned connection belongs - /// to one transaction, and a transaction is scoped to one database, so a - /// tab that switches databases mid-transaction must not silently keep - /// running statements on the old one. - database: String, - last_used: Instant, -} - -/// A session's pinned connection, if any. Holding the guard serializes runs. -#[derive(Default)] -pub struct Slot(Option); - -/// A slot dropped while still holding a connection closes it rather than -/// returning it to the pool, where the next borrower would inherit its transaction. -impl Drop for Slot { - fn drop(&mut self) { - if let Some(pinned) = self.0.take() { - drop(Client::take(pinned.client)); - } - } -} - -impl Slot { - /// Take the pinned connection; the caller must [`Slot::pin`] it again or end its transaction. - pub fn take(&mut self) -> Option { - self.0.take().map(|s| s.client) - } - - /// The database the pinned connection is on, if a session is pinned. - /// - /// Borrowed without unpinning, so [`execute_batch_in_session`] can reject - /// a database mismatch before [`Slot::take`] — leaving the pinned session - /// (and its open transaction) intact when the caller is on the wrong - /// database instead of silently consuming it. - pub fn database(&self) -> Option<&str> { - self.0.as_ref().map(|s| s.database.as_str()) - } - - /// Borrow the pinned connection without unpinning it. - pub fn client(&self) -> Option<&Client> { - self.0.as_ref().map(|s| &s.client) - } - - /// Mark the session as just used, so the idle sweep counts from now. - pub fn touch(&mut self) { - if let Some(s) = self.0.as_mut() { - s.last_used = Instant::now(); - } - } - - /// Pin `client` on `database` until the tab ends its transaction. - pub fn pin(&mut self, client: Client, database: String) { - self.0 = Some(PinnedSession { - client, - database, - last_used: Instant::now(), - }); - } -} - -/// Reject when a pinned session's database differs from the one a run or -/// export targets, returning an error naming both databases and the action. -/// `None` for `pinned` means no transaction is open and the caller may acquire -/// a fresh connection. -/// -/// `action` is the verb inserted into the message ("run" or "export") so the -/// two call sites — [`super::execute_batch_in_session`] and -/// [`super::export::stream_query`] — share one check without duplicating the -/// formatting, while keeping their messages distinct. -pub(crate) fn check_pinned_database( - pinned: Option<&str>, - requested: &str, - action: &str, -) -> Result<(), String> { - if let Some(pinned_db) = pinned { - if pinned_db != requested { - return Err(format!( - "This tab has an open transaction on database \"{pinned_db}\" \ - and cannot {action} on database \"{requested}\". End the \ - transaction (ROLLBACK or COMMIT) or switch back to \"{pinned_db}\"." - )); - } - } - Ok(()) -} - -/// A pinned connection holds its transaction's locks until the tab ends it. -/// A tab abandoned mid-transaction would hold them indefinitely, so a -/// session untouched for this long is rolled back and released by -/// the periodic [`sweep_idle`]. -const MAX_IDLE: Duration = Duration::from_secs(30 * 60); - -const SWEEP_INTERVAL: Duration = Duration::from_secs(60); - -type SessionMap = HashMap>>; - -fn sessions() -> &'static Mutex { - static SESSIONS: OnceLock> = OnceLock::new(); - SESSIONS.get_or_init(|| Mutex::new(HashMap::new())) -} - -/// End the transaction before the client goes back to the pool. -/// -/// The pool recycles connections without resetting them, so dropping a -/// client mid-transaction would leave the next borrower inside someone -/// else's transaction, holding its locks. A failing `ROLLBACK` is ignored: -/// the connection is already unusable and the pool will discard it. -pub async fn rollback_and_release(client: Client) { - if let Err(e) = client.batch_execute("ROLLBACK").await { - log::warn!("PostgreSQL: ROLLBACK while releasing a pinned session failed: {e}"); - } -} - -/// Lock `session_id`'s slot, waiting for any run already holding it. -pub async fn lock(session_id: &str) -> OwnedMutexGuard { - // Started on first use; the sweep also forgets the empty slots every run leaves behind. - static SWEEPER: std::sync::Once = std::sync::Once::new(); - SWEEPER.call_once(|| { - tokio::spawn(async { - let mut timer = tokio::time::interval(SWEEP_INTERVAL); - loop { - timer.tick().await; - sweep_idle().await; - } - }); - }); - let slot = sessions() - .lock() - .await - .entry(session_id.to_string()) - .or_default() - .clone(); - slot.lock_owned().await -} - -/// Roll back and release every session idle past [`MAX_IDLE`], and forget -/// slots nothing holds. A slot in use by a run is skipped. -pub async fn sweep_idle() { - let mut expired = Vec::new(); - { - let now = Instant::now(); - let mut map = sessions().lock().await; - map.retain(|_, slot| { - let Ok(mut guard) = slot.try_lock() else { - return true; - }; - if guard - .0 - .as_ref() - .is_some_and(|s| now.duration_since(s.last_used) > MAX_IDLE) - { - expired.extend(guard.take()); - } - // Only the map holds it and nothing is pinned, so nobody can be waiting on it. - guard.0.is_some() || Arc::strong_count(slot) > 1 - }); - } - - if expired.is_empty() { - return; - } - log::info!( - "PostgreSQL: releasing {} pinned session(s) idle for over {} minutes", - expired.len(), - MAX_IDLE.as_secs() / 60 - ); - for client in expired { - rollback_and_release(client).await; - } -} - -/// Roll back and release the connection pinned to `session_id`, if any, -/// after any run still in flight for it finishes. -/// -/// Called when the tab closes or the user discards the transaction. -pub async fn release(session_id: &str) { - let client = lock(session_id).await.take(); - if let Some(client) = client { - log::info!("PostgreSQL: releasing pinned session {session_id}"); - rollback_and_release(client).await; - } -} - -/// Roll back and release every pinned connection. Called on shutdown so no -/// transaction is left open on the server. A session a run still holds is -/// skipped rather than waited for; its connection closes with the process. -pub async fn release_all() { - let mut clients: Vec = Vec::new(); - // A busy slot stays in the map, so the run holding it can still pin into a tracked slot. - sessions() - .lock() - .await - .retain(|_, slot| match slot.try_lock() { - Ok(mut guard) => { - clients.extend(guard.take()); - false - } - Err(_) => true, - }); - - if clients.is_empty() { - return; - } - log::info!("PostgreSQL: releasing {} pinned session(s)", clients.len()); - for client in clients { - rollback_and_release(client).await; - } -} - -/// Whether `session_id` currently holds a pinned connection. -pub async fn is_pinned(session_id: &str) -> bool { - let slot = sessions().lock().await.get(session_id).cloned(); - match slot { - Some(slot) => slot.lock().await.0.is_some(), - None => false, - } -} - -#[cfg(test)] -#[path = "session_tests.rs"] -mod session_tests; diff --git a/src-tauri/src/drivers/postgres/session_tests.rs b/src-tauri/src/drivers/postgres/session_tests.rs deleted file mode 100644 index 8136d4a40..000000000 --- a/src-tauri/src/drivers/postgres/session_tests.rs +++ /dev/null @@ -1,119 +0,0 @@ -//! Unit tests for `session.rs`'s per-session lock. Pinning itself needs a -//! live connection and is covered by the postgres integration tests. - -use super::{check_pinned_database, lock, sweep_idle, Slot}; -use std::time::Duration; - -#[tokio::test] -async fn a_second_run_for_the_same_session_waits_for_the_first() { - let first = lock("session-tests-same").await; - let second = tokio::spawn(async { drop(lock("session-tests-same").await) }); - - tokio::time::sleep(Duration::from_millis(50)).await; - assert!( - !second.is_finished(), - "overlapping run must wait for the lock" - ); - - drop(first); - tokio::time::timeout(Duration::from_secs(1), second) - .await - .expect("second run proceeds once the first releases") - .unwrap(); -} - -#[tokio::test] -async fn different_sessions_do_not_block_each_other() { - let _a = lock("session-tests-a").await; - tokio::time::timeout(Duration::from_secs(1), lock("session-tests-b")) - .await - .expect("another session must not wait"); -} - -#[tokio::test] -async fn sweep_keeps_a_slot_that_a_run_holds() { - let held = lock("session-tests-held").await; - sweep_idle().await; - let waiter = tokio::spawn(async { drop(lock("session-tests-held").await) }); - tokio::time::sleep(Duration::from_millis(50)).await; - // Had the sweep dropped the slot, the waiter would get a fresh one and not block. - assert!(!waiter.is_finished()); - drop(held); - waiter.await.unwrap(); -} - -#[tokio::test] -async fn sweep_forgets_a_slot_nothing_uses() { - drop(lock("session-tests-unused").await); - sweep_idle().await; - assert!(!super::sessions() - .lock() - .await - .contains_key("session-tests-unused")); -} - -#[tokio::test] -async fn release_all_keeps_tracking_a_slot_a_run_holds() { - let held = lock("session-tests-busy-shutdown").await; - super::release_all().await; - // The run would otherwise pin into a slot nothing tracks, and it would never be rolled back. - assert!(super::sessions() - .lock() - .await - .contains_key("session-tests-busy-shutdown")); - drop(held); -} - -#[test] -fn an_empty_slot_reports_no_pinned_database() { - // A default slot holds no pinned connection, so `database()` returns - // `None` — the mismatch guard in `execute_batch_in_session` treats this - // as "no transaction open" and acquires a fresh client. - let slot = Slot::default(); - assert!(slot.database().is_none()); -} - -#[test] -fn check_pinned_database_allows_a_matching_database() { - // When the pinned and requested databases match, the run proceeds. - assert_eq!( - check_pinned_database(Some("orders"), "orders", "run"), - Ok(()) - ); -} - -#[test] -fn check_pinned_database_rejects_a_mismatch_with_the_action_in_the_message() { - // A mismatch names both databases and the action, so the user knows - // whether the rejected operation was a run or an export. Both verbs are - // exercised so a regression that hardcodes one verb is caught. - let run_err = check_pinned_database(Some("orders"), "inventory", "run").unwrap_err(); - assert!( - run_err.contains("cannot run on"), - "error should use the 'run' action verb: {run_err}" - ); - let export_err = check_pinned_database(Some("orders"), "inventory", "export").unwrap_err(); - assert!( - export_err.contains("\"orders\""), - "error should name the pinned database: {export_err}" - ); - assert!( - export_err.contains("\"inventory\""), - "error should name the requested database: {export_err}" - ); - assert!( - export_err.contains("cannot export on"), - "error should use the 'export' action verb: {export_err}" - ); - assert!( - export_err.contains("ROLLBACK or COMMIT"), - "error should tell the user how to resolve it: {export_err}" - ); -} - -#[test] -fn check_pinned_database_allows_any_database_when_nothing_is_pinned() { - // `None` means no transaction is open, so the caller may acquire a fresh - // connection on whatever database it was asked for. - assert_eq!(check_pinned_database(None, "anything", "run"), Ok(())); -} diff --git a/src-tauri/src/drivers/postgres/tests.rs b/src-tauri/src/drivers/postgres/tests.rs deleted file mode 100644 index 5f6e74c1d..000000000 --- a/src-tauri/src/drivers/postgres/tests.rs +++ /dev/null @@ -1,2130 +0,0 @@ -use super::binding::{ - bind_pg_boolean_string, bind_pg_enum_string, bind_pg_number, bind_pg_numeric_string, - bind_pg_temporal_string, bind_pg_value, build_pk_map_predicate, build_pk_predicate, BoundValue, - PgValueOptions, -}; -use super::helpers::{ - enum_data_type, extract_base_type, is_implicit_cast_compatible, postgres_column_types, - quote_qualified_type, -}; -use super::primary_key_exists_expression; - -mod primary_key_detection_tests { - use super::*; - - #[test] - fn primary_key_detection_uses_pg_catalog() { - let expression = primary_key_exists_expression(); - - assert!(expression.contains("pg_constraint")); - assert!(expression.contains("pg_attribute")); - assert!(expression.contains("pk_con.contype = 'p'")); - assert!(!expression.contains("information_schema.table_constraints")); - } -} - -mod extract_base_type_tests { - use super::*; - - #[test] - fn simple_type() { - assert_eq!(extract_base_type("INTEGER"), "INTEGER"); - } - - #[test] - fn type_with_length() { - assert_eq!(extract_base_type("VARCHAR(255)"), "VARCHAR"); - } - - #[test] - fn type_with_precision() { - assert_eq!(extract_base_type("NUMERIC(10,2)"), "NUMERIC"); - } - - #[test] - fn parameterized_geometry() { - assert_eq!(extract_base_type("GEOMETRY(Point, 4326)"), "GEOMETRY"); - } - - #[test] - fn type_with_spaces() { - assert_eq!(extract_base_type("DOUBLE PRECISION"), "DOUBLE PRECISION"); - } - - #[test] - fn lowercase_input() { - assert_eq!(extract_base_type("varchar(100)"), "VARCHAR"); - } - - #[test] - fn type_with_leading_trailing_spaces() { - assert_eq!(extract_base_type(" integer "), "INTEGER"); - } - - #[test] - fn geography_parameterized() { - assert_eq!(extract_base_type("GEOGRAPHY(Point, 4326)"), "GEOGRAPHY"); - } - - #[test] - fn serial_type() { - assert_eq!(extract_base_type("BIGSERIAL"), "BIGSERIAL"); - } -} - -mod is_implicit_cast_compatible_tests { - use super::*; - - #[test] - fn same_type_is_compatible() { - assert!(is_implicit_cast_compatible("INTEGER", "INTEGER")); - } - - #[test] - fn integer_to_bigint() { - assert!(is_implicit_cast_compatible("INTEGER", "BIGINT")); - } - - #[test] - fn smallint_to_bigint() { - assert!(is_implicit_cast_compatible("SMALLINT", "BIGINT")); - } - - #[test] - fn bigint_to_smallint() { - assert!(is_implicit_cast_compatible("BIGINT", "SMALLINT")); - } - - #[test] - fn serial_to_integer() { - assert!(is_implicit_cast_compatible("SERIAL", "INTEGER")); - } - - #[test] - fn varchar_to_text() { - assert!(is_implicit_cast_compatible("VARCHAR", "TEXT")); - } - - #[test] - fn char_to_text() { - assert!(is_implicit_cast_compatible("CHAR", "TEXT")); - } - - #[test] - fn text_to_citext() { - assert!(is_implicit_cast_compatible("TEXT", "CITEXT")); - } - - #[test] - fn timestamp_to_timestamptz() { - assert!(is_implicit_cast_compatible("TIMESTAMP", "TIMESTAMPTZ")); - } - - #[test] - fn time_to_timetz() { - assert!(is_implicit_cast_compatible("TIME", "TIMETZ")); - } - - #[test] - fn json_to_jsonb() { - assert!(is_implicit_cast_compatible("JSON", "JSONB")); - } - - #[test] - fn real_to_double_precision() { - assert!(is_implicit_cast_compatible("REAL", "DOUBLE PRECISION")); - } - - #[test] - fn numeric_to_decimal() { - assert!(is_implicit_cast_compatible("NUMERIC", "DECIMAL")); - } - - #[test] - fn bit_to_varbit() { - assert!(is_implicit_cast_compatible("BIT", "VARBIT")); - } - - #[test] - fn integer_to_text_not_compatible() { - assert!(!is_implicit_cast_compatible("INTEGER", "TEXT")); - } - - #[test] - fn text_to_boolean_not_compatible() { - assert!(!is_implicit_cast_compatible("TEXT", "BOOLEAN")); - } - - #[test] - fn varchar_to_integer_not_compatible() { - assert!(!is_implicit_cast_compatible("VARCHAR", "INTEGER")); - } - - #[test] - fn timestamp_to_integer_not_compatible() { - assert!(!is_implicit_cast_compatible("TIMESTAMP", "INTEGER")); - } - - #[test] - fn jsonb_to_integer_not_compatible() { - assert!(!is_implicit_cast_compatible("JSONB", "INTEGER")); - } - - #[test] - fn geometry_to_text_not_compatible() { - assert!(!is_implicit_cast_compatible("GEOMETRY", "TEXT")); - } - - #[test] - fn uuid_to_text_not_compatible() { - assert!(!is_implicit_cast_compatible("UUID", "TEXT")); - } -} - -mod pg_number_binding_tests { - use super::*; - - #[test] - fn positive_i64_casts_to_bigint() { - let n = serde_json::Number::from(42i64); - let bound = bind_pg_number(&n, 1).unwrap(); - assert_eq!(bound.sql, "CAST($1 AS bigint)"); - assert!(bound.param.is_some()); - } - - #[test] - fn negative_i64_casts_to_bigint() { - let n = serde_json::Number::from(-7i64); - let bound = bind_pg_number(&n, 5).unwrap(); - assert_eq!(bound.sql, "CAST($5 AS bigint)"); - } - - #[test] - fn zero_casts_to_bigint() { - let n = serde_json::Number::from(0i64); - let bound = bind_pg_number(&n, 2).unwrap(); - assert_eq!(bound.sql, "CAST($2 AS bigint)"); - } - - #[test] - #[allow(clippy::approx_constant)] - fn f64_casts_to_double_precision() { - let n = serde_json::Number::from_f64(3.14).unwrap(); - let bound = bind_pg_number(&n, 3).unwrap(); - assert_eq!(bound.sql, "CAST($3 AS double precision)"); - } - - #[test] - fn large_u64_falls_back_to_double_precision() { - // u64 above i64::MAX cannot be represented as i64, but as_f64 still returns Some. - let n = serde_json::Number::from(u64::MAX); - let bound = bind_pg_number(&n, 1).unwrap(); - assert_eq!(bound.sql, "CAST($1 AS double precision)"); - } - - #[test] - fn placeholder_index_is_preserved() { - let n = serde_json::Number::from(1i64); - let bound = bind_pg_number(&n, 99).unwrap(); - assert_eq!(bound.sql, "CAST($99 AS bigint)"); - } -} - -mod pg_numeric_string_binding_tests { - use super::*; - - #[test] - fn integer_string_for_integer_column_casts_to_bigint() { - let bound = bind_pg_numeric_string("22", "integer", 1).unwrap().unwrap(); - assert_eq!(bound.sql, "CAST($1 AS bigint)"); - assert!(bound.param.is_some()); - } - - #[test] - fn decimal_string_for_numeric_column_casts_to_numeric() { - let bound = bind_pg_numeric_string("12.34", "numeric(10,2)", 2) - .unwrap() - .unwrap(); - assert_eq!(bound.sql, "CAST($2 AS numeric)"); - } - - #[test] - fn float_string_for_real_column_casts_to_double_precision() { - let bound = bind_pg_numeric_string("3.14", "real", 3).unwrap().unwrap(); - assert_eq!(bound.sql, "CAST($3 AS double precision)"); - } - - #[test] - fn text_column_is_not_handled_as_numeric() { - assert!(bind_pg_numeric_string("22", "text", 1).is_none()); - } - - #[test] - fn invalid_integer_string_returns_detailed_error() { - let err = match bind_pg_numeric_string("not-a-number", "integer", 1).unwrap() { - Ok(_) => panic!("expected invalid integer binding to fail"), - Err(err) => err, - }; - assert!(err.contains("Cannot convert value")); - assert!(err.contains("integer")); - } -} - -mod pg_boolean_string_binding_tests { - use super::*; - - #[test] - fn true_string_for_boolean_column_binds_as_bool() { - let bound = bind_pg_boolean_string("true", "boolean", 1) - .unwrap() - .unwrap(); - assert_eq!(bound.sql, "$1"); - assert!(bound.param.is_some()); - } - - #[test] - fn false_string_for_boolean_column_binds_as_bool() { - let bound = bind_pg_boolean_string("false", "boolean", 2) - .unwrap() - .unwrap(); - assert_eq!(bound.sql, "$2"); - assert!(bound.param.is_some()); - } - - #[test] - fn pg_literal_aliases_are_accepted() { - for s in ["t", "T", "yes", "Y", "on", "1"] { - assert!( - bind_pg_boolean_string(s, "boolean", 1).unwrap().is_ok(), - "expected {:?} to parse as TRUE", - s - ); - } - for s in ["f", "F", "no", "N", "off", "0"] { - assert!( - bind_pg_boolean_string(s, "boolean", 1).unwrap().is_ok(), - "expected {:?} to parse as FALSE", - s - ); - } - } - - #[test] - fn surrounding_whitespace_is_tolerated() { - assert!(bind_pg_boolean_string(" true ", "boolean", 1) - .unwrap() - .is_ok()); - } - - #[test] - fn bool_alias_for_column_type_is_handled() { - assert!(bind_pg_boolean_string("true", "bool", 1).unwrap().is_ok()); - } - - #[test] - fn non_boolean_column_returns_none() { - assert!(bind_pg_boolean_string("true", "text", 1).is_none()); - assert!(bind_pg_boolean_string("1", "integer", 1).is_none()); - } - - #[test] - fn invalid_boolean_string_returns_detailed_error() { - let err = match bind_pg_boolean_string("maybe", "boolean", 1).unwrap() { - Ok(_) => panic!("expected invalid boolean binding to fail"), - Err(err) => err, - }; - assert!(err.contains("Cannot convert value")); - assert!(err.contains("boolean")); - } -} - -mod pg_temporal_string_binding_tests { - use super::*; - - #[test] - fn timestamptz_column_casts_to_canonical_type() { - let bound = - bind_pg_temporal_string("2025-06-30T12:00:00+00:00", "timestamp with time zone", 1) - .unwrap() - .unwrap(); - assert_eq!(bound.sql, "CAST($1 AS timestamptz)"); - let (_, pg_type) = bound.param.unwrap(); - // The placeholder must be pinned to TEXT — not TIMESTAMPTZ — or - // tokio-postgres rejects the bound String client-side before the CAST - // ever runs server-side (#401). - assert_eq!(pg_type, tokio_postgres::types::Type::TEXT); - } - - #[test] - fn timestamp_without_time_zone_casts_to_timestamp() { - let bound = - bind_pg_temporal_string("2025-06-30 12:00:00", "timestamp without time zone", 2) - .unwrap() - .unwrap(); - assert_eq!(bound.sql, "CAST($2 AS timestamp)"); - } - - #[test] - fn date_column_casts_to_date() { - let bound = bind_pg_temporal_string("2025-06-30", "date", 3) - .unwrap() - .unwrap(); - assert_eq!(bound.sql, "CAST($3 AS date)"); - } - - #[test] - fn time_columns_cast_to_time_or_timetz() { - let plain = bind_pg_temporal_string("12:00:00", "time without time zone", 1) - .unwrap() - .unwrap(); - assert_eq!(plain.sql, "CAST($1 AS time)"); - - let with_tz = bind_pg_temporal_string("12:00:00+02", "time with time zone", 1) - .unwrap() - .unwrap(); - assert_eq!(with_tz.sql, "CAST($1 AS timetz)"); - } - - #[test] - fn interval_column_casts_to_interval() { - let bound = bind_pg_temporal_string("1 day", "interval", 1) - .unwrap() - .unwrap(); - assert_eq!(bound.sql, "CAST($1 AS interval)"); - } - - #[test] - fn non_temporal_column_returns_none() { - assert!(bind_pg_temporal_string("2025-06-30", "text", 1).is_none()); - assert!(bind_pg_temporal_string("2025-06-30", "integer", 1).is_none()); - } -} - -mod bind_pg_value_tests { - use super::*; - - #[test] - fn update_string_for_boolean_column_uses_boolean_binding() { - let bound = bind_pg_value( - serde_json::json!("true"), - 1, - PgValueOptions { - column_type: Some("boolean"), - enum_type: None, - max_blob_size: 1024, - allow_default: true, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "$1"); - assert!(bound.param.is_some()); - } - - #[test] - fn invalid_boolean_string_for_boolean_column_returns_error() { - let err = match bind_pg_value( - serde_json::json!("maybe"), - 1, - PgValueOptions { - column_type: Some("boolean"), - enum_type: None, - max_blob_size: 1024, - allow_default: true, - hstore_oid: None, - }, - ) { - Ok(_) => panic!("expected invalid boolean binding to fail"), - Err(err) => err, - }; - assert!(err.contains("boolean")); - } - - #[test] - fn update_string_for_numeric_column_uses_numeric_binding() { - let bound = bind_pg_value( - serde_json::json!("22"), - 1, - PgValueOptions { - column_type: Some("integer"), - enum_type: None, - max_blob_size: 1024, - allow_default: true, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "CAST($1 AS bigint)"); - assert!(bound.param.is_some()); - } - - #[test] - fn default_sentinel_is_only_used_when_allowed() { - let bound = bind_pg_value( - serde_json::json!("__USE_DEFAULT__"), - 1, - PgValueOptions { - column_type: None, - enum_type: None, - max_blob_size: 1024, - allow_default: true, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "DEFAULT"); - assert!(bound.param.is_none()); - } - - #[test] - fn insert_path_treats_default_sentinel_as_regular_string() { - let bound = bind_pg_value( - serde_json::json!("__USE_DEFAULT__"), - 1, - PgValueOptions { - column_type: None, - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "$1"); - assert!(bound.param.is_some()); - } - - #[test] - fn json_array_becomes_literal_without_parameter() { - let bound = bind_pg_value( - serde_json::json!(["a", "b"]), - 1, - PgValueOptions { - column_type: None, - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "ARRAY['a', 'b']"); - assert!(bound.param.is_none()); - } - - #[test] - fn json_object_into_jsonb_column_bound_as_value() { - let bound = bind_pg_value( - serde_json::json!({"key": "value", "n": 42}), - 1, - PgValueOptions { - column_type: Some("jsonb"), - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "$1"); - assert!(bound.param.is_some()); - } - - #[test] - fn json_array_into_json_column_bound_as_value_not_pg_array() { - let bound = bind_pg_value( - serde_json::json!([1, 2, 3]), - 1, - PgValueOptions { - column_type: Some("json"), - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "$1"); - assert!(bound.param.is_some()); - } - - #[test] - fn json_null_into_jsonb_column_stays_sql_null() { - let bound = bind_pg_value( - serde_json::Value::Null, - 1, - PgValueOptions { - column_type: Some("jsonb"), - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "NULL"); - assert!(bound.param.is_none()); - } - - #[test] - fn json_object_into_non_json_column_returns_clear_error() { - let err = match bind_pg_value( - serde_json::json!({"key": "value"}), - 1, - PgValueOptions { - column_type: Some("text"), - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: None, - }, - ) { - Ok(_) => panic!("expected error binding JSON object to non-JSON column"), - Err(err) => err, - }; - assert!(err.contains("JSON object")); - } - - #[test] - fn hstore_object_bound_as_value_with_correct_type_name() { - let bound = bind_pg_value( - serde_json::json!({"key": "value", "other": "thing"}), - 1, - PgValueOptions { - column_type: Some("hstore"), - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: Some(16_500), - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "$1"); - let (_, pg_type) = bound.param.unwrap(); - assert_eq!(pg_type.name(), "hstore"); - assert_eq!(pg_type.oid(), 16_500); - } - - #[test] - fn hstore_object_with_null_value_bound_correctly() { - let bound = bind_pg_value( - serde_json::json!({"key": null}), - 1, - PgValueOptions { - column_type: Some("hstore"), - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: Some(16_500), - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "$1"); - assert!(bound.param.is_some()); - } - - #[test] - fn hstore_null_value_stays_sql_null() { - let bound = bind_pg_value( - serde_json::Value::Null, - 1, - PgValueOptions { - column_type: Some("hstore"), - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: Some(16_500), - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "NULL"); - assert!(bound.param.is_none()); - } - - #[test] - fn hstore_non_string_value_in_object_returns_clear_error() { - let err = match bind_pg_value( - serde_json::json!({"key": 42}), - 1, - PgValueOptions { - column_type: Some("hstore"), - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: Some(16_500), - }, - ) { - Ok(_) => panic!("expected an error for non-string hstore value"), - Err(e) => e, - }; - - assert!(err.contains("key")); - assert!(err.contains("string or null")); - } - - #[test] - fn hstore_non_object_value_returns_clear_error() { - let err = match bind_pg_value( - serde_json::json!("just a string"), - 1, - PgValueOptions { - column_type: Some("hstore"), - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: Some(16_500), - }, - ) { - Ok(_) => panic!("expected an error for non-object hstore value"), - Err(e) => e, - }; - - assert!(err.contains("JSON object")); - } - - #[test] - fn hstore_object_without_resolved_oid_returns_clear_error() { - let err = match bind_pg_value( - serde_json::json!({"key": "value"}), - 1, - PgValueOptions { - column_type: Some("hstore"), - enum_type: None, - max_blob_size: 1024, - allow_default: false, - hstore_oid: None, - }, - ) { - Ok(_) => panic!("expected an error when hstore_oid could not be resolved"), - Err(e) => e, - }; - - assert!(err.contains("hstore")); - } -} - -mod bind_pg_enum_string_tests { - use super::*; - use tokio_postgres::types::Type; - - #[test] - fn casts_through_the_qualified_enum_type_pinned_as_text() { - let bound = bind_pg_enum_string("pro", "\"public\".\"plan_type\"", 1); - assert_eq!(bound.sql, "CAST($1 AS \"public\".\"plan_type\")"); - let (_, ty) = bound.param.expect("expected a bound parameter"); - assert_eq!(ty, Type::TEXT); - } - - #[test] - fn placeholder_index_is_respected() { - let bound = bind_pg_enum_string("free", "\"public\".\"plan_type\"", 3); - assert_eq!(bound.sql, "CAST($3 AS \"public\".\"plan_type\")"); - } - - #[test] - fn bind_pg_value_uses_enum_coercion_for_enum_columns() { - let bound = bind_pg_value( - serde_json::json!("enterprise"), - 1, - PgValueOptions { - column_type: Some("USER-DEFINED"), - enum_type: Some("\"public\".\"plan_type\""), - max_blob_size: 1024, - allow_default: true, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "CAST($1 AS \"public\".\"plan_type\")"); - assert!(bound.param.is_some()); - } - - #[test] - fn enum_coercion_wins_over_shape_heuristics() { - // A label that happens to be uuid-shaped must still cast to the enum, - // not to uuid. - let bound = bind_pg_value( - serde_json::json!("123e4567-e89b-12d3-a456-426614174000"), - 1, - PgValueOptions { - column_type: Some("USER-DEFINED"), - enum_type: Some("\"public\".\"weird_enum\""), - max_blob_size: 1024, - allow_default: true, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "CAST($1 AS \"public\".\"weird_enum\")"); - } - - #[test] - fn null_for_enum_column_stays_sql_null() { - let bound = bind_pg_value( - serde_json::Value::Null, - 1, - PgValueOptions { - column_type: Some("USER-DEFINED"), - enum_type: Some("\"public\".\"plan_type\""), - max_blob_size: 1024, - allow_default: true, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "NULL"); - assert!(bound.param.is_none()); - } - - #[test] - fn default_sentinel_wins_over_enum_coercion() { - let bound = bind_pg_value( - serde_json::json!("__USE_DEFAULT__"), - 1, - PgValueOptions { - column_type: Some("USER-DEFINED"), - enum_type: Some("\"public\".\"plan_type\""), - max_blob_size: 1024, - allow_default: true, - hstore_oid: None, - }, - ) - .unwrap(); - - assert_eq!(bound.sql, "DEFAULT"); - assert!(bound.param.is_none()); - } -} - -mod enum_helpers_tests { - use super::*; - - #[test] - fn quote_qualified_type_quotes_schema_and_name() { - assert_eq!( - quote_qualified_type("public", "plan_type"), - "\"public\".\"plan_type\"" - ); - } - - #[test] - fn quote_qualified_type_escapes_embedded_quotes() { - assert_eq!( - quote_qualified_type("pub\"lic", "plan\"type"), - "\"pub\"\"lic\".\"plan\"\"type\"" - ); - } - - #[test] - fn enum_data_type_surfaces_allowed_values() { - assert_eq!( - enum_data_type( - "USER-DEFINED".to_string(), - Some("'free','basic','pro'".to_string()) - ), - "enum('free','basic','pro')" - ); - } - - #[test] - fn postgres_column_types_carries_format_type_as_full_type() { - assert_eq!( - postgres_column_types( - "character varying".to_string(), - None, - Some("character varying(255)".to_string()) - ), - ( - "character varying".to_string(), - Some("character varying(255)".to_string()) - ) - ); - assert_eq!( - postgres_column_types( - "numeric".to_string(), - None, - Some("numeric(10,2)".to_string()) - ), - ("numeric".to_string(), Some("numeric(10,2)".to_string())) - ); - assert_eq!( - postgres_column_types("ARRAY".to_string(), None, Some("integer[]".to_string())), - ("ARRAY".to_string(), Some("integer[]".to_string())) - ); - assert_eq!( - postgres_column_types( - "timestamp with time zone".to_string(), - None, - Some("timestamp(3) with time zone".to_string()) - ), - ( - "timestamp with time zone".to_string(), - Some("timestamp(3) with time zone".to_string()) - ) - ); - } - - #[test] - fn postgres_column_types_omits_full_type_for_plain_types() { - assert_eq!( - postgres_column_types("integer".to_string(), None, Some("integer".to_string())), - ("integer".to_string(), None) - ); - assert_eq!( - postgres_column_types("text".to_string(), None, None), - ("text".to_string(), None) - ); - } - - #[test] - fn postgres_column_types_keeps_enum_values_without_full_type() { - assert_eq!( - postgres_column_types( - "plan".to_string(), - Some("'free','pro'".to_string()), - Some("plan".to_string()) - ), - ("enum('free','pro')".to_string(), None) - ); - // An enum without labels falls back to the plain type handling. - assert_eq!( - postgres_column_types( - "plan".to_string(), - Some(String::new()), - Some("plan".to_string()) - ), - ("plan".to_string(), None) - ); - } - - #[test] - fn enum_data_type_keeps_raw_type_without_values() { - assert_eq!(enum_data_type("integer".to_string(), None), "integer"); - assert_eq!( - enum_data_type("USER-DEFINED".to_string(), Some(String::new())), - "USER-DEFINED" - ); - } -} - -mod build_pk_predicate_tests { - use super::*; - - #[test] - fn integer_pk_uses_bigint_cast() { - let (sql, _) = build_pk_predicate("id", serde_json::json!(1), 1, None).unwrap(); - assert_eq!(sql, "\"id\" = CAST($1 AS bigint)"); - } - - #[test] - fn float_pk_uses_double_precision_cast() { - let (sql, _) = build_pk_predicate("id", serde_json::json!(1.5), 2, None).unwrap(); - assert_eq!(sql, "\"id\" = CAST($2 AS double precision)"); - } - - #[test] - fn real_row_identity_compares_at_column_precision() { - for value in [serde_json::json!(89.9), serde_json::json!("89.9")] { - for column_type in ["real", "float4", "REAL"] { - let (sql, param) = - build_pk_predicate("price", value.clone(), 2, Some(column_type)).unwrap(); - assert_eq!( - sql, - "\"price\" = CAST(CAST($2 AS double precision) AS real)" - ); - assert_eq!(param.unwrap().1, tokio_postgres::types::Type::FLOAT8); - } - let (sql, _) = build_pk_predicate("price", value, 2, Some("double precision")).unwrap(); - assert_eq!(sql, "\"price\" = CAST($2 AS double precision)"); - } - } - - #[test] - fn uuid_string_pk_binds_without_cast() { - let uuid = "550e8400-e29b-41d4-a716-446655440000"; - let (sql, _) = build_pk_predicate("uuid", serde_json::json!(uuid), 1, None).unwrap(); - assert_eq!(sql, "\"uuid\" = $1"); - } - - // issue #392: a uuid-shaped string in a varchar/text PK column must bind as - // text, not the native Uuid type — otherwise tokio-postgres rejects it with - // "error serializing parameter N" against the varchar column. - #[test] - fn uuid_string_pk_binds_as_text_for_varchar_column() { - let uuid = "550e8400-e29b-41d4-a716-446655440000"; - let (sql, param) = build_pk_predicate( - "guid", - serde_json::json!(uuid), - 1, - Some("character varying"), - ) - .unwrap(); - let (param, pg_type) = param.unwrap(); - assert_eq!(sql, "\"guid\" = $1"); - assert_eq!(pg_type, tokio_postgres::types::Type::TEXT); - assert_eq!(format!("{:?}", param), format!("{:?}", uuid.to_string())); - } - - #[test] - fn uuid_string_pk_binds_as_uuid_for_uuid_column() { - let uuid = "550e8400-e29b-41d4-a716-446655440000"; - let (sql, param) = - build_pk_predicate("id", serde_json::json!(uuid), 1, Some("uuid")).unwrap(); - let (param, pg_type) = param.unwrap(); - assert_eq!(sql, "\"id\" = $1"); - assert_eq!(pg_type, tokio_postgres::types::Type::UUID); - let expected: uuid::Uuid = uuid.parse().unwrap(); - assert_eq!(format!("{:?}", param), format!("{:?}", expected)); - } - - // Keyless tables (#598) route numeric-column string values through the - // numeric coercion: a plain TEXT bind trips SQLSTATE 42883 - // ("operator does not exist: numeric = text"). - #[test] - fn numeric_column_string_value_casts_to_numeric() { - let (sql, param) = - build_pk_predicate("amount", serde_json::json!("1500.00"), 2, Some("numeric")).unwrap(); - let (_, pg_type) = param.unwrap(); - assert_eq!(sql, "\"amount\" = CAST($2 AS numeric)"); - assert_eq!(pg_type, tokio_postgres::types::Type::NUMERIC); - } - - #[test] - fn double_precision_column_string_value_casts_to_double() { - let (sql, param) = build_pk_predicate( - "score", - serde_json::json!("1.5"), - 1, - Some("double precision"), - ) - .unwrap(); - let (_, pg_type) = param.unwrap(); - assert_eq!(sql, "\"score\" = CAST($1 AS double precision)"); - assert_eq!(pg_type, tokio_postgres::types::Type::FLOAT8); - } - - #[test] - fn integer_column_string_value_casts_to_bigint() { - let (sql, param) = - build_pk_predicate("id", serde_json::json!("42"), 1, Some("integer")).unwrap(); - let (_, pg_type) = param.unwrap(); - assert_eq!(sql, "\"id\" = CAST($1 AS bigint)"); - assert_eq!(pg_type, tokio_postgres::types::Type::INT8); - } - - #[test] - fn numeric_column_unparsable_string_is_rejected() { - assert!( - build_pk_predicate("amount", serde_json::json!("abc"), 1, Some("numeric")).is_err() - ); - } - - // Temporal columns share the fate of numeric ones in keyless predicates: - // a TEXT bind against timestamp trips 42883, so the value casts through - // the canonical temporal type with the wire type pinned to TEXT (#401). - #[test] - fn timestamp_column_string_value_casts_through_text() { - let (sql, param) = build_pk_predicate( - "imported_at", - serde_json::json!("2024-05-01 10:30:00"), - 3, - Some("timestamp without time zone"), - ) - .unwrap(); - let (_, pg_type) = param.unwrap(); - assert_eq!(sql, "\"imported_at\" = CAST($3 AS timestamp)"); - assert_eq!(pg_type, tokio_postgres::types::Type::TEXT); - } - - #[test] - fn plain_string_pk_binds_without_cast() { - let (sql, _) = build_pk_predicate("name", serde_json::json!("alice"), 1, None).unwrap(); - assert_eq!(sql, "\"name\" = $1"); - } - - #[test] - fn pk_col_with_quotes_is_escaped() { - let (sql, _) = build_pk_predicate("a\"b", serde_json::json!(1), 1, None).unwrap(); - assert_eq!(sql, "\"a\"\"b\" = CAST($1 AS bigint)"); - } - - // Keyless tables (#598) identify rows by all comparable columns, so a - // pk_map entry may legitimately be NULL and must render as IS NULL. - #[test] - fn null_pk_renders_is_null_without_binding() { - let (sql, param) = build_pk_predicate("id", serde_json::Value::Null, 1, None).unwrap(); - assert_eq!(sql, "\"id\" IS NULL"); - assert!(param.is_none()); - } - - #[test] - fn bool_pk_binds_as_bool() { - let (sql, param) = build_pk_predicate("flag", serde_json::json!(true), 1, None).unwrap(); - let (_, pg_type) = param.unwrap(); - assert_eq!(sql, "\"flag\" = $1"); - assert_eq!(pg_type, tokio_postgres::types::Type::BOOL); - } -} - -mod build_pk_map_predicate_tests { - use super::*; - use std::collections::HashMap; - - #[test] - fn single_integer_column() { - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), serde_json::json!(1)); - let pk_types = HashMap::new(); - let (sql, params) = build_pk_map_predicate(&pk_map, &pk_types, 1).unwrap(); - assert_eq!(sql, "\"id\" = CAST($1 AS bigint)"); - assert_eq!(params.len(), 1); - } - - #[test] - fn composite_pk_sorted_alphabetically_with_consecutive_placeholders() { - let mut pk_map = HashMap::new(); - pk_map.insert("z_col".to_string(), serde_json::json!("alice")); - pk_map.insert("a_col".to_string(), serde_json::json!("bob")); - let pk_types = HashMap::new(); - let (sql, params) = build_pk_map_predicate(&pk_map, &pk_types, 1).unwrap(); - assert_eq!(sql, "\"a_col\" = $1 AND \"z_col\" = $2"); - assert_eq!(params.len(), 2); - } - - #[test] - fn non_one_starting_placeholder_idx() { - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), serde_json::json!(5)); - let pk_types = HashMap::new(); - let (sql, _) = build_pk_map_predicate(&pk_map, &pk_types, 3).unwrap(); - assert_eq!(sql, "\"id\" = CAST($3 AS bigint)"); - } - - #[test] - fn composite_pk_with_mixed_types() { - let mut pk_map = HashMap::new(); - pk_map.insert("b_col".to_string(), serde_json::json!("alice")); - pk_map.insert("a_col".to_string(), serde_json::json!(99)); - let pk_types = HashMap::new(); - let (sql, params) = build_pk_map_predicate(&pk_map, &pk_types, 1).unwrap(); - assert_eq!(sql, "\"a_col\" = CAST($1 AS bigint) AND \"b_col\" = $2"); - assert_eq!(params.len(), 2); - } - - // Combines #324 (composite PK) and #392 (uuid-shaped value in a varchar PK - // column): the uuid column binds as the native Uuid while the varchar member - // holding a uuid-shaped string binds as text, all within one compound predicate. - #[test] - fn composite_pk_threads_per_column_type_for_uuid_varchar() { - let uuid = "550e8400-e29b-41d4-a716-446655440000"; - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), serde_json::json!(uuid)); - pk_map.insert("guid".to_string(), serde_json::json!(uuid)); - let mut pk_types = HashMap::new(); - pk_types.insert("id".to_string(), "uuid".to_string()); - pk_types.insert("guid".to_string(), "character varying".to_string()); - let (sql, params) = build_pk_map_predicate(&pk_map, &pk_types, 1).unwrap(); - assert_eq!(sql, "\"guid\" = $1 AND \"id\" = $2"); - assert_eq!(params.len(), 2); - // guid (sorted first) binds as text, id binds as the native Uuid type. - let expected_uuid: uuid::Uuid = uuid.parse().unwrap(); - assert_eq!(params[0].1, tokio_postgres::types::Type::TEXT); - assert_eq!(params[1].1, tokio_postgres::types::Type::UUID); - assert_eq!( - format!("{:?}", params[0].0), - format!("{:?}", uuid.to_string()) - ); - assert_eq!(format!("{:?}", params[1].0), format!("{:?}", expected_uuid)); - } - - #[test] - fn empty_pk_map_is_rejected() { - let pk_map: HashMap = HashMap::new(); - let pk_types = HashMap::new(); - assert!(build_pk_map_predicate(&pk_map, &pk_types, 1).is_err()); - } - - // Keyless tables (#598): NULL entries render as IS NULL and must not - // consume a placeholder index, so following columns stay consecutive. - #[test] - fn null_entry_uses_is_null_and_keeps_placeholders_consecutive() { - let mut pk_map = HashMap::new(); - pk_map.insert("a_col".to_string(), serde_json::Value::Null); - pk_map.insert("b_col".to_string(), serde_json::json!("alice")); - pk_map.insert("c_col".to_string(), serde_json::json!("bob")); - let pk_types = HashMap::new(); - let (sql, params) = build_pk_map_predicate(&pk_map, &pk_types, 1).unwrap(); - assert_eq!( - sql, - "\"a_col\" IS NULL AND \"b_col\" = $1 AND \"c_col\" = $2" - ); - assert_eq!(params.len(), 2); - } -} - -/// Live-Postgres regression coverage for #401 (and the adjacent #392 uuid-cast -/// bug it shares a root cause with). Exercises the real `update_record` driver -/// function — not just `bind_pg_value`'s SQL/param shape — because the bug only -/// surfaces once tokio-postgres actually prepares and binds the statement -/// against a server: `CAST($N AS uuid/timestamptz)` makes PostgreSQL report the -/// placeholder's *effective* type as the cast target, so a bound `String` is -/// rejected client-side unless the placeholder is explicitly pinned to TEXT -/// (see `binding::TypedPgParam` / `client::execute_typed`). -/// -/// Ignored by default — requires a local PostgreSQL, e.g.: -/// docker run -d -e POSTGRES_PASSWORD=postgres -p 55432:5432 postgres:16 -/// TABULARIS_TEST_PG=1 cargo test --lib postgres::tests::live_pg -- --ignored --nocapture -/// Override TABULARIS_TEST_PG_{HOST,PORT,USER,PASSWORD,DB} for a non-default setup. -#[cfg(test)] -mod live_pg_temporal_and_uuid_regression { - use crate::models::{ConnectionParams, DatabaseSelection}; - use std::collections::HashMap; - - fn test_params() -> Option { - // Plain env vars rather than a connection-string parser, to avoid - // pulling in a URL-parsing crate for a single ignored test. - if std::env::var("TABULARIS_TEST_PG").is_err() { - return None; - } - Some(ConnectionParams { - driver: "postgres".to_string(), - host: Some( - std::env::var("TABULARIS_TEST_PG_HOST").unwrap_or_else(|_| "localhost".to_string()), - ), - port: std::env::var("TABULARIS_TEST_PG_PORT") - .ok() - .and_then(|p| p.parse().ok()) - .or(Some(55432)), - username: Some( - std::env::var("TABULARIS_TEST_PG_USER").unwrap_or_else(|_| "postgres".to_string()), - ), - password: Some( - std::env::var("TABULARIS_TEST_PG_PASSWORD") - .unwrap_or_else(|_| "postgres".to_string()), - ), - database: DatabaseSelection::Single( - std::env::var("TABULARIS_TEST_PG_DB").unwrap_or_else(|_| "postgres".to_string()), - ), - ..Default::default() - }) - } - - #[tokio::test] - #[ignore] - async fn live_pg_update_record_handles_temporal_and_uuid_columns() { - let Some(params) = test_params() else { - eprintln!("skipping: set TABULARIS_TEST_PG=1 to run this test"); - return; - }; - - let pool = crate::pool_manager::get_postgres_pool(¶ms) - .await - .expect("connect to test postgres"); - let setup_client = pool.get().await.expect("get client"); - setup_client - .batch_execute( - "DROP TABLE IF EXISTS tabularis_401_regression; \ - CREATE TABLE tabularis_401_regression ( \ - id uuid PRIMARY KEY, \ - created_at timestamptz NOT NULL, \ - due_date date, \ - start_time time without time zone \ - ); \ - INSERT INTO tabularis_401_regression (id, created_at, due_date, start_time) \ - VALUES ('550e8400-e29b-41d4-a716-446655440000', '2024-01-15 10:30:00+00', '2024-01-15', '08:00:00');", - ) - .await - .expect("seed table"); - drop(setup_client); - - let mut pk_map = HashMap::new(); - pk_map.insert( - "id".to_string(), - serde_json::json!("550e8400-e29b-41d4-a716-446655440000"), - ); - - // Exactly the #401 repro: edit a `timestamptz` cell via the data-grid path. - let updated = super::super::update_record( - ¶ms, - "tabularis_401_regression", - &pk_map, - "created_at", - serde_json::json!("2025-06-30T12:00:00+00:00"), - "public", - 10 * 1024 * 1024, - ) - .await - .expect("update timestamptz column"); - assert_eq!(updated, 1); - - // `date` column. - let updated = super::super::update_record( - ¶ms, - "tabularis_401_regression", - &pk_map, - "due_date", - serde_json::json!("2025-07-01"), - "public", - 10 * 1024 * 1024, - ) - .await - .expect("update date column"); - assert_eq!(updated, 1); - - // `time` column. - let updated = super::super::update_record( - ¶ms, - "tabularis_401_regression", - &pk_map, - "start_time", - serde_json::json!("09:30:00"), - "public", - 10 * 1024 * 1024, - ) - .await - .expect("update time column"); - assert_eq!(updated, 1); - - // #392 sibling bug: a uuid-shaped string PK must still bind correctly - // for the row to be found at all by the predicate above — implicitly - // covered by every assert_eq!(updated, 1) succeeding, since the WHERE - // clause uses the same uuid-cast binding path. - } -} - -mod routine_management { - use super::super::routines::{drop_routine_sql, routine_call_sql, routine_create_template}; - use crate::models::RoutineCallArg; - - fn arg(name: &str, mode: &str, value: Option<&str>, is_raw: bool) -> RoutineCallArg { - RoutineCallArg { - name: name.to_string(), - mode: mode.to_string(), - value: value.map(|v| v.to_string()), - is_raw, - } - } - - #[test] - fn function_call_uses_select_star_from() { - let sql = routine_call_sql( - "fn_report", - "FUNCTION", - &[arg("p_year", "IN", Some("2026"), true)], - Some("public"), - ); - assert_eq!(sql, "SELECT * FROM \"public\".\"fn_report\"(2026);"); - } - - #[test] - fn function_call_excludes_out_params() { - // PostgreSQL functions do not accept pure OUT parameters in the call - // signature; only IN/INOUT are passed. - let sql = routine_call_sql( - "fn_split", - "FUNCTION", - &[ - arg("p_in", "IN", Some("5"), true), - arg("p_lo", "OUT", None, false), - arg("p_hi", "OUT", None, false), - ], - Some("public"), - ); - assert_eq!(sql, "SELECT * FROM \"public\".\"fn_split\"(5);"); - } - - #[test] - fn function_call_keeps_inout_params() { - let sql = routine_call_sql( - "fn_adjust", - "FUNCTION", - &[ - arg("p_val", "INOUT", Some("10"), true), - arg("p_out", "OUT", None, false), - ], - Some("public"), - ); - assert_eq!(sql, "SELECT * FROM \"public\".\"fn_adjust\"(10);"); - } - - #[test] - fn procedure_call_renders_out_params_as_null() { - let sql = routine_call_sql( - "sp_test", - "PROCEDURE", - &[ - arg("p_in", "IN", Some("it's"), false), - arg("p_out", "OUT", None, false), - ], - Some("public"), - ); - assert_eq!(sql, "CALL \"public\".\"sp_test\"('it''s', NULL);"); - } - - #[test] - fn create_templates_are_schema_qualified_or_replace() { - let tpl = routine_create_template("FUNCTION", Some("app")); - assert!( - tpl.starts_with("CREATE OR REPLACE FUNCTION \"app\"."), - "{tpl}" - ); - let tpl = routine_create_template("PROCEDURE", None); - assert!( - tpl.starts_with("CREATE OR REPLACE PROCEDURE my_procedure"), - "{tpl}" - ); - } - - #[test] - fn drop_sql_includes_identity_signature() { - assert_eq!( - drop_routine_sql("fn_add", "FUNCTION", "integer, integer", Some("public")), - "DROP FUNCTION \"public\".\"fn_add\"(integer, integer)" - ); - assert_eq!( - drop_routine_sql("sp", "PROCEDURE", "", None), - "DROP PROCEDURE \"sp\"()" - ); - } -} - -mod build_connection_url_tests { - use super::super::PostgresDriver; - use crate::drivers::driver_trait::DatabaseDriver; - use crate::models::{ConnectionParams, DatabaseSelection}; - - fn params_with_ssl_mode(ssl_mode: Option<&str>) -> ConnectionParams { - ConnectionParams { - driver: "postgres".to_string(), - host: Some("127.0.0.1".to_string()), - port: Some(5432), - username: Some("postgres".to_string()), - password: Some("secret".to_string()), - database: DatabaseSelection::Single("app".to_string()), - ssl_mode: ssl_mode.map(|s| s.to_string()), - ..Default::default() - } - } - - #[test] - fn includes_disabled_ssl_mode() { - let driver = PostgresDriver::new(); - let url = driver - .build_connection_url(¶ms_with_ssl_mode(Some("disable"))) - .unwrap(); - assert!(url.contains("sslmode=disable"), "url was: {url}"); - } - - #[test] - fn defaults_to_prefer_when_unset() { - let driver = PostgresDriver::new(); - let url = driver - .build_connection_url(¶ms_with_ssl_mode(None)) - .unwrap(); - assert!(url.contains("sslmode=prefer"), "url was: {url}"); - } -} - -mod pg_vector_binding_tests { - use super::*; - - fn bind_vector(value: &str, column_type: &str) -> BoundValue { - bind_pg_value( - serde_json::json!(value), - 1, - PgValueOptions { - column_type: Some(column_type), - enum_type: None, - max_blob_size: u64::MAX, - allow_default: false, - hstore_oid: None, - }, - ) - .unwrap() - } - - #[test] - fn vector_value_is_inlined_as_typed_literal() { - let bound = bind_vector("[1,2,3]", "vector"); - assert_eq!(bound.sql, "'[1,2,3]'::vector"); - assert!(bound.param.is_none()); - } - - #[test] - fn halfvec_and_sparsevec_are_inlined_with_their_own_type() { - let halfvec = bind_vector("[1,2,3]", "halfvec"); - assert_eq!(halfvec.sql, "'[1,2,3]'::halfvec"); - assert!(halfvec.param.is_none()); - - let sparsevec = bind_vector("{1:1,3:2}/5", "sparsevec"); - assert_eq!(sparsevec.sql, "'{1:1,3:2}/5'::sparsevec"); - assert!(sparsevec.param.is_none()); - } - - #[test] - fn surrounding_whitespace_is_trimmed_before_inlining() { - let bound = bind_vector(" [1,2,3] ", "vector"); - assert_eq!(bound.sql, "'[1,2,3]'::vector"); - } - - #[test] - fn non_numeric_vector_value_is_rejected() { - let result = bind_pg_value( - serde_json::json!("[1,2,3]); DROP TABLE t"), - 1, - PgValueOptions { - column_type: Some("vector"), - enum_type: None, - max_blob_size: u64::MAX, - allow_default: false, - hstore_oid: None, - }, - ); - let err = match result { - Ok(_) => panic!("expected non-numeric vector value to be rejected"), - Err(err) => err, - }; - assert!(err.contains("Invalid vector value"), "{err}"); - } -} - -/// The catalog lookups that identify ONE routine out of a name's overloads (#893). -/// -/// Pure string builders, so what is asserted is the shape of the predicate: a -/// signature-keyed lookup names one row and must not fall back to `LIMIT 1`, -/// which is what silently answered about an arbitrary overload before. -mod routine_overload_sql_tests { - use super::super::routines::{ - routine_definition_sql, routine_exists_sql, routine_parameters_sql, - routine_return_type_sql, routine_specific_name_sql, - }; - - #[test] - fn definition_by_identity_filters_on_the_signature() { - let sql = routine_definition_sql(true); - assert!(sql.contains("pg_get_function_identity_arguments(p.oid) = $3")); - assert!(sql.contains("pg_get_functiondef(p.oid)")); - } - - #[test] - fn definition_by_identity_takes_no_limit() { - // A LIMIT here would mean the signature had not actually narrowed it. - assert!(!routine_definition_sql(true) - .to_uppercase() - .contains("LIMIT")); - } - - #[test] - fn definition_without_an_identity_keeps_the_old_lookup() { - let sql = routine_definition_sql(false); - assert!(sql.to_uppercase().contains("LIMIT 1")); - assert!(!sql.contains("pg_get_function_identity_arguments")); - } - - #[test] - fn the_two_definition_forms_are_not_the_same_statement() { - assert_ne!(routine_definition_sql(true), routine_definition_sql(false)); - } - - #[test] - fn exists_check_is_keyed_on_all_three_parts() { - let sql = routine_exists_sql(); - assert!(sql.contains("n.nspname = $1")); - assert!(sql.contains("p.proname = $2")); - assert!(sql.contains("pg_get_function_identity_arguments(p.oid) = $3")); - } - - #[test] - fn specific_name_uses_the_view_s_own_function_rather_than_reimplementing_it() { - // The obvious `proname || '_' || oid` is WRONG, and this test used to - // pin it, which is how it shipped. `information_schema` builds the - // column with `nameconcatoid`, which truncates the name part so the OID - // survives 63 bytes; the plain concatenation does not truncate at all, - // so a long-named routine matched nothing (#926 review). - let sql = routine_specific_name_sql(true); - assert!(sql.contains("nameconcatoid(p.proname, p.oid)::text")); - assert!(!sql.contains("p.proname || '_' || p.oid AS")); - assert!(sql.contains("pg_get_function_identity_arguments(p.oid) = $3")); - } - - #[test] - fn specific_name_before_postgresql_12_does_not_truncate_because_the_view_did_not() { - // `nameconcatoid` arrived in 12 and referencing it earlier fails at - // parse time, so those versions need their own expression - and theirs - // truncates nothing. `sql_identifier` was a domain over `character - // varying` until 12 made it a `name`, so the view carried the whole - // concatenation. Measured on 11.16: specific_name is the full 66 - // characters, the `::text` form matches it and a `::name` cast does not. - // - // Casting to `name` here would be the mirror of the bug this function - // exists to fix: truncating where the view does not. - let sql = routine_specific_name_sql(false); - assert!(sql.contains("(p.proname || '_' || p.oid)::text")); - assert!(!sql.contains("::name")); - assert!(!sql.contains("nameconcatoid")); - } - - #[test] - fn both_specific_name_forms_are_keyed_on_all_three_parts() { - for sql in [ - routine_specific_name_sql(true), - routine_specific_name_sql(false), - ] { - assert!(sql.contains("n.nspname = $1")); - assert!(sql.contains("p.proname = $2")); - assert!(sql.contains("pg_get_function_identity_arguments(p.oid) = $3")); - } - } - - #[test] - fn return_type_by_specific_name_drops_the_limit() { - let sql = routine_return_type_sql(true); - assert!(sql.contains("r.specific_name = $2")); - assert!(!sql.to_uppercase().contains("LIMIT")); - } - - #[test] - fn return_type_without_one_keeps_the_old_lookup() { - let sql = routine_return_type_sql(false); - assert!(sql.to_uppercase().contains("LIMIT 1")); - assert!(!sql.contains("specific_name")); - } - - #[test] - fn parameters_by_specific_name_need_no_join() { - // The join on routines existed only to filter by routine_name, which is - // what let every overload's parameters into one list. - let sql = routine_parameters_sql(true); - assert!(sql.contains("p.specific_name = $2")); - assert!(sql.contains("p.specific_schema = $1")); - assert!(!sql.to_uppercase().contains("JOIN")); - } - - #[test] - fn parameters_without_one_keep_the_old_join() { - let sql = routine_parameters_sql(false); - assert!(sql.to_uppercase().contains("JOIN")); - assert!(sql.contains("r.routine_name = $2")); - } - - #[test] - fn every_form_still_orders_parameters_by_position() { - for sql in [routine_parameters_sql(true), routine_parameters_sql(false)] { - assert!(sql.contains("ORDER BY p.ordinal_position")); - } - } -} - -/// Overloaded routines, against a real server (#893). -/// -/// These are the assertions the pure tests above cannot make: that the -/// signature the sidebar reports and the one the catalog renders are the same -/// string, so filtering on it reaches exactly the routine the user clicked. -/// TABULARIS_TEST_PG=1 cargo test --lib live_pg_routine_overloads -- --ignored -#[cfg(test)] -mod live_pg_routine_overloads { - use crate::models::{ConnectionParams, DatabaseSelection}; - - fn test_params() -> Option { - if std::env::var("TABULARIS_TEST_PG").is_err() { - return None; - } - Some(ConnectionParams { - driver: "postgres".to_string(), - host: Some( - std::env::var("TABULARIS_TEST_PG_HOST").unwrap_or_else(|_| "localhost".to_string()), - ), - port: std::env::var("TABULARIS_TEST_PG_PORT") - .ok() - .and_then(|p| p.parse().ok()) - .or(Some(55432)), - username: Some( - std::env::var("TABULARIS_TEST_PG_USER").unwrap_or_else(|_| "postgres".to_string()), - ), - password: Some( - std::env::var("TABULARIS_TEST_PG_PASSWORD") - .unwrap_or_else(|_| "postgres".to_string()), - ), - database: DatabaseSelection::Single( - std::env::var("TABULARIS_TEST_PG_DB").unwrap_or_else(|_| "postgres".to_string()), - ), - ..Default::default() - }) - } - - /// One schema per test, because `cargo test` runs them in parallel and a - /// shared one races on its own CREATE: three of four lost that race before - /// this took the name as an argument. - async fn seed(params: &ConnectionParams, schema: &str) { - let pool = crate::pool_manager::get_postgres_pool(params) - .await - .expect("connect to test postgres"); - let client = pool.get().await.expect("get client"); - client - .batch_execute(&format!( - "DROP SCHEMA IF EXISTS {schema} CASCADE; - CREATE SCHEMA {schema}; - CREATE FUNCTION {schema}.f() RETURNS integer LANGUAGE sql AS $$ SELECT 0 $$; - CREATE FUNCTION {schema}.f(a integer) RETURNS integer LANGUAGE sql AS $$ SELECT a + 1 $$; - CREATE FUNCTION {schema}.f(a text) RETURNS text LANGUAGE sql AS $$ SELECT a || '!' $$; - CREATE FUNCTION {schema}.f(a integer, b integer) RETURNS integer LANGUAGE sql AS $$ SELECT a + b $$; - CREATE PROCEDURE {schema}.p(a integer) LANGUAGE plpgsql AS $$ BEGIN RAISE NOTICE '%', a; END $$;" - )) - .await - .expect("seed schema"); - } - - #[tokio::test] - #[ignore] - async fn live_pg_routine_overloads_are_listed_one_row_each_with_a_signature() { - let Some(params) = test_params() else { - eprintln!("skipping: set TABULARIS_TEST_PG=1 to run this test"); - return; - }; - let schema = "tabularis_893_list"; - seed(¶ms, schema).await; - - let routines = super::super::get_routines(¶ms, schema) - .await - .expect("list routines"); - - let f: Vec<_> = routines.iter().filter(|r| r.name == "f").collect(); - assert_eq!(f.len(), 4, "four overloads of f"); - - // The signature is what tells them apart, and the empty one is a value: - // it is the signature of f(), not a missing field. - let mut signatures: Vec<&str> = f - .iter() - .map(|r| { - r.identity_args - .as_deref() - .expect("a signature per overload") - }) - .collect(); - signatures.sort_unstable(); - assert_eq!( - signatures, - vec!["", "a integer", "a integer, b integer", "a text"] - ); - } - - #[tokio::test] - #[ignore] - async fn live_pg_definition_follows_the_signature_rather_than_limit_one() { - let Some(params) = test_params() else { - eprintln!("skipping: set TABULARIS_TEST_PG=1 to run this test"); - return; - }; - let schema = "tabularis_893_def"; - seed(¶ms, schema).await; - - // Each overload asked for by its own signature answers its own body. - for (identity, body) in [ - ("a integer", "SELECT a + 1"), - ("a text", "SELECT a || '!'"), - ("a integer, b integer", "SELECT a + b"), - ("", "SELECT 0"), - ] { - let definition = super::super::get_routine_definition( - ¶ms, - "f", - "FUNCTION", - schema, - Some(identity), - ) - .await - .unwrap_or_else(|e| panic!("definition for f({identity}): {e}")); - assert!( - definition.contains(body), - "f({identity}) answered the wrong overload: {definition}" - ); - } - - // Without a signature it is still the pre-#893 read, which answers about - // whichever row the scan returns. Asserted as "one of them" rather than - // a particular one, because which it is was never a promise. - let any = super::super::get_routine_definition(¶ms, "f", "FUNCTION", schema, None) - .await - .expect("definition without a signature"); - assert!(any.contains(&format!("CREATE OR REPLACE FUNCTION {schema}.f"))); - } - - #[tokio::test] - #[ignore] - async fn live_pg_parameters_are_one_overloads_own() { - let Some(params) = test_params() else { - eprintln!("skipping: set TABULARIS_TEST_PG=1 to run this test"); - return; - }; - let schema = "tabularis_893_params"; - seed(¶ms, schema).await; - - // f(a integer, b integer) has two parameters plus the return row. - let two = super::super::get_routine_parameters( - ¶ms, - "f", - schema, - Some("a integer, b integer"), - ) - .await - .expect("parameters for f(a integer, b integer)"); - let names: Vec<&str> = two - .iter() - .filter(|p| !p.name.is_empty()) - .map(|p| p.name.as_str()) - .collect(); - assert_eq!(names, vec!["a", "b"]); - - // f(a text) has one, and it is a text one: with the old name-only filter - // this list carried every overload's parameters at once. - let one = super::super::get_routine_parameters(¶ms, "f", schema, Some("a text")) - .await - .expect("parameters for f(a text)"); - let typed: Vec<(&str, &str)> = one - .iter() - .filter(|p| !p.name.is_empty()) - .map(|p| (p.name.as_str(), p.data_type.as_str())) - .collect(); - assert_eq!(typed, vec![("a", "text")]); - - // f() has none. - let none = super::super::get_routine_parameters(¶ms, "f", schema, Some("")) - .await - .expect("parameters for f()"); - assert!( - none.iter().all(|p| p.name.is_empty()), - "f() takes no arguments" - ); - } - - /// A routine whose name is long enough that `information_schema` truncates - /// its `specific_name`, which the parameter read is keyed on (#926 review). - /// - /// Not an overload case at all, and that is the point: the UI sends a - /// signature for every routine on this driver, so a derivation that did not - /// truncate the same way the view does answered with no parameters for - /// long-named routines that work fine on main. - #[tokio::test] - #[ignore] - async fn live_pg_parameters_survive_a_name_information_schema_truncates() { - let Some(params) = test_params() else { - eprintln!("skipping: set TABULARIS_TEST_PG=1 to run this test"); - return; - }; - let schema = "tabularis_893_long"; - let long_name = "fn_with_a_really_long_name_to_hit_namedatalen_limit_abcdefgh"; - assert!( - long_name.len() > 40, - "the name has to be long enough to truncate" - ); - - let pool = crate::pool_manager::get_postgres_pool(¶ms) - .await - .expect("connect to test postgres"); - let client = pool.get().await.expect("get client"); - client - .batch_execute(&format!( - "DROP SCHEMA IF EXISTS {schema} CASCADE; - CREATE SCHEMA {schema}; - CREATE FUNCTION {schema}.{long_name}(a integer, b text) - RETURNS integer LANGUAGE sql AS $$ SELECT a $$;" - )) - .await - .expect("seed the long-named routine"); - - // The signature the listing reports, which is what the UI sends back. - let listed = super::super::get_routines(¶ms, schema) - .await - .expect("list routines"); - let identity = listed - .iter() - .find(|r| r.name == long_name) - .and_then(|r| r.identity_args.as_deref()) - .expect("the long-named routine is listed with a signature"); - - let parameters = - super::super::get_routine_parameters(¶ms, long_name, schema, Some(identity)) - .await - .expect("parameters for the long-named routine"); - - let named: Vec<&str> = parameters - .iter() - .filter(|p| !p.name.is_empty()) - .map(|p| p.name.as_str()) - .collect(); - assert_eq!( - named, - vec!["a", "b"], - "a truncated specific_name left this empty, got: {named:?}" - ); - // And the return type row, which came from the same lookup. - assert!( - parameters - .iter() - .any(|p| p.name.is_empty() && p.mode == "OUT"), - "the return type row is missing: {parameters:?}" - ); - } - - #[tokio::test] - #[ignore] - async fn live_pg_drop_takes_the_named_overload_and_leaves_the_rest() { - let Some(params) = test_params() else { - eprintln!("skipping: set TABULARIS_TEST_PG=1 to run this test"); - return; - }; - let schema = "tabularis_893_drop"; - seed(¶ms, schema).await; - - super::super::drop_routine(¶ms, "f", "FUNCTION", schema, Some("a text")) - .await - .expect("drop f(a text)"); - - let left = super::super::get_routines(¶ms, schema) - .await - .expect("list routines"); - let mut signatures: Vec<&str> = left - .iter() - .filter(|r| r.name == "f") - .map(|r| r.identity_args.as_deref().unwrap_or("?")) - .collect(); - signatures.sort_unstable(); - assert_eq!(signatures, vec!["", "a integer", "a integer, b integer"]); - - // A signature the server does not have is refused rather than dropping - // something else, which is the whole point of naming one. - let refused = - super::super::drop_routine(¶ms, "f", "FUNCTION", schema, Some("a text")).await; - assert!( - refused.is_err(), - "a missing overload must not be a silent no-op" - ); - - // A procedure too, by whatever signature the listing reported for it. - // Read rather than written out: PostgreSQL 18 renders a procedure's - // argument as `IN a integer` and 11.16 as `a integer`, so a literal - // here tested the server's spelling instead of the driver's round trip. - let procedure_identity = left - .iter() - .find(|r| r.name == "p") - .and_then(|r| r.identity_args.as_deref()) - .expect("the procedure is listed with a signature"); - - super::super::drop_routine(¶ms, "p", "PROCEDURE", schema, Some(procedure_identity)) - .await - .unwrap_or_else(|e| panic!("drop p({procedure_identity}): {e}")); - } -} - -/// Query timeout and Stop against a live server. Each test looks for its own -/// statement in `pg_stat_activity` to prove the server stopped running it, -/// not just that the client stopped waiting. -/// -/// Ignored by default; see `live_pg_temporal_and_uuid_regression` for setup. -#[cfg(test)] -mod live_pg_query_timeout { - use crate::models::{ConnectionParams, DatabaseSelection}; - use std::time::{Duration, Instant}; - - fn test_params() -> Option { - if std::env::var("TABULARIS_TEST_PG").is_err() { - return None; - } - Some(ConnectionParams { - driver: "postgres".to_string(), - host: Some( - std::env::var("TABULARIS_TEST_PG_HOST").unwrap_or_else(|_| "localhost".to_string()), - ), - port: std::env::var("TABULARIS_TEST_PG_PORT") - .ok() - .and_then(|p| p.parse().ok()) - .or(Some(55432)), - username: Some( - std::env::var("TABULARIS_TEST_PG_USER").unwrap_or_else(|_| "postgres".to_string()), - ), - password: Some( - std::env::var("TABULARIS_TEST_PG_PASSWORD") - .unwrap_or_else(|_| "postgres".to_string()), - ), - database: DatabaseSelection::Single( - std::env::var("TABULARIS_TEST_PG_DB").unwrap_or_else(|_| "postgres".to_string()), - ), - ..Default::default() - }) - } - - /// Whether another backend is running a statement containing `marker`. - async fn server_is_running(params: &ConnectionParams, marker: &str) -> bool { - let pool = crate::pool_manager::get_postgres_pool(params) - .await - .expect("connect to test postgres"); - let client = pool.get().await.expect("get client"); - let row = client - .query_one( - "SELECT count(*) FROM pg_stat_activity \ - WHERE state = 'active' AND pid <> pg_backend_pid() \ - AND position($1 in query) > 0", - &[&marker], - ) - .await - .expect("read pg_stat_activity"); - row.get::<_, i64>(0) > 0 - } - - async fn wait_until(params: &ConnectionParams, marker: &str, running: bool) -> bool { - let deadline = Instant::now() + Duration::from_secs(5); - while Instant::now() < deadline { - if server_is_running(params, marker).await == running { - return true; - } - tokio::time::sleep(Duration::from_millis(100)).await; - } - false - } - - #[tokio::test] - #[ignore] - async fn live_pg_query_timeout_stops_the_statement_on_the_server() { - let Some(mut params) = test_params() else { - eprintln!("skipping: set TABULARIS_TEST_PG=1 to run this test"); - return; - }; - params.query_timeout_secs = Some(1); - let marker = "tabularis_989_timeout"; - let queries = vec![ - format!("SELECT pg_sleep(60) /* {marker} */"), - "SELECT 1 AS still_usable".to_string(), - ]; - - let start = Instant::now(); - let results = super::super::execute_batch(¶ms, &queries, None, 1, None, None) - .await - .expect("the batch completes"); - - let elapsed = start.elapsed(); - assert!(elapsed < Duration::from_secs(10), "took {elapsed:?}"); - let error = results[0].error.as_deref().unwrap_or_default(); - assert!( - error.contains("stopped after 1 s"), - "unexpected error: {error}" - ); - assert!( - results[1].result.is_some(), - "the connection is usable after the cancel: {:?}", - results[1].error - ); - assert!( - wait_until(¶ms, marker, false).await, - "the server is still running the timed-out statement" - ); - } - - #[tokio::test] - #[ignore] - async fn live_pg_dropped_run_stops_the_statement_on_the_server() { - let Some(params) = test_params() else { - eprintln!("skipping: set TABULARIS_TEST_PG=1 to run this test"); - return; - }; - let marker = "tabularis_989_stop"; - let query = format!("SELECT pg_sleep(60) /* {marker} */"); - - // What the Stop button does: abort the task running the query. - let run = { - let params = params.clone(); - tokio::spawn(async move { - super::super::execute_query(¶ms, &query, None, 1, None).await - }) - }; - assert!( - wait_until(¶ms, marker, true).await, - "the statement never started" - ); - run.abort(); - - assert!( - wait_until(¶ms, marker, false).await, - "the server kept running the statement after Stop" - ); - } -} - -/// What `RoutineInfo` puts on the wire for each kind of dialect (#893). -/// -/// The field is read in TypeScript, where `null` and `undefined` are different -/// values and only one of them is what the declaration promises. `None` is -/// skipped rather than serialized, so on a dialect without signatures the field -/// is absent; that shape is pinned here rather than left to whoever next reads -/// the struct. -#[cfg(test)] -mod routine_info_wire_shape_tests { - use crate::models::RoutineInfo; - - fn info(identity_args: Option<&str>) -> RoutineInfo { - RoutineInfo { - name: "f".to_string(), - routine_type: "FUNCTION".to_string(), - definition: None, - identity_args: identity_args.map(str::to_string), - } - } - - #[test] - fn a_dialect_without_signatures_omits_the_field_entirely() { - // MySQL and SQLite send None. Absent reaches TypeScript as `undefined`, - // which is what `identity_args?: string` promises; `null` did not. - let json = serde_json::to_value(info(None)).expect("serialize"); - assert!( - json.get("identity_args").is_none(), - "identity_args must be absent, not null: {json}" - ); - } - - #[test] - fn a_signature_is_carried_verbatim() { - let json = serde_json::to_value(info(Some("a integer"))).expect("serialize"); - assert_eq!(json["identity_args"], "a integer"); - } - - #[test] - fn the_empty_signature_is_carried_rather_than_skipped() { - // THE case the skip must not swallow: "" is a no-argument routine's own - // signature, and it is what tells f() apart from f(a integer). Only - // `None` means "this dialect does not overload". - let json = serde_json::to_value(info(Some(""))).expect("serialize"); - assert_eq!(json["identity_args"], ""); - assert!(json.get("identity_args").is_some()); - } - - #[test] - fn an_absent_field_round_trips_back_to_none() { - // A plugin driver may send RoutineInfo without the field at all. - let info: RoutineInfo = - serde_json::from_str(r#"{"name":"f","routine_type":"FUNCTION","definition":null}"#) - .expect("deserialize without identity_args"); - assert_eq!(info.identity_args, None); - } - - #[test] - fn an_explicit_null_from_a_plugin_still_deserializes_to_none() { - let info: RoutineInfo = serde_json::from_str( - r#"{"name":"f","routine_type":"FUNCTION","definition":null,"identity_args":null}"#, - ) - .expect("deserialize with an explicit null"); - assert_eq!(info.identity_args, None); - } -} diff --git a/src-tauri/src/drivers/postgres/types.rs b/src-tauri/src/drivers/postgres/types.rs deleted file mode 100644 index 8f2fc1614..000000000 --- a/src-tauri/src/drivers/postgres/types.rs +++ /dev/null @@ -1,837 +0,0 @@ -use crate::models::DataTypeInfo; - -/// Returns the list of data types supported by PostgreSQL. -/// Includes types from extensions (hstore, ltree, citext, PostGIS, etc.). -pub fn get_data_types() -> Vec { - vec![ - // ============================================================ - // Numeric types - // ============================================================ - DataTypeInfo { - name: "SMALLINT".to_string(), - category: "numeric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: true, - requires_extension: None, - }, - DataTypeInfo { - name: "INTEGER".to_string(), - category: "numeric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: true, - requires_extension: None, - }, - DataTypeInfo { - name: "BIGINT".to_string(), - category: "numeric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: true, - requires_extension: None, - }, - DataTypeInfo { - name: "DECIMAL".to_string(), - category: "numeric".to_string(), - requires_length: false, - requires_precision: true, - default_length: Some("10,2".to_string()), - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "NUMERIC".to_string(), - category: "numeric".to_string(), - requires_length: false, - requires_precision: true, - default_length: Some("10,2".to_string()), - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "REAL".to_string(), - category: "numeric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "DOUBLE PRECISION".to_string(), - category: "numeric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "SMALLSERIAL".to_string(), - category: "numeric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "SERIAL".to_string(), - category: "numeric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "BIGSERIAL".to_string(), - category: "numeric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "MONEY".to_string(), - category: "numeric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // String / Character types - // ============================================================ - DataTypeInfo { - name: "VARCHAR".to_string(), - category: "string".to_string(), - requires_length: true, - requires_precision: false, - default_length: Some("255".to_string()), - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "CHAR".to_string(), - category: "string".to_string(), - requires_length: true, - requires_precision: false, - default_length: Some("10".to_string()), - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "TEXT".to_string(), - category: "string".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "NAME".to_string(), - category: "string".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "\"char\"".to_string(), - category: "string".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // Boolean - // ============================================================ - DataTypeInfo { - name: "BOOLEAN".to_string(), - category: "boolean".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // Date/Time types - // ============================================================ - DataTypeInfo { - name: "DATE".to_string(), - category: "date".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "TIME".to_string(), - category: "date".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "TIMETZ".to_string(), - category: "date".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "TIMESTAMP".to_string(), - category: "date".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "TIMESTAMPTZ".to_string(), - category: "date".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "INTERVAL".to_string(), - category: "date".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // JSON types - // ============================================================ - DataTypeInfo { - name: "JSON".to_string(), - category: "json".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "JSONB".to_string(), - category: "json".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "JSONPATH".to_string(), - category: "json".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // UUID - // ============================================================ - DataTypeInfo { - name: "UUID".to_string(), - category: "identifier".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // Binary types - // ============================================================ - DataTypeInfo { - name: "BYTEA".to_string(), - category: "binary".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // Bit string types - // ============================================================ - DataTypeInfo { - name: "BIT".to_string(), - category: "bit".to_string(), - requires_length: true, - requires_precision: false, - default_length: Some("1".to_string()), - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "VARBIT".to_string(), - category: "bit".to_string(), - requires_length: true, - requires_precision: false, - default_length: Some("64".to_string()), - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // Network address types - // ============================================================ - DataTypeInfo { - name: "INET".to_string(), - category: "network".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "CIDR".to_string(), - category: "network".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "MACADDR".to_string(), - category: "network".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "MACADDR8".to_string(), - category: "network".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // Geometric types (built-in) - // ============================================================ - DataTypeInfo { - name: "POINT".to_string(), - category: "geometric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "LINE".to_string(), - category: "geometric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "LSEG".to_string(), - category: "geometric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "BOX".to_string(), - category: "geometric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "PATH".to_string(), - category: "geometric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "POLYGON".to_string(), - category: "geometric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "CIRCLE".to_string(), - category: "geometric".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // Full text search types - // ============================================================ - DataTypeInfo { - name: "TSVECTOR".to_string(), - category: "fulltext".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "TSQUERY".to_string(), - category: "fulltext".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // XML - // ============================================================ - DataTypeInfo { - name: "XML".to_string(), - category: "xml".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // System / Internal types (rarely used in user tables) - // ============================================================ - DataTypeInfo { - name: "OID".to_string(), - category: "system".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "XID".to_string(), - category: "system".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "XID8".to_string(), - category: "system".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "CID".to_string(), - category: "system".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "TID".to_string(), - category: "system".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // Object identifier (Reg) types - // ============================================================ - DataTypeInfo { - name: "REGCLASS".to_string(), - category: "reg".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "REGTYPE".to_string(), - category: "reg".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "REGPROC".to_string(), - category: "reg".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "REGPROCEDURE".to_string(), - category: "reg".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "REGOPER".to_string(), - category: "reg".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "REGOPERATOR".to_string(), - category: "reg".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "REGCONFIG".to_string(), - category: "reg".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "REGDICTIONARY".to_string(), - category: "reg".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "REGNAMESPACE".to_string(), - category: "reg".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "REGROLE".to_string(), - category: "reg".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "REGCOLLATION".to_string(), - category: "reg".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - // ============================================================ - // Extension: hstore (CREATE EXTENSION hstore) - // ============================================================ - DataTypeInfo { - name: "HSTORE".to_string(), - category: "extension".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("hstore".to_string()), - }, - // ============================================================ - // Extension: ltree (CREATE EXTENSION ltree) - // ============================================================ - DataTypeInfo { - name: "LTREE".to_string(), - category: "extension".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("ltree".to_string()), - }, - DataTypeInfo { - name: "LQUERY".to_string(), - category: "extension".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("ltree".to_string()), - }, - DataTypeInfo { - name: "LTXTQUERY".to_string(), - category: "extension".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("ltree".to_string()), - }, - // ============================================================ - // Extension: citext (CREATE EXTENSION citext) - // ============================================================ - DataTypeInfo { - name: "CITEXT".to_string(), - category: "extension".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("citext".to_string()), - }, - // ============================================================ - // Extension: pg_trgm (CREATE EXTENSION pg_trgm) - // ============================================================ - DataTypeInfo { - name: "GTSVECTOR".to_string(), - category: "extension".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("pg_trgm".to_string()), - }, - // ============================================================ - // Extension: PostGIS (CREATE EXTENSION postgis) - // WARNING: These types are not supported by `tokio-postgres` - // ============================================================ - DataTypeInfo { - name: "GEOMETRY".to_string(), - category: "spatial".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("postgis".to_string()), - }, - DataTypeInfo { - name: "GEOGRAPHY".to_string(), - category: "spatial".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("postgis".to_string()), - }, - DataTypeInfo { - name: "GEOMETRY(Point, 4326)".to_string(), - category: "spatial".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("postgis".to_string()), - }, - DataTypeInfo { - name: "GEOMETRY(LineString, 4326)".to_string(), - category: "spatial".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("postgis".to_string()), - }, - DataTypeInfo { - name: "GEOMETRY(Polygon, 4326)".to_string(), - category: "spatial".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("postgis".to_string()), - }, - DataTypeInfo { - name: "GEOMETRY(MultiPoint, 4326)".to_string(), - category: "spatial".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("postgis".to_string()), - }, - DataTypeInfo { - name: "GEOMETRY(MultiLineString, 4326)".to_string(), - category: "spatial".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("postgis".to_string()), - }, - DataTypeInfo { - name: "GEOMETRY(MultiPolygon, 4326)".to_string(), - category: "spatial".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("postgis".to_string()), - }, - DataTypeInfo { - name: "GEOMETRY(GeometryCollection, 4326)".to_string(), - category: "spatial".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("postgis".to_string()), - }, - DataTypeInfo { - name: "GEOGRAPHY(Point, 4326)".to_string(), - category: "spatial".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("postgis".to_string()), - }, - // ============================================================ - // Extension: intarray (CREATE EXTENSION intarray) - // ============================================================ - DataTypeInfo { - name: "INTARRAY".to_string(), - category: "extension".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: Some("intarray".to_string()), - }, - // ============================================================ - // Arrays (PostgreSQL supports arrays of any type) - // ============================================================ - DataTypeInfo { - name: "INTEGER[]".to_string(), - category: "array".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "TEXT[]".to_string(), - category: "array".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "VARCHAR[]".to_string(), - category: "array".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "BOOLEAN[]".to_string(), - category: "array".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "UUID[]".to_string(), - category: "array".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "JSONB[]".to_string(), - category: "array".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "TIMESTAMP[]".to_string(), - category: "array".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - DataTypeInfo { - name: "NUMERIC[]".to_string(), - category: "array".to_string(), - requires_length: false, - requires_precision: false, - default_length: None, - supports_auto_increment: false, - requires_extension: None, - }, - ] -} diff --git a/src-tauri/src/drivers/registry.rs b/src-tauri/src/drivers/registry.rs index c9c54dc46..53edcf374 100644 --- a/src-tauri/src/drivers/registry.rs +++ b/src-tauri/src/drivers/registry.rs @@ -91,10 +91,23 @@ pub async fn get_connection_driver( ) -> Result, String> { let driver = get_driver(¶ms.driver) .await - .ok_or_else(|| format!("Unsupported driver: {}", params.driver))?; + .ok_or_else(|| unsupported_driver_message(¶ms.driver))?; Ok(driver.for_connection(params).await?.unwrap_or(driver)) } +/// The error for a connection whose driver id is not registered. A driver that +/// moved out of the app into a plugin names that plugin, so the person reading +/// it knows what to install rather than that something is "unsupported". +pub fn unsupported_driver_message(driver_id: &str) -> String { + let base = format!("Unsupported driver: {driver_id}"); + match crate::plugins::force_install::replacement_plugin_for(driver_id) { + Some(plugin_id) => format!( + "{base}. This driver is provided by the \"{plugin_id}\" plugin, which is not installed or not enabled. Install it from the plugin registry, then retry." + ), + None => base, + } +} + /// Returns `true` if `id` already has a registered driver or UI-only /// manifest. Lets a plugin-directory rescan (e.g. the standalone MCP /// subprocess reloading on a registry miss, issue #783) skip plugins it has diff --git a/src-tauri/src/drivers/sql_syntax_tests.rs b/src-tauri/src/drivers/sql_syntax_tests.rs index fe42a8229..e4053d8c0 100644 --- a/src-tauri/src/drivers/sql_syntax_tests.rs +++ b/src-tauri/src/drivers/sql_syntax_tests.rs @@ -149,8 +149,7 @@ fn without_sql_syntax_every_preset_resolves_unchanged() { #[test] fn builtin_drivers_declare_no_sql_syntax() { for driver in [ - Box::new(crate::drivers::postgres::PostgresDriver::new()) as Box, - Box::new(crate::drivers::mysql::MysqlDriver::new()), + Box::new(crate::drivers::mysql::MysqlDriver::new()) as Box, Box::new(crate::drivers::sqlite::SqliteDriver::new()), ] { let caps = &driver.manifest().capabilities; diff --git a/src-tauri/src/drivers/sqlite/mod.rs b/src-tauri/src/drivers/sqlite/mod.rs index c933e2817..69427e546 100644 --- a/src-tauri/src/drivers/sqlite/mod.rs +++ b/src-tauri/src/drivers/sqlite/mod.rs @@ -1154,6 +1154,7 @@ impl SqliteDriver { explain: true, readonly: false, read_only_queries: true, + table_copy: false, table_export: None, table_import: None, triggers: true, diff --git a/src-tauri/src/dump_utils.rs b/src-tauri/src/dump_utils.rs index 7e234a1c2..bdd34b38d 100644 --- a/src-tauri/src/dump_utils.rs +++ b/src-tauri/src/dump_utils.rs @@ -30,12 +30,10 @@ impl DumpDialect { /// Builds the dump dialect for a driver from its manifest capabilities. /// /// `driver_id` is only consulted to keep the historical Postgres handling - /// for the builtin `postgres` driver and the `postgresql` plugin when a - /// manifest predates `sql_dialect`; every other decision comes from the - /// capabilities. + /// for the `postgresql` plugin when a manifest predates `sql_dialect`; + /// every other decision comes from the capabilities. pub fn from_capabilities(driver_id: &str, caps: &DriverCapabilities) -> Self { - let postgres = caps.sql_dialect == Some(SqlDialect::Postgres) - || matches!(driver_id, "postgres" | "postgresql"); + let postgres = caps.sql_dialect == Some(SqlDialect::Postgres) || driver_id == "postgresql"; let identifier_quote = if caps.identifier_quote.is_empty() { "\"".to_string() } else { diff --git a/src-tauri/src/dump_utils/tests.rs b/src-tauri/src/dump_utils/tests.rs index b6e26e2fb..2a507f63d 100644 --- a/src-tauri/src/dump_utils/tests.rs +++ b/src-tauri/src/dump_utils/tests.rs @@ -5,7 +5,6 @@ use serde_json::json; fn builtin_drivers() -> Vec> { vec![ Box::new(crate::drivers::mysql::MysqlDriver::new()), - Box::new(crate::drivers::postgres::PostgresDriver::new()), Box::new(crate::drivers::sqlite::SqliteDriver::new()), ] } @@ -22,6 +21,18 @@ fn dialect_for(id: &str) -> DumpDialect { .unwrap_or_else(|| panic!("no builtin driver {id}")) } +/// Dialect for the `postgresql` plugin, which declares `sql_dialect: Postgres` +/// the same way the removed built-in driver did. +fn postgres_dialect() -> DumpDialect { + DumpDialect::from_capabilities( + "postgresql", + &DriverCapabilities { + sql_dialect: Some(SqlDialect::Postgres), + ..Default::default() + }, + ) +} + /// Capabilities of a plugin driver that quotes with backticks and exposes /// datasets as schemas (a BigQuery-like engine). fn backtick_schema_plugin() -> DriverCapabilities { @@ -314,7 +325,7 @@ fn postgresql_plugin_without_dialect_or_schemas_matches_the_legacy_output() { #[test] fn builtin_statements() { let mysql = dialect_for("mysql"); - let postgres = dialect_for("postgres"); + let postgres = postgres_dialect(); let sqlite = dialect_for("sqlite"); assert_eq!( mysql.drop_table_if_exists(None, "users"), @@ -341,7 +352,7 @@ fn flat_drivers_ignore_a_schema_and_postgres_defaults_to_public() { assert_eq!(mysql.scoped_schema(Some("mydb")), None); assert_eq!(mysql.table_ref(Some("mydb"), "users"), "`users`"); - let postgres = dialect_for("postgres"); + let postgres = postgres_dialect(); assert_eq!(postgres.resolve_schema(None).as_deref(), Some("public")); assert_eq!(postgres.resolve_schema(Some("")).as_deref(), Some("public")); assert_eq!(postgres.resolve_schema(Some("app")).as_deref(), Some("app")); @@ -351,7 +362,7 @@ fn flat_drivers_ignore_a_schema_and_postgres_defaults_to_public() { fn embedded_quote_characters_are_doubled() { assert_eq!(dialect_for("mysql").table_ref(None, "we`ird"), "`we``ird`"); assert_eq!( - dialect_for("postgres").table_ref(Some("s\"x"), "t"), + postgres_dialect().table_ref(Some("s\"x"), "t"), r#""s""x"."t""# ); } @@ -500,8 +511,11 @@ fn googlesql_dump_writes_boolean_keywords() { #[test] fn escape_value_common_cases() { - for id in ["mysql", "postgres", "sqlite"] { - let d = dialect_for(id); + for d in [ + dialect_for("mysql"), + dialect_for("sqlite"), + postgres_dialect(), + ] { assert_eq!(d.escape_value(json!(null)), "NULL"); assert_eq!(d.escape_value(json!(123)), "123"); assert_eq!(d.escape_value(json!(12.34)), "12.34"); @@ -510,8 +524,8 @@ fn escape_value_common_cases() { assert_eq!(d.escape_value(json!("Multi\nLine")), "'Multi\nLine'"); } // Postgres boolean columns reject integer literals (SQLSTATE 42804). - assert_eq!(dialect_for("postgres").escape_value(json!(true)), "TRUE"); - assert_eq!(dialect_for("postgres").escape_value(json!(false)), "FALSE"); + assert_eq!(postgres_dialect().escape_value(json!(true)), "TRUE"); + assert_eq!(postgres_dialect().escape_value(json!(false)), "FALSE"); for id in ["mysql", "sqlite"] { assert_eq!(dialect_for(id).escape_value(json!(true)), "1"); assert_eq!(dialect_for(id).escape_value(json!(false)), "0"); @@ -529,11 +543,8 @@ fn mysql_doubles_backslashes_and_escapes_nul() { #[test] fn postgres_and_sqlite_keep_backslashes_literal() { - for id in ["postgres", "sqlite"] { - assert_eq!( - dialect_for(id).escape_value(json!("Back\\slash")), - "'Back\\slash'" - ); + for d in [postgres_dialect(), dialect_for("sqlite")] { + assert_eq!(d.escape_value(json!("Back\\slash")), "'Back\\slash'"); } } @@ -544,7 +555,7 @@ fn nested_values_are_escaped_like_text() { r#"'{"path":"a\\\\b"}'"# ); assert_eq!( - dialect_for("postgres").escape_value(json!({"path": "a\\b"})), + postgres_dialect().escape_value(json!({"path": "a\\b"})), r#"'{"path":"a\\b"}'"# ); } @@ -577,7 +588,7 @@ fn json_column_values_mysql() { #[test] fn json_column_values_postgres() { - let d = dialect_for("postgres"); + let d = postgres_dialect(); assert_eq!( d.escape_json_value(json!({"html": ""})), r#"'{"html":""}'"# diff --git a/src-tauri/src/export.rs b/src-tauri/src/export.rs index 549f494d4..0aa454d0a 100644 --- a/src-tauri/src/export.rs +++ b/src-tauri/src/export.rs @@ -20,7 +20,7 @@ use std::sync::{Arc, Mutex}; use serde_json::Value; use crate::commands::AbortHandleMap; -use crate::drivers::{mysql, postgres, sqlite}; +use crate::drivers::{mysql, sqlite}; use crate::models::ConnectionParams; pub struct ExportCancellationState { @@ -109,10 +109,10 @@ where Ok(()) }; - // Only PostgreSQL connections pin, so only they receive a session. + // Plugin drivers receive session_id for pinned-connection streaming; + // built-in mysql/sqlite do not pin. match driver { "mysql" => mysql::export::stream_query(params, query, &mut on_row).await, - "postgres" => postgres::export::stream_query(params, query, session_id, &mut on_row).await, "sqlite" => sqlite::export::stream_query(params, query, &mut on_row).await, other => stream_query_via_plugin(other, params, query, session_id, &mut on_row).await, } @@ -137,6 +137,15 @@ where .ok_or_else(|| format!("Unsupported driver for export: {driver_id}"))?; let driver = driver.for_connection(params).await?.unwrap_or(driver); + // Paging re-sends the query once per page, which is only safe for a read. + // Anything else (`UPDATE ... RETURNING`, an unclassifiable statement) runs + // exactly once with no row cap, so it neither repeats nor truncates. A + // read-only connection was already restricted to reads above. + let single_run = !params.read_only + && crate::application::read_only::classify_query(driver.as_ref(), params, query).await + != "select"; + let limit = if single_run { None } else { Some(PAGE_SIZE) }; + let mut page: u32 = 1; loop { let result = if params.read_only { @@ -144,19 +153,31 @@ where driver.as_ref(), params, query, - Some(PAGE_SIZE), + limit, page, None, ) .await? } else { match session_id { + Some(id) if single_run => { + crate::commands::write_in_open_transaction( + driver.as_ref(), + params, + query, + limit, + page, + None, + id, + ) + .await? + } Some(id) => { crate::commands::read_in_open_transaction( driver.as_ref(), params, query, - Some(PAGE_SIZE), + limit, page, None, id, @@ -165,7 +186,7 @@ where } None => { driver - .execute_query(params, query, Some(PAGE_SIZE), page, None) + .execute_query(params, query, limit, page, None) .await? } } @@ -182,7 +203,7 @@ where .map(|pagination| pagination.has_more) .unwrap_or(fetched >= PAGE_SIZE); - if fetched == 0 || !has_more { + if single_run || fetched == 0 || !has_more { break; } page += 1; diff --git a/src-tauri/src/export/read_only_tests.rs b/src-tauri/src/export/read_only_tests.rs index 4930b00e0..ee5403d1a 100644 --- a/src-tauri/src/export/read_only_tests.rs +++ b/src-tauri/src/export/read_only_tests.rs @@ -240,3 +240,201 @@ async fn read_only_native_exports_reject_writes_and_policy_reset_statements() { json!([{"count":0}]) ); } + +/// A writable plugin connection whose `execute_query` returns full pages with +/// no pagination metadata, like PostgreSQL does for `UPDATE ... RETURNING`, +/// until `last_page`, which is short. Records `(page, limit)` per call. +async fn paging_plugin_params(last_page: u64) -> (ConnectionParams, Arc>>) { + let calls = Arc::new(Mutex::new(Vec::new())); + let recorded = calls.clone(); + let mut params = plugin_params(false, move |rpc| { + assert_eq!(rpc.method, "execute_query"); + let page = rpc.params["page"].as_u64().unwrap(); + recorded + .lock() + .unwrap() + .push((page, rpc.params["limit"].clone())); + let size = if page >= last_page { 3 } else { 1000 }; + let rows: Vec = (0..size).map(|id| json!([id])).collect(); + Ok(json!({"columns":["id"],"rows":rows,"affected_rows":0})) + }) + .await; + params.read_only = false; + (params, calls) +} + +#[tokio::test] +async fn a_writable_plugin_export_runs_a_modifying_statement_exactly_once() { + let _registry = crate::drivers::registry::REGISTRY_TEST_LOCK.lock().await; + let (params, calls) = paging_plugin_params(3).await; + + for statement in [ + "UPDATE counters SET value = value + 1 RETURNING id", + "INSERT INTO log(id) VALUES (1) RETURNING id", + "DELETE FROM log RETURNING id", + "WITH changed AS (UPDATE counters SET value = value + 1 RETURNING id) SELECT id FROM changed", + ] { + calls.lock().unwrap().clear(); + run_export( + ¶ms.driver, + ¶ms, + statement, + Vec::new(), + ExportFormat::Json, + b',', + None, + |_| {}, + ) + .await + .unwrap(); + + let calls = calls.lock().unwrap(); + assert_eq!( + calls.len(), + 1, + "{statement} was executed {} times", + calls.len() + ); + } + crate::drivers::registry::unregister_driver(¶ms.driver).await; +} + +#[tokio::test] +async fn a_writable_plugin_export_still_pages_a_plain_select() { + let _registry = crate::drivers::registry::REGISTRY_TEST_LOCK.lock().await; + let (params, calls) = paging_plugin_params(3).await; + + run_export( + ¶ms.driver, + ¶ms, + "SELECT id FROM items", + Vec::new(), + ExportFormat::Json, + b',', + None, + |_| {}, + ) + .await + .unwrap(); + + let pages: Vec = calls.lock().unwrap().iter().map(|c| c.0).collect(); + assert_eq!(pages, [1, 2, 3]); + crate::drivers::registry::unregister_driver(¶ms.driver).await; +} + +/// A writable plugin connection that answers `execute_query_batch` for an open +/// session, recording every statement of every batch in order. `fail_on` makes +/// the statement containing that text return an error. +async fn session_batch_plugin_params( + fail_on: Option<&'static str>, +) -> (ConnectionParams, Arc>>) { + let statements = Arc::new(Mutex::new(Vec::new())); + let recorded = statements.clone(); + let mut params = plugin_params(false, move |rpc| { + assert_eq!(rpc.method, "execute_query_batch"); + let queries: Vec = rpc.params["queries"] + .as_array() + .unwrap() + .iter() + .map(|q| q.as_str().unwrap().to_string()) + .collect(); + recorded.lock().unwrap().extend(queries.iter().cloned()); + let ok = json!({"columns":["id"],"rows":[[1]],"affected_rows":0}); + Ok(json!(queries + .iter() + .map(|q| match fail_on { + Some(text) if q.contains(text) => json!({"result":null,"error":"boom"}), + _ => json!({"result":ok,"error":null}), + }) + .collect::>())) + }) + .await; + params.read_only = false; + (params, statements) +} + +#[tokio::test] +async fn a_session_export_of_a_write_keeps_it_in_the_open_transaction() { + let _registry = crate::drivers::registry::REGISTRY_TEST_LOCK.lock().await; + let (params, statements) = session_batch_plugin_params(None).await; + + run_export( + ¶ms.driver, + ¶ms, + "UPDATE counters SET value = value + 1 RETURNING id", + Vec::new(), + ExportFormat::Json, + b',', + Some("writable-session"), + |_| {}, + ) + .await + .unwrap(); + + let sent = statements.lock().unwrap().clone(); + assert_eq!( + sent, + [ + "SAVEPOINT tabularis_write", + "UPDATE counters SET value = value + 1 RETURNING id", + "RELEASE SAVEPOINT tabularis_write", + ], + "a successful write must be released, never rolled back" + ); + crate::drivers::registry::unregister_driver(¶ms.driver).await; +} + +#[tokio::test] +async fn a_failed_session_export_write_rolls_back_to_its_savepoint_only() { + let _registry = crate::drivers::registry::REGISTRY_TEST_LOCK.lock().await; + let (params, statements) = session_batch_plugin_params(Some("UPDATE")).await; + + let error = run_export( + ¶ms.driver, + ¶ms, + "UPDATE counters SET value = value + 1 RETURNING id", + Vec::new(), + ExportFormat::Json, + b',', + Some("writable-session"), + |_| {}, + ) + .await + .unwrap_err(); + + assert!(error.contains("boom"), "{error}"); + let sent = statements.lock().unwrap().clone(); + assert!(sent + .iter() + .any(|s| s == "ROLLBACK TO SAVEPOINT tabularis_write")); + assert!(sent + .iter() + .any(|s| s == "RELEASE SAVEPOINT tabularis_write")); + crate::drivers::registry::unregister_driver(¶ms.driver).await; +} + +#[tokio::test] +async fn a_session_export_of_a_plain_select_still_rolls_back_its_read() { + let _registry = crate::drivers::registry::REGISTRY_TEST_LOCK.lock().await; + let (params, statements) = session_batch_plugin_params(None).await; + + run_export( + ¶ms.driver, + ¶ms, + "SELECT id FROM items", + Vec::new(), + ExportFormat::Json, + b',', + Some("writable-session"), + |_| {}, + ) + .await + .unwrap(); + + let sent = statements.lock().unwrap().clone(); + assert_eq!(sent[0], "SAVEPOINT tabularis_read"); + assert!(sent + .iter() + .any(|s| s == "ROLLBACK TO SAVEPOINT tabularis_read")); + crate::drivers::registry::unregister_driver(¶ms.driver).await; +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 2ae70f4ce..6db315c18 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -9,7 +9,6 @@ mod stderr; pub mod ai; -pub mod ai_assistants; pub mod ai_activity; #[cfg(test)] pub mod ai_activity_lexer_tests; @@ -19,6 +18,7 @@ pub mod ai_approval; #[cfg(test)] pub mod ai_approval_tests; pub mod ai_approval_watcher; +pub mod ai_assistants; pub mod ai_notebook_export; #[cfg(test)] @@ -123,9 +123,9 @@ pub mod ssh_socks5; pub mod ssh_tunnel; pub mod ssm_tunnel; pub mod storage_location; -pub mod table_transfer; #[cfg(test)] pub mod storage_location_tests; +pub mod table_transfer; pub mod table_sql; pub mod team_share; @@ -152,7 +152,6 @@ pub mod drivers { #[cfg(test)] pub mod driver_trait_tests; pub mod mysql; - pub mod postgres; pub mod registry; pub mod sql_dialect; #[cfg(test)] diff --git a/src-tauri/src/mcp/mod.rs b/src-tauri/src/mcp/mod.rs index c81cbfaa8..5d2ebcb89 100644 --- a/src-tauri/src/mcp/mod.rs +++ b/src-tauri/src/mcp/mod.rs @@ -10,7 +10,7 @@ use crate::credential_cache; use crate::drivers::driver_trait::{DatabaseDriver, SqlDialect}; use crate::drivers::registry as driver_registry; #[cfg(test)] -use crate::drivers::{mysql, postgres, sqlite}; +use crate::drivers::{mysql, sqlite}; use crate::heartbeat; use crate::keychain_utils; use crate::models::{ConnectionParams, K8sConnection, SshConnection}; @@ -387,8 +387,7 @@ async fn resolve_db_params( /// Populate the driver registry for the standalone MCP subprocess: the three /// built-in drivers plus any installed plugin drivers, honoring the user's /// `active_external_drivers` preference. Without this, MCP can only reach -/// mysql/postgres/sqlite connections — every other driver fails with -/// "Unsupported driver". +/// mysql/sqlite connections — every other driver fails with "Unsupported driver". async fn register_drivers_for_mcp() { if let Err(error) = crate::runtime::bootstrap::bootstrap_application( crate::runtime::RuntimeContext::system(), diff --git a/src-tauri/src/mcp/tests.rs b/src-tauri/src/mcp/tests.rs index 285b54a8f..6c628f5cc 100644 --- a/src-tauri/src/mcp/tests.rs +++ b/src-tauri/src/mcp/tests.rs @@ -156,21 +156,6 @@ async fn list_databases_unknown_connection_errors() { /// never got the `"public"` default. Exercised against the real concrete /// driver types — not a mock — so a manifest change on any of them would /// actually be caught here. -#[test] -fn resolve_default_schema_defaults_postgres_to_public() { - let driver: Arc = Arc::new(postgres::PostgresDriver::new()); - assert_eq!(resolve_default_schema(&driver, None), Some("public")); -} - -#[test] -fn resolve_default_schema_prefers_a_caller_supplied_schema_on_postgres() { - let driver: Arc = Arc::new(postgres::PostgresDriver::new()); - assert_eq!( - resolve_default_schema(&driver, Some("analytics")), - Some("analytics"), - ); -} - #[test] fn resolve_default_schema_passes_through_unchanged_on_non_postgres_drivers() { let mysql: Arc = Arc::new(mysql::MysqlDriver::new()); @@ -277,17 +262,17 @@ fn database_arg_ignores_a_missing_blank_or_non_string_value() { #[test] fn database_override_replaces_a_multi_database_selection() { let mut params = ConnectionParams { - driver: "postgres".to_string(), + driver: "postgresql".to_string(), database: DatabaseSelection::Multiple(vec!["main".to_string(), "analytics".to_string()]), ..Default::default() }; - apply_database_override( - &mut params, - Some("analytics"), - &postgres::PostgresDriver::new().manifest().capabilities, - ) - .unwrap(); + let pg_caps = crate::drivers::driver_trait::DriverCapabilities { + sql_dialect: Some(SqlDialect::Postgres), + schemas: true, + ..Default::default() + }; + apply_database_override(&mut params, Some("analytics"), &pg_caps).unwrap(); assert!(matches!(params.database, DatabaseSelection::Single(ref db) if db == "analytics")); } @@ -295,17 +280,17 @@ fn database_override_replaces_a_multi_database_selection() { #[test] fn database_override_keeps_the_saved_selection_without_a_database() { let mut params = ConnectionParams { - driver: "postgres".to_string(), + driver: "postgresql".to_string(), database: DatabaseSelection::Multiple(vec!["main".to_string(), "analytics".to_string()]), ..Default::default() }; - apply_database_override( - &mut params, - None, - &postgres::PostgresDriver::new().manifest().capabilities, - ) - .unwrap(); + let pg_caps = crate::drivers::driver_trait::DriverCapabilities { + sql_dialect: Some(SqlDialect::Postgres), + schemas: true, + ..Default::default() + }; + apply_database_override(&mut params, None, &pg_caps).unwrap(); assert_eq!(params.database.as_vec(), vec!["main", "analytics"]); } @@ -354,7 +339,7 @@ async fn database_scope_is_enforced_before_driver_access() { ), ( "saved-single", - "postgres", + "mysql", DatabaseSelection::Single("sandbox".to_string()), ), ( @@ -362,7 +347,7 @@ async fn database_scope_is_enforced_before_driver_access() { "mysql", DatabaseSelection::Multiple(vec!["sandbox".to_string(), "analytics".to_string()]), ), - ("saved-empty", "postgres", DatabaseSelection::default()), + ("saved-empty", "mysql", DatabaseSelection::default()), ] { connections.push(json!({ "id": id, @@ -413,7 +398,6 @@ async fn database_scope_is_enforced_before_driver_access() { } driver_registry::register_driver(sqlite::SqliteDriver::new()).await; - driver_registry::register_driver(postgres::PostgresDriver::new()).await; driver_registry::register_driver(mysql::MysqlDriver::new()).await; let private_path = paths::get_app_config_dir() .parent() diff --git a/src-tauri/src/models_tests.rs b/src-tauri/src/models_tests.rs index e2c3aa9be..f874433e8 100644 --- a/src-tauri/src/models_tests.rs +++ b/src-tauri/src/models_tests.rs @@ -168,8 +168,7 @@ mod tests { }; let json = serde_json::to_string(¶ms).expect("serialize params"); - let restored: ConnectionParams = - serde_json::from_str(&json).expect("deserialize params"); + let restored: ConnectionParams = serde_json::from_str(&json).expect("deserialize params"); assert_eq!(restored.default_database.as_deref(), Some("app/main")); assert_eq!(restored.database, DatabaseSelection::Single(String::new())); diff --git a/src-tauri/src/persistence.rs b/src-tauri/src/persistence.rs index a20d61bcd..7b7be1363 100644 --- a/src-tauri/src/persistence.rs +++ b/src-tauri/src/persistence.rs @@ -319,7 +319,10 @@ pub fn save_groups(path: &Path, groups: &[ConnectionGroup]) -> Result<(), String /// reached disk. A failed write must leave the previous snapshot readable. fn atomic_private_write(path: &Path, contents: &[u8]) -> Result<(), String> { use std::io::Write; - let parent = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); let mut file = tempfile::NamedTempFile::new_in(parent).map_err(|e| e.to_string())?; file.write_all(contents).map_err(|e| e.to_string())?; file.as_file().sync_all().map_err(|e| e.to_string())?; diff --git a/src-tauri/src/persistence_atomic_tests.rs b/src-tauri/src/persistence_atomic_tests.rs index 9bbd288de..f0cc1c479 100644 --- a/src-tauri/src/persistence_atomic_tests.rs +++ b/src-tauri/src/persistence_atomic_tests.rs @@ -4,13 +4,17 @@ use super::*; fn atomic_connection_snapshot_replaces_complete_file_and_is_private() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("connections.json"); - std::fs::write(&path,"previous snapshot").unwrap(); - atomic_private_write(&path,b"complete replacement").unwrap(); - assert_eq!(std::fs::read(&path).unwrap(),b"complete replacement"); - assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(),1); - #[cfg(unix)] { + std::fs::write(&path, "previous snapshot").unwrap(); + atomic_private_write(&path, b"complete replacement").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"complete replacement"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + #[cfg(unix)] + { use std::os::unix::fs::PermissionsExt; - assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,0o600); + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); } } @@ -19,8 +23,11 @@ fn failed_replacement_does_not_destroy_existing_target() { let dir = tempfile::tempdir().unwrap(); let target = dir.path().join("target"); std::fs::create_dir(&target).unwrap(); - std::fs::write(target.join("retained"),"data").unwrap(); - assert!(atomic_private_write(&target,b"new").is_err()); - assert_eq!(std::fs::read_to_string(target.join("retained")).unwrap(),"data"); - assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(),1); + std::fs::write(target.join("retained"), "data").unwrap(); + assert!(atomic_private_write(&target, b"new").is_err()); + assert_eq!( + std::fs::read_to_string(target.join("retained")).unwrap(), + "data" + ); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); } diff --git a/src-tauri/src/plugins/column_stats_tests.rs b/src-tauri/src/plugins/column_stats_tests.rs index 1dd6d8756..dd53c6c27 100644 --- a/src-tauri/src/plugins/column_stats_tests.rs +++ b/src-tauri/src/plugins/column_stats_tests.rs @@ -212,7 +212,6 @@ async fn column_stats_coerce_a_multi_database_selection_before_the_rpc() { async fn built_in_drivers_keep_the_generic_sql_column_stats() { let drivers: Vec> = vec![ Box::new(crate::drivers::mysql::MysqlDriver::new()), - Box::new(crate::drivers::postgres::PostgresDriver::new()), Box::new(crate::drivers::sqlite::SqliteDriver::new()), ]; for driver in drivers { diff --git a/src-tauri/src/plugins/driver.rs b/src-tauri/src/plugins/driver.rs index dfd72ffc1..5a91cf834 100644 --- a/src-tauri/src/plugins/driver.rs +++ b/src-tauri/src/plugins/driver.rs @@ -14,6 +14,7 @@ use crate::drivers::driver_trait::{ BatchProgressFn, DatabaseDriver, DatabaseSqlCapabilities, DatabaseSqlExportOptions, DatabaseSqlExportResult, DatabaseSqlImportResult, PluginManifest, }; +use crate::drivers::driver_trait::{CopyInsertOutcome, CopyRows}; use crate::models::{ AiSchemaContext, BatchStatementResult, ColumnDefinition, ConnectionParams, DataTypeInfo, DatabaseSelection, DbPrivilegeCatalog, DbUserInfo, ExplainQueryOutput, ForeignKey, Index, @@ -1541,6 +1542,55 @@ impl DatabaseDriver for RpcDriver { states.get(session_id).copied() } + async fn read_rows( + &self, + params: &ConnectionParams, + query: &str, + limit: u32, + page: u32, + schema: Option<&str>, + session_id: &str, + ) -> Result { + if !self.manifest.capabilities.table_copy { + return Err("This plugin does not support table copy".to_string()); + } + let res = self + .process + .call( + "read_rows", + json!({ + "params": self.with_primary_database(params), "query": query, + "limit": limit, "page": page, "schema": schema, "session_id": session_id, + }), + ) + .await?; + serde_json::from_value(res).map_err(|e| e.to_string()) + } + + async fn insert_records( + &self, + params: &ConnectionParams, + table: &str, + schema: Option<&str>, + rows: Vec>, + skip_conflicts: bool, + ) -> Result { + if !self.manifest.capabilities.table_copy { + return Err("This plugin does not support table copy".to_string()); + } + let res = self + .process + .call( + "insert_records", + json!({ + "params": self.with_primary_database(params), "table": table, "schema": schema, + "rows": rows, "on_conflict": if skip_conflicts { "skip" } else { "fail" }, + }), + ) + .await?; + serde_json::from_value(res).map_err(|e| e.to_string()) + } + async fn release_session(&self, session_id: &str) { plugin_session_states() .lock() diff --git a/src-tauri/src/plugins/extension_policy.rs b/src-tauri/src/plugins/extension_policy.rs index 13950cdb9..e8c8f22e3 100644 --- a/src-tauri/src/plugins/extension_policy.rs +++ b/src-tauri/src/plugins/extension_policy.rs @@ -14,7 +14,7 @@ fn valid_id(value: &str) -> bool { } pub fn validate_target(plugin_id: &str, driver: &str) -> Result<(), String> { - if !valid_id(plugin_id) || ["postgres", "mysql", "sqlite"].contains(&plugin_id) { + if !valid_id(plugin_id) || ["mysql", "sqlite"].contains(&plugin_id) { return Err("An external plugin identifier is required".into()); } if plugin_id != driver { diff --git a/src-tauri/src/plugins/extension_policy/tests.rs b/src-tauri/src/plugins/extension_policy/tests.rs index 0a65765fc..b961a38d4 100644 --- a/src-tauri/src/plugins/extension_policy/tests.rs +++ b/src-tauri/src/plugins/extension_policy/tests.rs @@ -5,7 +5,8 @@ use serde_json::json; fn plugin_extension_requires_matching_external_driver() { assert!(validate_target("neon", "neon").is_ok()); assert!(validate_target("neon", "postgres").is_err()); - assert!(validate_target("postgres", "postgres").is_err()); + assert!(validate_target("postgres", "postgres").is_ok()); + assert!(validate_target("mysql", "mysql").is_err()); assert!(validate_target("../neon", "../neon").is_err()); assert!(validate_target("", "").is_err()); } diff --git a/src-tauri/src/plugins/force_install.rs b/src-tauri/src/plugins/force_install.rs index 93a30f494..23fc49563 100644 --- a/src-tauri/src/plugins/force_install.rs +++ b/src-tauri/src/plugins/force_install.rs @@ -17,13 +17,65 @@ use serde::Serialize; use crate::config::AppConfig; -use crate::plugins::registry; +use crate::plugins::{installer, registry, tabularium}; +use crate::runtime::RuntimeContext; /// Built-in driver id → replacement plugin id pairs that the app keeps /// installed automatically when a connection on the built-in exists. Adding /// a pair is the whole change required for the next deprecation. pub const MIGRATABLE_DRIVERS: &[(&str, &str)] = &[("postgres", "postgresql")]; +/// Oldest release of a replacement plugin that can stand in for the built-in +/// driver it replaces. The built-in PostgreSQL driver connected through a Unix +/// socket and copied tables. rc.14 and before silently dial TCP instead of the +/// socket and cannot copy; rc.15 copies but can return a row twice or change a +/// value on read-back, which rc.16 fixes. A plugin below the floor is updated +/// before connections move to it. +pub const MINIMUM_PLUGIN_VERSIONS: &[(&str, &str)] = &[("postgresql", "1.0.0-rc.16")]; + +/// The floor for `plugin_id`, if it has one. +pub fn minimum_plugin_version(plugin_id: &str) -> Option<&'static str> { + MINIMUM_PLUGIN_VERSIONS + .iter() + .find(|(id, _)| *id == plugin_id) + .map(|(_, version)| *version) +} + +/// Whether `installed` meets `minimum`. An unparseable version does not: a +/// plugin that cannot show it is recent enough is updated. +pub(crate) fn meets_minimum(installed: &str, minimum: &str) -> bool { + match ( + semver::Version::parse(installed), + semver::Version::parse(minimum), + ) { + (Ok(have), Ok(floor)) => have >= floor, + _ => false, + } +} + +/// Whether the installed copy of `plugin_id` is new enough to receive the +/// connections that moved off the built-in driver. `true` for a plugin with no +/// floor, `false` when it is not installed at all. +pub fn installed_plugin_is_current(plugins_dir: &std::path::Path, plugin_id: &str) -> bool { + let Some(installed) = installer::list_installed_from(plugins_dir) + .into_iter() + .find(|p| p.id == plugin_id) + else { + return false; + }; + minimum_plugin_version(plugin_id).map_or(true, |floor| meets_minimum(&installed.version, floor)) +} + +/// The plugin that replaced `driver_id`, when `driver_id` is either the removed +/// built-in id or the plugin id itself. Lets an unregistered-driver error name +/// the plugin to install for both pre- and post-migration connections. +pub fn replacement_plugin_for(driver_id: &str) -> Option<&'static str> { + MIGRATABLE_DRIVERS + .iter() + .find(|(builtin, plugin)| *builtin == driver_id || *plugin == driver_id) + .map(|(_, plugin)| *plugin) +} + /// Log prefix shared by every message this module emits, so the force-install /// flow is greppable in logs at a glance. pub(crate) const LOG_PREFIX: &str = "[force-install]"; @@ -119,3 +171,203 @@ pub(crate) fn registry_base_url(config: &AppConfig) -> &str { .as_deref() .unwrap_or(registry::DEFAULT_TABULARIUM_URL) } + +/// True when at least one saved connection uses the built-in driver id +/// (pre-migration) or the replacement plugin id (post-migration). Checking +/// both ids lets the install retry on a later launch when the first download +/// failed after the migration had already moved the connections over. Pure so +/// it can be tested without a runtime. +pub(crate) fn needs_plugin_for(builtin_id: &str, plugin_id: &str, drivers: &[&str]) -> bool { + drivers.iter().any(|d| *d == builtin_id || *d == plugin_id) +} + +/// Environment switch that stops a headless process (the web server, `--mcp`) +/// from downloading a replacement plugin on its own. For air-gapped or +/// locked-down deployments, where fetching and running a binary at startup is a +/// policy decision the operator wants to make. The plugin can still be installed +/// by hand. The desktop app is not affected. +pub const DISABLE_AUTO_INSTALL_ENV: &str = "TABULARIS_DISABLE_PLUGIN_AUTO_INSTALL"; + +/// Whether a raw [`DISABLE_AUTO_INSTALL_ENV`] value turns auto-install off: +/// anything but an explicit "off" value (`0`, `false`, `no`, empty). Pure, so +/// it is tested without touching the process environment. +pub(crate) fn auto_install_disabled_by(value: Option<&str>) -> bool { + value.is_some_and(|value| { + !matches!( + value.trim().to_ascii_lowercase().as_str(), + "" | "0" | "false" | "no" + ) + }) +} + +/// True when the operator has turned headless auto-install off. +pub(crate) fn auto_install_disabled() -> bool { + auto_install_disabled_by(std::env::var(DISABLE_AUTO_INSTALL_ENV).ok().as_deref()) +} + +/// Install (and activate) the replacement plugin for every [`MIGRATABLE_DRIVERS`] +/// pair that a saved connection depends on. Runs from the web server and the +/// MCP process, which share one bootstrap with the desktop app but have no +/// desktop setup step to do it. Every failure is logged and swallowed: the +/// check restarts from scratch on every launch, so a transient failure (no +/// network, registry down) heals on the next one, and an air-gapped host simply +/// keeps logging that the plugin is missing. +pub async fn ensure_replacement_plugins(runtime: &RuntimeContext) { + let drivers: Vec = + match crate::persistence::load_connections(&runtime.paths.connections_file()) { + Ok(connections) => connections + .iter() + .map(|c| c.params.driver.clone()) + .collect(), + Err(error) => { + log::warn!("{LOG_PREFIX} could not read connections: {error}"); + return; + } + }; + let driver_refs: Vec<&str> = drivers.iter().map(String::as_str).collect(); + for (builtin_id, plugin_id) in MIGRATABLE_DRIVERS { + if needs_plugin_for(builtin_id, plugin_id, &driver_refs) { + ensure_plugin_installed(runtime, plugin_id).await; + } + } +} + +/// Replacement plugin ids that can serve a connection right now: installed at +/// their minimum version and registered. A plugin that is installed but +/// disabled (absent from an explicit `active_external_drivers`) is skipped at +/// load and never registers, so it does not qualify. +pub async fn usable_replacement_plugins(plugins_dir: &std::path::Path) -> Vec { + let mut usable = Vec::new(); + for (_, plugin_id) in MIGRATABLE_DRIVERS { + if installed_plugin_is_current(plugins_dir, plugin_id) + && crate::drivers::registry::get_driver(plugin_id) + .await + .is_some() + { + usable.push((*plugin_id).to_string()); + } + } + usable +} + +/// Moves saved connections off the built-in ids whose replacement plugin is +/// usable (see [`usable_replacement_plugins`]). +pub async fn migrate_ready_connections_result(runtime: &RuntimeContext) -> Result { + let usable = usable_replacement_plugins(&runtime.paths.plugins_dir()).await; + crate::connection_migrations::migrate_builtin_driver_ids_when( + &runtime.paths.connections_file(), + |plugin_id| usable.iter().any(|id| id == plugin_id), + ) + .await +} + +/// [`migrate_ready_connections_result`] for a caller with no error path: a +/// failure is logged and the move is retried on the next launch. Returns +/// whether any connection moved. +pub async fn migrate_ready_connections(runtime: &RuntimeContext) -> bool { + migrate_ready_connections_result(runtime) + .await + .unwrap_or_else(|error| { + log::warn!("{LOG_PREFIX} could not move connections to the plugin: {error}"); + false + }) +} + +/// Install (and activate) `plugin_id` unless a current copy is already +/// installed (an older one is updated) or the latest release needs a newer +/// Tabularis. Every failure path logs and returns, +/// so a caller never has to handle one. +pub async fn ensure_plugin_installed(runtime: &RuntimeContext, plugin_id: &str) { + if installed_plugin_is_current(&runtime.paths.plugins_dir(), plugin_id) { + return; + } + if !plugin_compatible_with_this_app(runtime, plugin_id).await { + log::warn!("{LOG_PREFIX} {plugin_id} has no compatible release, skipping"); + return; + } + if let Err(error) = + crate::application::plugins::install_plugin(runtime, plugin_id.to_string(), None, None) + .await + { + log::warn!("{LOG_PREFIX} {plugin_id} install failed: {error}"); + return; + } + // `install_plugin` hot-registers for this session but does not persist + // activation, so without this write the plugin vanishes on relaunch. + let activated = persist_activation(runtime, plugin_id); + match &activated { + // Connections waited on the built-in id for this plugin; move them + // now so the UI reloads them already on the plugin id. Not when the + // activation was not saved: the plugin would not load next launch and + // the moved connections would point at an unregistered driver. + Ok(()) => { + migrate_ready_connections(runtime).await; + } + Err(error) => log::warn!("{LOG_PREFIX} could not activate {plugin_id}: {error}"), + } + // Tell an already-open UI the plugin is installed and registered. Emitted + // even if the activation write failed: the driver is registered for this + // session either way. + let payload = serde_json::to_value(PluginActivatedPayload { plugin_id }).unwrap_or_default(); + if let Err(error) = runtime.events.emit(PLUGIN_ACTIVATED_EVENT, payload) { + log::warn!("{LOG_PREFIX} could not emit {PLUGIN_ACTIVATED_EVENT}: {error}"); + } +} + +/// Persist `plugin_id` into `active_external_drivers`, leaving every other +/// config field untouched. Idempotent. Bails without writing when the installed +/// plugin list cannot be read: narrowing the list to `plugin_id` on a guess +/// could silently deactivate every other installed plugin. +pub(crate) fn persist_activation(runtime: &RuntimeContext, plugin_id: &str) -> Result<(), String> { + let config = crate::application::persistence::load_config(runtime); + let installed_ids: Vec = installer::list_installed_from(&runtime.paths.plugins_dir()) + .into_iter() + .map(|p| p.id) + .collect(); + let updated = merge_active_driver(&config, plugin_id, &installed_ids); + if updated.active_external_drivers == config.active_external_drivers { + return Ok(()); + } + // Pass only `active_external_drivers`: save_config overwrites every `Some` + // field, so writing back the full snapshot would revert any other setting + // the user changed in the meantime. + crate::application::persistence::save_config( + runtime, + AppConfig { + active_external_drivers: updated.active_external_drivers, + ..AppConfig::default() + }, + ) + .map(|_| ()) +} + +/// Whether the latest release of `plugin_id` supports this app's version. +/// `install_plugin` does not check `min_tabularis_version` itself, so without +/// this an unattended install could leave a plugin that needs a newer Tabularis +/// installed but unusable. An unreachable registry counts as compatible, so a +/// network blip does not permanently block an otherwise-fine install. +async fn plugin_compatible_with_this_app(runtime: &RuntimeContext, plugin_id: &str) -> bool { + let config = crate::application::persistence::load_config(runtime); + let base = registry_base_url(&config).trim_end_matches('/'); + let Ok(detail) = tabularium::fetch_plugin_detail(base, plugin_id).await else { + log::warn!("{LOG_PREFIX} could not fetch detail for {plugin_id}, assuming compatible"); + return true; + }; + let target = if detail.latest_version.is_empty() { + detail.releases.first() + } else { + detail + .releases + .iter() + .find(|r| r.version == detail.latest_version) + .or_else(|| detail.releases.first()) + }; + let Some(release) = target else { + log::warn!("{LOG_PREFIX} {plugin_id} has no releases on the registry"); + return false; + }; + let Some(min) = &release.min_tabularis_version else { + return true; + }; + is_version_compatible(min, env!("CARGO_PKG_VERSION")) +} diff --git a/src-tauri/src/plugins/force_install_tests.rs b/src-tauri/src/plugins/force_install_tests.rs index 65c27a467..5bb50a816 100644 --- a/src-tauri/src/plugins/force_install_tests.rs +++ b/src-tauri/src/plugins/force_install_tests.rs @@ -135,3 +135,400 @@ fn is_version_compatible_treats_unparseable_as_compatible() { assert!(is_version_compatible("1.0.0", "not-a-version")); assert!(is_version_compatible("garbage", "alsogarbage")); } + +#[test] +fn needs_plugin_for_triggers_on_either_the_builtin_or_the_plugin_id() { + use super::force_install::needs_plugin_for; + // First launch after the upgrade: connections are still on the built-in id. + assert!(needs_plugin_for( + "postgres", + "postgresql", + &["postgres", "mysql"] + )); + // Retry after a failed first download: the migration already moved them. + assert!(needs_plugin_for("postgres", "postgresql", &["postgresql"])); + assert!(needs_plugin_for( + "postgres", + "postgresql", + &["postgres", "postgresql"] + )); + assert!(!needs_plugin_for( + "postgres", + "postgresql", + &["mysql", "sqlite"] + )); + assert!(!needs_plugin_for("postgres", "postgresql", &[])); +} + +#[test] +fn replacement_plugin_for_resolves_the_old_and_the_new_id() { + use super::force_install::replacement_plugin_for; + assert_eq!(replacement_plugin_for("postgres"), Some("postgresql")); + assert_eq!(replacement_plugin_for("postgresql"), Some("postgresql")); + assert_eq!(replacement_plugin_for("mysql"), None); + assert_eq!(replacement_plugin_for("sqlite"), None); +} + +#[test] +fn auto_install_opt_out_treats_only_explicit_off_values_as_enabled() { + use super::force_install::auto_install_disabled_by; + assert!( + !auto_install_disabled_by(None), + "unset must leave auto-install on" + ); + for off in ["", "0", "false", "FALSE", "no", " no "] { + assert!( + !auto_install_disabled_by(Some(off)), + "{off:?} must leave it on" + ); + } + for on in ["1", "true", "TRUE", "yes", "on"] { + assert!( + auto_install_disabled_by(Some(on)), + "{on:?} must turn it off" + ); + } +} + +struct NoSecrets; + +impl crate::runtime::secrets::RuntimeSecrets for NoSecrets { + fn get(&self, _account: &str) -> Result, String> { + Ok(None) + } + + fn set(&self, _account: &str, _secret: &str) -> Result<(), String> { + Ok(()) + } + + fn delete(&self, _account: &str) -> Result<(), String> { + Ok(()) + } +} + +fn runtime_in(dir: &std::path::Path) -> crate::runtime::RuntimeContext { + crate::runtime::RuntimeContext::new( + std::sync::Arc::new(crate::runtime::paths::FixedRuntimePaths::new( + dir.to_path_buf(), + dir.to_path_buf(), + )), + std::sync::Arc::new(crate::runtime::events::NoopRuntimeEvents), + std::sync::Arc::new(NoSecrets), + ) +} + +#[test] +fn activation_is_written_through_save_config_and_keeps_other_drivers() { + let dir = tempfile::tempdir().unwrap(); + let runtime = runtime_in(dir.path()); + crate::application::persistence::save_config( + &runtime, + AppConfig { + active_external_drivers: Some(vec!["mysql-extra".to_string()]), + language: Some("de".to_string()), + ..AppConfig::default() + }, + ) + .unwrap(); + + super::force_install::persist_activation(&runtime, "postgresql").unwrap(); + + let saved = crate::application::persistence::load_config(&runtime); + assert_eq!( + saved.active_external_drivers, + Some(vec!["mysql-extra".to_string(), "postgresql".to_string()]) + ); + assert_eq!( + saved.language.as_deref(), + Some("de"), + "other settings must survive" + ); +} + +#[test] +fn activation_is_idempotent_across_launches() { + let dir = tempfile::tempdir().unwrap(); + let runtime = runtime_in(dir.path()); + for _ in 0..3 { + super::force_install::persist_activation(&runtime, "postgresql").unwrap(); + } + let saved = crate::application::persistence::load_config(&runtime); + assert_eq!( + saved.active_external_drivers, + Some(vec!["postgresql".to_string()]) + ); +} + +#[tokio::test] +async fn no_install_is_attempted_when_no_connection_needs_the_plugin() { + let dir = tempfile::tempdir().unwrap(); + let runtime = runtime_in(dir.path()); + // A registry nothing listens on: any download attempt would be logged and + // would leave no plugin behind, so assert on the files instead. + crate::application::persistence::save_config( + &runtime, + AppConfig { + tabularium_registry_url: Some("http://127.0.0.1:1".to_string()), + ..AppConfig::default() + }, + ) + .unwrap(); + std::fs::write( + dir.path().join("connections.json"), + r#"[{"id":"c1","name":"m","params":{"driver":"mysql"}}]"#, + ) + .unwrap(); + + super::force_install::ensure_replacement_plugins(&runtime).await; + + assert!(!dir.path().join("plugins").join("postgresql").exists()); + let config = crate::application::persistence::load_config(&runtime); + assert_eq!( + config.active_external_drivers, None, + "nothing may be activated" + ); +} + +#[tokio::test] +async fn an_unreachable_registry_is_swallowed_and_nothing_is_activated() { + let dir = tempfile::tempdir().unwrap(); + let runtime = runtime_in(dir.path()); + crate::application::persistence::save_config( + &runtime, + AppConfig { + tabularium_registry_url: Some("http://127.0.0.1:1".to_string()), + ..AppConfig::default() + }, + ) + .unwrap(); + std::fs::write( + dir.path().join("connections.json"), + r#"[{"id":"c1","name":"p","params":{"driver":"postgresql"}}]"#, + ) + .unwrap(); + + // Must return (not panic, not hang) so a web or MCP start never fails on it. + tokio::time::timeout( + std::time::Duration::from_secs(30), + super::force_install::ensure_replacement_plugins(&runtime), + ) + .await + .expect("a failed download must not block"); + + let config = crate::application::persistence::load_config(&runtime); + assert_eq!( + config.active_external_drivers, None, + "a failed install must not record the plugin as active" + ); +} + +#[test] +fn the_unsupported_driver_error_names_the_plugin_to_install() { + let message = crate::drivers::registry::unsupported_driver_message("postgresql"); + assert!( + message.starts_with("Unsupported driver: postgresql"), + "{message}" + ); + assert!(message.contains("\"postgresql\" plugin"), "{message}"); + // The removed built-in id is explained the same way. + assert!( + crate::drivers::registry::unsupported_driver_message("postgres") + .contains("\"postgresql\" plugin") + ); + // An unrelated unknown driver keeps the plain message. + assert_eq!( + crate::drivers::registry::unsupported_driver_message("mongodb"), + "Unsupported driver: mongodb" + ); +} + +#[test] +fn the_activation_event_payload_matches_what_the_frontend_declares() { + // packages/web-ui/src/api/events.ts: 'tabularis://plugin-activated' carries {pluginId}. + let payload = serde_json::to_value(super::force_install::PluginActivatedPayload { + plugin_id: "postgresql", + }) + .unwrap(); + assert_eq!(payload, serde_json::json!({ "pluginId": "postgresql" })); +} + +#[test] +fn the_minimum_plugin_version_is_semver_not_text() { + use super::force_install::{meets_minimum, minimum_plugin_version}; + assert_eq!(minimum_plugin_version("postgresql"), Some("1.0.0-rc.16")); + assert_eq!(minimum_plugin_version("mysql"), None); + assert!(meets_minimum("1.0.0-rc.16", "1.0.0-rc.16")); + assert!(meets_minimum("1.0.0-rc.17", "1.0.0-rc.16")); + // rc.9 sorts after rc.16 as text, and is older as a version. + assert!(!meets_minimum("1.0.0-rc.9", "1.0.0-rc.16")); + assert!(!meets_minimum("1.0.0-rc.15", "1.0.0-rc.16")); + assert!(meets_minimum("1.0.0", "1.0.0-rc.16")); + assert!(meets_minimum("2.0.0", "1.0.0-rc.16")); + assert!(!meets_minimum("garbage", "1.0.0-rc.16")); +} + +fn install_fake_plugin(plugins_dir: &std::path::Path, id: &str, version: &str) { + let dir = plugins_dir.join("drivers").join(id); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join(".tabularium"), + format!( + r#"{{"id":"{id}","name":"{id}","version":"{version}","description":"d","executable":"x"}}"# + ), + ) + .unwrap(); +} + +#[test] +fn an_installed_plugin_below_its_minimum_is_not_current() { + use super::force_install::installed_plugin_is_current; + let dir = tempfile::tempdir().unwrap(); + let plugins = dir.path().join("plugins"); + assert!( + !installed_plugin_is_current(&plugins, "postgresql"), + "not installed" + ); + install_fake_plugin(&plugins, "postgresql", "1.0.0-rc.15"); + assert!(!installed_plugin_is_current(&plugins, "postgresql")); + install_fake_plugin(&plugins, "postgresql", "1.0.0-rc.16"); + assert!(installed_plugin_is_current(&plugins, "postgresql")); + install_fake_plugin(&plugins, "other", "0.0.1"); + assert!( + installed_plugin_is_current(&plugins, "other"), + "a plugin with no floor only has to be installed" + ); +} + +fn postgres_connection() -> crate::models::SavedConnection { + crate::models::SavedConnection { + id: "c1".into(), + name: "pg".into(), + params: crate::models::ConnectionParams { + driver: "postgres".into(), + ..Default::default() + }, + plugin_secret_keys: Vec::new(), + group_id: None, + sort_order: None, + detect_json_in_text_columns: None, + appearance: None, + tag_ids: None, + environment: None, + managed: false, + } +} + +fn save_postgres_connection(runtime: &crate::runtime::RuntimeContext) { + crate::persistence::save_connections_file( + &runtime.paths.connections_file(), + &crate::models::ConnectionsFile { + connections: vec![postgres_connection()], + ..Default::default() + }, + ) + .unwrap(); +} + +fn saved_driver(runtime: &crate::runtime::RuntimeContext) -> String { + crate::persistence::load_connections(&runtime.paths.connections_file()) + .unwrap() + .remove(0) + .params + .driver +} + +async fn register_fake_postgresql_driver() { + let manifest = crate::drivers::driver_trait::PluginManifest { + id: "postgresql".into(), + name: "postgresql".into(), + version: "1.0.0-rc.16".into(), + description: String::new(), + default_port: None, + capabilities: Default::default(), + is_builtin: false, + engine: None, + paradigms: Vec::new(), + default_username: String::new(), + color: String::new(), + icon: String::new(), + settings: Vec::new(), + ui_extensions: None, + explain_parsers: None, + connection_fields: None, + type_mappings: Default::default(), + deprecated: None, + }; + crate::drivers::registry::register_driver(crate::plugins::driver::test_driver_with_manifest( + manifest, + |_| Ok(serde_json::Value::Null), + )) + .await; +} + +#[tokio::test] +async fn connections_stay_on_the_builtin_id_while_the_installed_plugin_is_too_old() { + let _guard = crate::drivers::registry::REGISTRY_TEST_LOCK.lock().await; + let dir = tempfile::tempdir().unwrap(); + let runtime = runtime_in(dir.path()); + save_postgres_connection(&runtime); + install_fake_plugin(&dir.path().join("plugins"), "postgresql", "1.0.0-rc.15"); + register_fake_postgresql_driver().await; + + assert_eq!( + super::force_install::migrate_ready_connections_result(&runtime).await, + Ok(false) + ); + assert_eq!(saved_driver(&runtime), "postgres"); + + install_fake_plugin(&dir.path().join("plugins"), "postgresql", "1.0.0-rc.16"); + let outcome = super::force_install::migrate_ready_connections_result(&runtime).await; + crate::drivers::registry::unregister_driver("postgresql").await; + assert_eq!(outcome, Ok(true), "{outcome:?}"); + assert_eq!(saved_driver(&runtime), "postgresql"); +} + +#[tokio::test] +async fn connections_stay_on_the_builtin_id_when_the_current_plugin_is_installed_but_disabled() { + let _guard = crate::drivers::registry::REGISTRY_TEST_LOCK.lock().await; + let dir = tempfile::tempdir().unwrap(); + let runtime = runtime_in(dir.path()); + save_postgres_connection(&runtime); + // An explicit active list that leaves the plugin out: the loader skips it, + // so nothing is registered under its id. + crate::drivers::registry::unregister_driver("postgresql").await; + crate::application::persistence::save_config( + &runtime, + AppConfig { + active_external_drivers: Some(vec!["other".to_string()]), + ..AppConfig::default() + }, + ) + .unwrap(); + install_fake_plugin(&dir.path().join("plugins"), "postgresql", "1.0.0-rc.16"); + + assert_eq!( + super::force_install::migrate_ready_connections_result(&runtime).await, + Ok(false) + ); + assert_eq!(saved_driver(&runtime), "postgres"); +} + +#[tokio::test] +async fn enabling_the_installed_plugin_lets_the_waiting_connections_move() { + let _guard = crate::drivers::registry::REGISTRY_TEST_LOCK.lock().await; + let dir = tempfile::tempdir().unwrap(); + let runtime = runtime_in(dir.path()); + save_postgres_connection(&runtime); + install_fake_plugin(&dir.path().join("plugins"), "postgresql", "1.0.0-rc.16"); + + assert_eq!( + super::force_install::migrate_ready_connections_result(&runtime).await, + Ok(false), + "installed but not registered" + ); + register_fake_postgresql_driver().await; + let outcome = super::force_install::migrate_ready_connections_result(&runtime).await; + crate::drivers::registry::unregister_driver("postgresql").await; + assert_eq!(outcome, Ok(true), "{outcome:?}"); + assert_eq!(saved_driver(&runtime), "postgresql"); +} diff --git a/src-tauri/src/plugins/manager.rs b/src-tauri/src/plugins/manager.rs index 7f7878f63..649a3a939 100644 --- a/src-tauri/src/plugins/manager.rs +++ b/src-tauri/src/plugins/manager.rs @@ -106,7 +106,7 @@ pub struct ConfigManifest { /// refusal (never silently skipped by the registered-plugin fast path below) /// so the collision is still surfaced as a logged `PluginLoadError`, not /// swallowed because the built-in of the same id is already registered. -const BUILTIN_DRIVER_IDS: [&str; 3] = ["mysql", "postgres", "sqlite"]; +const BUILTIN_DRIVER_IDS: [&str; 2] = ["mysql", "sqlite"]; /// Re-scans installed plugins against the latest on-disk config and registers /// any that are missing from the driver registry. Idempotent — plugins diff --git a/src-tauri/src/plugins/query_classification_tests.rs b/src-tauri/src/plugins/query_classification_tests.rs index 4fdd851d8..e89fe05cc 100644 --- a/src-tauri/src/plugins/query_classification_tests.rs +++ b/src-tauri/src/plugins/query_classification_tests.rs @@ -141,7 +141,6 @@ async fn a_failed_classify_query_is_an_error_and_never_a_verdict() { async fn built_in_drivers_do_not_classify() { let drivers: Vec> = vec![ Box::new(crate::drivers::mysql::MysqlDriver::new()), - Box::new(crate::drivers::postgres::PostgresDriver::new()), Box::new(crate::drivers::sqlite::SqliteDriver::new()), ]; for driver in drivers { diff --git a/src-tauri/src/plugins/table_query_template_tests.rs b/src-tauri/src/plugins/table_query_template_tests.rs index fe3e7b825..981b09310 100644 --- a/src-tauri/src/plugins/table_query_template_tests.rs +++ b/src-tauri/src/plugins/table_query_template_tests.rs @@ -151,7 +151,6 @@ async fn table_query_template_coerces_a_multi_database_selection_before_the_rpc( async fn built_in_drivers_keep_the_default_table_query_template_behavior() { let drivers: Vec> = vec![ Box::new(crate::drivers::mysql::MysqlDriver::new()), - Box::new(crate::drivers::postgres::PostgresDriver::new()), Box::new(crate::drivers::sqlite::SqliteDriver::new()), ]; for driver in drivers { diff --git a/src-tauri/src/plugins/tests.rs b/src-tauri/src/plugins/tests.rs index 29ced8d3f..8ff72e037 100644 --- a/src-tauri/src/plugins/tests.rs +++ b/src-tauri/src/plugins/tests.rs @@ -421,7 +421,6 @@ fn should_skip_rescan_does_not_skip_a_plugin_not_yet_registered() { #[test] fn should_skip_rescan_never_skips_a_builtin_id_even_when_registered() { assert!(!should_skip_rescan("mysql", true)); - assert!(!should_skip_rescan("postgres", true)); assert!(!should_skip_rescan("sqlite", true)); } diff --git a/src-tauri/src/pool_manager.rs b/src-tauri/src/pool_manager.rs index 332fda0fd..288522f44 100644 --- a/src-tauri/src/pool_manager.rs +++ b/src-tauri/src/pool_manager.rs @@ -1,19 +1,6 @@ use crate::models::ConnectionParams; use crate::sqlite_database::expand_sqlite_filename; -use deadpool_postgres::{ - Hook as PgHook, HookError as PgHookError, Manager as PgPoolManager, Pool as PgPool, -}; use once_cell::sync::Lazy; -use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; -use rustls::client::{verify_server_cert_signed_by_trust_anchor, WebPkiServerVerifier}; -use rustls::crypto::verify_tls12_signature; -use rustls::crypto::verify_tls13_signature; -use rustls::crypto::CryptoProvider; -use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime}; -use rustls::server::ParsedCertificate; -use rustls::DigitallySignedStruct; -use rustls::{ClientConfig, Error as TlsError, RootCertStore}; -use rustls_platform_verifier::BuilderVerifierExt; use sha2::{Digest, Sha256}; use sqlx::{ sqlite::SqliteConnectOptions, ConnectOptions, Connection, Executor, MySql, Pool, Sqlite, @@ -22,45 +9,6 @@ use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; use tokio::sync::RwLock; -use tokio_postgres::tls::MakeTlsConnect; -use tokio_postgres::{config::SslMode as PgSslMode, Config as PgConfig}; -use tokio_postgres_rustls::MakeRustlsConnect; - -/// A `MakeTlsConnect` wrapper around `MakeRustlsConnect` that gracefully handles -/// Unix socket connections (which have no DNS hostname). `tokio_postgres` passes -/// `hostname.unwrap_or("")` to `make_tls_connect` before entering its SSL-disabled -/// branch; `MakeRustlsConnect` rejects an empty string as `InvalidDnsNameError`. -/// For empty hostnames, we supply `"localhost"` so construction succeeds. For TCP -/// connections, the real hostname is passed through unchanged to preserve chain -/// and hostname validation. -#[derive(Clone)] -pub(crate) struct PostgresTlsConnector { - inner: MakeRustlsConnect, -} - -impl PostgresTlsConnector { - pub fn new(inner: MakeRustlsConnect) -> Self { - Self { inner } - } -} - -impl MakeTlsConnect for PostgresTlsConnector -where - S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static, -{ - type Stream = >::Stream; - type TlsConnect = >::TlsConnect; - type Error = >::Error; - - fn make_tls_connect(&mut self, hostname: &str) -> Result { - let host = if hostname.is_empty() { - "localhost" - } else { - hostname - }; - >::make_tls_connect(&mut self.inner, host) - } -} /// Walks `Error::source()` to surface the real cause, which `tokio_postgres` /// hides behind a generic "error performing TLS handshake". @@ -75,35 +23,18 @@ pub(crate) fn format_error_chain(err: &E) -> Stri out } -fn ensure_rustls_crypto_provider() { - use std::sync::Once; - static INSTALL: Once = Once::new(); - INSTALL.call_once(|| { - let _ = rustls::crypto::ring::default_provider().install_default(); - }); -} - type PoolMap = Arc>>>; -type PgPoolMap = Arc>>; static MYSQL_POOLS: Lazy> = Lazy::new(|| Arc::new(RwLock::new(HashMap::new()))); -static POSTGRES_POOLS: Lazy = Lazy::new(|| Arc::new(RwLock::new(HashMap::new()))); static SQLITE_POOLS: Lazy> = Lazy::new(|| Arc::new(RwLock::new(HashMap::new()))); const DEFAULT_MYSQL_CONNECT_TIMEOUT_MS: u64 = 60_000; -pub(crate) const DEFAULT_POSTGRES_POOL_MAX_SIZE: usize = 10; -const MAX_POSTGRES_POOL_MAX_SIZE: usize = 64; /// SQLite is file-based so the preflight is effectively local, but a custom /// VFS or a path on a stalled network mount could still hang it; bound it so a /// broken script can never wedge pool creation indefinitely. const SQLITE_STARTUP_SCRIPT_TIMEOUT_MS: u64 = 30_000; -/// The PostgreSQL startup-script preflight opens a real network connection, so -/// bound it the same way as SQLite: a broken script or a stalled host must -/// never wedge pool creation indefinitely. -const POSTGRES_STARTUP_SCRIPT_TIMEOUT_MS: u64 = 30_000; - fn mysql_setting_value(key: &str) -> Option { crate::config::get_cached_config() .plugins @@ -162,13 +93,6 @@ pub(crate) async fn with_connect_timeout( } } -/// The limit for one run of the PostgreSQL startup script: the connection's -/// connect timeout, else the default 30 s. -pub(crate) fn postgres_startup_script_timeout(params: &ConnectionParams) -> Duration { - connect_timeout(params) - .unwrap_or_else(|| Duration::from_millis(POSTGRES_STARTUP_SCRIPT_TIMEOUT_MS)) -} - /// The MySQL connect timeout: the connection's own value, else the global /// `connectTimeout` setting. pub(crate) fn mysql_connect_timeout(params: &ConnectionParams) -> Duration { @@ -180,42 +104,6 @@ pub(crate) fn mysql_connect_timeout(params: &ConnectionParams) -> Duration { }) } -fn postgres_setting_value(key: &str) -> Option { - crate::config::get_cached_config() - .plugins - .and_then(|plugins| plugins.get("postgres").cloned()) - .and_then(|plugin| plugin.settings.get(key).cloned()) -} - -pub(crate) fn postgres_pool_max_size_from_value(value: Option<&serde_json::Value>) -> usize { - value - .and_then(|value| { - value - .as_u64() - .or_else(|| value.as_i64().and_then(|item| u64::try_from(item).ok())) - .or_else(|| value.as_str().and_then(|item| item.parse::().ok())) - }) - .and_then(|value| usize::try_from(value).ok()) - .filter(|value| *value > 0) - .map(|value| value.min(MAX_POSTGRES_POOL_MAX_SIZE)) - .unwrap_or(DEFAULT_POSTGRES_POOL_MAX_SIZE) -} - -fn postgres_pool_max_size() -> usize { - postgres_pool_max_size_from_value(postgres_setting_value("poolMaxSize").as_ref()) -} - -/// PostgreSQL `ssl_mode` values produced by the connection form, connection -/// importers, and the #614 spelling migration. -const POSTGRES_ACCEPTED_SSL_MODES: &[&str] = &[ - "disable", - "allow", - "prefer", - "require", - "verify-ca", - "verify-full", -]; - /// MySQL `ssl_mode` values produced by the connection form, the JDBC URL /// importer, and connection importers. Importers store libpq spellings /// (`verify-ca`, `verify-full`, `require`, `prefer`) on MySQL connections @@ -250,35 +138,6 @@ fn non_empty_ssl_mode(value: Option<&str>) -> Option<&str> { value.map(str::trim).filter(|s| !s.is_empty()) } -#[derive(Clone, Copy)] -enum PostgresSslChoice { - Disable, - Allow, - Prefer, - Require, - VerifyCa, - VerifyFull, -} - -fn parse_postgres_ssl_mode(raw: &str) -> Result { - match normalized_ssl_mode(raw).as_str() { - "disable" => Ok(PostgresSslChoice::Disable), - "allow" => Ok(PostgresSslChoice::Allow), - "prefer" => Ok(PostgresSslChoice::Prefer), - "require" => Ok(PostgresSslChoice::Require), - "verify-ca" => Ok(PostgresSslChoice::VerifyCa), - "verify-full" => Ok(PostgresSslChoice::VerifyFull), - _ => Err(unknown_ssl_mode_message(raw, POSTGRES_ACCEPTED_SSL_MODES)), - } -} - -fn postgres_ssl_mode_verifies_certificate(raw: &str) -> bool { - matches!( - parse_postgres_ssl_mode(raw), - Ok(PostgresSslChoice::VerifyCa | PostgresSslChoice::VerifyFull) - ) -} - fn parse_mysql_ssl_mode(raw: &str) -> Result { use sqlx::mysql::MySqlSslMode; match normalized_ssl_mode(raw).as_str() { @@ -321,27 +180,6 @@ pub(crate) fn build_connection_key( "false" } )), - "postgres" => { - // Unset matches `build_postgres_tls_connector` (`prefer`). The raw - // value stays in the key so an unknown mode cannot share a pool - // with that default; only modes that verify the certificate fold - // the CA path into the key. - let ssl_mode = non_empty_ssl_mode(params.ssl_mode.as_deref()).unwrap_or("prefer"); - let ssl_ca = if postgres_ssl_mode_verifies_certificate(ssl_mode) { - params.ssl_ca.as_deref().unwrap_or("") - } else { - "" - }; - let (ssl_cert, ssl_key) = if normalized_ssl_mode(ssl_mode) == "disable" { - ("", "") - } else { - ( - params.ssl_cert.as_deref().unwrap_or(""), - params.ssl_key.as_deref().unwrap_or(""), - ) - }; - Some(format!("ssl:{ssl_mode}:{ssl_ca}:{ssl_cert}:{ssl_key}")) - } _ => None, }; @@ -697,384 +535,6 @@ pub(crate) fn is_pipes_as_concat_unsupported(err: &str) -> bool { err.contains("pipes_as_concat") || err.contains("no_engine_substitution") } -/// Split a user-entered PostgreSQL socket path into what tokio_postgres wants: -/// the *directory* holding the socket plus the port that names it. Users point -/// at the socket file (`/var/run/postgresql/.s.PGSQL.5432`), matching the SSH -/// forward field; a path whose last component is not `.s.PGSQL.` is -/// taken as the directory itself, paired with `default_port`. -#[cfg_attr(not(unix), allow(dead_code))] -pub(crate) fn split_postgres_socket_path(path: &str, default_port: u16) -> (String, u16) { - if let Some((dir, file)) = path.rsplit_once('/') { - if let Some(port) = file - .strip_prefix(".s.PGSQL.") - .and_then(|p| p.parse::().ok()) - { - let dir = if dir.is_empty() { "/" } else { dir }; - return (dir.to_string(), port); - } - } - (path.to_string(), default_port) -} - -pub(crate) fn build_postgres_configurations(params: &ConnectionParams) -> Result { - let mut cfg = PgConfig::new(); - cfg.user(params.username.as_deref().unwrap_or_default()) - .password(params.password.as_deref().unwrap_or_default()) - .dbname(&format!("{}", params.database)); - if let Some(timeout) = connect_timeout(params) { - cfg.connect_timeout(timeout); - } - if params.read_only { - cfg.options("-c default_transaction_read_only=on"); - } - - if let Some(socket) = params.local_unix_socket_path() { - // tokio_postgres only dials Unix sockets on Unix platforms. - #[cfg(unix)] - { - let (dir, port) = split_postgres_socket_path(socket, params.port.unwrap_or(5432)); - cfg.host_path(dir).port(port); - // TLS cannot be negotiated over a local Unix socket, and the traffic - // never leaves the machine: force it off so `prefer`-style defaults - // don't stall the handshake. - cfg.ssl_mode(PgSslMode::Disable); - return Ok(cfg); - } - #[cfg(not(unix))] - { - let _ = socket; - return Err("Unix socket connections are not supported on Windows. \ - Connect with host and port instead." - .to_string()); - } - } - - cfg.port(params.port.unwrap_or(5432)) - .host(params.host.as_deref().unwrap_or_default()); - - // Unset leaves tokio_postgres's default (`Prefer`). A set but unknown - // mode is a connection error rather than that default. - if let Some(ssl_mode) = non_empty_ssl_mode(params.ssl_mode.as_deref()) { - match parse_postgres_ssl_mode(ssl_mode)? { - PostgresSslChoice::Disable => { - cfg.ssl_mode(PgSslMode::Disable); - } - // tokio_postgres does not have SslMode::Allow. - // "allow" (try non-SSL first, fallback to SSL) requires application-level - // logic that this codebase does not implement. For now, map to Prefer - // which at least allows both SSL and non-SSL connections. - PostgresSslChoice::Allow | PostgresSslChoice::Prefer => { - cfg.ssl_mode(PgSslMode::Prefer); - } - PostgresSslChoice::Require - | PostgresSslChoice::VerifyCa - | PostgresSslChoice::VerifyFull => { - cfg.ssl_mode(PgSslMode::Require); - } - } - } - - Ok(cfg) -} - -/// Build the rustls connector for the PostgreSQL pool. -/// -/// `rustls` (not `native-tls`) because macOS Secure Transport applies a -/// strict `id-kp-serverAuth` EKU check to user-supplied root anchors and -/// rejects valid CA certs. `ssl_ca` overrides the platform trust store — -/// RDS users point it at the AWS global bundle -/// (`https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem`). -/// The bundle is intentionally not vendored: AWS rotates these CAs every -/// 1-3 years, so distributors pull a fresh copy at packaging time. -/// -/// SSL modes: -/// - `disable`: no TLS -/// - `allow`/`prefer`: TLS without certificate verification -/// - `require`: force TLS without certificate verification -/// (prior to v0.10.3 this validated the chain; it now matches libpq). -/// - `verify-ca`: force TLS, validate chain, skip hostname check -/// - `verify-full`: force TLS, validate chain and hostname -/// -/// An unrecognised `ssl_mode` is an error. Unset keeps `prefer`. -pub(crate) fn build_postgres_tls_connector( - params: &ConnectionParams, -) -> Result { - ensure_rustls_crypto_provider(); - let ssl_mode = if params.local_unix_socket_path().is_some() { - // Match the PostgreSQL config: local sockets do not use TLS, so stale - // certificate paths and TLS modes from a TCP connection are inactive. - PostgresSslChoice::Disable - } else { - parse_postgres_ssl_mode(non_empty_ssl_mode(params.ssl_mode.as_deref()).unwrap_or("prefer"))? - }; - let user_ca = params.ssl_ca.as_deref().filter(|s| !s.trim().is_empty()); - let user_cert = params.ssl_cert.as_deref().filter(|s| !s.trim().is_empty()); - let user_key = params.ssl_key.as_deref().filter(|s| !s.trim().is_empty()); - - let client_auth = if matches!(ssl_mode, PostgresSslChoice::Disable) { - None - } else { - match (user_cert, user_key) { - (Some(cert), Some(key)) => Some(load_client_auth_from_pem(cert, key)?), - (Some(_), None) => { - return Err( - "Client certificate provided (ssl_cert) without a client private key (ssl_key)" - .to_string(), - ); - } - (None, Some(_)) => { - return Err( - "Client private key provided (ssl_key) without a client certificate (ssl_cert)" - .to_string(), - ); - } - (None, None) => None, - } - }; - - let builder = match ssl_mode { - PostgresSslChoice::Disable | PostgresSslChoice::Allow | PostgresSslChoice::Prefer => { - // No cert verification; PgSslMode below controls whether TLS is attempted. - let verifier = Arc::new(NoCertVerifier::new()); - ClientConfig::builder() - .dangerous() - .with_custom_certificate_verifier(verifier) - } - PostgresSslChoice::Require => { - // Force TLS, skip cert validation. - let verifier = Arc::new(NoCertVerifier::new()); - ClientConfig::builder() - .dangerous() - .with_custom_certificate_verifier(verifier) - } - PostgresSslChoice::VerifyCa => { - // Validate chain, skip hostname. Requires an explicit CA file — - // platform roots are not used (macOS EKU check rejects them). - let ca_path = user_ca.ok_or_else(|| { - "verify-ca mode requires an explicit CA file via the connection's \ - CA Certificate field. On macOS, platform root certificates are \ - not compatible with strict EKU checks. For automatic platform \ - trust, use verify-full instead." - .to_string() - })?; - let roots = load_roots_from_pem(ca_path)?; - let verifier = Arc::new(VerifyCaCertVerifier::new(roots)?); - ClientConfig::builder() - .dangerous() - .with_custom_certificate_verifier(verifier) - } - PostgresSslChoice::VerifyFull => { - // Validate certificate chain AND hostname. - if user_ca.is_none() { - // Use platform verifier for full validation. - ClientConfig::builder() - .with_platform_verifier() - .map_err(|e| format!("Failed to build platform TLS verifier: {}", e))? - } else { - // Use custom CA with full hostname verification. - let roots = load_roots_from_pem(user_ca.unwrap())?; - let verifier = WebPkiServerVerifier::builder(Arc::new(roots)) - .build() - .map_err(|e| format!("Failed to build certificate verifier: {e}"))?; - ClientConfig::builder() - .dangerous() - .with_custom_certificate_verifier(verifier) - } - } - }; - - let config = match client_auth { - Some((certs, key)) => builder - .with_client_auth_cert(certs, key) - .map_err(|e| format!("Failed to configure client certificate: {e}"))?, - None => builder.with_no_client_auth(), - }; - - Ok(PostgresTlsConnector::new(MakeRustlsConnect::new(config))) -} - -/// Load client certificate chain and private key from PEM files for mTLS. -pub(crate) fn load_client_auth_from_pem( - cert_path: &str, - key_path: &str, -) -> Result<(Vec>, PrivateKeyDer<'static>), String> { - let cert_bytes = std::fs::read(cert_path) - .map_err(|e| format!("Failed to read ssl_cert file '{}': {}", cert_path, e))?; - let mut cert_cursor = std::io::Cursor::new(&cert_bytes[..]); - let certs: Vec> = rustls_pemfile::certs(&mut cert_cursor) - .collect::, _>>() - .map_err(|e| format!("Failed to parse ssl_cert '{}': {}", cert_path, e))?; - - if certs.is_empty() { - return Err(format!( - "ssl_cert '{}' contained no PEM CERTIFICATE blocks", - cert_path - )); - } - - let key_bytes = std::fs::read(key_path) - .map_err(|e| format!("Failed to read ssl_key file '{}': {}", key_path, e))?; - let mut key_cursor = std::io::Cursor::new(&key_bytes[..]); - let key = rustls_pemfile::private_key(&mut key_cursor) - .map_err(|e| format!("Failed to parse ssl_key '{}': {}", key_path, e))? - .ok_or_else(|| { - format!( - "ssl_key '{}' contained no private key in PEM format", - key_path - ) - })?; - - Ok((certs, key)) -} - -/// Load root certificates from a PEM file. -pub(crate) fn load_roots_from_pem(path: &str) -> Result { - let pem = - std::fs::read(path).map_err(|e| format!("Failed to read ssl_ca file '{}': {}", path, e))?; - let mut roots = RootCertStore::empty(); - let mut cursor = std::io::Cursor::new(&pem[..]); - for cert in rustls_pemfile::certs(&mut cursor) { - let cert = cert.map_err(|e| format!("Failed to parse ssl_ca '{}': {}", path, e))?; - roots - .add(cert) - .map_err(|e| format!("Failed to add ssl_ca cert from '{}': {}", path, e))?; - } - if roots.is_empty() { - return Err(format!( - "ssl_ca '{}' contained no PEM CERTIFICATE blocks", - path - )); - } - Ok(roots) -} - -/// A certificate verifier that skips certificate validation entirely. -/// Used for sslmode=require, prefer, allow. -#[derive(Debug)] -struct NoCertVerifier { - supported: rustls::crypto::WebPkiSupportedAlgorithms, -} - -impl NoCertVerifier { - fn new() -> Self { - let provider = CryptoProvider::get_default().expect("rustls CryptoProvider not installed"); - Self { - supported: provider.signature_verification_algorithms, - } - } -} - -impl ServerCertVerifier for NoCertVerifier { - 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 { - Ok(HandshakeSignatureValid::assertion()) - } - - fn verify_tls13_signature( - &self, - _message: &[u8], - _cert: &CertificateDer<'_>, - _dss: &DigitallySignedStruct, - ) -> Result { - Ok(HandshakeSignatureValid::assertion()) - } - - fn supported_verify_schemes(&self) -> Vec { - self.supported.supported_schemes() - } -} - -/// A certificate verifier that validates the certificate chain against -/// a custom root store but skips hostname verification. -/// Matches libpq `sslmode=verify-ca` behavior. -/// -/// Uses `verify_server_cert_signed_by_trust_anchor` directly rather than -/// wrapping `WebPkiServerVerifier` — this makes the "skip hostname check" -/// intent explicit, avoids double-verifying the chain, and prevents the -/// fragile `.or(Ok(...))` error-recovery pattern. -#[derive(Debug)] -struct VerifyCaCertVerifier { - roots: Arc, - supported: rustls::crypto::WebPkiSupportedAlgorithms, -} - -impl VerifyCaCertVerifier { - fn new(roots: RootCertStore) -> Result { - if roots.is_empty() { - return Err("No root certificates available. For verify-ca mode, \ - you must specify an explicit CA file via the connection's \ - CA Certificate field. On macOS, the system keychain does \ - not provide root anchors compatible with strict EKU checks." - .to_string()); - } - let provider = CryptoProvider::get_default().ok_or("No rustls CryptoProvider installed")?; - Ok(Self { - roots: Arc::new(roots), - supported: provider.signature_verification_algorithms, - }) - } -} - -impl ServerCertVerifier for VerifyCaCertVerifier { - fn verify_server_cert( - &self, - end_entity: &CertificateDer<'_>, - intermediates: &[CertificateDer<'_>], - _server_name: &ServerName<'_>, - _ocsp_response: &[u8], - now: UnixTime, - ) -> Result { - // Validate the certificate chain against our root store. - // We intentionally skip hostname verification (verify-ca semantics). - let cert = ParsedCertificate::try_from(end_entity)?; - verify_server_cert_signed_by_trust_anchor( - &cert, - &self.roots, - intermediates, - now, - self.supported.all, - )?; - Ok(ServerCertVerified::assertion()) - } - - fn verify_tls12_signature( - &self, - message: &[u8], - cert: &CertificateDer<'_>, - dss: &DigitallySignedStruct, - ) -> Result { - verify_tls12_signature(message, cert, dss, &self.supported) - } - - fn verify_tls13_signature( - &self, - message: &[u8], - cert: &CertificateDer<'_>, - dss: &DigitallySignedStruct, - ) -> Result { - verify_tls13_signature(message, cert, dss, &self.supported) - } - - fn supported_verify_schemes(&self) -> Vec { - self.supported.supported_schemes() - } -} - fn build_sqlite_connectoptions(params: &ConnectionParams) -> SqliteConnectOptions { let options = SqliteConnectOptions::new().filename(expand_sqlite_filename(params.database.primary())); @@ -1113,7 +573,7 @@ fn startup_script_error(err: impl std::fmt::Display) -> String { fn startup_script_timeout_error(timeout: Duration) -> String { format!( - "Timed out running PostgreSQL startup script after {} ms", + "Timed out running startup script after {} ms", timeout.as_millis() ) } @@ -1161,33 +621,6 @@ async fn run_sqlite_startup_script( outcome.map_err(startup_script_error) } -/// PostgreSQL counterpart to [`run_mysql_startup_script`]. deadpool surfaces a -/// failing `post_create` hook as a raw `PoolError::PostCreateHook(..)` debug -/// struct on first use; this preflight instead fails fast at pool-creation time -/// with the same clean `Startup script failed: …` attribution as the other -/// drivers. The script is validated inside a transaction that is rolled back, -/// so side effects are applied only by the per-connection `post_create` hook. -async fn run_postgres_startup_script( - cfg: &PgConfig, - tls: PostgresTlsConnector, - script: &str, -) -> Result<(), String> { - let (mut client, connection) = cfg.connect(tls).await.map_err(|e| format_error_chain(&e))?; - // tokio_postgres needs the connection future polled on its own task. - let driver = tokio::spawn(async move { - let _ = connection.await; - }); - let outcome: Result<(), tokio_postgres::Error> = async { - let tx = client.transaction().await?; - tx.batch_execute(script).await?; - tx.rollback().await - } - .await; - drop(client); - driver.abort(); - outcome.map_err(|e| startup_script_error(format_error_chain(&e))) -} - pub async fn get_mysql_pool(params: &ConnectionParams) -> Result, String> { let connection_id = params.connection_id.as_deref(); get_mysql_pool_with_id(params, connection_id).await @@ -1239,10 +672,9 @@ async fn get_mysql_pool_for_database_with_id( params.host, key ); - // sqlx-mysql is built with `tls-native-tls` (not `tls-rustls`) so the OS - // trust store is used; a process-level rustls CryptoProvider is not - // required here. The Postgres deadpool path still installs one in - // build_postgres_configurations via the same helper. + // sqlx-mysql is built with `tls-rustls-ring-native-roots`: rustls with the + // ring provider and the OS trust store. It relies on the process-level + // CryptoProvider that `install_process_prerequisites` installs at startup. let connect_timeout = mysql_connect_timeout(params); let script = startup_script(params); @@ -1293,105 +725,6 @@ async fn get_mysql_pool_for_database_with_id( Ok(pool) } -pub async fn get_postgres_pool(params: &ConnectionParams) -> Result { - let connection_id = params.connection_id.as_deref(); - get_postgres_pool_with_id(params, connection_id).await -} - -pub async fn get_postgres_pool_with_id( - params: &ConnectionParams, - connection_id: Option<&str>, -) -> Result { - let key = build_connection_key(params, connection_id); - - // Try to get existing pool - { - let pools = POSTGRES_POOLS.read().await; - if let Some(pool) = pools.get(&key) { - log::debug!( - "Using existing PostgreSQL connection pool for: {} (key: {})", - params.database, - key - ); - return Ok(pool.clone()); - } - } - - // Create new pool - log::info!( - "Creating new PostgreSQL connection pool for: {}@{:?} (key: {})", - params.username.as_deref().unwrap_or("unknown"), - params.host, - key - ); - - let cfg = build_postgres_configurations(params)?; - - let tls_connector = build_postgres_tls_connector(params).map_err(|e| { - log::error!("Failed to create TLS connector for PostgreSQL pool: {}", e); - e - })?; - - if let Some(script) = startup_script(params) { - let timeout = postgres_startup_script_timeout(params); - tokio::time::timeout( - timeout, - run_postgres_startup_script(&cfg, tls_connector.clone(), &script), - ) - .await - .map_err(|_| startup_script_timeout_error(timeout))??; - } - - let mut builder = - PgPool::builder(PgPoolManager::new(cfg, tls_connector)).max_size(postgres_pool_max_size()); - // The config's connect_timeout only bounds the TCP connect; this also - // bounds TLS and authentication. deadpool runs post_create hooks after - // this timeout, so the hook below bounds the startup script separately. - let script_timeout = connect_timeout(params); - if let Some(timeout) = script_timeout { - builder = builder - .runtime(deadpool_postgres::Runtime::Tokio1) - .create_timeout(Some(timeout)); - } - if let Some(script) = startup_script(params) { - builder = builder.post_create(PgHook::async_fn(move |client, _metrics| { - let script = script.clone(); - Box::pin(async move { - let run = client.batch_execute(&script); - let outcome = match script_timeout { - Some(timeout) => tokio::time::timeout(timeout, run) - .await - .map_err(|_| PgHookError::message(startup_script_timeout_error(timeout)))?, - None => run.await, - }; - outcome.map_err(|e| { - PgHookError::message(startup_script_error(format_error_chain(&e))) - })?; - Ok(()) - }) - })); - } - let pool = builder.build().map_err(|e| { - let detail = format_error_chain(&e); - log::error!("Failed to create PostgreSQL connection pool: {}", detail); - detail - })?; - - log::info!( - "PostgreSQL connection pool created successfully for: {} (key: {})", - params.database, - key - ); - - // Store pool - { - let mut pools = POSTGRES_POOLS.write().await; - pools.insert(key, pool.clone()); - } - - Ok(pool) -} - pub async fn get_sqlite_pool(params: &ConnectionParams) -> Result, String> { let connection_id = params.connection_id.as_deref(); get_sqlite_pool_with_id(params, connection_id).await @@ -1480,7 +813,6 @@ pub async fn has_pool_for_database( }; match params.driver.as_str() { "mysql" => MYSQL_POOLS.read().await.contains_key(&key), - "postgres" => POSTGRES_POOLS.read().await.contains_key(&key), "sqlite" => SQLITE_POOLS.read().await.contains_key(&key), _ => false, } @@ -1513,22 +845,6 @@ pub async fn close_pool_with_id(params: &ConnectionParams, connection_id: Option ); } } - "postgres" => { - let mut pools = POSTGRES_POOLS.write().await; - if let Some(pool) = pools.remove(&key) { - log::info!( - "Closing PostgreSQL connection pool for: {} (key: {})", - params.database, - key - ); - pool.close(); - log::info!( - "PostgreSQL connection pool closed for: {} (key: {})", - params.database, - key - ); - } - } "sqlite" => { let mut pools = SQLITE_POOLS.write().await; if let Some(pool) = pools.remove(&key) { @@ -1581,9 +897,8 @@ pub(crate) fn remove_pools_with_prefix

( .collect() } -/// Close a pool, abstracting over the async `sqlx::Pool::close` and the -/// sync `deadpool_postgres::Pool::close` so the remove/close/log loop can be -/// shared across drivers. +/// Close a pool, abstracting over the async `sqlx::Pool::close` so the +/// remove/close/log loop can be shared across drivers. trait PoolClose { async fn close_pool(&self); } @@ -1594,14 +909,6 @@ impl PoolClose for Pool { } } -impl PoolClose for PgPool { - async fn close_pool(&self) { - // `deadpool_postgres::Pool::close` is synchronous; wrap it so the - // trait signature matches the async `sqlx` pools. - self.close(); - } -} - impl PoolClose for Pool { async fn close_pool(&self) { self.close().await; @@ -1642,7 +949,6 @@ pub async fn close_pools_for_connection_id(driver: &str, connection_id: &str) { match driver { "mysql" => close_pools_with_prefix(&MYSQL_POOLS, &prefix, "MySQL").await, - "postgres" => close_pools_with_prefix(&POSTGRES_POOLS, &prefix, "PostgreSQL").await, "sqlite" => close_pools_with_prefix(&SQLITE_POOLS, &prefix, "SQLite").await, _ => {} } @@ -1673,12 +979,6 @@ pub async fn close_all_pools() { pool.close().await; } } - { - let mut pools = POSTGRES_POOLS.write().await; - for (_, pool) in pools.drain() { - pool.close(); - } - } { let mut pools = SQLITE_POOLS.write().await; for (_, pool) in pools.drain() { diff --git a/src-tauri/src/pool_manager/read_only_tests.rs b/src-tauri/src/pool_manager/read_only_tests.rs index dd8a31edb..9a52c9108 100644 --- a/src-tauri/src/pool_manager/read_only_tests.rs +++ b/src-tauri/src/pool_manager/read_only_tests.rs @@ -24,26 +24,6 @@ fn protected_pool_keys_are_isolated_and_disconnect_collects_both_policies() { assert_eq!(pools.len(), 1); } -#[test] -fn postgres_read_only_is_installed_before_the_first_query() { - let params = ConnectionParams { - driver: "postgres".into(), - read_only: true, - ..Default::default() - }; - let config = build_postgres_configurations(¶ms).unwrap(); - assert_eq!( - config.get_options(), - Some("-c default_transaction_read_only=on") - ); - let config = build_postgres_configurations(&ConnectionParams { - read_only: false, - ..params - }) - .unwrap(); - assert_eq!(config.get_options(), None); -} - #[tokio::test] async fn sqlite_read_only_pool_protects_internal_reads_and_never_contaminates_writable_pools() { let temp = tempfile::NamedTempFile::new().unwrap(); diff --git a/src-tauri/src/pool_manager_tests.rs b/src-tauri/src/pool_manager_tests.rs index 5c484efe2..1879b24ee 100644 --- a/src-tauri/src/pool_manager_tests.rs +++ b/src-tauri/src/pool_manager_tests.rs @@ -4,9 +4,8 @@ mod tests { use crate::pool_manager::{ build_connection_key, build_mysql_options, connect_timeout, connection_pool_prefix, format_error_chain, is_pipes_as_concat_unsupported, mysql_connect_timeout, - mysql_idle_needs_ping, postgres_pool_max_size_from_value, postgres_startup_script_timeout, - query_timeout, remove_pools_with_prefix, with_connect_timeout, - DEFAULT_POSTGRES_POOL_MAX_SIZE, MYSQL_PING_AFTER_IDLE, + mysql_idle_needs_ping, query_timeout, remove_pools_with_prefix, with_connect_timeout, + MYSQL_PING_AFTER_IDLE, }; use sqlx::mysql::MySqlSslMode; use std::collections::HashMap; @@ -104,17 +103,6 @@ mod tests { ); } - #[test] - fn postgres_pool_key_changes_when_ssl_mode_changes() { - let required = connection_params("postgres", Some("require")); - let disabled = connection_params("postgres", Some("disable")); - - assert_ne!( - build_connection_key(&required, Some("conn-1")), - build_connection_key(&disabled, Some("conn-1")) - ); - } - #[test] fn connection_pool_prefix_matches_every_database_for_a_connection() { // The prefix matches both the primary pool key and per-database override @@ -151,54 +139,6 @@ mod tests { ); } - #[test] - fn postgres_pool_key_with_tls_suffix_starts_with_connection_prefix() { - // A Postgres key appends a `:ssl:...` TLS suffix after the database. - // The connection prefix (which ends at the connection id) must still - // match it, so `close_pools_for_connection_id` closes TLS-keyed pools. - let params = connection_params("postgres", Some("require")); - let prefix = connection_pool_prefix("postgres", "conn-1"); - let primary_key = build_connection_key(¶ms, Some("conn-1")); - - let mut overridden = params.clone(); - overridden.database = DatabaseSelection::Single("other_db".to_string()); - let override_key = build_connection_key(&overridden, Some("conn-1")); - - assert!( - primary_key.starts_with(&prefix), - "primary key {primary_key} should start with prefix {prefix}" - ); - assert!( - override_key.starts_with(&prefix), - "override key {override_key} should start with prefix {prefix}" - ); - } - - #[test] - fn postgres_pool_key_with_startup_script_starts_with_connection_prefix() { - // A startup script appends a `:startup:` suffix after the TLS - // suffix. The connection prefix must still match it, so - // `close_pools_for_connection_id` closes pools whose keys carry a - // startup-script digest. - let mut params = connection_params("postgres", Some("require")); - params.startup_script = Some("SET app.bypass_rls = 'on';".to_string()); - let prefix = connection_pool_prefix("postgres", "conn-1"); - let primary_key = build_connection_key(¶ms, Some("conn-1")); - - let mut overridden = params.clone(); - overridden.database = DatabaseSelection::Single("other_db".to_string()); - let override_key = build_connection_key(&overridden, Some("conn-1")); - - assert!( - primary_key.starts_with(&prefix), - "primary key {primary_key} should start with prefix {prefix}" - ); - assert!( - override_key.starts_with(&prefix), - "override key {override_key} should start with prefix {prefix}" - ); - } - #[test] fn remove_pools_with_prefix_collects_only_matching_keys() { let mut pools: HashMap = HashMap::new(); @@ -221,98 +161,6 @@ mod tests { assert!(pools.contains_key("postgres:conn:1:db_a")); } - #[test] - fn postgres_pool_key_changes_when_ssl_ca_changes() { - let without_ca = connection_params("postgres", Some("verify-ca")); - let mut with_ca = connection_params("postgres", Some("verify-ca")); - with_ca.ssl_ca = Some("/tmp/postgres-ca.pem".to_string()); - - assert_ne!( - build_connection_key(&without_ca, Some("conn-1")), - build_connection_key(&with_ca, Some("conn-1")) - ); - } - - #[test] - fn postgres_pool_key_changes_when_ssl_cert_or_key_changes() { - let base = connection_params("postgres", Some("require")); - let mut with_cert = connection_params("postgres", Some("require")); - with_cert.ssl_cert = Some("/tmp/client-cert.pem".to_string()); - let mut with_key = connection_params("postgres", Some("require")); - with_key.ssl_key = Some("/tmp/client-key.pem".to_string()); - - assert_ne!( - build_connection_key(&base, Some("conn-1")), - build_connection_key(&with_cert, Some("conn-1")) - ); - assert_ne!( - build_connection_key(&base, Some("conn-1")), - build_connection_key(&with_key, Some("conn-1")) - ); - assert_ne!( - build_connection_key(&with_cert, Some("conn-1")), - build_connection_key(&with_key, Some("conn-1")) - ); - } - - #[test] - fn postgres_pool_max_size_defaults_without_setting() { - assert_eq!( - postgres_pool_max_size_from_value(None), - DEFAULT_POSTGRES_POOL_MAX_SIZE - ); - } - - #[test] - fn postgres_pool_max_size_accepts_numeric_and_string_settings() { - assert_eq!( - postgres_pool_max_size_from_value(Some(&serde_json::json!(1))), - 1 - ); - assert_eq!( - postgres_pool_max_size_from_value(Some(&serde_json::json!("3"))), - 3 - ); - } - - #[test] - fn postgres_pool_max_size_ignores_invalid_or_zero_settings() { - assert_eq!( - postgres_pool_max_size_from_value(Some(&serde_json::json!(0))), - DEFAULT_POSTGRES_POOL_MAX_SIZE - ); - assert_eq!( - postgres_pool_max_size_from_value(Some(&serde_json::json!("not-a-number"))), - DEFAULT_POSTGRES_POOL_MAX_SIZE - ); - } - - #[test] - fn postgres_pool_max_size_caps_oversized_settings() { - assert_eq!( - postgres_pool_max_size_from_value(Some(&serde_json::json!(10_000))), - 64 - ); - } - - #[test] - fn postgres_pool_key_ignores_ssl_cert_and_key_when_ssl_disabled() { - let base = connection_params("postgres", Some("disable")); - let mut with_cert = connection_params("postgres", Some("disable")); - with_cert.ssl_cert = Some("/tmp/client-cert.pem".to_string()); - let mut with_key = connection_params("postgres", Some("disable")); - with_key.ssl_key = Some("/tmp/client-key.pem".to_string()); - - assert_eq!( - build_connection_key(&base, Some("conn-1")), - build_connection_key(&with_cert, Some("conn-1")) - ); - assert_eq!( - build_connection_key(&base, Some("conn-1")), - build_connection_key(&with_key, Some("conn-1")) - ); - } - #[test] fn sqlite_pool_key_ignores_tls_key_fields() { let required = connection_params("sqlite", Some("required")); @@ -325,38 +173,6 @@ mod tests { ); } - #[test] - fn pool_key_changes_when_startup_script_changes() { - let none = connection_params("postgres", Some("require")); - let mut script_a = none.clone(); - script_a.startup_script = Some("SET app.bypass_rls = 'on';".to_string()); - let mut script_b = none.clone(); - script_b.startup_script = Some("SET app.bypass_rls = 'off';".to_string()); - - let key_none = build_connection_key(&none, Some("conn-1")); - let key_a = build_connection_key(&script_a, Some("conn-1")); - let key_b = build_connection_key(&script_b, Some("conn-1")); - - // A script changes the key, and different scripts differ — otherwise an - // edited startup script would silently reuse the old cached pool. - assert_ne!(key_none, key_a); - assert_ne!(key_a, key_b); - } - - #[test] - fn pool_key_ignores_blank_startup_script() { - let none = connection_params("postgres", Some("require")); - let mut blank = none.clone(); - blank.startup_script = Some(" \n\t".to_string()); - - // Whitespace-only scripts are treated as absent (no hook runs), so they - // must not fragment the pool away from the no-script connection. - assert_eq!( - build_connection_key(&none, Some("conn-1")), - build_connection_key(&blank, Some("conn-1")) - ); - } - #[test] fn connect_timeout_is_unset_for_none_and_zero() { let mut params = connection_params("postgres", None); @@ -407,27 +223,6 @@ mod tests { assert_eq!(mysql_connect_timeout(¶ms), global); } - #[test] - fn postgres_startup_script_timeout_uses_the_connect_timeout() { - let mut params = connection_params("postgres", None); - assert_eq!( - postgres_startup_script_timeout(¶ms), - Duration::from_secs(30) - ); - - params.connect_timeout_secs = Some(0); - assert_eq!( - postgres_startup_script_timeout(¶ms), - Duration::from_secs(30) - ); - - params.connect_timeout_secs = Some(2); - assert_eq!( - postgres_startup_script_timeout(¶ms), - Duration::from_secs(2) - ); - } - #[test] fn pool_key_changes_only_when_connect_timeout_is_set() { let none = connection_params("postgres", Some("require")); @@ -999,11 +794,6 @@ mod tests { // the active `sqlx` feature is `tls-rustls-ring-native-roots` // and not `tls-native-tls`, native-tls is unreachable from // the build, so the bug cannot return. - // 3. The Postgres path keeps using `rustls-platform-verifier` - // for `verify-full` so non-IAM users who rely on the OS - // trust store (e.g. an internal CA pushed through MDM) keep - // working — the switch for MySQL must not ripple into - // Postgres. // ------------------------------------------------------------------- /// Compile-time check that the MySQL TLS backend is rustls, not @@ -1167,546 +957,6 @@ mod tests { } } -#[cfg(test)] -mod postgres_ssl_config_tests { - use crate::models::{ConnectionParams, DatabaseSelection}; - use crate::pool_manager::build_postgres_configurations; - use tokio_postgres::config::SslMode as PgSslMode; - - fn params_with_ssl(mode: &str) -> ConnectionParams { - ConnectionParams { - driver: "postgres".to_string(), - host: Some("localhost".to_string()), - port: Some(5432), - username: Some("test".to_string()), - password: Some("test".to_string()), - database: DatabaseSelection::Single("testdb".to_string()), - ssl_mode: Some(mode.to_string()), - ..Default::default() - } - } - - fn params_no_ssl() -> ConnectionParams { - ConnectionParams { - driver: "postgres".to_string(), - host: Some("localhost".to_string()), - port: Some(5432), - username: Some("test".to_string()), - password: Some("test".to_string()), - database: DatabaseSelection::Single("testdb".to_string()), - ..Default::default() - } - } - - #[test] - fn test_ssl_mode_disable() { - let params = params_with_ssl("disable"); - let cfg = build_postgres_configurations(¶ms).expect("accepted ssl mode"); - assert_eq!(cfg.get_ssl_mode(), PgSslMode::Disable); - } - - #[test] - fn connect_timeout_is_applied_only_when_set() { - let mut params = params_no_ssl(); - let cfg = build_postgres_configurations(¶ms).expect("valid config"); - assert_eq!(cfg.get_connect_timeout(), None); - - params.connect_timeout_secs = Some(4); - let cfg = build_postgres_configurations(¶ms).expect("valid config"); - assert_eq!( - cfg.get_connect_timeout(), - Some(&std::time::Duration::from_secs(4)) - ); - } - - #[test] - fn test_ssl_mode_allow() { - let params = params_with_ssl("allow"); - let cfg = build_postgres_configurations(¶ms).expect("accepted ssl mode"); - // tokio_postgres does not have SslMode::Allow. - // "allow" is mapped to Prefer since the client library doesn't support - // "try non-SSL first, fallback to SSL" natively. - assert_eq!(cfg.get_ssl_mode(), PgSslMode::Prefer); - } - - #[test] - fn test_ssl_mode_prefer() { - let params = params_with_ssl("prefer"); - let cfg = build_postgres_configurations(¶ms).expect("accepted ssl mode"); - assert_eq!(cfg.get_ssl_mode(), PgSslMode::Prefer); - } - - #[test] - fn test_ssl_mode_require() { - let params = params_with_ssl("require"); - let cfg = build_postgres_configurations(¶ms).expect("accepted ssl mode"); - assert_eq!(cfg.get_ssl_mode(), PgSslMode::Require); - } - - #[test] - fn test_ssl_mode_verify_ca() { - let params = params_with_ssl("verify-ca"); - let cfg = build_postgres_configurations(¶ms).expect("accepted ssl mode"); - // verify-ca maps to Require at the protocol level (cert validation is in TLS connector) - assert_eq!(cfg.get_ssl_mode(), PgSslMode::Require); - } - - #[test] - fn test_ssl_mode_verify_full() { - let params = params_with_ssl("verify-full"); - let cfg = build_postgres_configurations(¶ms).expect("accepted ssl mode"); - // verify-full maps to Require at the protocol level - assert_eq!(cfg.get_ssl_mode(), PgSslMode::Require); - } - - #[test] - fn test_ssl_mode_default_is_prefer() { - // No ssl_mode set -> tokio_postgres defaults to Prefer - let params = params_no_ssl(); - let cfg = build_postgres_configurations(¶ms).expect("accepted ssl mode"); - assert_eq!(cfg.get_ssl_mode(), PgSslMode::Prefer); - } - - #[test] - fn test_ssl_mode_allow_vs_prefer() { - // Note: tokio_postgres does not have SslMode::Allow. - // Both "allow" and "prefer" map to PgSslMode::Prefer in the client library. - // The true libpq distinction (allow=non-SSL first, prefer=SSL first) cannot - // be implemented at the tokio_postgres level without application-level connection logic. - let allow_params = params_with_ssl("allow"); - let prefer_params = params_with_ssl("prefer"); - - let allow_cfg = build_postgres_configurations(&allow_params).expect("accepted ssl mode"); - let prefer_cfg = build_postgres_configurations(&prefer_params).expect("accepted ssl mode"); - - // Both map to Prefer in tokio_postgres - assert_eq!(allow_cfg.get_ssl_mode(), PgSslMode::Prefer); - assert_eq!(prefer_cfg.get_ssl_mode(), PgSslMode::Prefer); - } - - #[test] - fn test_ssl_mode_unknown_is_rejected() { - let err = match build_postgres_configurations(¶ms_with_ssl("verfy-full")) { - Err(err) => err, - Ok(_) => panic!("unknown ssl mode should fail"), - }; - assert!(err.contains("verfy-full"), "{err}"); - for accepted in [ - "disable", - "allow", - "prefer", - "require", - "verify-ca", - "verify-full", - ] { - assert!(err.contains(accepted), "{err} missing {accepted}"); - } - } - - #[test] - fn test_ssl_mode_blank_equals_default() { - let blank_cfg = - build_postgres_configurations(¶ms_with_ssl(" ")).expect("blank ssl_mode"); - let unset_params = ConnectionParams { - driver: "postgres".to_string(), - host: Some("localhost".to_string()), - port: Some(5432), - username: Some("test".to_string()), - password: Some("test".to_string()), - database: DatabaseSelection::Single("testdb".to_string()), - ssl_mode: None, - ..Default::default() - }; - let unset_cfg = build_postgres_configurations(&unset_params).expect("unset ssl_mode"); - assert_eq!(blank_cfg.get_ssl_mode(), PgSslMode::Prefer); - assert_eq!(unset_cfg.get_ssl_mode(), PgSslMode::Prefer); - assert_eq!(blank_cfg.get_ssl_mode(), unset_cfg.get_ssl_mode()); - } -} - -#[cfg(test)] -mod postgres_tls_connector_tests { - use crate::models::{ConnectionParams, DatabaseSelection}; - use crate::pool_manager::build_postgres_tls_connector; - - fn params_with_ssl(mode: &str) -> ConnectionParams { - ConnectionParams { - driver: "postgres".to_string(), - host: Some("localhost".to_string()), - port: Some(5432), - username: Some("test".to_string()), - password: Some("test".to_string()), - database: DatabaseSelection::Single("testdb".to_string()), - ssl_mode: Some(mode.to_string()), - ..Default::default() - } - } - - #[test] - fn test_tls_connector_disable() { - let params = params_with_ssl("disable"); - let result = build_postgres_tls_connector(¶ms); - // Should succeed - connector is created even for disable mode - assert!(result.is_ok()); - } - - #[test] - fn test_tls_connector_allow() { - let params = params_with_ssl("allow"); - let result = build_postgres_tls_connector(¶ms); - // Should succeed with NoCertVerifier - assert!(result.is_ok()); - } - - #[test] - fn test_tls_connector_prefer() { - let params = params_with_ssl("prefer"); - let result = build_postgres_tls_connector(¶ms); - // Should succeed with NoCertVerifier - assert!(result.is_ok()); - } - - #[test] - fn test_tls_connector_require() { - let params = params_with_ssl("require"); - let result = build_postgres_tls_connector(¶ms); - // Should succeed with NoCertVerifier - assert!(result.is_ok()); - } - - #[test] - fn test_tls_connector_verify_ca_requires_ca_file() { - let params = params_with_ssl("verify-ca"); - let result = build_postgres_tls_connector(¶ms); - // verify-ca requires an explicit CA file — no platform roots fallback - match result { - Err(e) => assert!(e.contains("verify-ca mode requires an explicit CA file")), - Ok(_) => panic!("Expected error for verify-ca without CA file"), - } - } - - #[test] - fn test_tls_connector_verify_ca_with_ca_file() { - use std::io::Write; - - // Create a minimal test CA certificate - let temp_dir = std::env::temp_dir(); - let file_path = temp_dir.join("test_verify_ca_ca.pem"); - { - // Write a minimal valid PEM certificate block for testing - let cert_pem = include_bytes!("../tests/test_ca.pem"); - let mut file = std::fs::File::create(&file_path).unwrap(); - file.write_all(cert_pem).unwrap(); - } - - let params = ConnectionParams { - driver: "postgres".to_string(), - host: Some("localhost".to_string()), - port: Some(5432), - username: Some("test".to_string()), - password: Some("test".to_string()), - database: DatabaseSelection::Single("testdb".to_string()), - ssl_mode: Some("verify-ca".to_string()), - ssl_ca: Some(file_path.to_str().unwrap().to_string()), - ..Default::default() - }; - let result = build_postgres_tls_connector(¶ms); - assert!(result.is_ok()); - - let _ = std::fs::remove_file(&file_path); - } - - #[test] - fn test_tls_connector_verify_full() { - let params = params_with_ssl("verify-full"); - let result = build_postgres_tls_connector(¶ms); - // Should succeed with platform verifier - assert!(result.is_ok()); - } - - fn tls_connector_error(mode: &str) -> String { - match build_postgres_tls_connector(¶ms_with_ssl(mode)) { - Err(err) => err, - Ok(_) => panic!("{mode} should have failed"), - } - } - - #[test] - fn test_tls_connector_accepts_every_produced_ssl_mode() { - for mode in ["disable", "allow", "prefer", "require", "verify-full"] { - if let Err(err) = build_postgres_tls_connector(¶ms_with_ssl(mode)) { - panic!("{mode} should be accepted, got: {err}"); - } - } - // verify-ca is accepted, but still requires a CA file. - let err = tls_connector_error("verify-ca"); - assert!(err.contains("verify-ca mode requires"), "{err}"); - assert!(!err.contains("Unknown SSL mode"), "{err}"); - } - - #[test] - fn test_tls_connector_verify_ca_is_case_insensitive() { - let err = tls_connector_error("VERIFY-CA"); - assert!(err.contains("verify-ca mode requires"), "{err}"); - } - - #[test] - fn test_tls_connector_rejects_unknown_ssl_mode() { - let err = tls_connector_error("verfy-full"); - assert!(err.contains("verfy-full"), "{err}"); - for accepted in [ - "disable", - "allow", - "prefer", - "require", - "verify-ca", - "verify-full", - ] { - assert!(err.contains(accepted), "{err} missing {accepted}"); - } - } - - #[test] - fn test_tls_connector_default_ssl_mode_is_prefer() { - let mut params = params_with_ssl("prefer"); - params.ssl_mode = None; - assert!(build_postgres_tls_connector(¶ms).is_ok()); - } - - #[test] - fn test_tls_connector_blank_ssl_mode_equals_default() { - let blank = params_with_ssl(" "); - let mut unset = params_with_ssl("prefer"); - unset.ssl_mode = None; - assert!(build_postgres_tls_connector(&blank).is_ok()); - assert!(build_postgres_tls_connector(&unset).is_ok()); - } - - #[test] - fn test_load_roots_from_pem_missing_file() { - use crate::pool_manager::load_roots_from_pem; - let result = load_roots_from_pem("/nonexistent/path/to/ca.pem"); - assert!(result.is_err()); - let err = result.unwrap_err(); - assert!(err.contains("Failed to read ssl_ca file")); - } - - #[test] - fn test_load_roots_from_pem_invalid_content() { - use crate::pool_manager::load_roots_from_pem; - use std::io::Write; - - let temp_dir = std::env::temp_dir(); - let file_path = temp_dir.join("test_invalid_ca.pem"); - { - let mut file = std::fs::File::create(&file_path).unwrap(); - writeln!(file, "this is not a valid PEM file").unwrap(); - writeln!(file, "no certificates here").unwrap(); - } - - let result = load_roots_from_pem(file_path.to_str().unwrap()); - assert!(result.is_err()); - let err = result.unwrap_err(); - assert!(err.contains("contained no PEM CERTIFICATE blocks")); - - // Cleanup - let _ = std::fs::remove_file(&file_path); - } - - #[test] - fn test_load_client_auth_from_pem_valid() { - use crate::pool_manager::load_client_auth_from_pem; - use openssl::asn1::Asn1Time; - use openssl::bn::BigNum; - use openssl::ec::{EcGroup, EcKey}; - use openssl::hash::MessageDigest; - use openssl::nid::Nid; - use openssl::pkey::PKey; - use openssl::x509::{X509NameBuilder, X509}; - use std::io::Write; - - let temp_dir = tempfile::tempdir().unwrap(); - let cert_path = temp_dir.path().join("test_client_cert.pem"); - let key_path = temp_dir.path().join("test_client_key.pem"); - - let curve = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); - let private_key = PKey::from_ec_key(EcKey::generate(&curve).unwrap()).unwrap(); - let mut subject = X509NameBuilder::new().unwrap(); - subject.append_entry_by_text("CN", "test-client").unwrap(); - let subject = subject.build(); - - let mut certificate = X509::builder().unwrap(); - certificate.set_version(2).unwrap(); - let serial_number = BigNum::from_u32(1).unwrap().to_asn1_integer().unwrap(); - certificate.set_serial_number(&serial_number).unwrap(); - certificate.set_subject_name(&subject).unwrap(); - certificate.set_issuer_name(&subject).unwrap(); - certificate.set_pubkey(&private_key).unwrap(); - certificate - .set_not_before(&Asn1Time::days_from_now(0).unwrap()) - .unwrap(); - certificate - .set_not_after(&Asn1Time::days_from_now(1).unwrap()) - .unwrap(); - certificate - .sign(&private_key, MessageDigest::sha256()) - .unwrap(); - - let cert_pem = certificate.build().to_pem().unwrap(); - let key_pem = private_key.private_key_to_pem_pkcs8().unwrap(); - - std::fs::File::create(&cert_path) - .unwrap() - .write_all(&cert_pem) - .unwrap(); - std::fs::File::create(&key_path) - .unwrap() - .write_all(&key_pem) - .unwrap(); - - let result = - load_client_auth_from_pem(cert_path.to_str().unwrap(), key_path.to_str().unwrap()); - assert!(result.is_ok()); - let (certs, _key) = result.unwrap(); - assert_eq!(certs.len(), 1); - - // Test connector builder with client auth - let mut params = params_with_ssl("require"); - params.ssl_cert = Some(cert_path.to_str().unwrap().to_string()); - params.ssl_key = Some(key_path.to_str().unwrap().to_string()); - let conn_res = build_postgres_tls_connector(¶ms); - assert!(conn_res.is_ok()); - } - - #[test] - fn test_tls_connector_disabled_ssl_ignores_client_cert_and_key() { - let mut params = params_with_ssl("disable"); - // Mismatched or non-existent client cert/key paths should be ignored when SSL is disabled. - params.ssl_cert = Some("/path/to/nonexistent_cert.pem".to_string()); - params.ssl_key = None; - - let result = build_postgres_tls_connector(¶ms); - assert!(result.is_ok()); - - params.ssl_key = Some("/path/to/nonexistent_key.pem".to_string()); - let result = build_postgres_tls_connector(¶ms); - assert!(result.is_ok()); - } - - #[test] - fn test_tls_connector_client_cert_without_key_fails() { - let mut params = params_with_ssl("require"); - params.ssl_cert = Some("/path/to/cert.pem".to_string()); - params.ssl_key = None; - - let result = build_postgres_tls_connector(¶ms); - match result { - Err(e) => assert!(e.contains("ssl_cert")), - Ok(_) => panic!("Expected error when ssl_cert is provided without ssl_key"), - } - } - - #[test] - fn test_tls_connector_client_key_without_cert_fails() { - let mut params = params_with_ssl("require"); - params.ssl_cert = None; - params.ssl_key = Some("/path/to/key.pem".to_string()); - - let result = build_postgres_tls_connector(¶ms); - match result { - Err(e) => assert!(e.contains("ssl_key")), - Ok(_) => panic!("Expected error when ssl_key is provided without ssl_cert"), - } - } - - #[test] - fn postgres_socket_ignores_inactive_tls_settings() { - let missing = tempfile::tempdir().expect("temporary TLS directory"); - for mode in ["require", "verify-ca", "verify-full", "obsolete-mode"] { - for (cert, key) in [(true, true), (true, false), (false, true), (false, false)] { - let mut params = params_with_ssl(mode); - params.unix_socket_path = Some("/tmp/.s.PGSQL.5432".to_string()); - params.ssl_ca = Some(missing.path().join("ca.pem").display().to_string()); - params.ssl_cert = - cert.then(|| missing.path().join("client.pem").display().to_string()); - params.ssl_key = key.then(|| missing.path().join("key.pem").display().to_string()); - assert!( - build_postgres_tls_connector(¶ms).is_ok(), - "socket must ignore inactive TLS settings: mode={mode}, cert={cert}, key={key}" - ); - } - } - } - - #[test] - fn postgres_tcp_and_tunnels_still_validate_tls_settings() { - let missing = tempfile::tempdir().expect("temporary TLS directory"); - for tunnel in ["tcp", "ssh", "k8s", "blank-socket"] { - let mut params = params_with_ssl("verify-full"); - params.ssl_ca = Some(missing.path().join("ca.pem").display().to_string()); - match tunnel { - "ssh" => { - params.unix_socket_path = Some("/tmp/.s.PGSQL.5432".to_string()); - params.ssh_enabled = Some(true); - } - "k8s" => { - params.unix_socket_path = Some("/tmp/.s.PGSQL.5432".to_string()); - params.k8s_enabled = Some(true); - } - "blank-socket" => params.unix_socket_path = Some(" ".to_string()), - _ => {} - } - let err = build_postgres_tls_connector(¶ms) - .err() - .expect("missing CA must fail"); - assert!(err.contains("ca.pem"), "{tunnel}: {err}"); - params.ssl_mode = Some("obsolete-mode".to_string()); - assert!( - build_postgres_tls_connector(¶ms).is_err(), - "{tunnel}: unknown TLS mode must fail" - ); - } - } - - #[test] - fn postgres_tls_connector_accepts_empty_hostname_for_unix_sockets() { - use tokio_postgres::tls::MakeTlsConnect; - let params = params_with_ssl("prefer"); - let mut connector = build_postgres_tls_connector(¶ms).expect("connector"); - // A Unix socket has no DNS hostname. tokio_postgres falls back to - // hostname.unwrap_or("") before entering the SSL-disabled branch. - // The wrapper must supply a valid fallback (e.g. localhost) so - // MakeRustlsConnect does not fail with InvalidDnsNameError. - let tls_connect = - MakeTlsConnect::::make_tls_connect(&mut connector, ""); - assert!( - tls_connect.is_ok(), - "make_tls_connect(\"\") must succeed for Unix socket connections: {:?}", - tls_connect.err() - ); - } - - #[test] - fn postgres_tls_connector_preserves_hostname_verification_for_tcp() { - use tokio_postgres::tls::MakeTlsConnect; - let params = params_with_ssl("verify-full"); - let mut connector = build_postgres_tls_connector(¶ms).expect("connector"); - // A valid hostname passes through unchanged. - let tls_connect = MakeTlsConnect::::make_tls_connect( - &mut connector, - "db.example.com", - ); - assert!(tls_connect.is_ok()); - - // An invalid DNS name must still be rejected. - let invalid = MakeTlsConnect::::make_tls_connect( - &mut connector, - "invalid name with spaces", - ); - assert!(invalid.is_err()); - } -} - #[cfg(test)] mod sqlite_path_tests { use crate::sqlite_database::expand_sqlite_filename_with_home; @@ -1743,100 +993,6 @@ mod sqlite_path_tests { } } -#[cfg(test)] -mod startup_script_tests { - use crate::models::{ConnectionParams, DatabaseSelection}; - use crate::pool_manager::{close_pool_with_id, get_sqlite_pool_with_id}; - use tempfile::NamedTempFile; - - fn sqlite_params(path: &str, startup_script: Option<&str>) -> ConnectionParams { - ConnectionParams { - driver: "sqlite".to_string(), - database: DatabaseSelection::Single(path.to_string()), - startup_script: startup_script.map(ToOwned::to_owned), - ..Default::default() - } - } - - #[tokio::test] - async fn startup_script_runs_on_each_new_connection() { - let file = NamedTempFile::new().expect("temp file"); - let path = file.path().to_str().expect("utf8 path").to_string(); - // Unique connection id keeps this pool out of other tests' cached pools. - let conn_id = format!("startup-runs-{}", ulid::Ulid::new()); - - let params = sqlite_params( - &path, - Some( - "CREATE TABLE IF NOT EXISTS startup_marker (id INTEGER); \ - INSERT INTO startup_marker (id) VALUES (1);", - ), - ); - - let pool = get_sqlite_pool_with_id(¶ms, Some(&conn_id)) - .await - .expect("pool should be created"); - - // The marker table only exists if the startup script ran on the - // physical connection the pool just handed out. - let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM startup_marker") - .fetch_one(&pool) - .await - .expect("startup_marker table should exist"); - assert!( - count >= 1, - "expected at least one startup INSERT, got {count}" - ); - - close_pool_with_id(¶ms, Some(&conn_id)).await; - } - - #[tokio::test] - async fn blank_startup_script_is_skipped() { - let file = NamedTempFile::new().expect("temp file"); - let path = file.path().to_str().expect("utf8 path").to_string(); - let conn_id = format!("startup-blank-{}", ulid::Ulid::new()); - - // A whitespace-only script must be treated as absent: if it were run - // as SQL the connection would fail and `SELECT 1` below would error. - let params = sqlite_params(&path, Some(" \n ")); - - let pool = get_sqlite_pool_with_id(¶ms, Some(&conn_id)) - .await - .expect("pool should be created"); - - let (one,): (i64,) = sqlx::query_as("SELECT 1") - .fetch_one(&pool) - .await - .expect("query on pool with blank startup script should work"); - assert_eq!(one, 1); - - close_pool_with_id(¶ms, Some(&conn_id)).await; - } - - #[tokio::test] - async fn invalid_startup_script_surfaces_attributed_error() { - let file = NamedTempFile::new().expect("temp file"); - let path = file.path().to_str().expect("utf8 path").to_string(); - let conn_id = format!("startup-invalid-{}", ulid::Ulid::new()); - - let params = sqlite_params(&path, Some("THIS IS NOT VALID SQL;")); - - // A broken startup script must fail the connection with an error that - // clearly names the startup script as the cause, rather than sqlx's - // misleading "pool timed out" or a generic connection error. - let err = get_sqlite_pool_with_id(¶ms, Some(&conn_id)) - .await - .expect_err("invalid startup script should fail the connection"); - assert!( - err.contains("Startup script failed"), - "error should be attributed to the startup script, got: {err}" - ); - - close_pool_with_id(¶ms, Some(&conn_id)).await; - } -} - #[cfg(test)] mod bounded_close_tests { use crate::models::{ConnectionParams, DatabaseSelection}; @@ -1885,304 +1041,3 @@ mod bounded_close_tests { ); } } - -/// Live checks that the connect timeout bounds a slow PostgreSQL startup -/// script, both in the preflight and in each new pooled connection's hook. -/// Run against a local server: -/// TABULARIS_TEST_PG=1 cargo test --lib live_pg_connect_timeout -- --ignored -/// Override TABULARIS_TEST_PG_{HOST,PORT,USER,PASSWORD,DB} for a non-default setup. -#[cfg(test)] -mod live_pg_connect_timeout { - use crate::models::{ConnectionParams, DatabaseSelection}; - use crate::pool_manager::{close_pool_with_id, get_postgres_pool_with_id}; - use std::time::{Duration, Instant}; - - fn test_params() -> Option { - if std::env::var("TABULARIS_TEST_PG").is_err() { - return None; - } - Some(ConnectionParams { - driver: "postgres".to_string(), - host: Some( - std::env::var("TABULARIS_TEST_PG_HOST").unwrap_or_else(|_| "localhost".to_string()), - ), - port: std::env::var("TABULARIS_TEST_PG_PORT") - .ok() - .and_then(|p| p.parse().ok()) - .or(Some(55432)), - username: Some( - std::env::var("TABULARIS_TEST_PG_USER").unwrap_or_else(|_| "postgres".to_string()), - ), - password: Some( - std::env::var("TABULARIS_TEST_PG_PASSWORD") - .unwrap_or_else(|_| "postgres".to_string()), - ), - database: DatabaseSelection::Single( - std::env::var("TABULARIS_TEST_PG_DB").unwrap_or_else(|_| "postgres".to_string()), - ), - ssl_mode: Some("disable".to_string()), - ..Default::default() - }) - } - - #[tokio::test] - #[ignore] - async fn live_pg_connect_timeout_bounds_a_slow_startup_preflight() { - let Some(mut params) = test_params() else { - eprintln!("skipping: set TABULARIS_TEST_PG=1 to run this test"); - return; - }; - let conn_id = format!("timeout-preflight-{}", ulid::Ulid::new()); - params.connect_timeout_secs = Some(1); - params.startup_script = Some("SELECT pg_sleep(3);".to_string()); - - let started = Instant::now(); - let result = get_postgres_pool_with_id(¶ms, Some(&conn_id)).await; - - let err = result.expect_err("a 3 s startup script must fail a 1 s budget"); - assert!( - err.contains("Timed out running PostgreSQL startup script after 1000 ms"), - "{err}" - ); - assert!( - started.elapsed() < Duration::from_millis(2500), - "{:?}", - started.elapsed() - ); - close_pool_with_id(¶ms, Some(&conn_id)).await; - } - - #[tokio::test] - #[ignore] - async fn live_pg_connect_timeout_bounds_a_slow_startup_hook() { - let Some(mut params) = test_params() else { - eprintln!("skipping: set TABULARIS_TEST_PG=1 to run this test"); - return; - }; - let conn_id = format!("timeout-hook-{}", ulid::Ulid::new()); - let sequence = format!("tabularis_startup_runs_{}", ulid::Ulid::new()).to_lowercase(); - let setup = get_postgres_pool_with_id(¶ms, Some(&format!("{conn_id}-setup"))) - .await - .expect("connect to test postgres"); - setup - .get() - .await - .expect("setup client") - .batch_execute(&format!("CREATE SEQUENCE {sequence};")) - .await - .expect("create sequence"); - - // nextval is not rolled back, so the preflight (first run, inside a - // rolled-back transaction) is fast and the pooled connection's hook - // (second run) sleeps for 3 s. - params.connect_timeout_secs = Some(1); - params.startup_script = Some(format!( - "SELECT pg_sleep(CASE WHEN nextval('{sequence}') > 1 THEN 3 ELSE 0 END);" - )); - let pool = get_postgres_pool_with_id(¶ms, Some(&conn_id)) - .await - .expect("the preflight run is fast"); - - let started = Instant::now(); - let err = pool - .get() - .await - .expect_err("a 3 s hook must fail a 1 s budget"); - assert!( - err.to_string() - .contains("Timed out running PostgreSQL startup script after 1000 ms"), - "{err}" - ); - assert!( - started.elapsed() < Duration::from_millis(2500), - "{:?}", - started.elapsed() - ); - - close_pool_with_id(¶ms, Some(&conn_id)).await; - setup - .get() - .await - .expect("setup client") - .batch_execute(&format!("DROP SEQUENCE {sequence};")) - .await - .expect("drop sequence"); - let mut setup_params = params.clone(); - setup_params.connect_timeout_secs = None; - setup_params.startup_script = None; - close_pool_with_id(&setup_params, Some(&format!("{conn_id}-setup"))).await; - } -} - -#[cfg(test)] -mod local_unix_socket_tests { - use crate::models::{ConnectionParams, DatabaseSelection}; - use crate::pool_manager::{ - build_connection_key, build_mysql_options, build_postgres_configurations, - split_postgres_socket_path, - }; - #[cfg(unix)] - use sqlx::mysql::MySqlSslMode; - #[cfg(unix)] - use tokio_postgres::config::Host as PgHost; - #[cfg(unix)] - use tokio_postgres::config::SslMode as PgSslMode; - - fn socket_params(driver: &str, socket: &str) -> ConnectionParams { - ConnectionParams { - driver: driver.to_string(), - host: Some("localhost".to_string()), - port: Some(if driver == "postgres" { 5432 } else { 3306 }), - username: Some("dec".to_string()), - password: Some("secret".to_string()), - database: DatabaseSelection::Single("dec".to_string()), - unix_socket_path: Some(socket.to_string()), - ..Default::default() - } - } - - #[test] - fn local_socket_ignored_while_tunnel_enabled() { - let mut params = socket_params("mysql", "/tmp/mysql.sock"); - params.ssh_enabled = Some(true); - assert_eq!(params.local_unix_socket_path(), None); - - params.ssh_enabled = None; - params.k8s_enabled = Some(true); - assert_eq!(params.local_unix_socket_path(), None); - } - - #[test] - fn local_socket_trims_and_ignores_blank_path() { - let mut params = socket_params("mysql", " /tmp/mysql.sock "); - assert_eq!(params.local_unix_socket_path(), Some("/tmp/mysql.sock")); - - params.unix_socket_path = Some(" ".to_string()); - assert_eq!(params.local_unix_socket_path(), None); - } - - #[cfg(unix)] - #[test] - fn mysql_options_use_socket_and_disable_tls() { - let mut params = socket_params("mysql", "/tmp/mysql.sock"); - // Even an enforced TLS mode must be overridden: a socket peer cannot - // negotiate TLS and the traffic never leaves the machine. - params.ssl_mode = Some("required".to_string()); - - let options = build_mysql_options(¶ms, None).unwrap(); - assert!(matches!(options.get_ssl_mode(), MySqlSslMode::Disabled)); - let dbg = format!("{options:?}"); - assert!( - dbg.contains("/tmp/mysql.sock"), - "expected socket path in options, got: {dbg}" - ); - } - - #[cfg(unix)] - #[test] - fn mysql_local_socket_rejects_iam_auth() { - let mut params = socket_params("mysql", "/tmp/mysql.sock"); - params.use_iam_auth = Some(true); - let err = build_mysql_options(¶ms, None).expect_err("IAM needs TLS to RDS"); - assert!(err.contains("Unix socket"), "unexpected error: {err}"); - } - - #[cfg(unix)] - #[test] - fn mysql_cleartext_plugin_allowed_over_local_socket() { - let mut params = socket_params("mysql", "/tmp/mysql.sock"); - params.enable_cleartext_plugin = Some(true); - - assert!(build_mysql_options(¶ms, None).is_ok()); - } - - #[cfg(unix)] - #[test] - fn postgres_config_uses_socket_dir_and_port_from_path() { - let params = socket_params("postgres", "/var/run/postgresql/.s.PGSQL.5433"); - let cfg = build_postgres_configurations(¶ms).expect("socket config"); - - assert_eq!(cfg.get_ports(), &[5433]); - assert_eq!(cfg.get_ssl_mode(), PgSslMode::Disable); - match cfg.get_hosts() { - [PgHost::Unix(dir)] => assert_eq!(dir.to_str(), Some("/var/run/postgresql")), - other => panic!("expected a single unix host, got: {other:?}"), - } - } - - #[cfg(unix)] - #[test] - fn postgres_config_accepts_socket_directory() { - // A plain directory (no .s.PGSQL. component) pairs with the - // connection's configured port. - let params = socket_params("postgres", "/var/run/postgresql"); - let cfg = build_postgres_configurations(¶ms).expect("socket config"); - - assert_eq!(cfg.get_ports(), &[5432]); - match cfg.get_hosts() { - [PgHost::Unix(dir)] => assert_eq!(dir.to_str(), Some("/var/run/postgresql")), - other => panic!("expected a single unix host, got: {other:?}"), - } - } - - #[cfg(windows)] - #[test] - fn local_sockets_are_rejected_on_windows() { - let mysql = build_mysql_options(&socket_params("mysql", "/tmp/mysql.sock"), None) - .expect_err("no Unix sockets on Windows"); - assert!( - mysql.contains("not supported on Windows"), - "unexpected error: {mysql}" - ); - let postgres = build_postgres_configurations(&socket_params( - "postgres", - "/var/run/postgresql/.s.PGSQL.5432", - )) - .expect_err("no Unix sockets on Windows"); - assert!( - postgres.contains("not supported on Windows"), - "unexpected error: {postgres}" - ); - } - - #[test] - fn split_postgres_socket_path_variants() { - assert_eq!( - split_postgres_socket_path("/var/run/postgresql/.s.PGSQL.5432", 1111), - ("/var/run/postgresql".to_string(), 5432) - ); - // Socket file directly under the root keeps "/" as the directory. - assert_eq!( - split_postgres_socket_path("/.s.PGSQL.5432", 1111), - ("/".to_string(), 5432) - ); - // Non-numeric suffix is not a socket file name: treat as a directory. - assert_eq!( - split_postgres_socket_path("/var/run/.s.PGSQL.abc", 1111), - ("/var/run/.s.PGSQL.abc".to_string(), 1111) - ); - assert_eq!( - split_postgres_socket_path("/var/run/postgresql", 1111), - ("/var/run/postgresql".to_string(), 1111) - ); - } - - #[test] - fn adhoc_pool_key_distinguishes_socket_from_tcp() { - let tcp = ConnectionParams { - unix_socket_path: None, - ..socket_params("mysql", "/tmp/mysql.sock") - }; - let socket = socket_params("mysql", "/tmp/mysql.sock"); - let other_socket = socket_params("mysql", "/tmp/other.sock"); - - assert_ne!( - build_connection_key(&tcp, None), - build_connection_key(&socket, None) - ); - assert_ne!( - build_connection_key(&socket, None), - build_connection_key(&other_socket, None) - ); - } -} diff --git a/src-tauri/src/runtime/bootstrap.rs b/src-tauri/src/runtime/bootstrap.rs index 3ff33ffb2..0221cb8bb 100644 --- a/src-tauri/src/runtime/bootstrap.rs +++ b/src-tauri/src/runtime/bootstrap.rs @@ -1,6 +1,6 @@ use super::RuntimeContext; use crate::config::AppConfig; -use crate::drivers::{mysql, postgres, registry, sqlite}; +use crate::drivers::{mysql, registry, sqlite}; use crate::logger::{create_log_buffer, init_logger, SharedLogBuffer}; use std::fs; use std::sync::atomic::{AtomicBool, Ordering}; @@ -110,16 +110,58 @@ pub async fn bootstrap_application( } if options.run_connection_migrations { - crate::connection_migrations::migrate_postgres_ssl_mode_spelling_at_path( + // Driver-id migration runs first so connections are on the plugin id + // ("postgresql") before the ssl-mode migration tries to resolve their + // dialect — otherwise the removed "postgres" driver can't resolve and + // stale ssl_mode spellings are skipped for one launch cycle. + // A connection moves only once the installed plugin can serve it; the + // auto-install spawned below fetches or updates the plugin and then + // moves what was waiting. + match crate::plugins::force_install::migrate_ready_connections_result(&context).await { + Ok(true) => {} + Ok(false) => { + log::info!("Driver-id migration: nothing to migrate or skipped (file changed concurrently)"); + } + Err(e) => { + log::warn!("Driver-id migration failed: {e}. Connections on \"postgres\" will be retried next launch."); + } + } + if let Err(e) = crate::connection_migrations::migrate_postgres_ssl_mode_spelling_at_path( &context.paths.connections_file(), ) .await - .ok(); + { + log::warn!("SSL-mode spelling migration failed: {e}"); + } + // Headless processes (web, `--mcp`) have no desktop setup step, so + // install the replacement plugin here for the connections just + // migrated onto it. Spawned so a slow or failed registry fetch never + // delays startup, and retried on every launch. Skipped without + // external plugins (nothing could register it), and for operators who + // set `TABULARIS_DISABLE_PLUGIN_AUTO_INSTALL`. + if should_auto_install_plugins( + &options, + crate::plugins::force_install::auto_install_disabled(), + ) { + let runtime = context.clone(); + tokio::spawn(async move { + crate::plugins::force_install::ensure_replacement_plugins(&runtime).await; + }); + } } Ok(BootstrappedApplication { context, config }) } +/// Whether bootstrap should spawn the replacement-plugin install. Only a +/// process that runs the connection migration itself (web, `--mcp`) installs +/// here; desktop migrates lazily and installs from its own setup. Needs external +/// plugins loaded (nothing could register the driver otherwise) and the +/// operator's opt-out not set. +pub(crate) fn should_auto_install_plugins(options: &BootstrapOptions, disabled: bool) -> bool { + options.run_connection_migrations && options.load_external_plugins && !disabled +} + fn load_config(config_dir: &std::path::Path) -> AppConfig { let path = config_dir.join("config.json"); let mut config = fs::read_to_string(path) @@ -133,6 +175,5 @@ fn load_config(config_dir: &std::path::Path) -> AppConfig { async fn register_builtin_drivers() { registry::register_driver(mysql::MysqlDriver::new()).await; - registry::register_driver(postgres::PostgresDriver::new()).await; registry::register_driver(sqlite::SqliteDriver::new()).await; } diff --git a/src-tauri/src/runtime/lifecycle.rs b/src-tauri/src/runtime/lifecycle.rs index f2a953203..cb0794498 100644 --- a/src-tauri/src/runtime/lifecycle.rs +++ b/src-tauri/src/runtime/lifecycle.rs @@ -29,7 +29,6 @@ impl ShutdownHooks { pub async fn shutdown_headless_runtime(state: &super::state::ApplicationState) { state.abort_background_jobs(); - release_pinned_sessions().await; crate::pool_manager::close_all_pools().await; crate::ssh_tunnel::stop_all_tunnels(); crate::k8s_tunnel::stop_all_tunnels(); @@ -38,18 +37,6 @@ pub async fn shutdown_headless_runtime(state: &super::state::ApplicationState) { crate::drivers::registry::shutdown_external_drivers().await; } -pub async fn release_pinned_sessions() { - if tokio::time::timeout( - std::time::Duration::from_secs(3), - crate::drivers::postgres::session::release_all(), - ) - .await - .is_err() - { - log::warn!("Releasing pinned PostgreSQL sessions timed out on exit"); - } -} - pub fn start_approval_heartbeat( context: &super::RuntimeContext, ) -> crate::heartbeat::HeartbeatTask { diff --git a/src-tauri/src/runtime/tests.rs b/src-tauri/src/runtime/tests.rs index 644c58b29..3d9a9a3a6 100644 --- a/src-tauri/src/runtime/tests.rs +++ b/src-tauri/src/runtime/tests.rs @@ -95,7 +95,7 @@ async fn bootstraps_application_services_without_a_webview() { .filter(|manifest| manifest.is_builtin) .map(|manifest| manifest.id) .collect(); - assert_eq!(driver_ids, vec!["mysql", "postgres", "sqlite"]); + assert_eq!(driver_ids, vec!["mysql", "sqlite"]); assert!(bootstrapped.context.paths.data_dir().ends_with("data")); } @@ -218,3 +218,26 @@ async fn stopping_one_approval_host_preserves_liveness_for_another() { assert!(crate::heartbeat::is_alive_in(root.path())); drop(desktop); } + +#[test] +fn only_a_migrating_process_with_plugins_and_no_opt_out_installs_the_replacement() { + use super::bootstrap::should_auto_install_plugins; + let opts = |plugins, migrate| BootstrapOptions { + load_external_plugins: plugins, + run_connection_migrations: migrate, + }; + // Web and --mcp: default options. + assert!(should_auto_install_plugins( + &BootstrapOptions::default(), + false + )); + // Desktop bootstraps with migrations off and installs from its own setup. + assert!(!should_auto_install_plugins(&opts(true, false), false)); + // Without external plugins nothing could register the driver. + assert!(!should_auto_install_plugins(&opts(false, true), false)); + // The operator's opt-out wins. + assert!(!should_auto_install_plugins( + &BootstrapOptions::default(), + true + )); +} diff --git a/src-tauri/src/table_transfer/convert.rs b/src-tauri/src/table_transfer/convert.rs index b30c16c70..850c085f7 100644 --- a/src-tauri/src/table_transfer/convert.rs +++ b/src-tauri/src/table_transfer/convert.rs @@ -22,14 +22,26 @@ fn parse_decimal(text: &str) -> Option> { let int = int.trim_start_matches('0'); let frac = frac.trim_end_matches('0'); let negative = negative && !(int.is_empty() && frac.is_empty()); - Some(Decimal { negative, int, frac }) + Some(Decimal { + negative, + int, + frac, + }) } -fn decimal_fits(text: &str, precision: Option, scale: Option) -> Result<(), ConvertError> { +fn decimal_fits( + text: &str, + precision: Option, + scale: Option, +) -> Result<(), ConvertError> { match text { "NaN" => return Ok(()), "Infinity" | "-Infinity" => { - return if precision.is_none() { Ok(()) } else { Err(ConvertError::OutOfRange) }; + return if precision.is_none() { + Ok(()) + } else { + Err(ConvertError::OutOfRange) + }; } _ => {} } @@ -55,8 +67,16 @@ fn decimal_to_i64(text: &str, min: i64, max: i64) -> Result { if parts.int.len() > 19 { return Err(ConvertError::OutOfRange); } - let magnitude: i128 = if parts.int.is_empty() { 0 } else { parts.int.parse().map_err(|_| ConvertError::Malformed)? }; - let value = if parts.negative { -magnitude } else { magnitude }; + let magnitude: i128 = if parts.int.is_empty() { + 0 + } else { + parts.int.parse().map_err(|_| ConvertError::Malformed)? + }; + let value = if parts.negative { + -magnitude + } else { + magnitude + }; i64::try_from(value) .ok() .filter(|v| *v >= min && *v <= max) @@ -75,6 +95,32 @@ fn fits_f32(value: f64) -> bool { ((value as f32).to_string()).parse::().ok() == Some(value) } +/// True unless `text` is a whole number that `value` does not hold exactly. +/// Numbers with a fraction, or too long for an `i128`, are judged by their +/// decimal text instead. +fn integer_survives(text: &str, value: f64) -> bool { + let Some(parts) = parse_decimal(text) else { + return true; + }; + if !parts.frac.is_empty() || parts.int.len() > 38 { + return true; + } + let magnitude: i128 = if parts.int.is_empty() { + 0 + } else { + match parts.int.parse() { + Ok(v) => v, + Err(_) => return true, + } + }; + let expected = if parts.negative { + -magnitude + } else { + magnitude + }; + value as i128 == expected +} + fn decimal_to_f64(text: &str, bits: u8, allow_non_finite: bool) -> Result { let special = match text { "NaN" => Some(f64::NAN), @@ -83,13 +129,24 @@ fn decimal_to_f64(text: &str, bits: u8, allow_non_finite: bool) -> Result None, }; if let Some(value) = special { - return if allow_non_finite { Ok(value) } else { Err(ConvertError::NonFinite) }; + return if allow_non_finite { + Ok(value) + } else { + Err(ConvertError::NonFinite) + }; } parse_decimal(text).ok_or(ConvertError::Malformed)?; let value: f64 = text.parse().map_err(|_| ConvertError::Malformed)?; if !value.is_finite() { return Err(ConvertError::OutOfRange); } + // An integer must come back as the same integer. The shortest decimal form + // of a rounded float can still print as the original digits (1e18 + 100 + // rounds to 1e18 + 128 yet prints as 1000000000000000100), so compare the + // values, not their text. + if !integer_survives(text, value) { + return Err(ConvertError::Lossy); + } let shown = if bits == 32 { if !fits_f32(value) { return Err(ConvertError::Lossy); @@ -118,6 +175,18 @@ fn text_of(value: TransferValue) -> Result { } } +/// The exact decimal text of a numeric cell. A SQLite NUMERIC column stores +/// integers and reals natively, so a decimal source can arrive as any of them. +fn decimal_text(value: TransferValue) -> Result { + match value { + TransferValue::Text(text) => Ok(text), + TransferValue::Int(v) => Ok(v.to_string()), + TransferValue::Float(v) if v.is_finite() => Ok(v.to_string()), + TransferValue::Float(_) => Err(ConvertError::NonFinite), + _ => Err(ConvertError::Malformed), + } +} + fn int_of(value: &TransferValue) -> Result { match value { TransferValue::Int(v) => Ok(*v), @@ -133,11 +202,18 @@ pub fn apply(conversion: &Conversion, value: TransferValue) -> Result Ok(value), Op::BoolToInt => match value { TransferValue::Bool(b) => Ok(TransferValue::Int(i64::from(b))), + // SQLite sources produce Int for boolean columns (storing the + // raw integer 0/1/2/…). Pass through unchanged — no lossy coercion. + TransferValue::Int(v) => Ok(TransferValue::Int(v)), _ => Err(ConvertError::Malformed), }, Op::IntRange { min, max } => { let v = int_of(&value)?; - if v < min || v > max { Err(ConvertError::OutOfRange) } else { Ok(value) } + if v < min || v > max { + Err(ConvertError::OutOfRange) + } else { + Ok(value) + } } Op::IntToFloat { max_exact } => { let v = int_of(&value)?; @@ -152,28 +228,42 @@ pub fn apply(conversion: &Conversion, value: TransferValue) -> Result { + Op::FloatCheck { + bits, + allow_non_finite, + } => { let TransferValue::Float(v) = value else { return Err(ConvertError::Malformed); }; if !v.is_finite() { - return if allow_non_finite { Ok(value) } else { Err(ConvertError::NonFinite) }; + return if allow_non_finite { + Ok(value) + } else { + Err(ConvertError::NonFinite) + }; + } + if bits == 32 && !fits_f32(v) { + Err(ConvertError::Lossy) + } else { + Ok(value) } - if bits == 32 && !fits_f32(v) { Err(ConvertError::Lossy) } else { Ok(value) } } Op::DecimalFit { precision, scale } => { - let text = text_of(value)?; + let text = decimal_text(value)?; decimal_fits(&text, precision, scale)?; Ok(TransferValue::Text(text)) } Op::DecimalToInt { min, max } => { - decimal_to_i64(&text_of(value)?, min, max).map(TransferValue::Int) + decimal_to_i64(&decimal_text(value)?, min, max).map(TransferValue::Int) } - Op::DecimalToFloat { bits, allow_non_finite } => { - decimal_to_f64(&text_of(value)?, bits, allow_non_finite).map(TransferValue::Float) + Op::DecimalToFloat { + bits, + allow_non_finite, + } => { + decimal_to_f64(&decimal_text(value)?, bits, allow_non_finite).map(TransferValue::Float) } Op::DecimalToNumeric => { - let text = text_of(value)?; + let text = decimal_text(value)?; match decimal_to_i64(&text, i64::MIN, i64::MAX) { Ok(v) => Ok(TransferValue::Int(v)), Err(ConvertError::Malformed) => Err(ConvertError::Malformed), @@ -182,15 +272,27 @@ pub fn apply(conversion: &Conversion, value: TransferValue) -> Result { let text = text_of(value)?; - if text.chars().count() as u64 > max { Err(ConvertError::TooLong) } else { Ok(TransferValue::Text(text)) } + if text.chars().count() as u64 > max { + Err(ConvertError::TooLong) + } else { + Ok(TransferValue::Text(text)) + } } Op::Temporal { precision } => { let text = text_of(value)?; - if fraction_digits(&text) > precision as usize { Err(ConvertError::Lossy) } else { Ok(TransferValue::Text(text)) } + if fraction_digits(&text) > precision as usize { + Err(ConvertError::Lossy) + } else { + Ok(TransferValue::Text(text)) + } } Op::JsonNotNumeric => { let text = text_of(value)?; - if text.trim().parse::().is_ok() { Err(ConvertError::Lossy) } else { Ok(TransferValue::Text(text)) } + if text.trim().parse::().is_ok() { + Err(ConvertError::Lossy) + } else { + Ok(TransferValue::Text(text)) + } } } } diff --git a/src-tauri/src/table_transfer/mapping.rs b/src-tauri/src/table_transfer/mapping.rs index 4649f8fd1..bf961f324 100644 --- a/src-tauri/src/table_transfer/mapping.rs +++ b/src-tauri/src/table_transfer/mapping.rs @@ -14,7 +14,10 @@ pub struct PlanInputs<'a> { } fn display_type(column: &TableColumn) -> String { - column.full_type.clone().unwrap_or_else(|| column.data_type.clone()) + column + .full_type + .clone() + .unwrap_or_else(|| column.data_type.clone()) } fn find_target<'a>(targets: &'a [TableColumn], name: &str) -> Option<&'a TableColumn> { @@ -89,10 +92,11 @@ pub fn build_table_plan(inputs: &PlanInputs<'_>) -> PlannedTable { skipped: false, issue: None, }; - let fail = |plan: &mut ColumnPlan, issues: &mut Vec, code: &str, column: &str| { - plan.issue = Some(code.to_string()); - issues.push(PlanIssue::new(code, Some(column))); - }; + let fail = + |plan: &mut ColumnPlan, issues: &mut Vec, code: &str, column: &str| { + plan.issue = Some(code.to_string()); + issues.push(PlanIssue::new(code, Some(column))); + }; let target = match explicit.get(source.name.as_str()) { Some(None) => { plan.skipped = true; @@ -120,12 +124,27 @@ pub fn build_table_plan(inputs: &PlanInputs<'_>) -> PlannedTable { plan.target_column = Some(target.name.clone()); plan.target_type = Some(display_type(target)); if !used.insert(target.name.as_str()) { - fail(&mut plan, &mut issues, "duplicateTargetColumn", &target.name); + fail( + &mut plan, + &mut issues, + "duplicateTargetColumn", + &target.name, + ); } else if target.is_generated { - fail(&mut plan, &mut issues, "targetColumnGenerated", &target.name); + fail( + &mut plan, + &mut issues, + "targetColumnGenerated", + &target.name, + ); } else if let Some(kind) = classify_source(source) { match classify_target(inputs.target_dialect, target, inputs.target_strict) { - None => fail(&mut plan, &mut issues, "unsupportedTargetType", &source.name), + None => fail( + &mut plan, + &mut issues, + "unsupportedTargetType", + &source.name, + ), Some(target_type) => match plan_conversion(kind, &target_type) { Err(code) => fail(&mut plan, &mut issues, code, &source.name), Ok(conversion) => { @@ -141,7 +160,12 @@ pub fn build_table_plan(inputs: &PlanInputs<'_>) -> PlannedTable { }, } } else { - fail(&mut plan, &mut issues, "unsupportedSourceType", &source.name); + fail( + &mut plan, + &mut issues, + "unsupportedSourceType", + &source.name, + ); } columns.push(plan); } @@ -152,7 +176,10 @@ pub fn build_table_plan(inputs: &PlanInputs<'_>) -> PlannedTable { && !target.is_auto_increment && !target.is_generated; if needs_value && !used.contains(target.name.as_str()) { - issues.push(PlanIssue::new("requiredTargetColumnUnmapped", Some(&target.name))); + issues.push(PlanIssue::new( + "requiredTargetColumnUnmapped", + Some(&target.name), + )); } } if columns.iter().all(|c| c.target_column.is_none()) { diff --git a/src-tauri/src/table_transfer/mod.rs b/src-tauri/src/table_transfer/mod.rs index e5e0474c5..229d1254e 100644 --- a/src-tauri/src/table_transfer/mod.rs +++ b/src-tauri/src/table_transfer/mod.rs @@ -13,4 +13,4 @@ mod tests; pub use convert::apply as apply_conversion; pub use mapping::{build_table_plan, PlanInputs}; pub use model::*; -pub use types::{capabilities, dialect_for_driver, ensure_supported_pair}; +pub use types::{capabilities, classify_source, dialect_for_manifest, ensure_supported_pair}; diff --git a/src-tauri/src/table_transfer/model.rs b/src-tauri/src/table_transfer/model.rs index 26e6be336..e55bb30bd 100644 --- a/src-tauri/src/table_transfer/model.rs +++ b/src-tauri/src/table_transfer/model.rs @@ -147,16 +147,40 @@ pub enum ConversionRule { pub enum Op { Copy, BoolToInt, - IntRange { min: i64, max: i64 }, - IntToFloat { max_exact: i64 }, - IntToDecimal { precision: Option, scale: Option }, - FloatCheck { bits: u8, allow_non_finite: bool }, - DecimalFit { precision: Option, scale: Option }, - DecimalToInt { min: i64, max: i64 }, - DecimalToFloat { bits: u8, allow_non_finite: bool }, + IntRange { + min: i64, + max: i64, + }, + IntToFloat { + max_exact: i64, + }, + IntToDecimal { + precision: Option, + scale: Option, + }, + FloatCheck { + bits: u8, + allow_non_finite: bool, + }, + DecimalFit { + precision: Option, + scale: Option, + }, + DecimalToInt { + min: i64, + max: i64, + }, + DecimalToFloat { + bits: u8, + allow_non_finite: bool, + }, DecimalToNumeric, - TextMaxLen { max: u64 }, - Temporal { precision: u32 }, + TextMaxLen { + max: u64, + }, + Temporal { + precision: u32, + }, JsonNotNumeric, } diff --git a/src-tauri/src/table_transfer/tests.rs b/src-tauri/src/table_transfer/tests.rs index 7e08b56b2..46d89904c 100644 --- a/src-tauri/src/table_transfer/tests.rs +++ b/src-tauri/src/table_transfer/tests.rs @@ -42,28 +42,33 @@ fn numeric(precision: u32, scale: u32) -> TargetType { }) } -#[test] -fn only_postgres_sources_and_builtin_targets_are_supported() { - assert!(ensure_supported_pair("postgres", "postgres").is_ok()); - assert!(ensure_supported_pair("postgres", "sqlite").is_ok()); - assert!(ensure_supported_pair("sqlite", "postgres").is_err()); - assert!(ensure_supported_pair("postgres", "mysql").is_err()); - assert!(ensure_supported_pair("postgres", "custom-plugin").is_err()); - assert!(dialect_for_driver("custom-plugin").is_none()); -} - #[test] fn numeric_must_fit_target_precision_and_scale() { let target = || numeric(5, 2); - assert_eq!(run(SourceKind::Decimal, target(), text("123.45")), Ok(text("123.45"))); - assert_eq!(run(SourceKind::Decimal, target(), text("123.450")), Ok(text("123.450"))); - assert_eq!(run(SourceKind::Decimal, target(), text("1.234")), Err(ConvertError::Lossy)); - assert_eq!(run(SourceKind::Decimal, target(), text("1234.5")), Err(ConvertError::OutOfRange)); + assert_eq!( + run(SourceKind::Decimal, target(), text("123.45")), + Ok(text("123.45")) + ); + assert_eq!( + run(SourceKind::Decimal, target(), text("123.450")), + Ok(text("123.450")) + ); + assert_eq!( + run(SourceKind::Decimal, target(), text("1.234")), + Err(ConvertError::Lossy) + ); + assert_eq!( + run(SourceKind::Decimal, target(), text("1234.5")), + Err(ConvertError::OutOfRange) + ); assert_eq!( run(SourceKind::Decimal, target(), TransferValue::Null), Ok(TransferValue::Null) ); - assert_eq!(run(SourceKind::Int, target(), TransferValue::Int(999)), Ok(text("999"))); + assert_eq!( + run(SourceKind::Int, target(), TransferValue::Int(999)), + Ok(text("999")) + ); assert_eq!( run(SourceKind::Int, target(), TransferValue::Int(1000)), Err(ConvertError::OutOfRange) @@ -79,12 +84,18 @@ fn integer_targets_check_range() { Err(ConvertError::OutOfRange) ); let int = TargetType::Pg(PgTarget::Int(32)); - assert_eq!(run(SourceKind::Decimal, int.clone(), text("10.5")), Err(ConvertError::Lossy)); + assert_eq!( + run(SourceKind::Decimal, int.clone(), text("10.5")), + Err(ConvertError::Lossy) + ); assert_eq!( run(SourceKind::Decimal, int.clone(), text("2147483648")), Err(ConvertError::OutOfRange) ); - assert_eq!(run(SourceKind::Decimal, int, text("-5.00")), Ok(TransferValue::Int(-5))); + assert_eq!( + run(SourceKind::Decimal, int, text("-5.00")), + Ok(TransferValue::Int(-5)) + ); } #[test] @@ -95,7 +106,11 @@ fn sqlite_numeric_values_must_round_trip() { Ok(TransferValue::Float(0.1)) ); assert_eq!( - run(SourceKind::Decimal, real.clone(), text("0.12345678901234567890123")), + run( + SourceKind::Decimal, + real.clone(), + text("0.12345678901234567890123") + ), Err(ConvertError::Lossy) ); assert_eq!( @@ -123,7 +138,11 @@ fn float32_targets_reject_double_precision_values() { let real = TargetType::Pg(PgTarget::Float(32)); assert!(run(SourceKind::Float, real.clone(), TransferValue::Float(0.1)).is_ok()); assert_eq!( - run(SourceKind::Float, real, TransferValue::Float(0.123456789012345)), + run( + SourceKind::Float, + real, + TransferValue::Float(0.123456789012345) + ), Err(ConvertError::Lossy) ); let sqlite = TargetType::Sqlite(SqliteTarget::Real); @@ -142,7 +161,10 @@ fn float32_targets_reject_double_precision_values() { #[test] fn text_length_is_counted_in_characters() { let target = TargetType::Pg(PgTarget::Text { max_len: Some(3) }); - assert_eq!(run(SourceKind::Text, target.clone(), text("héé")), Ok(text("héé"))); + assert_eq!( + run(SourceKind::Text, target.clone(), text("héé")), + Ok(text("héé")) + ); assert_eq!( run(SourceKind::Text, target, text("日本語子")), Err(ConvertError::TooLong) @@ -152,7 +174,12 @@ fn text_length_is_counted_in_characters() { #[test] fn temporal_precision_is_not_rounded() { let target = TargetType::Pg(PgTarget::Timestamp { precision: Some(0) }); - assert!(run(SourceKind::Timestamp, target.clone(), text("2024-01-02 03:04:05")).is_ok()); + assert!(run( + SourceKind::Timestamp, + target.clone(), + text("2024-01-02 03:04:05") + ) + .is_ok()); assert_eq!( run(SourceKind::Timestamp, target, text("2024-01-02 03:04:05.5")), Err(ConvertError::Lossy) @@ -163,7 +190,10 @@ fn temporal_precision_is_not_rounded() { fn sqlite_json_columns_refuse_bare_numbers() { let target = TargetType::Sqlite(SqliteTarget::Json); assert!(run(SourceKind::Json, target.clone(), text("{\"a\":1}")).is_ok()); - assert_eq!(run(SourceKind::Json, target, text("123")), Err(ConvertError::Lossy)); + assert_eq!( + run(SourceKind::Json, target, text("123")), + Err(ConvertError::Lossy) + ); } #[test] @@ -196,25 +226,46 @@ fn implicit_coercions_are_refused() { #[test] fn sqlite_declared_types_follow_affinity_rules() { - assert_eq!(classify_sqlite_target("BIGINT", false), SqliteTarget::Integer); - assert_eq!(classify_sqlite_target("VARCHAR(20)", false), SqliteTarget::Text); - assert_eq!(classify_sqlite_target("DOUBLE PRECISION", false), SqliteTarget::Real); - assert_eq!(classify_sqlite_target("DECIMAL(10,2)", false), SqliteTarget::Numeric); + assert_eq!( + classify_sqlite_target("BIGINT", false), + SqliteTarget::Integer + ); + assert_eq!( + classify_sqlite_target("VARCHAR(20)", false), + SqliteTarget::Text + ); + assert_eq!( + classify_sqlite_target("DOUBLE PRECISION", false), + SqliteTarget::Real + ); + assert_eq!( + classify_sqlite_target("DECIMAL(10,2)", false), + SqliteTarget::Numeric + ); assert_eq!(classify_sqlite_target("", false), SqliteTarget::Untyped); assert_eq!(classify_sqlite_target("BLOB", false), SqliteTarget::Blob); - assert_eq!(classify_sqlite_target("DATETIME", false), SqliteTarget::Temporal); + assert_eq!( + classify_sqlite_target("DATETIME", false), + SqliteTarget::Temporal + ); assert_eq!(classify_sqlite_target("BOOLEAN", false), SqliteTarget::Bool); } #[test] fn any_is_untyped_only_on_strict_tables() { assert_eq!(classify_sqlite_target("ANY", false), SqliteTarget::Numeric); - assert_eq!(classify_sqlite_target(" any ", false), SqliteTarget::Numeric); + assert_eq!( + classify_sqlite_target(" any ", false), + SqliteTarget::Numeric + ); assert_eq!(classify_sqlite_target("ANY", true), SqliteTarget::Untyped); assert_eq!(classify_sqlite_target("", false), SqliteTarget::Untyped); assert_eq!(classify_sqlite_target("", true), SqliteTarget::Untyped); assert_eq!(classify_sqlite_target("TEXT", true), SqliteTarget::Text); - assert_eq!(classify_sqlite_target("DECIMAL(10,2)", true), SqliteTarget::Numeric); + assert_eq!( + classify_sqlite_target("DECIMAL(10,2)", true), + SqliteTarget::Numeric + ); } fn plan_into_any(source_type: &str, strict: bool) -> PlannedTable { @@ -236,7 +287,10 @@ fn decimal_into_ordinary_any_is_checked_not_exact() { let ordinary = plan_into_any("numeric", false); assert!(!ordinary.plan.blocking, "{:?}", ordinary.plan.issues); assert_eq!(ordinary.bindings[0].conversion.op, Op::DecimalToNumeric); - assert_eq!(ordinary.bindings[0].conversion.rule, ConversionRule::Checked); + assert_eq!( + ordinary.bindings[0].conversion.rule, + ConversionRule::Checked + ); let strict = plan_into_any("numeric", true); assert_eq!(strict.bindings[0].conversion.op, Op::Copy); @@ -290,7 +344,12 @@ fn codes(planned: &PlannedTable) -> Vec { fn plan_maps_by_name_and_is_clean_for_compatible_columns() { let source = [column("id", "integer"), column("Name", "text")]; let target = [column("id", "INTEGER"), column("name", "TEXT")]; - let planned = plan(&selection(vec![]), &source, &target, TransferDialect::Sqlite); + let planned = plan( + &selection(vec![]), + &source, + &target, + TransferDialect::Sqlite, + ); assert!(!planned.plan.blocking, "{:?}", planned.plan.issues); assert_eq!(planned.bindings.len(), 2); assert_eq!(planned.bindings[1].target_column, "name"); @@ -306,7 +365,12 @@ fn plan_blocks_unmapped_missing_and_incompatible_columns() { let mut required = column("must", "text"); required.is_nullable = false; let target = [column("id", "TEXT"), required]; - let planned = plan(&selection(vec![]), &source, &target, TransferDialect::Sqlite); + let planned = plan( + &selection(vec![]), + &source, + &target, + TransferDialect::Sqlite, + ); let found = codes(&planned); assert!(found.contains(&"incompatibleTypes".to_string())); assert!(found.contains(&"noTargetColumn".to_string())); @@ -318,7 +382,12 @@ fn plan_blocks_unmapped_missing_and_incompatible_columns() { fn explicit_skip_is_not_an_issue_but_duplicates_and_unknowns_are() { let source = [column("id", "integer"), column("note", "text")]; let target = [column("id", "INTEGER")]; - let ok = plan(&selection(vec![("note", None)]), &source, &target, TransferDialect::Sqlite); + let ok = plan( + &selection(vec![("note", None)]), + &source, + &target, + TransferDialect::Sqlite, + ); assert!(!ok.plan.blocking); assert!(ok.plan.columns[1].skipped); let duplicate = plan( @@ -361,15 +430,21 @@ fn generated_and_unsupported_target_columns_block() { let source = [column("id", "integer")]; let mut generated = column("id", "integer"); generated.is_generated = true; - assert!( - codes(&plan(&selection(vec![]), &source, &[generated], TransferDialect::Postgres)) - .contains(&"targetColumnGenerated".to_string()) - ); + assert!(codes(&plan( + &selection(vec![]), + &source, + &[generated], + TransferDialect::Postgres + )) + .contains(&"targetColumnGenerated".to_string())); let target = [column("id", "inet")]; - assert!( - codes(&plan(&selection(vec![]), &source, &target, TransferDialect::Postgres)) - .contains(&"unsupportedTargetType".to_string()) - ); + assert!(codes(&plan( + &selection(vec![]), + &source, + &target, + TransferDialect::Postgres + )) + .contains(&"unsupportedTargetType".to_string())); } #[test] @@ -377,6 +452,217 @@ fn pg_target_reads_precision_from_declared_type() { let mut ts = column("at", "timestamp without time zone"); ts.full_type = Some("timestamp(3) without time zone".into()); let source = [column("at", "timestamp without time zone")]; - let planned = plan(&selection(vec![]), &source, &[ts], TransferDialect::Postgres); + let planned = plan( + &selection(vec![]), + &source, + &[ts], + TransferDialect::Postgres, + ); assert_eq!(planned.bindings[0].conversion.rule, ConversionRule::Checked); } + +// --- Regression tests for SQLite source type classification (#631 review #3) --- + +#[test] +fn classify_source_recognizes_sqlite_blob() { + assert_eq!( + classify_source(&column("data", "BLOB")), + Some(SourceKind::Bytes) + ); +} + +#[test] +fn classify_source_recognizes_sqlite_float_and_double() { + assert_eq!( + classify_source(&column("price", "FLOAT")), + Some(SourceKind::Float) + ); + assert_eq!( + classify_source(&column("price", "DOUBLE")), + Some(SourceKind::Float) + ); +} + +#[test] +fn classify_source_recognizes_sqlite_varchar_and_char() { + assert_eq!( + classify_source(&column("name", "VARCHAR(20)")), + Some(SourceKind::Text) + ); + assert_eq!( + classify_source(&column("code", "CHAR(2)")), + Some(SourceKind::Text) + ); +} + +#[test] +fn classify_source_recognizes_sqlite_datetime() { + assert_eq!( + classify_source(&column("created", "DATETIME")), + Some(SourceKind::Timestamp) + ); +} + +#[test] +fn bool_to_int_preserves_integer_value_from_sqlite_source() { + // SQLite stores booleans as integers. When sqlite_read_cell returns + // Int(2) for a Bool source, Op::BoolToInt must pass it through as Int(2), + // not coerce to 1. + let conversion = Conversion { + op: Op::BoolToInt, + out: OutKind::Int, + rule: ConversionRule::Exact, + }; + assert_eq!( + apply(&conversion, TransferValue::Int(2)), + Ok(TransferValue::Int(2)) + ); + assert_eq!( + apply(&conversion, TransferValue::Int(0)), + Ok(TransferValue::Int(0)) + ); + // Bool input still works (postgres path) + assert_eq!( + apply(&conversion, TransferValue::Bool(true)), + Ok(TransferValue::Int(1)) + ); +} + +fn decimal_to_real(value: TransferValue) -> Result { + let planned = + plan_conversion(SourceKind::Decimal, &TargetType::Sqlite(SqliteTarget::Real)).unwrap(); + apply(&planned, value) +} + +#[test] +fn an_integer_a_real_column_cannot_hold_exactly_is_refused() { + // 1e18 + 100 rounds to 1e18 + 128 in an f64 yet prints as the same digits. + for value in [ + 1_000_000_000_000_000_100_i64, + -1_000_000_000_000_000_100, + (1 << 53) + 1, + ] { + assert_eq!( + decimal_to_real(TransferValue::Int(value)), + Err(ConvertError::Lossy), + "{value}" + ); + } +} + +#[test] +fn an_integer_a_real_column_holds_exactly_still_converts() { + for value in [0_i64, 42, -7, 1 << 53, 1_000_000_000_000_000_000] { + assert_eq!( + decimal_to_real(TransferValue::Int(value)), + Ok(TransferValue::Float(value as f64)), + "{value}" + ); + } +} + +#[test] +fn fractional_decimals_are_still_judged_by_their_text() { + assert_eq!(decimal_to_real(text("0.1")), Ok(TransferValue::Float(0.1))); + assert_eq!( + decimal_to_real(text("0.30000000000000004")), + Ok(TransferValue::Float(0.30000000000000004)) + ); +} + +// --- Capability-driven pairs --- + +fn manifest( + id: &str, + table_copy: bool, + dialect: Option, +) -> crate::drivers::driver_trait::PluginManifest { + let mut manifest = crate::plugins::driver::test_manifest(); + manifest.id = id.to_string(); + manifest.capabilities.table_copy = table_copy; + manifest.capabilities.sql_dialect = dialect; + manifest +} + +fn postgres_plugin(id: &str) -> crate::drivers::driver_trait::PluginManifest { + manifest( + id, + true, + Some(crate::drivers::driver_trait::SqlDialect::Postgres), + ) +} + +fn sqlite_manifest() -> crate::drivers::driver_trait::PluginManifest { + manifest( + "sqlite", + false, + Some(crate::drivers::driver_trait::SqlDialect::Sqlite), + ) +} + +#[test] +fn a_postgres_dialect_plugin_with_table_copy_pairs_with_itself_and_sqlite() { + let manifests = [sqlite_manifest(), postgres_plugin("postgresql")]; + assert!(ensure_supported_pair(&manifests, "postgresql", "postgresql").is_ok()); + assert!(ensure_supported_pair(&manifests, "postgresql", "sqlite").is_ok()); + assert!(ensure_supported_pair(&manifests, "sqlite", "sqlite").is_ok()); + assert!(ensure_supported_pair(&manifests, "sqlite", "postgresql").is_err()); +} + +#[test] +fn the_pairs_follow_the_declared_capability_not_the_driver_id() { + let postgres = crate::drivers::driver_trait::SqlDialect::Postgres; + let manifests = [ + sqlite_manifest(), + postgres_plugin("my-pg-fork"), + manifest("no-table-copy", false, Some(postgres)), + manifest( + "wrong-dialect", + true, + Some(crate::drivers::driver_trait::SqlDialect::Mysql), + ), + manifest("undeclared-dialect", true, None), + ]; + assert!(ensure_supported_pair(&manifests, "my-pg-fork", "sqlite").is_ok()); + assert!(ensure_supported_pair(&manifests, "my-pg-fork", "my-pg-fork").is_ok()); + for id in ["no-table-copy", "wrong-dialect", "undeclared-dialect"] { + assert!( + ensure_supported_pair(&manifests, id, "sqlite").is_err(), + "{id}" + ); + assert!( + ensure_supported_pair(&manifests, "my-pg-fork", id).is_err(), + "{id}" + ); + } +} + +#[test] +fn two_postgres_plugins_pair_with_each_other() { + let manifests = [postgres_plugin("postgresql"), postgres_plugin("my-pg-fork")]; + assert!(ensure_supported_pair(&manifests, "postgresql", "my-pg-fork").is_ok()); + assert!(ensure_supported_pair(&manifests, "my-pg-fork", "postgresql").is_ok()); +} + +#[test] +fn without_a_copy_capable_plugin_only_sqlite_pairs_with_itself() { + let pairs = capabilities(&[sqlite_manifest()]).pairs; + assert_eq!(pairs.len(), 1); + assert_eq!( + (pairs[0].source.as_str(), pairs[0].target.as_str()), + ("sqlite", "sqlite") + ); +} + +#[test] +fn dialect_comes_from_the_manifest() { + assert_eq!( + dialect_for_manifest(&sqlite_manifest()), + Some(TransferDialect::Sqlite) + ); + assert_eq!( + dialect_for_manifest(&postgres_plugin("anything")), + Some(TransferDialect::Postgres) + ); + assert_eq!(dialect_for_manifest(&manifest("x", false, None)), None); +} diff --git a/src-tauri/src/table_transfer/types.rs b/src-tauri/src/table_transfer/types.rs index a74769dc3..9a7a310bf 100644 --- a/src-tauri/src/table_transfer/types.rs +++ b/src-tauri/src/table_transfer/types.rs @@ -1,24 +1,44 @@ use super::model::*; +use crate::drivers::driver_trait::PluginManifest; use crate::models::TableColumn; -const POSTGRES: &str = "postgres"; const SQLITE: &str = "sqlite"; -pub fn dialect_for_driver(driver: &str) -> Option { - match driver { - POSTGRES => Some(TransferDialect::Postgres), - SQLITE => Some(TransferDialect::Sqlite), - _ => None, +/// The transfer dialect a driver speaks, read from what it declares rather than +/// from its id: the built-in SQLite driver, and any plugin that implements the +/// table-copy RPCs for a PostgreSQL-dialect database. +pub fn dialect_for_manifest(manifest: &PluginManifest) -> Option { + if manifest.id == SQLITE { + return Some(TransferDialect::Sqlite); } + let caps = &manifest.capabilities; + (caps.table_copy + && caps.sql_dialect == Some(crate::drivers::driver_trait::SqlDialect::Postgres)) + .then_some(TransferDialect::Postgres) } -pub fn capabilities() -> TableTransferCapabilities { - let pair = |target: &str| TransferPair { - source: POSTGRES.to_string(), +/// Driver pairs a transfer can run between: PostgreSQL-dialect drivers that +/// declare `table_copy` copy to each other and to SQLite, and SQLite copies to +/// SQLite. +pub fn capabilities(manifests: &[PluginManifest]) -> TableTransferCapabilities { + let postgres: Vec<&str> = manifests + .iter() + .filter(|m| dialect_for_manifest(m) == Some(TransferDialect::Postgres)) + .map(|m| m.id.as_str()) + .collect(); + let pair = |source: &str, target: &str| TransferPair { + source: source.to_string(), target: target.to_string(), }; + let mut pairs = vec![pair(SQLITE, SQLITE)]; + for source in &postgres { + for target in &postgres { + pairs.push(pair(source, target)); + } + pairs.push(pair(source, SQLITE)); + } TableTransferCapabilities { - pairs: vec![pair(POSTGRES), pair(SQLITE)], + pairs, write_modes: vec!["append".to_string()], conflict_modes: vec!["fail".to_string(), "skip".to_string()], max_batch_rows: MAX_BATCH_ROWS, @@ -26,8 +46,12 @@ pub fn capabilities() -> TableTransferCapabilities { } } -pub fn ensure_supported_pair(source: &str, target: &str) -> Result<(), String> { - let supported = capabilities() +pub fn ensure_supported_pair( + manifests: &[PluginManifest], + source: &str, + target: &str, +) -> Result<(), String> { + let supported = capabilities(manifests) .pairs .iter() .any(|pair| pair.source == source && pair.target == target); @@ -41,19 +65,30 @@ pub fn ensure_supported_pair(source: &str, target: &str) -> Result<(), String> { } pub fn classify_source(column: &TableColumn) -> Option { - Some(match column.data_type.to_ascii_lowercase().as_str() { + // Strip a length/precision suffix (e.g. "varchar(20)" → "varchar") so + // SQLite's type-with-length declarations match the arms below. + let base = column + .data_type + .split_once('(') + .map(|(base, _)| base) + .unwrap_or(&column.data_type) + .trim() + .to_ascii_lowercase(); + Some(match base.as_str() { "boolean" => SourceKind::Bool, - "smallint" | "integer" | "bigint" => SourceKind::Int, - "real" | "double precision" => SourceKind::Float, + "smallint" | "integer" | "bigint" | "int" | "int2" | "int8" => SourceKind::Int, + "real" | "double precision" | "double" | "float" => SourceKind::Float, "numeric" => SourceKind::Decimal, - "text" | "character varying" | "character" => SourceKind::Text, + "text" | "character varying" | "character" | "varchar" | "char" | "clob" => { + SourceKind::Text + } "uuid" => SourceKind::Uuid, "json" | "jsonb" => SourceKind::Json, "date" => SourceKind::Date, "time without time zone" => SourceKind::Time, - "timestamp without time zone" => SourceKind::Timestamp, + "timestamp without time zone" | "datetime" => SourceKind::Timestamp, "timestamp with time zone" => SourceKind::TimestampTz, - "bytea" => SourceKind::Bytes, + "bytea" | "blob" => SourceKind::Bytes, _ => return None, }) } @@ -160,7 +195,10 @@ const INCOMPATIBLE: &str = "incompatibleTypes"; /// Decides whether `source` may be written into `target`, and how. Anything /// that would need an implicit, information-losing coercion is refused. -pub fn plan_conversion(source: SourceKind, target: &TargetType) -> Result { +pub fn plan_conversion( + source: SourceKind, + target: &TargetType, +) -> Result { use ConversionRule::{Checked, Exact}; use SourceKind as S; match target { @@ -176,26 +214,46 @@ pub fn plan_conversion(source: SourceKind, target: &TargetType) -> Result conv( - Op::IntToDecimal { precision: *precision, scale: *scale }, + Op::IntToDecimal { + precision: *precision, + scale: *scale, + }, OutKind::Text, Checked, ), (S::Float, PgTarget::Float(bits)) => conv( - Op::FloatCheck { bits: *bits, allow_non_finite: true }, + Op::FloatCheck { + bits: *bits, + allow_non_finite: true, + }, OutKind::Float, if *bits == 64 { Exact } else { Checked }, ), (S::Decimal, PgTarget::Decimal { precision, scale }) => conv( - Op::DecimalFit { precision: *precision, scale: *scale }, + Op::DecimalFit { + precision: *precision, + scale: *scale, + }, OutKind::Text, if precision.is_none() { Exact } else { Checked }, ), (S::Decimal, PgTarget::Int(bits)) => { - let max = if *bits == 64 { i64::MAX } else { (1i64 << (bits - 1)) - 1 }; - conv(Op::DecimalToInt { min: -max - 1, max }, OutKind::Int, Checked) + let max = if *bits == 64 { + i64::MAX + } else { + (1i64 << (bits - 1)) - 1 + }; + conv( + Op::DecimalToInt { min: -max - 1, max }, + OutKind::Int, + Checked, + ) } (S::Decimal, PgTarget::Float(bits)) => conv( - Op::DecimalToFloat { bits: *bits, allow_non_finite: true }, + Op::DecimalToFloat { + bits: *bits, + allow_non_finite: true, + }, OutKind::Float, Checked, ), @@ -232,18 +290,27 @@ pub fn plan_conversion(source: SourceKind, target: &TargetType) -> Result conv( - Op::FloatCheck { bits: 64, allow_non_finite: false }, + Op::FloatCheck { + bits: 64, + allow_non_finite: false, + }, OutKind::Float, Checked, ), (S::Decimal, T::Text | T::Untyped) => conv(Op::Copy, OutKind::Text, Exact), (S::Decimal, T::Integer) => conv( - Op::DecimalToInt { min: i64::MIN, max: i64::MAX }, + Op::DecimalToInt { + min: i64::MIN, + max: i64::MAX, + }, OutKind::Int, Checked, ), (S::Decimal, T::Real) => conv( - Op::DecimalToFloat { bits: 64, allow_non_finite: false }, + Op::DecimalToFloat { + bits: 64, + allow_non_finite: false, + }, OutKind::Float, Checked, ), @@ -253,7 +320,9 @@ pub fn plan_conversion(source: SourceKind, target: &TargetType) -> Result conv(Op::Copy, OutKind::Bytes, Exact), - (_, T::Text) if text && source != S::Decimal => conv(Op::Copy, OutKind::Text, Exact), + (_, T::Text) if text && source != S::Decimal => { + conv(Op::Copy, OutKind::Text, Exact) + } (_, _) if any && text => conv(Op::Copy, OutKind::Text, Exact), _ => Err(INCOMPATIBLE), } diff --git a/src-tauri/src/transport/desktop/commands.rs b/src-tauri/src/transport/desktop/commands.rs index fd1d6f3a6..074341423 100644 --- a/src-tauri/src/transport/desktop/commands.rs +++ b/src-tauri/src/transport/desktop/commands.rs @@ -52,7 +52,12 @@ async fn execute_connection_command( #[tauri::command] pub async fn get_connections(app: AppHandle) -> Result { migrate_ssh_connections(&app).await.ok(); - migrate_postgres_ssl_mode_spelling(&app).await.ok(); + if let Err(e) = migrate_builtin_driver_ids(&app).await { + log::warn!("Driver-id migration failed: {e}"); + } + if let Err(e) = migrate_postgres_ssl_mode_spelling(&app).await { + log::warn!("SSL-mode spelling migration failed: {e}"); + } execute_connection_command( &app, crate::application::connections::ConnectionCommand::GetConnections, @@ -65,7 +70,12 @@ pub async fn get_connections_with_groups( app: AppHandle, ) -> Result { migrate_ssh_connections(&app).await.ok(); - migrate_postgres_ssl_mode_spelling(&app).await.ok(); + if let Err(e) = migrate_builtin_driver_ids(&app).await { + log::warn!("Driver-id migration failed: {e}"); + } + if let Err(e) = migrate_postgres_ssl_mode_spelling(&app).await { + log::warn!("SSL-mode spelling migration failed: {e}"); + } execute_connection_command( &app, crate::application::connections::ConnectionCommand::GetConnectionsWithGroups, @@ -908,9 +918,10 @@ async fn migrate_ssh_connections(app: &AppHandle) -> Result<(), S let mut conn_file = persistence::read_connections_file(&conn_path)?; // Check if any connections have old embedded SSH params - let needs_migration = conn_file.connections.iter().any(|c| { - c.params.ssh_enabled.unwrap_or(false) && c.params.ssh_connection_id.is_none() - }); + let needs_migration = conn_file + .connections + .iter() + .any(|c| c.params.ssh_enabled.unwrap_or(false) && c.params.ssh_connection_id.is_none()); if !needs_migration { return Ok(None); @@ -1008,8 +1019,7 @@ async fn migrate_ssh_connections(app: &AppHandle) -> Result<(), S } // Save migrated SSH connections - let ssh_json = - serde_json::to_string_pretty(&ssh_connections).map_err(|e| e.to_string())?; + let ssh_json = serde_json::to_string_pretty(&ssh_connections).map_err(|e| e.to_string())?; persistence::write_private_file(&ssh_path, ssh_json)?; // Save migrated connections using new format (preserving groups) @@ -1032,10 +1042,9 @@ async fn migrate_ssh_connections(app: &AppHandle) -> Result<(), S } /// Migrates already-persisted `ssl_mode` values on postgres-dialect -/// connections (driver id other than the builtin `"postgres"`) from the -/// stale MySQL-style spelling to the Postgres-style spelling the plugin -/// actually understands. Idempotent — a no-op once every affected -/// connection has been rewritten. See +/// connections from the stale MySQL-style spelling to the Postgres-style +/// spelling the plugin actually understands. Idempotent — a no-op once +/// every affected connection has been rewritten. See /// `connection_migrations::migrate_postgres_ssl_mode_spelling_at_path` for /// the full rationale, including the concurrency guard against a race with /// the `--mcp` process's own call to the same function. @@ -1051,6 +1060,31 @@ async fn migrate_postgres_ssl_mode_spelling(app: &AppHandle) -> R Ok(()) } +/// Force-migrates saved connections still on the built-in `"postgres"` driver +/// to the `"postgresql"` plugin, now that the built-in driver is being +/// removed. Runs automatically at launch (no dismissible nudge, no undo) so +/// no saved connection is left pointing at a driver id that no longer +/// resolves. See `connection_migrations::migrate_builtin_driver_ids_at_path` +/// for the full rationale, including the concurrency guard. +async fn migrate_builtin_driver_ids(app: &AppHandle) -> Result<(), String> { + let conn_path = get_config_path(app)?; + let plugins_dir = app + .state::() + .paths + .plugins_dir(); + let usable = crate::plugins::force_install::usable_replacement_plugins(&plugins_dir).await; + let migrated = + crate::connection_migrations::migrate_builtin_driver_ids_when(&conn_path, |plugin_id| { + usable.iter().any(|id| id == plugin_id) + }) + .await?; + if migrated { + app.state::>() + .invalidate(); + } + Ok(()) +} + #[tauri::command] pub async fn get_ssh_connections( app: AppHandle, diff --git a/src-tauri/src/transport/desktop/dump_commands.rs b/src-tauri/src/transport/desktop/dump_commands.rs index f933aafa5..4795fe4e7 100644 --- a/src-tauri/src/transport/desktop/dump_commands.rs +++ b/src-tauri/src/transport/desktop/dump_commands.rs @@ -1,10 +1,10 @@ use crate::application::connection_files::GeneratedFile; use crate::application::database_transfers::{self, DumpDestination, ImportSource, JobKind}; use crate::application::table_row_transfers::{self, TableTransferPlan, TableTransferResult}; -use crate::table_transfer::{TableTransferCapabilities, TableTransferRequest}; use crate::application::table_transfers; use crate::dump_commands::*; use crate::runtime::RuntimeContext; +use crate::table_transfer::{TableTransferCapabilities, TableTransferRequest}; use std::path::PathBuf; use tauri::State; @@ -80,7 +80,7 @@ pub async fn import_database( #[tauri::command] pub async fn get_table_transfer_capabilities() -> Result { - Ok(table_row_transfers::get_capabilities()) + Ok(table_row_transfers::get_capabilities().await) } #[tauri::command] diff --git a/src-tauri/src/transport/desktop/health_check.rs b/src-tauri/src/transport/desktop/health_check.rs index 9082f3047..b1509727e 100644 --- a/src-tauri/src/transport/desktop/health_check.rs +++ b/src-tauri/src/transport/desktop/health_check.rs @@ -195,7 +195,7 @@ async fn recover_connection(app: &tauri::AppHandle, connection_id: &str) { } fn is_builtin_driver(driver: &str) -> bool { - matches!(driver, "mysql" | "postgres" | "sqlite") + matches!(driver, "mysql" | "sqlite") } /// Open a fresh pool for a built-in driver and ping through it. Plugin drivers @@ -206,7 +206,6 @@ async fn reconnect( ) -> Result<(), String> { let id = Some(connection_id); match params.driver.as_str() { - "postgres" => drop(crate::pool_manager::get_postgres_pool_with_id(params, id).await?), "mysql" => drop(crate::pool_manager::get_mysql_pool_with_id(params, id).await?), "sqlite" => drop(crate::pool_manager::get_sqlite_pool_with_id(params, id).await?), _ => {} diff --git a/src-tauri/src/transport/desktop/mod.rs b/src-tauri/src/transport/desktop/mod.rs index aff1c9393..778981d34 100644 --- a/src-tauri/src/transport/desktop/mod.rs +++ b/src-tauri/src/transport/desktop/mod.rs @@ -13,9 +13,9 @@ pub mod config; pub mod connection_appearance; pub mod connection_import_commands; pub mod connection_window; -pub mod data_files; #[cfg(test)] mod connection_window_tests; +pub mod data_files; pub mod database_backup; pub mod dump_commands; #[cfg(feature = "e2e-testing")] @@ -216,18 +216,17 @@ pub fn run(args: crate::cli::Args, log_buffer: crate::logger::SharedLogBuffer) { // `postgresql` plugin when a `postgres` connection exists). Spawned, // not `block_on`, so a slow or failed registry fetch never delays // window creation — same pattern as the health-check spawn below. - // See `.github/planning/postgres-plugin-force-install.md`. - for (builtin_id, plugin_id) in crate::plugins::force_install::MIGRATABLE_DRIVERS { - let handle = app.handle().clone(); - let builtin_id = builtin_id.to_string(); - let plugin_id = plugin_id.to_string(); + // The web server and `--mcp` run the same function from bootstrap. + { + let runtime = app.state::().inner().clone(); + let cache = app + .state::>() + .inner() + .clone(); tauri::async_runtime::spawn(async move { - crate::transport::desktop::plugins::force_install::ensure_plugin_installed_if_needed( - &handle, - &builtin_id, - &plugin_id, - ) - .await; + crate::plugins::force_install::ensure_replacement_plugins(&runtime).await; + // The install step may have moved connections on disk. + cache.invalidate(); }); } @@ -754,7 +753,6 @@ pub fn run(args: crate::cli::Args, log_buffer: crate::logger::SharedLogBuffer) { // Back up the freshest state before the process ends (no-op // unless backups are enabled and due). backup::run_exit_backup(app_handle); - tauri::async_runtime::block_on(crate::runtime::lifecycle::release_pinned_sessions()); run_shutdown_hooks.run(); } }); diff --git a/src-tauri/src/transport/desktop/plugins.rs b/src-tauri/src/transport/desktop/plugins.rs index 345e8ce90..862823a02 100644 --- a/src-tauri/src/transport/desktop/plugins.rs +++ b/src-tauri/src/transport/desktop/plugins.rs @@ -1,8 +1,7 @@ -pub mod commands; pub mod accounts; +pub mod commands; pub mod connection_metadata; pub mod deep_link; pub mod extensions; -pub mod force_install; pub mod manager; pub mod runtime_version; diff --git a/src-tauri/src/transport/desktop/plugins/force_install.rs b/src-tauri/src/transport/desktop/plugins/force_install.rs deleted file mode 100644 index bc455c8e0..000000000 --- a/src-tauri/src/transport/desktop/plugins/force_install.rs +++ /dev/null @@ -1,155 +0,0 @@ -use crate::config::AppConfig; -use crate::plugins::force_install::*; -use crate::plugins::{installer, tabularium}; -use crate::transport::desktop::config; -use tauri::{AppHandle, Emitter}; - -/// Ensure the plugin for `builtin_id` is installed, but only when at least one -/// saved connection is still on the built-in driver. A user with no such -/// connection is left untouched — no plugin they don't need. -/// -/// Public entry point spawned from `setup()`. -pub async fn ensure_plugin_installed_if_needed(app: &AppHandle, builtin_id: &str, plugin_id: &str) { - match connections_use_driver(app, builtin_id) { - Ok(false) => return, // nothing on this built-in driver, nothing to do - Ok(true) => {} - Err(e) => { - log::warn!("{LOG_PREFIX} could not read connections: {e}"); - return; - } - } - ensure_plugin_installed(app, plugin_id).await; -} - -/// Install (and activate) `plugin_id` if it isn't already installed and the -/// latest release is compatible with this app build. Every failure path -/// logs and returns silently — there's no UI-visible error and no retry loop -/// within a single launch. The check re-runs from scratch on every launch, -/// so a transient failure self-heals next time; a persistent one (no network, -/// corporate proxy) is handled by the frontend nudge staying suppressed until -/// the plugin is actually present (see the design doc's connectivity section). -pub async fn ensure_plugin_installed(app: &AppHandle, plugin_id: &str) { - match installer::list_installed() { - Ok(installed) if installed.iter().any(|p| p.id == plugin_id) => return, - Ok(_) => {} - Err(e) => { - log::warn!("{LOG_PREFIX} could not list installed plugins: {e}"); - return; - } - } - if !plugin_compatible_with_this_app(app, plugin_id).await { - log::warn!("{LOG_PREFIX} {plugin_id} has no compatible release, skipping"); - return; - } - let runtime = tauri::Manager::state::(app); - if let Err(e) = - crate::application::plugins::install_plugin(&runtime, plugin_id.to_string(), None, None) - .await - { - log::warn!("{LOG_PREFIX} {plugin_id} install failed: {e}"); - return; - } - // `install_plugin` hot-registers for this session but does not persist - // activation — without this write the plugin vanishes on relaunch - // (`load_plugins` skips installed-but-unlisted drivers). Same effect as - // `NewConnectionModal`'s `updateSetting("activeExternalDrivers", ...)`, - // written from the backend because this runs in a spawned task. - if let Err(e) = persist_activation(app, plugin_id) { - log::warn!("{LOG_PREFIX} could not activate {plugin_id}: {e}"); - } - // Tell the already-running frontend the plugin is installed and - // (activation errors aside) registered — see `PLUGIN_ACTIVATED_EVENT`'s - // doc comment for why this can't wait for the next launch. Emitted even - // if `persist_activation` above failed: `install_plugin` still - // hot-registered the driver for this session, so `useDrivers`' - // `get_registered_drivers`/`get_installed_plugins` refetch has something - // new to report regardless of whether the config write landed. - if let Err(e) = app.emit(PLUGIN_ACTIVATED_EVENT, PluginActivatedPayload { plugin_id }) { - log::warn!("{LOG_PREFIX} could not emit {PLUGIN_ACTIVATED_EVENT}: {e}"); - } -} - -/// Persist `plugin_id` into `active_external_drivers` via the `save_config` -/// merge, leaving every other config field untouched. Idempotent: a no-op if -/// the id is already active. -/// -/// Reads the currently-installed plugin ids first: `merge_active_driver` needs -/// them to seed the list correctly when no preference has been saved yet (see -/// its doc comment). Bails without writing if that read fails — narrowing to -/// just `plugin_id` on a guess would be worse than not activating it this -/// launch, since it could silently deactivate every other installed plugin. -fn persist_activation(app: &AppHandle, plugin_id: &str) -> Result<(), String> { - let config = config::load_config_internal(app); - let installed_ids: Vec = installer::list_installed()? - .into_iter() - .map(|p| p.id) - .collect(); - let updated = merge_active_driver(&config, plugin_id, &installed_ids); - // Only write when something actually changed — avoids a pointless - // config.json rewrite (and cache invalidation) on every launch. - if updated.active_external_drivers == config.active_external_drivers { - return Ok(()); - } - // Pass save_config a config with only `active_external_drivers` set, - // not the full `updated` snapshot: save_config re-reads disk and - // overwrites every `Some` field, so writing back the stale snapshot - // taken above would silently revert any other setting the user changed - // in the meantime — the inverse of the race the frontend's - // `plugin-activated` listener already guards against. - config::save_config( - app.clone(), - AppConfig { - active_external_drivers: updated.active_external_drivers, - ..AppConfig::default() - }, - ) -} - -/// True when at least one saved connection has `params.driver == driver_id`. -/// Reads the connections file directly via `persistence::load_connections` -/// (the same path `get_connections` uses internally) rather than invoking the -/// Tauri command — the command wrapper runs per-call SSH/SSL migrations we -/// don't want firing on every launch just to detect a trigger. -fn connections_use_driver(app: &AppHandle, driver_id: &str) -> Result { - let path = crate::transport::desktop::commands::get_config_path(app)?; - let connections = crate::persistence::load_connections(&path)?; - Ok(connections.iter().any(|c| c.params.driver == driver_id)) -} - -/// Check the latest release's `min_tabularis_version` against the running -/// app's own version. `install_plugin` doesn't gate on this itself, so without -/// this check an unattended install could silently install a release that -/// requires a newer Tabularis than the user is running, leaving them -/// installed-but-non-functional. Reuses the `semver::Version::parse` primitive -/// `classify_install` (`registry.rs:43`) already uses, applied to a different -/// comparison. -async fn plugin_compatible_with_this_app(app: &AppHandle, plugin_id: &str) -> bool { - let config = config::load_config_internal(app); - let base = registry_base_url(&config).trim_end_matches('/'); - let Ok(detail) = tabularium::fetch_plugin_detail(base, plugin_id).await else { - // Couldn't reach the registry — treat as compatible-by-default so a - // network blip doesn't permanently block an otherwise-fine install; - // the install itself will surface a real download error if it persists. - log::warn!("{LOG_PREFIX} could not fetch detail for {plugin_id}, assuming compatible"); - return true; - }; - // Find the release matching the registry's latest_version; fall back to - // the first release if the version string can't be matched. - let target = if detail.latest_version.is_empty() { - detail.releases.first() - } else { - detail - .releases - .iter() - .find(|r| r.version == detail.latest_version) - .or_else(|| detail.releases.first()) - }; - let Some(release) = target else { - log::warn!("{LOG_PREFIX} {plugin_id} has no releases on the registry"); - return false; - }; - let Some(min) = &release.min_tabularis_version else { - return true; // no minimum declared → compatible with any version - }; - is_version_compatible(min, env!("CARGO_PKG_VERSION")) -} diff --git a/src-tauri/src/transport/desktop/sandbox_protocol.rs b/src-tauri/src/transport/desktop/sandbox_protocol.rs index 732ea8b0e..53978d941 100644 --- a/src-tauri/src/transport/desktop/sandbox_protocol.rs +++ b/src-tauri/src/transport/desktop/sandbox_protocol.rs @@ -8,7 +8,8 @@ use tauri::http::{header, Request, Response, StatusCode}; use tauri::{AppHandle, Runtime}; // WebKit does not match 'self' for custom-scheme resources in an opaque sandbox. -const GUEST_CSP: &str = "sandbox allow-scripts; default-src 'none'; script-src 'self' tabularis-plugin:; \ +const GUEST_CSP: &str = + "sandbox allow-scripts; default-src 'none'; script-src 'self' tabularis-plugin:; \ style-src 'self' tabularis-plugin: 'unsafe-inline'; img-src data: blob:; font-src data:; \ connect-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'"; diff --git a/src-tauri/src/transport/web/managed_mode_tests.rs b/src-tauri/src/transport/web/managed_mode_tests.rs index b9d54e1ba..f6472fa34 100644 --- a/src-tauri/src/transport/web/managed_mode_tests.rs +++ b/src-tauri/src/transport/web/managed_mode_tests.rs @@ -667,11 +667,18 @@ async fn managed_only_refuses_to_start_with_high_risk_capabilities() { #[tokio::test] async fn managed_browser_cannot_replace_provisioned_database_selection() { let server = ManagedServer::start(ManagedConnectionPolicy::managed_only()).await; - let (status, body) = server.rpc("set_selected_databases", json!({ - "connectionId": "file-1", "databases": ["another_tenant"] - })).await; + let (status, body) = server + .rpc( + "set_selected_databases", + json!({ + "connectionId": "file-1", "databases": ["another_tenant"] + }), + ) + .await; assert_eq!(status, 403); assert_eq!(body["error"]["code"], DENIED); - let file = crate::persistence::load_connections_file(&server._temp.path().join("connections.json")).unwrap(); + let file = + crate::persistence::load_connections_file(&server._temp.path().join("connections.json")) + .unwrap(); assert_eq!(file.connections[0].params.database.primary(), "app"); } diff --git a/src-tauri/src/transport/web/mod.rs b/src-tauri/src/transport/web/mod.rs index a52ffb1ef..f44ab3906 100644 --- a/src-tauri/src/transport/web/mod.rs +++ b/src-tauri/src/transport/web/mod.rs @@ -13,10 +13,10 @@ mod events_tests; #[cfg(test)] mod login_page_tests; #[cfg(test)] -mod managed_mode_tests; -#[cfg(test)] mod login_target_tests; #[cfg(test)] +mod managed_mode_tests; +#[cfg(test)] mod tests; pub mod provisioning; diff --git a/src-tauri/src/transport/web/provisioning_tests.rs b/src-tauri/src/transport/web/provisioning_tests.rs index c8bef852e..80c43fd79 100644 --- a/src-tauri/src/transport/web/provisioning_tests.rs +++ b/src-tauri/src/transport/web/provisioning_tests.rs @@ -38,8 +38,6 @@ const TOKEN: &str = "machine-secret-for-integration-tests-123456"; #[tokio::test] async fn machine_crud_retries_secrets_and_browser_separation() { - crate::drivers::registry::register_driver(crate::drivers::postgres::PostgresDriver::new()) - .await; crate::drivers::registry::register_driver(crate::drivers::mysql::MysqlDriver::new()).await; let temp = tempfile::tempdir().unwrap(); std::fs::write(temp.path().join("index.html"), "app").unwrap(); @@ -117,7 +115,7 @@ async fn machine_crud_retries_secrets_and_browser_separation() { .status(), 401 ); - for driver in ["postgres", "mysql"] { + for driver in ["mysql"] { let url = format!("{collection}/{driver}-database"); let mut body = json!({"name":"Managed database","params":{"driver":driver,"database":"app","host":"127.0.0.1","username":"reader","password":"first-credential","read_only":true},"plugin_secret_changes":{"token":"plugin-credential"}}); let first: Value = client @@ -264,8 +262,7 @@ fn provisioning_token_validation_and_reference_contract() { async fn provisioning_validation_and_body_limits_preserve_error_statuses() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; - crate::drivers::registry::register_driver(crate::drivers::postgres::PostgresDriver::new()) - .await; + crate::drivers::registry::register_driver(crate::drivers::mysql::MysqlDriver::new()).await; let temp = tempfile::tempdir().unwrap(); let runtime = RuntimeContext::new( Arc::new(FixedRuntimePaths::new( @@ -294,7 +291,7 @@ async fn provisioning_validation_and_body_limits_preserve_error_statuses() { let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); let client = reqwest::Client::new(); let collection = format!("{base}/api/v1/provisioning/connections"); - let baseline = json!({"name":"Original", "params":{"driver":"postgres", "database":"app", "password":"original-secret"}}); + let baseline = json!({"name":"Original", "params":{"driver":"mysql", "database":"app", "password":"original-secret"}}); assert_eq!( client .put(format!("{collection}/existing")) @@ -389,8 +386,7 @@ async fn provisioning_delete_waits_for_in_flight_saved_connection_open() { }; use std::time::{Duration, Instant}; - crate::drivers::registry::register_driver(crate::drivers::postgres::PostgresDriver::new()) - .await; + crate::drivers::registry::register_driver(crate::drivers::mysql::MysqlDriver::new()).await; let temp = tempfile::tempdir().unwrap(); let runtime = RuntimeContext::new( Arc::new(FixedRuntimePaths::new( @@ -406,7 +402,7 @@ async fn provisioning_delete_waits_for_in_flight_saved_connection_open() { let database = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = database.local_addr().unwrap().port(); let input = serde_json::from_value(json!({"name":"Blocked handshake", "params":{ - "driver":"postgres", "host":"127.0.0.1", "port":port, + "driver":"mysql", "host":"127.0.0.1", "port":port, "database":"app", "username":"user", "password":"private-secret", "ssl_mode":"disable" }})) .unwrap(); @@ -477,8 +473,6 @@ async fn provisioned_mysql_and_postgres_reach_real_databases() { provisioning::{ProvisionCommand, ProvisionConnection}, ApplicationApi, ApplicationRequestContext, AuthorizationLevel, }; - crate::drivers::registry::register_driver(crate::drivers::postgres::PostgresDriver::new()) - .await; crate::drivers::registry::register_driver(crate::drivers::mysql::MysqlDriver::new()).await; let temp = tempfile::tempdir().unwrap(); let runtime = RuntimeContext::new( @@ -490,7 +484,7 @@ async fn provisioned_mysql_and_postgres_reach_real_databases() { Arc::new(MemorySecrets::default()), ); let application = RuntimeApplicationApi::new(runtime, Arc::new(ApplicationState::default())); - for (driver, port, user) in [("postgres", 25432, "postgres"), ("mysql", 23306, "root")] { + for (driver, port, user) in [("mysql", 23306, "root")] { let params = json!({"name": "Live lab", "params": {"driver":driver,"host":"127.0.0.1","port":port, "database":"example","username":user,"password":"lab-provision-secret","ssl_mode":"disable"}}); let input: ProvisionConnection = serde_json::from_value(params).unwrap(); diff --git a/src-tauri/src/transport/web/rpc.rs b/src-tauri/src/transport/web/rpc.rs index 1bb99555e..0b217f2e6 100644 --- a/src-tauri/src/transport/web/rpc.rs +++ b/src-tauri/src/transport/web/rpc.rs @@ -3030,15 +3030,21 @@ fn decode_database_transfer_command( } DatabaseTransferRpcCommand::PlanTableTransfer => { let request: TableTransferRpcRequest = decode_payload(body)?; - DatabaseTransferCommand::PlanTableTransfer { request: request.request } + DatabaseTransferCommand::PlanTableTransfer { + request: request.request, + } } DatabaseTransferRpcCommand::RunTableTransfer => { let request: TableTransferRpcRequest = decode_payload(body)?; - DatabaseTransferCommand::RunTableTransfer { request: request.request } + DatabaseTransferCommand::RunTableTransfer { + request: request.request, + } } DatabaseTransferRpcCommand::CancelTableTransfer => { let request: CancelTableTransferRequest = decode_payload(body)?; - DatabaseTransferCommand::CancelTableTransfer { transfer_id: request.transfer_id } + DatabaseTransferCommand::CancelTableTransfer { + transfer_id: request.transfer_id, + } } DatabaseTransferRpcCommand::PreviewTableImport => { let request: ReadTableSqlHeaderRequest = decode_payload(body)?; diff --git a/src-tauri/tests/integration_tests.rs b/src-tauri/tests/integration_tests.rs index ac984b9ca..38bf687b2 100644 --- a/src-tauri/tests/integration_tests.rs +++ b/src-tauri/tests/integration_tests.rs @@ -1,5 +1,5 @@ use std::time::Duration; -use tabularis_lib::drivers::{mysql, postgres}; +use tabularis_lib::drivers::mysql; use tabularis_lib::models::{ConnectionParams, DatabaseSelection}; use tokio::time::sleep; @@ -16,18 +16,6 @@ fn get_mysql_params() -> ConnectionParams { } } -fn get_postgres_params() -> ConnectionParams { - ConnectionParams { - driver: "postgres".to_string(), - host: Some("127.0.0.1".to_string()), - port: Some(54320), - username: Some("postgres".to_string()), - password: Some("password".to_string()), - database: DatabaseSelection::Single("testdb".to_string()), - ..Default::default() - } -} - #[tokio::test] #[ignore] // Ignored by default in CI/local unless explicitly requested with --include-ignored async fn test_mysql_integration_flow() { @@ -115,69 +103,6 @@ async fn test_mysql_integration_flow() { let _ = mysql::execute_query(¶ms, "DROP TABLE test_users", None, 1, None).await; } -#[tokio::test] -#[ignore] // Run via pg-integration.yml CI or --include-ignored -async fn test_postgres_integration_flow() { - let params = get_postgres_params(); - - // 1. Wait for DB - let mut connected = false; - for _ in 0..10 { - if postgres::get_tables(¶ms, "public").await.is_ok() { - connected = true; - break; - } - sleep(Duration::from_millis(500)).await; - } - - if !connected { - eprintln!("SKIPPING Postgres Test: Could not connect to Docker container on port 54320"); - return; - } - - // 2. Create Table - let create_sql = "CREATE TABLE IF NOT EXISTS test_users ( - id SERIAL PRIMARY KEY, - name TEXT, - email TEXT - )"; - let res = postgres::execute_query(¶ms, create_sql, None, 1, None).await; - assert!( - res.is_ok(), - "Failed to create table in Postgres: {:?}", - res.err() - ); - - // 3. Clean table - let _ = postgres::execute_query(¶ms, "TRUNCATE TABLE test_users", None, 1, None).await; - - // 4. Insert Data - let insert_sql = - "INSERT INTO test_users (name, email) VALUES ('Luigi Verdi', 'luigi@test.com')"; - let res = postgres::execute_query(¶ms, insert_sql, None, 1, None).await; - assert!(res.is_ok(), "Failed to insert data in Postgres"); - - // 5. Select Data - let select_sql = "SELECT * FROM test_users WHERE email = 'luigi@test.com'"; - let res = postgres::execute_query(¶ms, select_sql, None, 1, None).await; - match res { - Ok(data) => { - assert_eq!(data.rows.len(), 1, "Expected 1 row"); - let name_idx = data - .columns - .iter() - .position(|c| c == "name") - .expect("Column 'name' not found"); - let name_val = &data.rows[0][name_idx]; - assert_eq!(name_val.as_str(), Some("Luigi Verdi")); - } - Err(e) => panic!("Select failed: {}", e), - } - - // 6. Cleanup - let _ = postgres::execute_query(¶ms, "DROP TABLE test_users", None, 1, None).await; -} - // --------------------------------------------------------------------------- // execute_batch — session-state continuity across statements. // Each test invokes the driver-level `execute_batch` directly; the Tauri @@ -195,16 +120,6 @@ async fn wait_for_mysql(params: &ConnectionParams) -> bool { false } -async fn wait_for_postgres(params: &ConnectionParams) -> bool { - for _ in 0..10 { - if postgres::get_tables(params, "public").await.is_ok() { - return true; - } - sleep(Duration::from_millis(500)).await; - } - false -} - /// `SET @pid = LAST_INSERT_ID()` must survive into the two following /// INSERT statements so the children link to the freshly inserted parent. #[tokio::test] @@ -352,59 +267,6 @@ async fn test_mysql_batch_preserves_transaction_atomicity() { let _ = mysql::execute_query(¶ms, "DROP TABLE test_batch_tx", None, 1, None).await; } -/// A `TEMP TABLE` created inside a transaction must be visible to a -/// subsequent `SELECT` in the same batch — i.e. all statements observe -/// the same session. -#[tokio::test] -#[ignore] // Run via pg-integration.yml CI or --include-ignored -async fn test_postgres_batch_preserves_temp_table_and_transaction() { - let params = get_postgres_params(); - if !wait_for_postgres(¶ms).await { - eprintln!("SKIPPING: Postgres not reachable on 54320"); - return; - } - - let queries: Vec = [ - "BEGIN", - "CREATE TEMP TABLE test_batch_tmp (id SERIAL PRIMARY KEY, val TEXT)", - "INSERT INTO test_batch_tmp (val) VALUES ('a'), ('b'), ('c')", - "SELECT COUNT(*)::int AS n FROM test_batch_tmp", - "COMMIT", - ] - .iter() - .map(|s| s.to_string()) - .collect(); - - let results = postgres::execute_batch(¶ms, &queries, None, 1, None, None) - .await - .expect("batch setup should succeed"); - - assert_eq!(results.len(), queries.len()); - for (i, r) in results.iter().enumerate() { - assert!( - r.error.is_none(), - "stmt {} ({}) failed: {:?}", - i, - queries[i], - r.error - ); - } - - // The SELECT is at index 3; verify the temp table was visible and held 3 rows. - let count_result = results[3] - .result - .as_ref() - .expect("SELECT statement must return a result set"); - assert_eq!(count_result.rows.len(), 1); - let n = count_result.rows[0][0].as_i64(); - assert_eq!( - n, - Some(3), - "temp table must contain 3 rows and be visible to the SELECT (got {:?})", - n - ); -} - // --------------------------------------------------------------------------- // affected_rows — drivers must report the real INSERT/UPDATE/DELETE row // count rather than a constant zero. @@ -549,54 +411,6 @@ async fn test_mysql_delete_record_with_binary_primary_key() { let _ = mysql::execute_query(¶ms, "DROP TABLE test_binary_pk_delete", None, 1, None).await; } -#[tokio::test] -#[ignore] // Run via pg-integration.yml CI or --include-ignored -async fn test_postgres_affected_rows_reported_correctly() { - let params = get_postgres_params(); - if !wait_for_postgres(¶ms).await { - eprintln!("SKIPPING: Postgres not reachable on 54320"); - return; - } - - let _ = - postgres::execute_query(¶ms, "DROP TABLE IF EXISTS test_affected", None, 1, None).await; - - let queries: Vec = [ - "CREATE TABLE test_affected (id SERIAL PRIMARY KEY, v INT)", - "INSERT INTO test_affected (v) VALUES (1), (2), (3)", - "UPDATE test_affected SET v = v + 10 WHERE v >= 2", - "DELETE FROM test_affected WHERE v >= 12", - ] - .iter() - .map(|s| s.to_string()) - .collect(); - - let results = postgres::execute_batch(¶ms, &queries, None, 1, None, None) - .await - .expect("batch setup should succeed"); - - for (i, r) in results.iter().enumerate() { - assert!( - r.error.is_none(), - "stmt {} ({}) failed: {:?}", - i, - queries[i], - r.error - ); - } - - let insert_result = results[1].result.as_ref().expect("INSERT result"); - assert_eq!(insert_result.affected_rows, 3, "INSERT should report 3"); - - let update_result = results[2].result.as_ref().expect("UPDATE result"); - assert_eq!(update_result.affected_rows, 2, "UPDATE should report 2"); - - let delete_result = results[3].result.as_ref().expect("DELETE result"); - assert_eq!(delete_result.affected_rows, 2, "DELETE should report 2"); - - let _ = postgres::execute_query(¶ms, "DROP TABLE test_affected", None, 1, None).await; -} - // --------------------------------------------------------------------------- // cancel_query — when several queries share the same connection_id slot, // a single cancel must abort all of them, not just the most recently @@ -672,196 +486,3 @@ async fn test_concurrent_cancel_aborts_all_in_flight_queries() { "slot should be cleared after cancellation" ); } - -// --------------------------------------------------------------------------- -// get_foreign_keys / get_all_foreign_keys_batch — pg_catalog must resolve -// cross-schema references and composite keys (information_schema can miss or -// misreport these). -// --------------------------------------------------------------------------- - -#[tokio::test] -#[ignore] // Run via pg-integration.yml CI or --include-ignored -async fn test_postgres_foreign_keys_via_pg_catalog() { - let params = get_postgres_params(); - if !wait_for_postgres(¶ms).await { - eprintln!("SKIPPING: Postgres not reachable on 54320"); - return; - } - - let setup: Vec = [ - "DROP TABLE IF EXISTS public.test_fk_child", - "DROP TABLE IF EXISTS fk_ref.test_fk_parent", - "DROP SCHEMA IF EXISTS fk_ref CASCADE", - "CREATE SCHEMA fk_ref", - "CREATE TABLE fk_ref.test_fk_parent (id SERIAL PRIMARY KEY)", - "CREATE TABLE public.test_fk_child ( - parent_id INT NOT NULL, - CONSTRAINT test_fk_child_parent_fk - FOREIGN KEY (parent_id) - REFERENCES fk_ref.test_fk_parent (id) - ON DELETE CASCADE - ON UPDATE RESTRICT - )", - "DROP TABLE IF EXISTS public.test_fk_comp_child", - "DROP TABLE IF EXISTS public.test_fk_comp_parent", - "CREATE TABLE public.test_fk_comp_parent (a INT NOT NULL, b INT NOT NULL, PRIMARY KEY (a, b))", - "CREATE TABLE public.test_fk_comp_child ( - x INT NOT NULL, - y INT NOT NULL, - CONSTRAINT test_fk_comp_pair - FOREIGN KEY (x, y) REFERENCES public.test_fk_comp_parent (a, b) - )", - ] - .iter() - .map(|s| s.to_string()) - .collect(); - - for sql in &setup { - postgres::execute_query(¶ms, sql, None, 1, None) - .await - .unwrap_or_else(|e| panic!("setup failed on {sql:?}: {e}")); - } - - let single = postgres::get_foreign_keys(¶ms, "test_fk_child", "public") - .await - .expect("get_foreign_keys should succeed"); - assert_eq!(single.len(), 1, "expected one single-column FK row"); - let fk = &single[0]; - assert_eq!(fk.name, "test_fk_child_parent_fk"); - assert_eq!(fk.column_name, "parent_id"); - assert_eq!(fk.ref_table, "test_fk_parent"); - assert_eq!(fk.ref_column, "id"); - assert_eq!(fk.on_delete.as_deref(), Some("CASCADE")); - assert_eq!(fk.on_update.as_deref(), Some("RESTRICT")); - - let parent_columns = postgres::get_columns(¶ms, "test_fk_parent", "fk_ref") - .await - .expect("get_columns should succeed"); - let parent_id = parent_columns - .iter() - .find(|column| column.name == "id") - .expect("parent id column should be present"); - assert!( - parent_id.is_pk, - "primary key detection should use pg_catalog, not information_schema.table_constraints" - ); - - let batch = postgres::get_all_foreign_keys_batch(¶ms, "public") - .await - .expect("get_all_foreign_keys_batch should succeed"); - let batch_single = batch - .get("test_fk_child") - .expect("batch should include test_fk_child"); - assert_eq!(batch_single.len(), 1); - assert_eq!(batch_single[0].ref_table, "test_fk_parent"); - - let composite = postgres::get_foreign_keys(¶ms, "test_fk_comp_child", "public") - .await - .expect("composite get_foreign_keys should succeed"); - assert_eq!( - composite.len(), - 2, - "composite FK should expand to one row per column" - ); - assert!( - composite.iter().all(|r| r.name == "test_fk_comp_pair"), - "both composite rows must share the constraint name" - ); - let cols: Vec<_> = composite.iter().map(|r| r.column_name.as_str()).collect(); - assert!(cols.contains(&"x")); - assert!(cols.contains(&"y")); - - let teardown: Vec = [ - "DROP TABLE IF EXISTS public.test_fk_child", - "DROP TABLE IF EXISTS fk_ref.test_fk_parent", - "DROP SCHEMA IF EXISTS fk_ref CASCADE", - "DROP TABLE IF EXISTS public.test_fk_comp_child", - "DROP TABLE IF EXISTS public.test_fk_comp_parent", - ] - .iter() - .map(|s| s.to_string()) - .collect(); - for sql in &teardown { - let _ = postgres::execute_query(¶ms, sql, None, 1, None).await; - } -} - -/// Live Unix socket regression test for PostgreSQL. -/// Verifies that test_connection, pool checkout, query execution, and startup-script preflight -/// succeed over a Unix domain socket without TLS / InvalidDnsNameError. -#[cfg(unix)] -#[tokio::test] -#[ignore] -async fn test_postgres_unix_socket_live_regression() { - let socket_path = std::env::var("PG_UNIX_SOCKET").unwrap_or_else(|_| { - let candidates = [ - "/var/run/postgresql/.s.PGSQL.5432", - "/tmp/.s.PGSQL.5432", - "/tmp/.s.PGSQL.54320", - ]; - for candidate in candidates { - if std::path::Path::new(candidate).exists() { - return candidate.to_string(); - } - } - String::new() - }); - - if socket_path.is_empty() { - eprintln!("SKIPPING: No PG_UNIX_SOCKET or standard .s.PGSQL socket file found"); - return; - } - - let mut params = get_postgres_params(); - params.host = None; - params.port = None; - params.unix_socket_path = Some(socket_path); - - // 1. Verify test_connection works over Unix socket - use tabularis_lib::drivers::driver_trait::DatabaseDriver; - let driver = tabularis_lib::drivers::postgres::PostgresDriver::new(); - driver - .test_connection(¶ms) - .await - .expect("test_connection over Unix socket should succeed"); - - // 2. Verify pool creation and checkout with a query - let conn_id = format!("test-pg-socket-{}", uuid::Uuid::new_v4()); - let pool = tabularis_lib::pool_manager::get_postgres_pool_with_id(¶ms, Some(&conn_id)) - .await - .expect("get_postgres_pool_with_id over Unix socket should succeed"); - let client = pool - .get() - .await - .expect("pool checkout over Unix socket must not fail with InvalidDnsNameError"); - let row = client - .query_one("SELECT 1 + 1 AS sum", &[]) - .await - .expect("query_one should succeed over Unix socket"); - let sum: i32 = row.get("sum"); - assert_eq!(sum, 2); - - // 3. Verify startup script preflight and post_create hook over Unix socket - let mut script_params = params.clone(); - script_params.startup_script = Some("SET client_min_messages = warning;".to_string()); - let script_conn_id = format!("test-pg-socket-script-{}", uuid::Uuid::new_v4()); - let script_pool = tabularis_lib::pool_manager::get_postgres_pool_with_id( - &script_params, - Some(&script_conn_id), - ) - .await - .expect("pool with startup script over Unix socket should succeed"); - let script_client = script_pool - .get() - .await - .expect("checkout with startup script over Unix socket should succeed"); - let test_row = script_client - .query_one("SELECT 42", &[]) - .await - .expect("query with startup script should succeed"); - let val: i32 = test_row.get(0); - assert_eq!(val, 42); - - tabularis_lib::pool_manager::close_pool_with_id(¶ms, Some(&conn_id)).await; - tabularis_lib::pool_manager::close_pool_with_id(&script_params, Some(&script_conn_id)).await; -} diff --git a/src-tauri/tests/mysql_columns.rs b/src-tauri/tests/mysql_columns.rs index ef2e07428..c24f9a982 100644 --- a/src-tauri/tests/mysql_columns.rs +++ b/src-tauri/tests/mysql_columns.rs @@ -380,7 +380,11 @@ async fn rename_keeps_defaults( format!("{name}_renamed {rest}") }) .collect(); - assert_eq!(defaults(&renamed), expected_renamed, "{table}: after renaming"); + assert_eq!( + defaults(&renamed), + expected_renamed, + "{table}: after renaming" + ); } #[tokio::test] diff --git a/src-tauri/tests/postgres_integration/blob.rs b/src-tauri/tests/postgres_integration/blob.rs deleted file mode 100644 index 3bf864c7a..000000000 --- a/src-tauri/tests/postgres_integration/blob.rs +++ /dev/null @@ -1,123 +0,0 @@ -//! BLOB (bytea) handling tests. - -use crate::helpers::pg_params; -use serde_json::json; -use std::collections::HashMap; -use tabularis_lib::drivers::postgres; - -#[tokio::test] -#[ignore] -async fn test_insert_and_query_bytea() { - require_pg!(); - let params = pg_params(); - - // The driver expects blob data in the wire format: "BLOB:::" - // 4 bytes (0xCA 0xFE 0xBA 0xBE) encoded as base64 = "yv66vg==" - let blob_wire = "BLOB:4:application/octet-stream:yv66vg=="; - - let mut data = HashMap::new(); - data.insert("col_bytea".to_string(), json!(blob_wire)); - data.insert("col_text".to_string(), json!("blob_test")); - - let affected = postgres::insert_record(¶ms, "all_types", data, "test_schema", 10_000_000) - .await - .expect("insert bytea should succeed"); - - assert_eq!(affected, 1); - - // Verify the data comes back - let result = postgres::execute_query( - ¶ms, - "SELECT col_bytea FROM test_schema.all_types WHERE col_text = 'blob_test'", - None, - 1, - None, - ) - .await - .expect("query bytea should succeed"); - - assert_eq!(result.rows.len(), 1); - assert!(!result.rows[0][0].is_null(), "bytea should not be null"); - - // Clean up - let _ = postgres::execute_query( - ¶ms, - "DELETE FROM test_schema.all_types WHERE col_text = 'blob_test'", - None, - 1, - None, - ) - .await; -} - -#[tokio::test] -#[ignore] -async fn test_save_blob_to_file() { - require_pg!(); - let params = pg_params(); - - // Use the seeded row (id=1) which has col_bytea = '\xDEADBEEF' - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), json!(1)); - - let tmp_path = std::env::temp_dir().join("tabularis_blob_test.bin"); - let path_str = tmp_path.to_str().unwrap(); - - let result = postgres::save_blob_column_to_file( - ¶ms, - "all_types", - "col_bytea", - &pk_map, - "test_schema", - path_str, - ) - .await; - - assert!( - result.is_ok(), - "save_blob_to_file should succeed: {:?}", - result.err() - ); - - // Verify file was written and has content - let metadata = std::fs::metadata(&tmp_path); - assert!(metadata.is_ok(), "File should exist"); - assert!(metadata.unwrap().len() > 0, "File should have content"); - - // Clean up - let _ = std::fs::remove_file(&tmp_path); -} - -#[tokio::test] -#[ignore] -async fn test_fetch_blob_as_data_url() { - require_pg!(); - let params = pg_params(); - - // Use the seeded row (id=1) which has col_bytea = '\xDEADBEEF' - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), json!(1)); - - let result = postgres::fetch_blob_column_as_data_url( - ¶ms, - "all_types", - "col_bytea", - &pk_map, - "test_schema", - ) - .await; - - assert!( - result.is_ok(), - "fetch_blob_as_data_url should succeed: {:?}", - result.err() - ); - - let data_url = result.unwrap(); - // Should be in BLOB wire format: "BLOB:::" - assert!( - data_url.starts_with("BLOB:") || data_url.starts_with("data:"), - "Should return BLOB wire format or data URL, got: {}", - &data_url[..data_url.len().min(50)] - ); -} diff --git a/src-tauri/tests/postgres_integration/column_comments.rs b/src-tauri/tests/postgres_integration/column_comments.rs deleted file mode 100644 index a97074b3a..000000000 --- a/src-tauri/tests/postgres_integration/column_comments.rs +++ /dev/null @@ -1,142 +0,0 @@ -use crate::helpers::pg_params; -use futures::FutureExt; -use tabularis_lib::drivers::driver_trait::DatabaseDriver; -use tabularis_lib::drivers::postgres::{self, PostgresDriver}; -use tabularis_lib::models::ColumnDefinition; - -#[tokio::test] -#[ignore] -async fn column_comments_round_trip_without_changing_defaults_or_constraints() { - require_pg!(); - let params = pg_params(); - let driver = PostgresDriver::new(); - let schema = format!("comment_test_{}", uuid::Uuid::new_v4().simple()); - postgres::execute_query( - ¶ms, - &format!("CREATE SCHEMA \"{schema}\""), - None, - 1, - None, - ) - .await - .unwrap(); - let outcome = std::panic::AssertUnwindSafe(async { - postgres::execute_query( - ¶ms, - &format!("CREATE TABLE \"{schema}\".customers (id SERIAL PRIMARY KEY, email VARCHAR(255) NOT NULL DEFAULT 'unknown', UNIQUE (email))"), - None, 1, None, - ).await.unwrap(); - - let old = ColumnDefinition { - name: "email".into(), - data_type: "VARCHAR(255)".into(), - is_nullable: false, - is_pk: false, - is_auto_increment: false, - default_value: Some("'unknown'::character varying".into()), - comment: None, - on_update: None, - }; - let before_columns = postgres::get_columns(¶ms, "customers", &schema) - .await - .unwrap(); - let before_indexes = postgres::get_indexes(¶ms, "customers", &schema) - .await - .unwrap(); - let mut previous = old.clone(); - for text in [ - Some(" Customer's email\\path\n日本語 "), - Some("replacement"), - None, - ] { - let new = ColumnDefinition { - comment: text.map(str::to_string), - ..old.clone() - }; - let statements = driver - .get_alter_column_sql("customers", previous, new.clone(), Some(&schema)) - .await - .unwrap(); - assert_eq!(statements.len(), 1); - for sql in statements { - postgres::execute_query(¶ms, &sql, None, 1, Some(&schema)) - .await - .unwrap(); - } - let mut after = postgres::get_columns(¶ms, "customers", &schema) - .await - .unwrap(); - assert_eq!( - after - .iter() - .find(|c| c.name == "email") - .unwrap() - .comment - .as_deref(), - text - ); - // Compare all other metadata with the original, using the same serialization. - after.iter_mut().find(|c| c.name == "email").unwrap().comment = None; - assert_eq!( - serde_json::to_value(&after).unwrap(), - serde_json::to_value(&before_columns).unwrap() - ); - assert_eq!( - serde_json::to_value( - postgres::get_indexes(¶ms, "customers", &schema) - .await - .unwrap() - ) - .unwrap(), - serde_json::to_value(&before_indexes).unwrap() - ); - previous = new; - } - - let added = ColumnDefinition { - name: "notes".into(), - data_type: "TEXT".into(), - is_nullable: true, - default_value: None, - comment: Some("New column's note".into()), - ..old - }; - for sql in driver - .get_add_column_sql("customers", added, Some(&schema)) - .await - .unwrap() - { - postgres::execute_query(¶ms, &sql, None, 1, Some(&schema)) - .await - .unwrap(); - } - let columns = postgres::get_columns(¶ms, "customers", &schema) - .await - .unwrap(); - assert_eq!( - columns - .iter() - .find(|c| c.name == "notes") - .unwrap() - .comment - .as_deref(), - Some("New column's note") - ); - }) - .catch_unwind() - .await; - - // A failed assertion must not leave a schema that breaks later golden tests. - postgres::execute_query( - ¶ms, - &format!("DROP SCHEMA \"{schema}\" CASCADE"), - None, - 1, - None, - ) - .await - .unwrap(); - if let Err(panic) = outcome { - std::panic::resume_unwind(panic); - } -} diff --git a/src-tauri/tests/postgres_integration/column_metadata.rs b/src-tauri/tests/postgres_integration/column_metadata.rs deleted file mode 100644 index d0cf68860..000000000 --- a/src-tauri/tests/postgres_integration/column_metadata.rs +++ /dev/null @@ -1,205 +0,0 @@ -//! Column metadata tests: get_columns for various table types. - -use crate::helpers::pg_params; -use tabularis_lib::drivers::postgres; - -#[tokio::test] -#[ignore] -async fn test_get_columns_all_types_count() { - require_pg!(); - let params = pg_params(); - - let columns = postgres::get_columns(¶ms, "all_types", "test_schema") - .await - .expect("get_columns should succeed"); - - // all_types has 27 columns (id + 26 typed columns) - assert_eq!(columns.len(), 27, "Expected 27 columns in all_types"); -} - -#[tokio::test] -#[ignore] -async fn test_get_columns_pk_detection() { - require_pg!(); - let params = pg_params(); - - let columns = postgres::get_columns(¶ms, "all_types", "test_schema") - .await - .expect("get_columns should succeed"); - - let id_col = columns - .iter() - .find(|c| c.name == "id") - .expect("id column should exist"); - assert!(id_col.is_pk, "id should be primary key"); - assert!( - id_col.is_auto_increment, - "SERIAL id should be auto_increment" - ); - assert_eq!(id_col.data_type, "integer", "SERIAL resolves to integer"); - - // Non-PK columns should not be marked as PK - let text_col = columns.iter().find(|c| c.name == "col_text").unwrap(); - assert!(!text_col.is_pk); - assert!(!text_col.is_auto_increment); -} - -#[tokio::test] -#[ignore] -async fn test_table_and_column_comments() { - require_pg!(); - let params = pg_params(); - - let tables = postgres::get_tables(¶ms, "test_schema") - .await - .expect("get_tables should succeed"); - let table = tables - .iter() - .find(|table| table.name == "all_types") - .expect("all_types table should exist"); - assert_eq!( - table.comment.as_deref(), - Some("PostgreSQL metadata integration fixture") - ); - - let columns = postgres::get_columns(¶ms, "all_types", "test_schema") - .await - .expect("get_columns should succeed"); - let text_column = columns - .iter() - .find(|column| column.name == "col_text") - .expect("col_text column should exist"); - assert_eq!( - text_column.comment.as_deref(), - Some("Free-form text used by metadata tests") - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_columns_nullable_detection() { - require_pg!(); - let params = pg_params(); - - let columns = postgres::get_columns(¶ms, "all_types", "test_schema") - .await - .expect("get_columns should succeed"); - - // id (SERIAL PRIMARY KEY) is NOT NULL - let id_col = columns.iter().find(|c| c.name == "id").unwrap(); - assert!(!id_col.is_nullable, "PK should not be nullable"); - - // col_text has no NOT NULL constraint - let text_col = columns.iter().find(|c| c.name == "col_text").unwrap(); - assert!(text_col.is_nullable, "col_text should be nullable"); -} - -#[tokio::test] -#[ignore] -async fn test_get_columns_type_detection() { - require_pg!(); - let params = pg_params(); - - let columns = postgres::get_columns(¶ms, "all_types", "test_schema") - .await - .expect("get_columns should succeed"); - - let find = |name: &str| columns.iter().find(|c| c.name == name).unwrap(); - - assert_eq!(find("col_text").data_type, "text"); - assert_eq!(find("col_int").data_type, "integer"); - assert_eq!(find("col_bigint").data_type, "bigint"); - assert_eq!(find("col_bool").data_type, "boolean"); - assert_eq!(find("col_uuid").data_type, "uuid"); - assert_eq!(find("col_jsonb").data_type, "jsonb"); - assert_eq!(find("col_bytea").data_type, "bytea"); - assert_eq!( - find("col_timestamptz").data_type, - "timestamp with time zone" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_columns_character_max_length() { - require_pg!(); - let params = pg_params(); - - let columns = postgres::get_columns(¶ms, "all_types", "test_schema") - .await - .expect("get_columns should succeed"); - - let varchar_col = columns.iter().find(|c| c.name == "col_varchar").unwrap(); - assert_eq!( - varchar_col.character_maximum_length, - Some(255), - "PG driver returns character_maximum_length for varchar(n)" - ); - - let text_col = columns.iter().find(|c| c.name == "col_text").unwrap(); - assert_eq!( - text_col.character_maximum_length, None, - "TEXT has no max length" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_columns_enum_type() { - require_pg!(); - let params = pg_params(); - - let columns = postgres::get_columns(¶ms, "with_enum", "test_schema") - .await - .expect("get_columns should succeed"); - - let mood_col = columns.iter().find(|c| c.name == "current_mood").unwrap(); - // The PG driver resolves enum types to "enum('val1','val2',...)" format - assert!( - mood_col.data_type.contains("mood") - || mood_col.data_type.starts_with("enum(") - || mood_col.data_type == "USER-DEFINED", - "Enum column should have type containing 'mood', start with 'enum(', or be 'USER-DEFINED', got: {}", - mood_col.data_type - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_columns_full_type() { - require_pg!(); - let params = pg_params(); - - let columns = postgres::get_columns(¶ms, "all_types", "test_schema") - .await - .expect("get_columns should succeed"); - let full_type = |name: &str| { - let column = columns - .iter() - .find(|c| c.name == name) - .unwrap_or_else(|| panic!("{name} column should exist")); - (column.data_type.as_str(), column.full_type.as_deref()) - }; - - // `data_type` keeps the base name; `full_type` is `format_type(...)` when - // it says more (#1277). - assert_eq!( - full_type("col_varchar"), - ("character varying", Some("character varying(255)")) - ); - assert_eq!(full_type("col_numeric"), ("numeric", Some("numeric(10,2)"))); - assert_eq!(full_type("col_int_array"), ("ARRAY", Some("integer[]"))); - assert_eq!(full_type("col_text"), ("text", None)); - assert_eq!(full_type("col_int"), ("integer", None)); - - // Enums keep their values in `data_type` and get no full type. - let enum_columns = postgres::get_columns(¶ms, "with_enum", "test_schema") - .await - .expect("get_columns should succeed"); - let mood = enum_columns - .iter() - .find(|c| c.name == "current_mood") - .unwrap(); - assert!(mood.data_type.starts_with("enum("), "{}", mood.data_type); - assert_eq!(mood.full_type, None); -} diff --git a/src-tauri/tests/postgres_integration/crud.rs b/src-tauri/tests/postgres_integration/crud.rs deleted file mode 100644 index 2ce305cb3..000000000 --- a/src-tauri/tests/postgres_integration/crud.rs +++ /dev/null @@ -1,319 +0,0 @@ -//! CRUD operation tests (insert, update, delete). - -use crate::helpers::pg_params; -use serde_json::json; -use std::collections::HashMap; -use tabularis_lib::drivers::postgres; - -#[tokio::test] -#[ignore] -async fn test_insert_basic_types() { - require_pg!(); - let params = pg_params(); - - let mut data = HashMap::new(); - data.insert("name".to_string(), json!("insert_test")); - data.insert("value".to_string(), json!(42)); - - let affected = - postgres::insert_record(¶ms, "crud_scratch", data, "test_schema", 10_000_000) - .await - .expect("insert_record should succeed"); - - assert_eq!(affected, 1); - - // Cleanup - let _ = postgres::execute_query( - ¶ms, - "DELETE FROM test_schema.crud_scratch WHERE name = 'insert_test'", - None, - 1, - None, - ) - .await; -} - -#[tokio::test] -#[ignore] -async fn test_insert_null_values() { - require_pg!(); - let params = pg_params(); - - let mut data = HashMap::new(); - data.insert("name".to_string(), json!(null)); - data.insert("value".to_string(), json!(null)); - - let affected = - postgres::insert_record(¶ms, "crud_scratch", data, "test_schema", 10_000_000) - .await - .expect("insert_record with nulls should succeed"); - - assert_eq!(affected, 1); - - // Cleanup — delete rows with null name (our insert) - let _ = postgres::execute_query( - ¶ms, - "DELETE FROM test_schema.crud_scratch WHERE name IS NULL", - None, - 1, - None, - ) - .await; -} - -#[tokio::test] -#[ignore] -async fn test_update_with_single_pk() { - require_pg!(); - let params = pg_params(); - - // Insert a row to update - let mut insert_data = HashMap::new(); - insert_data.insert("name".to_string(), json!("to_update")); - insert_data.insert("value".to_string(), json!(1)); - postgres::insert_record( - ¶ms, - "crud_scratch", - insert_data, - "test_schema", - 10_000_000, - ) - .await - .expect("insert for update test"); - - // Find the row's ID - let result = postgres::execute_query( - ¶ms, - "SELECT id FROM test_schema.crud_scratch WHERE name = 'to_update' ORDER BY id DESC LIMIT 1", - None, - 1, - None, - ) - .await - .expect("find row"); - let row_id = result.rows[0][0].as_i64().unwrap(); - - // Update it (update_record updates one column at a time) - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), json!(row_id)); - - let affected = postgres::update_record( - ¶ms, - "crud_scratch", - &pk_map, - "value", - json!(999), - "test_schema", - 10_000_000, - ) - .await - .expect("update_record should succeed"); - - assert_eq!(affected, 1); - - // Verify the update took effect - let verify = postgres::execute_query( - ¶ms, - &format!( - "SELECT value FROM test_schema.crud_scratch WHERE id = {}", - row_id - ), - None, - 1, - None, - ) - .await - .unwrap(); - assert_eq!(verify.rows[0][0], json!(999)); -} - -#[tokio::test] -#[ignore] -async fn test_update_composite_pk() { - require_pg!(); - let params = pg_params(); - - // order_items has composite PK (order_id, item_no) - let mut pk_map = HashMap::new(); - pk_map.insert("order_id".to_string(), json!(1)); - pk_map.insert("item_no".to_string(), json!(1)); - - let affected = postgres::update_record( - ¶ms, - "order_items", - &pk_map, - "product", - json!("Updated Widget"), - "test_schema", - 10_000_000, - ) - .await - .expect("update_record with composite PK should succeed"); - - assert_eq!(affected, 1); - - // Restore original value - let _ = postgres::update_record( - ¶ms, - "order_items", - &pk_map, - "product", - json!("Widget"), - "test_schema", - 10_000_000, - ) - .await; -} - -#[tokio::test] -#[ignore] -async fn test_delete_single_pk() { - require_pg!(); - let params = pg_params(); - - // Insert a row to delete - let mut data = HashMap::new(); - data.insert("name".to_string(), json!("to_delete")); - data.insert("value".to_string(), json!(0)); - postgres::insert_record(¶ms, "crud_scratch", data, "test_schema", 10_000_000) - .await - .expect("insert for delete test"); - - // Find the row - let result = postgres::execute_query( - ¶ms, - "SELECT id FROM test_schema.crud_scratch WHERE name = 'to_delete' ORDER BY id DESC LIMIT 1", - None, - 1, - None, - ) - .await - .unwrap(); - let row_id = result.rows[0][0].as_i64().unwrap(); - - // Delete it - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), json!(row_id)); - - let affected = postgres::delete_record(¶ms, "crud_scratch", &pk_map, "test_schema") - .await - .expect("delete_record should succeed"); - - assert_eq!(affected, 1); - - // Verify gone - let verify = postgres::execute_query( - ¶ms, - &format!( - "SELECT COUNT(*) FROM test_schema.crud_scratch WHERE id = {}", - row_id - ), - None, - 1, - None, - ) - .await - .unwrap(); - assert_eq!(verify.rows[0][0], json!(0_i64)); -} - -#[tokio::test] -#[ignore] -async fn test_insert_json_object() { - require_pg!(); - let params = pg_params(); - - let mut data = HashMap::new(); - data.insert( - "col_jsonb".to_string(), - json!({"nested": {"key": "value"}, "arr": [1, 2, 3]}), - ); - data.insert("col_text".to_string(), json!("json_test")); - - let affected = postgres::insert_record(¶ms, "all_types", data, "test_schema", 10_000_000) - .await - .expect("insert JSON object should succeed"); - - assert_eq!(affected, 1); - - // Clean up - let _ = postgres::execute_query( - ¶ms, - "DELETE FROM test_schema.all_types WHERE col_text = 'json_test'", - None, - 1, - None, - ) - .await; -} - -#[tokio::test] -#[ignore] -async fn test_insert_array_value() { - require_pg!(); - let params = pg_params(); - - let mut data = HashMap::new(); - data.insert("col_int_array".to_string(), json!([10, 20, 30])); - data.insert("col_text".to_string(), json!("array_test")); - - let affected = postgres::insert_record(¶ms, "all_types", data, "test_schema", 10_000_000) - .await - .expect("insert array value should succeed"); - - assert_eq!(affected, 1); - - // Verify round-trip - let result = postgres::execute_query( - ¶ms, - "SELECT col_int_array FROM test_schema.all_types WHERE col_text = 'array_test'", - None, - 1, - None, - ) - .await - .unwrap(); - - assert_eq!(result.rows.len(), 1); - assert!( - result.rows[0][0].is_array(), - "Expected array, got: {:?}", - result.rows[0][0] - ); - - // Clean up - let _ = postgres::execute_query( - ¶ms, - "DELETE FROM test_schema.all_types WHERE col_text = 'array_test'", - None, - 1, - None, - ) - .await; -} - -#[tokio::test] -#[ignore] -async fn test_insert_enum_value() { - require_pg!(); - let params = pg_params(); - - let mut data = HashMap::new(); - data.insert("current_mood".to_string(), json!("sad")); - - let affected = postgres::insert_record(¶ms, "with_enum", data, "test_schema", 10_000_000) - .await - .expect("insert enum value should succeed"); - - assert_eq!(affected, 1); - - // Clean up the extra row - let _ = postgres::execute_query( - ¶ms, - "DELETE FROM test_schema.with_enum WHERE id > 1", - None, - 1, - None, - ) - .await; -} diff --git a/src-tauri/tests/postgres_integration/ddl_generation.rs b/src-tauri/tests/postgres_integration/ddl_generation.rs deleted file mode 100644 index c2e768c57..000000000 --- a/src-tauri/tests/postgres_integration/ddl_generation.rs +++ /dev/null @@ -1,285 +0,0 @@ -//! DDL generation tests. - -use crate::helpers::pg_params; -use tabularis_lib::drivers::driver_trait::DatabaseDriver; -use tabularis_lib::drivers::postgres::PostgresDriver; -use tabularis_lib::models::ColumnDefinition; - -#[tokio::test] -#[ignore] -async fn test_get_create_table_sql() { - require_pg!(); - let _params = pg_params(); - - let columns = vec![ - ColumnDefinition { - name: "id".to_string(), - data_type: "SERIAL".to_string(), - is_nullable: false, - is_pk: true, - is_auto_increment: true, - default_value: None, - comment: None, - on_update: None, - }, - ColumnDefinition { - name: "name".to_string(), - data_type: "TEXT".to_string(), - is_nullable: false, - is_pk: false, - is_auto_increment: false, - default_value: None, - comment: None, - on_update: None, - }, - ColumnDefinition { - name: "email".to_string(), - data_type: "VARCHAR(255)".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: Some("'unknown@example.com'".to_string()), - comment: None, - on_update: None, - }, - ]; - - let sql_statements = PostgresDriver::new() - .get_create_table_sql("ddl_test_table", columns, Some("test_schema")) - .await - .expect("get_create_table_sql should succeed"); - - assert!( - !sql_statements.is_empty(), - "Should return at least one SQL statement" - ); - let sql = sql_statements.join("; "); - let lower = sql.to_lowercase(); - - assert!( - lower.contains("create table"), - "Should contain CREATE TABLE" - ); - assert!( - lower.contains("ddl_test_table"), - "Should contain table name" - ); - assert!( - lower.contains("serial") || lower.contains("generated"), - "Should handle auto-increment" - ); - assert!( - lower.contains("not null"), - "Should contain NOT NULL for non-nullable columns" - ); - assert!( - lower.contains("varchar(255)") || lower.contains("character varying(255)"), - "Should preserve varchar type" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_add_column_sql() { - require_pg!(); - - let column = ColumnDefinition { - name: "new_col".to_string(), - data_type: "INTEGER".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: Some("0".to_string()), - comment: None, - on_update: None, - }; - - let sql_statements = PostgresDriver::new() - .get_add_column_sql("all_types", column, Some("test_schema")) - .await - .expect("get_add_column_sql should succeed"); - - assert!(!sql_statements.is_empty()); - let sql = sql_statements.join("; "); - let lower = sql.to_lowercase(); - - assert!(lower.contains("alter table"), "Should contain ALTER TABLE"); - assert!(lower.contains("add column"), "Should contain ADD COLUMN"); - assert!(lower.contains("new_col"), "Should contain column name"); - assert!(lower.contains("integer"), "Should contain type"); -} - -#[tokio::test] -#[ignore] -async fn test_get_alter_column_rename() { - require_pg!(); - - let old_column = ColumnDefinition { - name: "old_name".to_string(), - data_type: "TEXT".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: None, - comment: None, - on_update: None, - }; - - let new_column = ColumnDefinition { - name: "new_name".to_string(), - data_type: "TEXT".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: None, - comment: None, - on_update: None, - }; - - let sql_statements = PostgresDriver::new() - .get_alter_column_sql("all_types", old_column, new_column, Some("test_schema")) - .await - .expect("get_alter_column_sql for rename should succeed"); - - assert!(!sql_statements.is_empty()); - let sql = sql_statements.join("; "); - let lower = sql.to_lowercase(); - - assert!( - lower.contains("rename column") || lower.contains("alter column"), - "Should rename" - ); - assert!(lower.contains("old_name"), "Should reference old name"); - assert!(lower.contains("new_name"), "Should reference new name"); -} - -#[tokio::test] -#[ignore] -async fn test_get_alter_column_type_change() { - require_pg!(); - - let old_column = ColumnDefinition { - name: "col_text".to_string(), - data_type: "TEXT".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: None, - comment: None, - on_update: None, - }; - - let new_column = ColumnDefinition { - name: "col_text".to_string(), - data_type: "VARCHAR(500)".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: None, - comment: None, - on_update: None, - }; - - let sql_statements = PostgresDriver::new() - .get_alter_column_sql("all_types", old_column, new_column, Some("test_schema")) - .await - .expect("get_alter_column_sql for type change should succeed"); - - assert!(!sql_statements.is_empty()); - let sql = sql_statements.join("; "); - let lower = sql.to_lowercase(); - - assert!( - lower.contains("type") || lower.contains("alter column"), - "Should change type, got: {}", - sql - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_create_index_sql() { - require_pg!(); - - let sql_statements = PostgresDriver::new() - .get_create_index_sql( - "all_types", - "idx_ddl_test", - vec!["col_text".to_string(), "col_int".to_string()], - false, // not unique - Some("test_schema"), - ) - .await - .expect("get_create_index_sql should succeed"); - - assert!(!sql_statements.is_empty()); - let sql = sql_statements.join("; "); - let lower = sql.to_lowercase(); - - assert!( - lower.contains("create index"), - "Should contain CREATE INDEX" - ); - assert!(lower.contains("idx_ddl_test"), "Should contain index name"); - assert!(lower.contains("col_text"), "Should contain first column"); - assert!(lower.contains("col_int"), "Should contain second column"); -} - -#[tokio::test] -#[ignore] -async fn test_get_create_index_sql_unique() { - require_pg!(); - - let sql_statements = PostgresDriver::new() - .get_create_index_sql( - "all_types", - "idx_ddl_unique_test", - vec!["col_varchar".to_string()], - true, // unique - Some("test_schema"), - ) - .await - .expect("get_create_index_sql unique should succeed"); - - let sql = sql_statements.join("; "); - let lower = sql.to_lowercase(); - - assert!( - lower.contains("create unique index"), - "Should contain CREATE UNIQUE INDEX" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_create_foreign_key_sql() { - require_pg!(); - let params = pg_params(); - - let sql_statements = PostgresDriver::new() - .get_create_foreign_key_sql( - ¶ms, - "crud_scratch", - "fk_ddl_test", - "value", - "all_types", - "id", - None, - None, - Some("test_schema"), - ) - .await - .expect("get_create_foreign_key_sql should succeed"); - - assert!(!sql_statements.is_empty()); - let sql = sql_statements.join("; "); - let lower = sql.to_lowercase(); - - assert!(lower.contains("alter table"), "Should contain ALTER TABLE"); - assert!( - lower.contains("add constraint"), - "Should contain ADD CONSTRAINT" - ); - assert!(lower.contains("foreign key"), "Should contain FOREIGN KEY"); - assert!(lower.contains("references"), "Should contain REFERENCES"); -} diff --git a/src-tauri/tests/postgres_integration/dml_preview.rs b/src-tauri/tests/postgres_integration/dml_preview.rs deleted file mode 100644 index b5a1da5d2..000000000 --- a/src-tauri/tests/postgres_integration/dml_preview.rs +++ /dev/null @@ -1,388 +0,0 @@ -//! "Preview changes" for PostgreSQL UPDATE and DELETE (issue #1404): each -//! test previews a statement in its own schema and checks the table was not -//! written. - -use crate::helpers::pg_params; -use std::sync::Arc; -use tabularis_lib::application::dml_preview::{ - preview_with_driver, DmlKind, DmlPreview, DmlPreviewRequest, -}; -use tabularis_lib::drivers::driver_trait::DatabaseDriver; -use tabularis_lib::drivers::postgres::PostgresDriver; -use tabularis_lib::models::ConnectionParams; -use uuid::Uuid; - -fn ident(name: &str) -> String { - format!("\"{}\"", name.replace('"', "\"\"")) -} - -struct LiveHarness { - driver: Arc, - params: ConnectionParams, - schema: String, -} - -impl LiveHarness { - async fn setup() -> Option { - if !crate::helpers::wait_for_pg().await { - eprintln!("SKIPPING: PostgreSQL not available on port 54320"); - return None; - } - let params = pg_params(); - let driver: Arc = Arc::new(PostgresDriver::new()); - let schema = format!("dmlp_1404_{}", Uuid::new_v4().simple()); - let harness = Self { - driver, - params, - schema, - }; - harness - .exec(&format!( - "CREATE SCHEMA {} AUTHORIZATION CURRENT_USER", - ident(&harness.schema) - )) - .await - .expect("create test schema"); - Some(harness) - } - - async fn exec(&self, sql: &str) -> Result<(), String> { - self.driver - .execute_query(&self.params, sql, None, 1, Some(self.schema.as_str())) - .await - .map(|_| ()) - } - - async fn query_scalar(&self, sql: &str) -> Result { - let result = self - .driver - .execute_query(&self.params, sql, None, 1, Some(self.schema.as_str())) - .await?; - let value = result - .rows - .first() - .and_then(|row| row.first()) - .cloned() - .unwrap_or(serde_json::Value::Null); - Ok(match value { - serde_json::Value::String(s) => s, - other => other.to_string(), - }) - } - - async fn preview(&self, sql: &str, limit: Option) -> Result { - preview_with_driver( - self.driver.as_ref(), - &self.params, - DmlPreviewRequest { - connection_id: "live-pg".into(), - sql: sql.to_string(), - schema: Some(self.schema.clone()), - database: None, - limit, - }, - ) - .await - } - - async fn teardown(&self) { - let sql = format!("DROP SCHEMA IF EXISTS {} CASCADE", ident(&self.schema)); - if let Err(error) = self - .driver - .execute_query(&self.params, &sql, None, 1, None) - .await - { - eprintln!("failed to drop test schema {}: {error}", self.schema); - } - } -} - -macro_rules! live_test { - ($name:ident, $h:ident, $($body:tt)*) => { - #[tokio::test] - #[ignore] - async fn $name() { - let Some($h) = LiveHarness::setup().await else { - return; - }; - let body = async { - $($body)* - }; - body.await; - $h.teardown().await; - } - }; -} - -live_test!(test_dml_preview_update_preview_shows_current_and_proposed_values, h, - h.exec(&format!( - "CREATE TABLE {}.orders (id int PRIMARY KEY, status text, total numeric(10,2), note text, \"My Col\" text)", - ident(&h.schema) - )) - .await - .unwrap(); - h.exec(&format!( - "INSERT INTO {}.orders VALUES (1, 'open', 10.50, NULL, 'x'), (2, 'void', 3, 'n', 'y')", - ident(&h.schema) - )) - .await - .unwrap(); - - let preview = h - .preview( - &format!( - "UPDATE {}.orders SET status = 'paid', note = COALESCE(note, 'none') WHERE id = 1", - ident(&h.schema) - ), - Some(10), - ) - .await - .expect("preview update"); - assert_eq!(preview.kind, DmlKind::Update); - assert!(preview.has_filter); - assert!(!preview.truncated); - assert_eq!( - preview.assigned_columns, - vec!["status".to_string(), "note".to_string()] - ); - assert_eq!(preview.result.rows.len(), 1); - assert_eq!(preview.result.rows[0][0], serde_json::json!("open")); - assert_eq!(preview.result.rows[0][1], serde_json::json!("paid")); - assert_eq!(preview.result.rows[0][2], serde_json::Value::Null); - assert_eq!(preview.result.rows[0][3], serde_json::json!("none")); - - let quoted = h - .preview( - &format!( - "UPDATE {}.orders SET \"My Col\" = upper(\"My Col\") WHERE \"My Col\" LIKE 'x%'", - ident(&h.schema) - ), - None, - ) - .await - .expect("preview quoted column"); - assert_eq!(quoted.assigned_columns, vec!["My Col".to_string()]); - assert_eq!(quoted.result.rows[0][0], serde_json::json!("x")); - assert_eq!(quoted.result.rows[0][1], serde_json::json!("X")); - - let rows = h - .query_scalar(&format!( - "SELECT status || ':' || coalesce(note, '') FROM {}.orders WHERE id = 1", - ident(&h.schema) - )) - .await - .unwrap(); - assert_eq!(rows, "open:", "preview must not write the table"); -); - -live_test!(test_dml_preview_delete_preview_and_truncation, h, - h.exec(&format!( - "CREATE TABLE {}.orders (id int PRIMARY KEY, status text)", - ident(&h.schema) - )) - .await - .unwrap(); - h.exec(&format!( - "INSERT INTO {}.orders VALUES (1, 'open'), (2, 'open'), (3, 'void')", - ident(&h.schema) - )) - .await - .unwrap(); - - let preview = h - .preview( - &format!( - "DELETE FROM {}.orders WHERE status <> 'void'", - ident(&h.schema) - ), - Some(1), - ) - .await - .expect("preview delete"); - assert_eq!(preview.kind, DmlKind::Delete); - assert!(preview.has_filter); - assert!(preview.truncated); - assert_eq!(preview.result.rows.len(), 1); - assert_eq!(preview.limit, 1); - - let unfiltered = h - .preview(&format!("DELETE FROM {}.orders", ident(&h.schema)), Some(10)) - .await - .expect("preview unfiltered delete"); - assert!(!unfiltered.has_filter); - assert_eq!(unfiltered.result.rows.len(), 3); -); - -live_test!(test_dml_preview_rejects_unsupported_syntax_and_side_effects, h, - h.exec(&format!( - "CREATE TABLE {}.orders (id int PRIMARY KEY, status text)", - ident(&h.schema) - )) - .await - .unwrap(); - h.exec(&format!( - "CREATE TABLE {}.calls (n int)", - ident(&h.schema) - )) - .await - .unwrap(); - h.exec(&format!( - "CREATE FUNCTION bump(a text, b text) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN INSERT INTO {}.calls VALUES (1); RETURN a = b; END $$", - ident(&h.schema) - )) - .await - .unwrap(); - - let err = h - .preview( - &format!( - "UPDATE {}.orders SET status = nextval('seq')", - ident(&h.schema) - ), - None, - ) - .await - .expect_err("nextval must be rejected"); - assert!( - err.to_lowercase().contains("nextval"), - "unexpected rejection: {err}" - ); - - let side = h - .preview( - &format!( - "UPDATE {}.orders SET status = 'x' WHERE bump(status, 'open')", - ident(&h.schema) - ), - None, - ) - .await - .expect_err("user function must be rejected"); - assert!( - side.to_lowercase().contains("bump"), - "unexpected rejection: {side}" - ); - let count = h - .query_scalar(&format!( - "SELECT count(*)::text FROM {}.calls", - ident(&h.schema) - )) - .await - .unwrap(); - assert_eq!(count, "0", "rejected preview must not run the function"); -); - -live_test!(test_dml_preview_rejects_views_and_reports_triggers, h, - h.exec(&format!( - "CREATE TABLE {}.orders (id int PRIMARY KEY, status text)", - ident(&h.schema) - )) - .await - .unwrap(); - h.exec(&format!( - "INSERT INTO {}.orders VALUES (1, 'open')", - ident(&h.schema) - )) - .await - .unwrap(); - h.exec(&format!( - "CREATE VIEW {}.orders_v AS SELECT * FROM {}.orders", - ident(&h.schema), - ident(&h.schema) - )) - .await - .unwrap(); - h.exec(&format!( - "CREATE FUNCTION {}.touch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NEW; END $$", - ident(&h.schema) - )) - .await - .unwrap(); - h.exec(&format!( - "CREATE TRIGGER orders_touch BEFORE UPDATE ON {}.orders FOR EACH ROW EXECUTE PROCEDURE {}.touch()", - ident(&h.schema), - ident(&h.schema) - )) - .await - .unwrap(); - - let view_err = h - .preview( - &format!( - "UPDATE {}.orders_v SET status = 'paid' WHERE id = 1", - ident(&h.schema) - ), - None, - ) - .await - .expect_err("views must be rejected"); - assert!( - view_err.to_lowercase().contains("view"), - "unexpected rejection: {view_err}" - ); - - let preview = h - .preview( - &format!( - "UPDATE {}.orders SET status = 'paid' WHERE id = 1", - ident(&h.schema) - ), - None, - ) - .await - .expect("preview table with trigger"); - assert!( - preview.triggers >= 1, - "expected trigger count, got {}", - preview.triggers - ); -); - -live_test!(test_dml_preview_rejects_columns_whose_type_has_its_own_operators, h, - h.exec("CREATE EXTENSION IF NOT EXISTS citext").await.unwrap(); - let ext = h - .query_scalar("SELECT extnamespace::regnamespace::text FROM pg_extension WHERE extname = 'citext'") - .await - .unwrap(); - let s = ident(&h.schema); - for sql in [ - "CREATE TYPE {s}.mood AS ENUM ('ok', 'sad')", - "CREATE DOMAIN {s}.ci AS {ext}.citext", - "CREATE DOMAIN {s}.pos AS int CHECK (VALUE > 0)", - "CREATE TABLE {s}.users (id {s}.pos, email {ext}.citext, alias {s}.ci, tags {ext}.citext[], \ - mood {s}.mood, name text)", - "INSERT INTO {s}.users VALUES (1, 'alice@example.com', 'a', '{x}', 'ok', 'n'), \ - (2, 'ALICE@EXAMPLE.COM', 'b', '{y}', 'sad', 'm')", - ] { - h.exec(&sql.replace("{s}", &s).replace("{ext}", &ext)) - .await - .unwrap(); - } - - for (sql, column) in [ - ("DELETE FROM {s}.users WHERE email = 'Alice@Example.com'", "email ("), - ("DELETE FROM {s}.users WHERE alias LIKE 'A%'", "alias ("), - ("UPDATE {s}.users SET name = 'x' WHERE tags = '{X}'", "tags ("), - ("UPDATE {s}.users SET email = 'x' WHERE id = 1", "email ("), - ] { - let error = h - .preview(&sql.replace("{s}", &s), None) - .await - .expect_err(sql); - assert!(error.contains(column), "{sql}: {error}"); - } - - let allowed = h - .preview( - &format!("DELETE FROM {s}.users WHERE mood = 'ok' AND id > 0 AND name = 'n'"), - None, - ) - .await - .expect("enum, domain over int and text columns are previewed"); - assert_eq!(allowed.result.rows.len(), 1); - let count = h - .query_scalar(&format!("SELECT count(*) FROM {s}.users")) - .await - .unwrap(); - assert_eq!(count, "2", "preview must not write the table"); -); diff --git a/src-tauri/tests/postgres_integration/explain.rs b/src-tauri/tests/postgres_integration/explain.rs deleted file mode 100644 index 337a108c2..000000000 --- a/src-tauri/tests/postgres_integration/explain.rs +++ /dev/null @@ -1,88 +0,0 @@ -//! EXPLAIN query plan tests. - -use crate::helpers::pg_params; -use tabularis_lib::drivers::driver_trait::DatabaseDriver; -use tabularis_lib::drivers::postgres::PostgresDriver; -use tabularis_lib::models::ExplainQueryOutput; - -#[tokio::test] -#[ignore] -async fn test_explain_simple_select() { - require_pg!(); - let params = pg_params(); - - let output = PostgresDriver::new() - .explain_query( - ¶ms, - "SELECT * FROM test_schema.all_types WHERE id = 1", - false, - Some("test_schema"), - ) - .await - .expect("explain_query should succeed"); - - match &output { - ExplainQueryOutput::Plan { plan } => { - assert!(!plan.is_null(), "Plan should not be null"); - } - ExplainQueryOutput::Raw { raw } => { - assert!(!raw.payload.is_empty(), "Raw output should have lines"); - } - } -} - -#[tokio::test] -#[ignore] -async fn test_explain_analyze() { - require_pg!(); - let params = pg_params(); - - let output = PostgresDriver::new() - .explain_query( - ¶ms, - "SELECT * FROM test_schema.all_types WHERE id = 1", - true, - Some("test_schema"), - ) - .await - .expect("explain_query with analyze should succeed"); - - match &output { - ExplainQueryOutput::Plan { plan } => { - assert!(!plan.is_null(), "ANALYZE plan should not be null"); - } - ExplainQueryOutput::Raw { raw } => { - assert!( - !raw.payload.is_empty(), - "ANALYZE raw output should have lines" - ); - } - } -} - -#[tokio::test] -#[ignore] -async fn test_explain_join_query() { - require_pg!(); - let params = pg_params(); - - let output = PostgresDriver::new() - .explain_query( - ¶ms, - "SELECT o.id, oi.product FROM test_schema.orders o \ - JOIN test_schema.order_items oi ON o.id = oi.order_id", - false, - Some("test_schema"), - ) - .await - .expect("explain JOIN should succeed"); - - match &output { - ExplainQueryOutput::Plan { plan } => { - assert!(!plan.is_null(), "JOIN plan should not be null"); - } - ExplainQueryOutput::Raw { raw } => { - assert!(!raw.payload.is_empty(), "JOIN raw output should have lines"); - } - } -} diff --git a/src-tauri/tests/postgres_integration/foreign_keys.rs b/src-tauri/tests/postgres_integration/foreign_keys.rs deleted file mode 100644 index 5ab1d89e5..000000000 --- a/src-tauri/tests/postgres_integration/foreign_keys.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! Foreign key introspection tests. - -use crate::helpers::pg_params; -use tabularis_lib::drivers::postgres; - -#[tokio::test] -#[ignore] -async fn test_get_foreign_keys_basic() { - require_pg!(); - let params = pg_params(); - - let fks = postgres::get_foreign_keys(¶ms, "orders", "test_schema") - .await - .expect("get_foreign_keys should succeed"); - - assert!(!fks.is_empty(), "orders table should have foreign keys"); - - let user_fk = fks.iter().find(|f| f.column_name == "user_id"); - assert!(user_fk.is_some(), "Expected FK on user_id column"); - let user_fk = user_fk.unwrap(); - assert_eq!(user_fk.ref_table, "all_types"); - assert_eq!(user_fk.ref_column, "id"); - assert_eq!( - user_fk.on_delete.as_deref(), - Some("CASCADE"), - "Expected ON DELETE CASCADE" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_foreign_keys_composite_table() { - require_pg!(); - let params = pg_params(); - - let fks = postgres::get_foreign_keys(¶ms, "order_items", "test_schema") - .await - .expect("get_foreign_keys should succeed"); - - let order_fk = fks.iter().find(|f| f.column_name == "order_id"); - assert!(order_fk.is_some(), "Expected FK on order_id"); - let order_fk = order_fk.unwrap(); - assert_eq!(order_fk.ref_table, "orders"); - assert_eq!(order_fk.ref_column, "id"); - assert_eq!(order_fk.on_delete.as_deref(), Some("CASCADE")); -} - -#[tokio::test] -#[ignore] -async fn test_get_foreign_keys_cross_schema() { - require_pg!(); - let params = pg_params(); - - let fks = postgres::get_foreign_keys(¶ms, "with_cross_schema_fk", "test_schema") - .await - .expect("get_foreign_keys should succeed"); - - let lookup_fk = fks.iter().find(|f| f.column_name == "lookup_code"); - assert!(lookup_fk.is_some(), "Expected FK on lookup_code"); - let lookup_fk = lookup_fk.unwrap(); - assert_eq!(lookup_fk.ref_table, "lookup"); - assert_eq!(lookup_fk.ref_column, "code"); - assert_eq!(lookup_fk.ref_schema.as_deref(), Some("other_schema")); - - let batch = postgres::get_all_foreign_keys_batch(¶ms, "test_schema") - .await - .expect("get_all_foreign_keys_batch should succeed"); - let batch_fk = &batch["with_cross_schema_fk"][0]; - assert_eq!(batch_fk.ref_schema.as_deref(), Some("other_schema")); -} - -#[tokio::test] -#[ignore] -async fn test_get_foreign_keys_table_without_fks() { - require_pg!(); - let params = pg_params(); - - let fks = postgres::get_foreign_keys(¶ms, "crud_scratch", "test_schema") - .await - .expect("get_foreign_keys should succeed"); - - assert!(fks.is_empty(), "crud_scratch has no foreign keys"); -} diff --git a/src-tauri/tests/postgres_integration/golden.rs b/src-tauri/tests/postgres_integration/golden.rs deleted file mode 100644 index 7419c9b10..000000000 --- a/src-tauri/tests/postgres_integration/golden.rs +++ /dev/null @@ -1,367 +0,0 @@ -//! Golden file capture tests. -//! -//! These tests capture the exact output of every driver method and compare against -//! committed golden files. To regenerate: -//! -//! ```bash -//! REGENERATE_GOLDEN=1 cargo test --test postgres_integration golden -- --include-ignored --test-threads=1 -//! ``` - -use crate::golden_utils::{assert_golden, write_golden}; -use crate::helpers::{pg_params, pg_params_secondary}; -use tabularis_lib::drivers::driver_trait::DatabaseDriver; -use tabularis_lib::drivers::postgres; -use tabularis_lib::drivers::postgres::PostgresDriver; - -#[tokio::test] -#[ignore] -async fn golden_get_schemas() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_schemas(¶ms).await.expect("get_schemas"); - write_golden("get_schemas.json", &result); - assert_golden("get_schemas.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_databases() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_databases(¶ms) - .await - .expect("get_databases"); - write_golden("get_databases.json", &result); - assert_golden("get_databases.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_tables() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_tables(¶ms, "test_schema") - .await - .expect("get_tables"); - write_golden("get_tables.json", &result); - assert_golden("get_tables.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_columns_all_types() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_columns(¶ms, "all_types", "test_schema") - .await - .expect("get_columns"); - write_golden("get_columns_all_types.json", &result); - assert_golden("get_columns_all_types.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_columns_with_enum() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_columns(¶ms, "with_enum", "test_schema") - .await - .expect("get_columns"); - write_golden("get_columns_with_enum.json", &result); - assert_golden("get_columns_with_enum.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_indexes() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_indexes(¶ms, "all_types", "test_schema") - .await - .expect("get_indexes"); - write_golden("get_indexes_all_types.json", &result); - assert_golden("get_indexes_all_types.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_foreign_keys_orders() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_foreign_keys(¶ms, "orders", "test_schema") - .await - .expect("get_foreign_keys"); - write_golden("get_foreign_keys_orders.json", &result); - assert_golden("get_foreign_keys_orders.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_foreign_keys_cross_schema() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_foreign_keys(¶ms, "with_cross_schema_fk", "test_schema") - .await - .expect("get_foreign_keys"); - write_golden("get_foreign_keys_cross_schema.json", &result); - assert_golden("get_foreign_keys_cross_schema.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_views() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_views(¶ms, "test_schema") - .await - .expect("get_views"); - write_golden("get_views.json", &result); - assert_golden("get_views.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_view_definition() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_view_definition(¶ms, "active_users", "test_schema") - .await - .expect("get_view_definition"); - write_golden("get_view_definition_active_users.json", &result); - assert_golden("get_view_definition_active_users.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_materialized_views() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_materialized_views(¶ms, "test_schema") - .await - .expect("get_materialized_views"); - write_golden("get_materialized_views.json", &result); - assert_golden("get_materialized_views.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_routines() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_routines(¶ms, "test_schema") - .await - .expect("get_routines"); - write_golden("get_routines.json", &result); - assert_golden("get_routines.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_triggers() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_triggers(¶ms, "test_schema") - .await - .expect("get_triggers"); - write_golden("get_triggers.json", &result); - assert_golden("get_triggers.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_execute_query_all_types() { - require_pg!(); - let params = pg_params(); - let mut result = postgres::execute_query( - ¶ms, - "SELECT * FROM test_schema.all_types WHERE id = 1", - None, - 1, - None, - ) - .await - .expect("execute_query"); - result.server_time_ms = None; - result.fetch_time_ms = None; - write_golden("execute_query_all_types.json", &result); - assert_golden("execute_query_all_types.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_explain_simple() { - require_pg!(); - let params = pg_params(); - let result = PostgresDriver::new() - .explain_query( - ¶ms, - "SELECT * FROM test_schema.all_types WHERE id = 1", - false, - Some("test_schema"), - ) - .await - .expect("explain_query"); - // EXPLAIN output contains volatile cost/width values that change with table - // statistics, PG version, and row count. Write golden for documentation only; - // do NOT assert exact match. The structural assertions in explain.rs cover - // correctness. The plugin parity test should verify the output SHAPE matches - // (Plan vs Raw variant, key presence) rather than exact numeric values. - write_golden("explain_simple.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_multi_db_get_tables_secondary() { - require_pg!(); - let params = pg_params_secondary(); - let result = postgres::get_tables(¶ms, "secondary_schema") - .await - .expect("get_tables secondary"); - write_golden("multi_db/get_tables_secondary.json", &result); - assert_golden("multi_db/get_tables_secondary.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_multi_db_get_schemas_secondary() { - require_pg!(); - let params = pg_params_secondary(); - let result = postgres::get_schemas(¶ms) - .await - .expect("get_schemas secondary"); - write_golden("multi_db/get_schemas_secondary.json", &result); - assert_golden("multi_db/get_schemas_secondary.json", &result); -} - -// --- Missing golden captures below --- - -#[tokio::test] -#[ignore] -async fn golden_get_view_columns_active_users() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_view_columns(¶ms, "active_users", "test_schema") - .await - .expect("get_view_columns"); - write_golden("get_view_columns_active_users.json", &result); - assert_golden("get_view_columns_active_users.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_materialized_view_definition() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_materialized_view_definition(¶ms, "user_stats", "test_schema") - .await - .expect("get_materialized_view_definition"); - write_golden("get_mv_definition.json", &result); - assert_golden("get_mv_definition.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_materialized_view_columns() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_materialized_view_columns(¶ms, "user_stats", "test_schema") - .await - .expect("get_materialized_view_columns"); - write_golden("get_mv_columns.json", &result); - assert_golden("get_mv_columns.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_routine_parameters() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_routine_parameters(¶ms, "add_numbers", "test_schema", None) - .await - .expect("get_routine_parameters"); - write_golden("get_routine_parameters_add_numbers.json", &result); - assert_golden("get_routine_parameters_add_numbers.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_routine_definition() { - require_pg!(); - let params = pg_params(); - let result = - postgres::get_routine_definition(¶ms, "add_numbers", "FUNCTION", "test_schema", None) - .await - .expect("get_routine_definition"); - write_golden("get_routine_definition_add_numbers.json", &result); - assert_golden("get_routine_definition_add_numbers.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_get_trigger_definition() { - require_pg!(); - let params = pg_params(); - let result = postgres::get_trigger_definition(¶ms, "trg_audit", "all_types", "test_schema") - .await - .expect("get_trigger_definition"); - write_golden("get_trigger_definition_audit.json", &result); - assert_golden("get_trigger_definition_audit.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_execute_query_with_pagination() { - require_pg!(); - let params = pg_params(); - let mut result = postgres::execute_query( - ¶ms, - "SELECT id, col_text FROM test_schema.all_types ORDER BY id", - Some(2), - 1, - Some("test_schema"), - ) - .await - .expect("execute_query with pagination"); - result.server_time_ms = None; - result.fetch_time_ms = None; - write_golden("execute_query_with_pagination.json", &result); - assert_golden("execute_query_with_pagination.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_explain_analyze() { - require_pg!(); - let params = pg_params(); - let result = postgres::explain_query( - ¶ms, - "SELECT * FROM test_schema.all_types WHERE id = 1", - true, - Some("test_schema"), - ) - .await - .expect("explain_query with analyze"); - // EXPLAIN ANALYZE output contains volatile timing and buffer values. - // Write for documentation; do NOT assert exact match. - write_golden("explain_analyze.json", &result); -} - -#[tokio::test] -#[ignore] -async fn golden_count_query() { - require_pg!(); - let params = pg_params(); - let mut result = postgres::execute_query( - ¶ms, - "SELECT COUNT(*) AS cnt FROM test_schema.all_types", - None, - 1, - Some("test_schema"), - ) - .await - .expect("count query"); - result.server_time_ms = None; - result.fetch_time_ms = None; - write_golden("count_query.json", &result); - assert_golden("count_query.json", &result); -} diff --git a/src-tauri/tests/postgres_integration/golden/count_query.json b/src-tauri/tests/postgres_integration/golden/count_query.json deleted file mode 100644 index edd054a64..000000000 --- a/src-tauri/tests/postgres_integration/golden/count_query.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "columns": [ - "cnt" - ], - "rows": [ - [ - 2 - ] - ], - "affected_rows": 0, - "truncated": false, - "pagination": null -} diff --git a/src-tauri/tests/postgres_integration/golden/execute_query_all_types.json b/src-tauri/tests/postgres_integration/golden/execute_query_all_types.json deleted file mode 100644 index 5c5033859..000000000 --- a/src-tauri/tests/postgres_integration/golden/execute_query_all_types.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "columns": [ - "id", - "col_text", - "col_varchar", - "col_int", - "col_bigint", - "col_smallint", - "col_float", - "col_double", - "col_numeric", - "col_bool", - "col_date", - "col_time", - "col_timetz", - "col_timestamp", - "col_timestamptz", - "col_uuid", - "col_json", - "col_jsonb", - "col_bytea", - "col_inet", - "col_cidr", - "col_macaddr", - "col_int_array", - "col_text_array", - "col_int4range", - "col_tsrange", - "col_interval" - ], - "rows": [ - [ - 1, - "hello", - "world", - 42, - "9223372036854775807", - 32767, - 3.14, - 2.718281828459045, - "12345.67", - true, - "2026-01-15", - "14:30:00", - "14:30:00+02", - "2026-01-15 14:30:00", - "2026-01-15 14:30:00", - "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", - { - "key": "value" - }, - { - "nested": { - "arr": [ - 1, - 2, - 3 - ] - } - }, - "BLOB:4:application/octet-stream:3q2+7w==", - "192.168.1.1/32", - "10.0.0.0/8", - "08:00:2b:01:02:03", - [ - 1, - 2, - 3 - ], - [ - "a", - "b", - "c" - ], - "[1, 10)", - "[\"2026-01-01 00:00:00\", \"2026-12-31 00:00:00\")", - "1 year 2 months 3 days " - ] - ], - "affected_rows": 0, - "truncated": false, - "pagination": null -} diff --git a/src-tauri/tests/postgres_integration/golden/execute_query_with_pagination.json b/src-tauri/tests/postgres_integration/golden/execute_query_with_pagination.json deleted file mode 100644 index 4753b8b19..000000000 --- a/src-tauri/tests/postgres_integration/golden/execute_query_with_pagination.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "columns": [ - "id", - "col_text" - ], - "rows": [ - [ - 1, - "hello" - ], - [ - 2, - null - ] - ], - "affected_rows": 0, - "truncated": false, - "pagination": { - "page": 1, - "page_size": 2, - "total_rows": null, - "has_more": false - } -} diff --git a/src-tauri/tests/postgres_integration/golden/explain_analyze.json b/src-tauri/tests/postgres_integration/golden/explain_analyze.json deleted file mode 100644 index 455860907..000000000 --- a/src-tauri/tests/postgres_integration/golden/explain_analyze.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "kind": "raw", - "raw": { - "engine": "postgres", - "format": "postgres-json", - "payload": "[{\"Execution Time\":0.012,\"Plan\":{\"Actual Loops\":1,\"Actual Rows\":1,\"Actual Startup Time\":0.004,\"Actual Total Time\":0.005,\"Alias\":\"all_types\",\"Async Capable\":false,\"Filter\":\"(id = 1)\",\"Local Dirtied Blocks\":0,\"Local Hit Blocks\":0,\"Local Read Blocks\":0,\"Local Written Blocks\":0,\"Node Type\":\"Seq Scan\",\"Parallel Aware\":false,\"Plan Rows\":1,\"Plan Width\":961,\"Relation Name\":\"all_types\",\"Rows Removed by Filter\":1,\"Shared Dirtied Blocks\":0,\"Shared Hit Blocks\":1,\"Shared Read Blocks\":0,\"Shared Written Blocks\":0,\"Startup Cost\":0.0,\"Temp Read Blocks\":0,\"Temp Written Blocks\":0,\"Total Cost\":1.02},\"Planning\":{\"Local Dirtied Blocks\":0,\"Local Hit Blocks\":0,\"Local Read Blocks\":0,\"Local Written Blocks\":0,\"Shared Dirtied Blocks\":0,\"Shared Hit Blocks\":122,\"Shared Read Blocks\":0,\"Shared Written Blocks\":0,\"Temp Read Blocks\":0,\"Temp Written Blocks\":0},\"Planning Time\":0.125,\"Triggers\":[]}]", - "original_query": "SELECT * FROM test_schema.all_types WHERE id = 1" - } -} diff --git a/src-tauri/tests/postgres_integration/golden/explain_simple.json b/src-tauri/tests/postgres_integration/golden/explain_simple.json deleted file mode 100644 index 4fde85508..000000000 --- a/src-tauri/tests/postgres_integration/golden/explain_simple.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "kind": "raw", - "raw": { - "engine": "postgres", - "format": "postgres-json", - "payload": "[{\"Plan\":{\"Alias\":\"all_types\",\"Async Capable\":false,\"Filter\":\"(id = 1)\",\"Node Type\":\"Seq Scan\",\"Parallel Aware\":false,\"Plan Rows\":1,\"Plan Width\":961,\"Relation Name\":\"all_types\",\"Startup Cost\":0.0,\"Total Cost\":1.02}}]", - "original_query": "SELECT * FROM test_schema.all_types WHERE id = 1" - } -} diff --git a/src-tauri/tests/postgres_integration/golden/get_columns_all_types.json b/src-tauri/tests/postgres_integration/golden/get_columns_all_types.json deleted file mode 100644 index 5246b96c8..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_columns_all_types.json +++ /dev/null @@ -1,236 +0,0 @@ -[ - { - "name": "id", - "data_type": "integer", - "is_pk": true, - "is_nullable": false, - "is_auto_increment": true, - "is_generated": false, - "numeric_precision": 32, - "numeric_scale": 0 - }, - { - "name": "col_text", - "data_type": "text", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false, - "comment": "Free-form text used by metadata tests" - }, - { - "name": "col_varchar", - "data_type": "character varying", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false, - "character_maximum_length": 255, - "full_type": "character varying(255)" - }, - { - "name": "col_int", - "data_type": "integer", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false, - "numeric_precision": 32, - "numeric_scale": 0 - }, - { - "name": "col_bigint", - "data_type": "bigint", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false, - "numeric_precision": 64, - "numeric_scale": 0 - }, - { - "name": "col_smallint", - "data_type": "smallint", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false, - "numeric_precision": 16, - "numeric_scale": 0 - }, - { - "name": "col_float", - "data_type": "real", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false, - "numeric_precision": 24 - }, - { - "name": "col_double", - "data_type": "double precision", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false, - "numeric_precision": 53 - }, - { - "name": "col_numeric", - "data_type": "numeric", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false, - "numeric_precision": 10, - "numeric_scale": 2, - "full_type": "numeric(10,2)" - }, - { - "name": "col_bool", - "data_type": "boolean", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_date", - "data_type": "date", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_time", - "data_type": "time without time zone", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_timetz", - "data_type": "time with time zone", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_timestamp", - "data_type": "timestamp without time zone", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_timestamptz", - "data_type": "timestamp with time zone", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_uuid", - "data_type": "uuid", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_json", - "data_type": "json", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_jsonb", - "data_type": "jsonb", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_bytea", - "data_type": "bytea", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_inet", - "data_type": "inet", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_cidr", - "data_type": "cidr", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_macaddr", - "data_type": "macaddr", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_int_array", - "data_type": "ARRAY", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false, - "full_type": "integer[]" - }, - { - "name": "col_text_array", - "data_type": "ARRAY", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false, - "full_type": "text[]" - }, - { - "name": "col_int4range", - "data_type": "int4range", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_tsrange", - "data_type": "tsrange", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "col_interval", - "data_type": "interval", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_columns_with_enum.json b/src-tauri/tests/postgres_integration/golden/get_columns_with_enum.json deleted file mode 100644 index 4c5f7d0fd..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_columns_with_enum.json +++ /dev/null @@ -1,22 +0,0 @@ -[ - { - "name": "id", - "data_type": "integer", - "is_pk": true, - "is_nullable": false, - "is_auto_increment": true, - "is_generated": false, - "numeric_precision": 32, - "numeric_scale": 0 - }, - { - "name": "current_mood", - "data_type": "enum('happy','sad','neutral')", - "is_pk": false, - "is_nullable": false, - "is_auto_increment": false, - "is_generated": false, - "default_value": "'neutral'::test_schema.mood", - "default_sql": "'neutral'::test_schema.mood" - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_databases.json b/src-tauri/tests/postgres_integration/golden/get_databases.json deleted file mode 100644 index cb51bb6d2..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_databases.json +++ /dev/null @@ -1,5 +0,0 @@ -[ - "postgres", - "tabularis_test_secondary", - "testdb" -] diff --git a/src-tauri/tests/postgres_integration/golden/get_foreign_keys_cross_schema.json b/src-tauri/tests/postgres_integration/golden/get_foreign_keys_cross_schema.json deleted file mode 100644 index a0f8f3752..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_foreign_keys_cross_schema.json +++ /dev/null @@ -1,12 +0,0 @@ -[ - { - "name": "with_cross_schema_fk_lookup_code_fkey", - "column_name": "lookup_code", - "ref_table": "lookup", - "ref_column": "code", - "ref_schema": "other_schema", - "on_delete": "NO ACTION", - "on_update": "NO ACTION", - "seq_in_fk": 1 - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_foreign_keys_orders.json b/src-tauri/tests/postgres_integration/golden/get_foreign_keys_orders.json deleted file mode 100644 index ea213943b..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_foreign_keys_orders.json +++ /dev/null @@ -1,12 +0,0 @@ -[ - { - "name": "orders_user_id_fkey", - "column_name": "user_id", - "ref_table": "all_types", - "ref_column": "id", - "ref_schema": "test_schema", - "on_delete": "CASCADE", - "on_update": "NO ACTION", - "seq_in_fk": 1 - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_indexes_all_types.json b/src-tauri/tests/postgres_integration/golden/get_indexes_all_types.json deleted file mode 100644 index 463eddae9..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_indexes_all_types.json +++ /dev/null @@ -1,26 +0,0 @@ -[ - { - "name": "all_types_pkey", - "column_name": "id", - "is_unique": true, - "is_primary": true, - "seq_in_index": 1, - "is_expression": false - }, - { - "name": "idx_all_types_text", - "column_name": "col_text", - "is_unique": false, - "is_primary": false, - "seq_in_index": 1, - "is_expression": false - }, - { - "name": "idx_all_types_uuid", - "column_name": "col_uuid", - "is_unique": true, - "is_primary": false, - "seq_in_index": 1, - "is_expression": false - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_materialized_views.json b/src-tauri/tests/postgres_integration/golden/get_materialized_views.json deleted file mode 100644 index 526648d2d..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_materialized_views.json +++ /dev/null @@ -1,6 +0,0 @@ -[ - { - "name": "user_stats", - "definition": null - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_mv_columns.json b/src-tauri/tests/postgres_integration/golden/get_mv_columns.json deleted file mode 100644 index faee7b2e2..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_mv_columns.json +++ /dev/null @@ -1,18 +0,0 @@ -[ - { - "name": "total", - "data_type": "bigint", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "max_id", - "data_type": "integer", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_mv_definition.json b/src-tauri/tests/postgres_integration/golden/get_mv_definition.json deleted file mode 100644 index 4cd027068..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_mv_definition.json +++ /dev/null @@ -1 +0,0 @@ -"CREATE MATERIALIZED VIEW \"test_schema\".\"user_stats\" AS\n SELECT count(*) AS total,\n max(id) AS max_id\n FROM test_schema.all_types;" diff --git a/src-tauri/tests/postgres_integration/golden/get_routine_definition_add_numbers.json b/src-tauri/tests/postgres_integration/golden/get_routine_definition_add_numbers.json deleted file mode 100644 index 3d703d524..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_routine_definition_add_numbers.json +++ /dev/null @@ -1 +0,0 @@ -"CREATE OR REPLACE FUNCTION test_schema.add_numbers(a integer, b integer)\n RETURNS integer\n LANGUAGE sql\n IMMUTABLE\nAS $function$ SELECT a + b $function$\n" diff --git a/src-tauri/tests/postgres_integration/golden/get_routine_parameters_add_numbers.json b/src-tauri/tests/postgres_integration/golden/get_routine_parameters_add_numbers.json deleted file mode 100644 index 186d83203..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_routine_parameters_add_numbers.json +++ /dev/null @@ -1,38 +0,0 @@ -[ - { - "name": "", - "data_type": "integer", - "mode": "OUT", - "ordinal_position": 0 - }, - { - "name": "a", - "data_type": "integer", - "mode": "IN", - "ordinal_position": 1 - }, - { - "name": "a", - "data_type": "integer", - "mode": "IN", - "ordinal_position": 1 - }, - { - "name": "b", - "data_type": "integer", - "mode": "IN", - "ordinal_position": 2 - }, - { - "name": "b", - "data_type": "integer", - "mode": "IN", - "ordinal_position": 2 - }, - { - "name": "c", - "data_type": "integer", - "mode": "IN", - "ordinal_position": 3 - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_routines.json b/src-tauri/tests/postgres_integration/golden/get_routines.json deleted file mode 100644 index 15cb744ba..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_routines.json +++ /dev/null @@ -1,32 +0,0 @@ -[ - { - "name": "add_numbers", - "routine_type": "FUNCTION", - "definition": null, - "identity_args": "a integer, b integer" - }, - { - "name": "add_numbers", - "routine_type": "FUNCTION", - "definition": null, - "identity_args": "a integer, b integer, c integer" - }, - { - "name": "audit_trigger_fn", - "routine_type": "FUNCTION", - "definition": null, - "identity_args": "" - }, - { - "name": "get_user", - "routine_type": "FUNCTION", - "definition": null, - "identity_args": "p_id integer" - }, - { - "name": "reset_orders", - "routine_type": "PROCEDURE", - "definition": null, - "identity_args": "" - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_schemas.json b/src-tauri/tests/postgres_integration/golden/get_schemas.json deleted file mode 100644 index b3b631e57..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_schemas.json +++ /dev/null @@ -1,5 +0,0 @@ -[ - "other_schema", - "public", - "test_schema" -] diff --git a/src-tauri/tests/postgres_integration/golden/get_tables.json b/src-tauri/tests/postgres_integration/golden/get_tables.json deleted file mode 100644 index 06d3ee7f2..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_tables.json +++ /dev/null @@ -1,21 +0,0 @@ -[ - { - "name": "all_types", - "comment": "PostgreSQL metadata integration fixture" - }, - { - "name": "crud_scratch" - }, - { - "name": "order_items" - }, - { - "name": "orders" - }, - { - "name": "with_cross_schema_fk" - }, - { - "name": "with_enum" - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_trigger_definition_audit.json b/src-tauri/tests/postgres_integration/golden/get_trigger_definition_audit.json deleted file mode 100644 index 5d5e01d73..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_trigger_definition_audit.json +++ /dev/null @@ -1 +0,0 @@ -"CREATE TRIGGER trg_audit AFTER UPDATE ON test_schema.all_types FOR EACH ROW EXECUTE FUNCTION test_schema.audit_trigger_fn()" diff --git a/src-tauri/tests/postgres_integration/golden/get_triggers.json b/src-tauri/tests/postgres_integration/golden/get_triggers.json deleted file mode 100644 index 8fe5b24db..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_triggers.json +++ /dev/null @@ -1,9 +0,0 @@ -[ - { - "name": "trg_audit", - "table_name": "all_types", - "event": "UPDATE", - "timing": "AFTER", - "definition": null - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_view_columns_active_users.json b/src-tauri/tests/postgres_integration/golden/get_view_columns_active_users.json deleted file mode 100644 index faff95a3e..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_view_columns_active_users.json +++ /dev/null @@ -1,28 +0,0 @@ -[ - { - "name": "id", - "data_type": "integer", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false, - "numeric_precision": 32, - "numeric_scale": 0 - }, - { - "name": "name", - "data_type": "text", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - }, - { - "name": "is_active", - "data_type": "boolean", - "is_pk": false, - "is_nullable": true, - "is_auto_increment": false, - "is_generated": false - } -] diff --git a/src-tauri/tests/postgres_integration/golden/get_view_definition_active_users.json b/src-tauri/tests/postgres_integration/golden/get_view_definition_active_users.json deleted file mode 100644 index 1b88fed65..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_view_definition_active_users.json +++ /dev/null @@ -1 +0,0 @@ -"CREATE OR REPLACE VIEW \"test_schema\".\"active_users\" AS\n SELECT id,\n col_text AS name,\n col_bool AS is_active\n FROM test_schema.all_types\n WHERE col_bool = true;" diff --git a/src-tauri/tests/postgres_integration/golden/get_views.json b/src-tauri/tests/postgres_integration/golden/get_views.json deleted file mode 100644 index d1d0744bf..000000000 --- a/src-tauri/tests/postgres_integration/golden/get_views.json +++ /dev/null @@ -1,6 +0,0 @@ -[ - { - "name": "active_users", - "definition": null - } -] diff --git a/src-tauri/tests/postgres_integration/golden/multi_db/get_schemas_secondary.json b/src-tauri/tests/postgres_integration/golden/multi_db/get_schemas_secondary.json deleted file mode 100644 index fcc9c2a05..000000000 --- a/src-tauri/tests/postgres_integration/golden/multi_db/get_schemas_secondary.json +++ /dev/null @@ -1,4 +0,0 @@ -[ - "public", - "secondary_schema" -] diff --git a/src-tauri/tests/postgres_integration/golden/multi_db/get_tables_secondary.json b/src-tauri/tests/postgres_integration/golden/multi_db/get_tables_secondary.json deleted file mode 100644 index c5fafb578..000000000 --- a/src-tauri/tests/postgres_integration/golden/multi_db/get_tables_secondary.json +++ /dev/null @@ -1,5 +0,0 @@ -[ - { - "name": "remote_data" - } -] diff --git a/src-tauri/tests/postgres_integration/golden_utils.rs b/src-tauri/tests/postgres_integration/golden_utils.rs deleted file mode 100644 index 1a16a0809..000000000 --- a/src-tauri/tests/postgres_integration/golden_utils.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! Golden file capture and comparison utilities. -//! -//! Golden files record the exact output of driver methods against the seeded test -//! database. They serve as the parity contract: the plugin must produce output that -//! matches these files. -//! -//! # Regenerating golden files -//! -//! ```bash -//! cd src-tauri -//! REGENERATE_GOLDEN=1 cargo test --test postgres_integration golden -- --include-ignored --test-threads=1 -//! ``` - -use serde::Serialize; -use std::path::{Path, PathBuf}; - -/// Directory where golden files are stored (relative to the test binary's CWD). -fn golden_dir() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("tests") - .join("postgres_integration") - .join("golden") -} - -/// Write a golden file (only when REGENERATE_GOLDEN=1 is set). -pub fn write_golden(filename: &str, data: &T) { - if std::env::var("REGENERATE_GOLDEN").unwrap_or_default() != "1" { - return; - } - let path = golden_dir().join(filename); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent).expect("create golden dir"); - } - let json = serde_json::to_string_pretty(data).expect("serialize golden data"); - std::fs::write(&path, format!("{}\n", json)) - .unwrap_or_else(|e| panic!("write golden file {:?}: {}", path, e)); - eprintln!(" [golden] wrote {}", path.display()); -} - -/// Assert that the given data matches the golden file exactly. -/// Panics if the golden file doesn't exist — a missing fixture in a normal -/// (non-regeneration) run means a golden file was deleted, renamed, or never -/// committed, and must fail loud rather than being silently skipped. -pub fn assert_golden(filename: &str, data: &T) { - let path = golden_dir().join(filename); - let actual = serde_json::to_string_pretty(data).expect("serialize for comparison"); - - if !path.exists() { - panic!( - "Golden file missing: {}\n\ - If this is a new capture, run with REGENERATE_GOLDEN=1 to create it; \ - if it was unexpectedly deleted or renamed, restore it.\n\ - Actual output from this run:\n{}", - path.display(), - actual - ); - } - - let expected = std::fs::read_to_string(&path) - .unwrap_or_else(|e| panic!("read golden file {:?}: {}", path, e)); - - assert_eq!( - actual.trim(), - expected.trim(), - "Golden file mismatch: {}\n\ - To update, run: REGENERATE_GOLDEN=1 cargo test --test postgres_integration golden -- --include-ignored --test-threads=1", - filename - ); -} diff --git a/src-tauri/tests/postgres_integration/helpers.rs b/src-tauri/tests/postgres_integration/helpers.rs deleted file mode 100644 index 14b30ae45..000000000 --- a/src-tauri/tests/postgres_integration/helpers.rs +++ /dev/null @@ -1,80 +0,0 @@ -//! Shared helpers for PostgreSQL parity tests. - -use std::future::Future; -use std::time::Duration; -use tabularis_lib::drivers::postgres; -use tabularis_lib::models::{ConnectionParams, DatabaseSelection}; -use tokio::time::sleep; - -/// Standard connection parameters matching the CI service and local Docker setup. -pub fn pg_params() -> ConnectionParams { - ConnectionParams { - driver: "postgres".to_string(), - host: Some("127.0.0.1".to_string()), - port: Some(54320), - username: Some("postgres".to_string()), - password: Some("password".to_string()), - database: DatabaseSelection::Single("testdb".to_string()), - ..Default::default() - } -} - -/// Connection params targeting the secondary database (multi-database tests). -pub fn pg_params_secondary() -> ConnectionParams { - ConnectionParams { - database: DatabaseSelection::Single("tabularis_test_secondary".to_string()), - ..pg_params() - } -} - -/// Wait for PostgreSQL to be ready, retrying up to 10 times. -/// Returns `true` if connected, `false` if all retries failed. -pub async fn wait_for_pg() -> bool { - let params = pg_params(); - for _ in 0..10 { - if postgres::get_tables(¶ms, "public").await.is_ok() { - return true; - } - sleep(Duration::from_millis(500)).await; - } - false -} - -/// Retry a fallible async operation up to `attempts` times when the error looks -/// like a transient pool/connection issue ("connection closed", "pool timed out", -/// "broken pipe"). Non-transient errors are returned immediately. -pub async fn retry_transient(attempts: u32, mut f: F) -> Result -where - E: AsRef, - F: FnMut() -> Fut, - Fut: Future>, -{ - let mut last_err = None; - for attempt in 0..attempts { - match f().await { - Ok(val) => return Ok(val), - Err(e) => { - let msg = e.as_ref(); - let transient = msg.contains("connection closed") - || msg.contains("pool timed out") - || msg.contains("broken pipe") - || msg.contains("Connection reset"); - if !transient || attempt + 1 == attempts { - return Err(e); - } - last_err = Some(e); - sleep(Duration::from_millis(100 * (attempt as u64 + 1))).await; - } - } - } - Err(last_err.unwrap()) -} - -/// Convenience wrapper: retry up to 3 times on transient pool errors. -pub async fn retry(f: F) -> Result -where - F: FnMut() -> Fut, - Fut: Future>, -{ - retry_transient(3, f).await -} diff --git a/src-tauri/tests/postgres_integration/indexes.rs b/src-tauri/tests/postgres_integration/indexes.rs deleted file mode 100644 index 11464c886..000000000 --- a/src-tauri/tests/postgres_integration/indexes.rs +++ /dev/null @@ -1,84 +0,0 @@ -//! Index introspection tests. - -use crate::helpers::pg_params; -use tabularis_lib::drivers::postgres; - -#[tokio::test] -#[ignore] -async fn test_get_indexes_btree() { - require_pg!(); - let params = pg_params(); - - let indexes = postgres::get_indexes(¶ms, "all_types", "test_schema") - .await - .expect("get_indexes should succeed"); - - let idx = indexes.iter().find(|i| i.name == "idx_all_types_text"); - assert!(idx.is_some(), "Expected idx_all_types_text index"); - let idx = idx.unwrap(); - assert_eq!(idx.column_name, "col_text"); - assert!(!idx.is_unique); - assert!(!idx.is_primary); -} - -#[tokio::test] -#[ignore] -async fn test_get_indexes_unique() { - require_pg!(); - let params = pg_params(); - - let indexes = postgres::get_indexes(¶ms, "all_types", "test_schema") - .await - .expect("get_indexes should succeed"); - - let idx = indexes.iter().find(|i| i.name == "idx_all_types_uuid"); - assert!(idx.is_some(), "Expected idx_all_types_uuid unique index"); - let idx = idx.unwrap(); - assert_eq!(idx.column_name, "col_uuid"); - assert!(idx.is_unique); -} - -#[tokio::test] -#[ignore] -async fn test_get_indexes_composite() { - require_pg!(); - let params = pg_params(); - - let indexes = postgres::get_indexes(¶ms, "order_items", "test_schema") - .await - .expect("get_indexes should succeed"); - - // The composite index idx_order_items_composite covers (order_id, product) - let idx_entries: Vec<_> = indexes - .iter() - .filter(|i| i.name == "idx_order_items_composite") - .collect(); - - assert_eq!( - idx_entries.len(), - 2, - "Composite index should have 2 entries (one per column)" - ); - // Verify seq_in_index ordering - let first = idx_entries.iter().find(|i| i.seq_in_index == 1).unwrap(); - assert_eq!(first.column_name, "order_id"); - let second = idx_entries.iter().find(|i| i.seq_in_index == 2).unwrap(); - assert_eq!(second.column_name, "product"); -} - -#[tokio::test] -#[ignore] -async fn test_get_indexes_primary_key() { - require_pg!(); - let params = pg_params(); - - let indexes = postgres::get_indexes(¶ms, "all_types", "test_schema") - .await - .expect("get_indexes should succeed"); - - let pk = indexes.iter().find(|i| i.is_primary); - assert!(pk.is_some(), "Expected primary key index"); - let pk = pk.unwrap(); - assert_eq!(pk.column_name, "id"); - assert!(pk.is_unique, "PK index should also be unique"); -} diff --git a/src-tauri/tests/postgres_integration/main.rs b/src-tauri/tests/postgres_integration/main.rs deleted file mode 100644 index 2da480a6e..000000000 --- a/src-tauri/tests/postgres_integration/main.rs +++ /dev/null @@ -1,78 +0,0 @@ -//! PostgreSQL parity integration tests. -//! -//! These tests exercise every public method of the PostgreSQL driver against a -//! real PostgreSQL instance. They serve as the baseline specification that the -//! plugin driver must also pass (Phase 1 TDD). -//! -//! # Running locally -//! -//! Start a PostgreSQL 16 container: -//! ```bash -//! docker run -d --name pg-parity -p 54320:5432 \ -//! -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=password -e POSTGRES_DB=testdb \ -//! postgres:16 -//! ``` -//! -//! Seed the database: -//! ```bash -//! bash tests/fixtures/seed_postgres.sh -//! ``` -//! -//! Run the tests (sequential to avoid pool contention): -//! ```bash -//! cd src-tauri && cargo test --test postgres_integration -- --include-ignored --test-threads=1 -//! ``` - -/// Skip the test gracefully if PostgreSQL is unavailable. -macro_rules! require_pg { - () => { - if !crate::helpers::wait_for_pg().await { - eprintln!("SKIPPING: PostgreSQL not available on port 54320"); - return; - } - }; -} - -mod blob; -mod column_comments; -mod column_metadata; -mod crud; -mod ddl_generation; -mod dml_preview; -mod explain; -mod foreign_keys; -mod golden; -mod golden_utils; -mod helpers; -mod indexes; -mod materialized_views; -mod multi_database; -mod parity; -mod parity_batch; -mod parity_blob; -mod parity_column_metadata; -mod parity_crud; -mod parity_crud_extra; -mod parity_ddl; -mod parity_explain; -mod parity_foreign_keys; -mod parity_indexes; -mod parity_multi_db; -mod parity_multi_db_extra; -mod parity_mv_extra; -mod parity_query; -mod parity_query_extra; -mod parity_routines_extra; -mod parity_routines_full; -mod parity_schema_discovery; -mod parity_tests; -mod parity_triggers_extra; -mod parity_views_extra; -mod parity_views_full; -mod query_execution; -mod read_only; -mod routines; -mod schema_discovery; -mod table_transfer; -mod triggers; -mod views; diff --git a/src-tauri/tests/postgres_integration/materialized_views.rs b/src-tauri/tests/postgres_integration/materialized_views.rs deleted file mode 100644 index ea652062d..000000000 --- a/src-tauri/tests/postgres_integration/materialized_views.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! Materialized view tests. - -use crate::helpers::pg_params; -use tabularis_lib::drivers::postgres; - -#[tokio::test] -#[ignore] -async fn test_get_materialized_views() { - require_pg!(); - let params = pg_params(); - - let mvs = postgres::get_materialized_views(¶ms, "test_schema") - .await - .expect("get_materialized_views should succeed"); - - let mv_names: Vec<&str> = mvs.iter().map(|v| v.name.as_str()).collect(); - assert!( - mv_names.contains(&"user_stats"), - "Expected user_stats MV, got: {:?}", - mv_names - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_materialized_view_columns() { - require_pg!(); - let params = pg_params(); - - let columns = postgres::get_materialized_view_columns(¶ms, "user_stats", "test_schema") - .await - .expect("get_materialized_view_columns should succeed"); - - let col_names: Vec<&str> = columns.iter().map(|c| c.name.as_str()).collect(); - assert!(col_names.contains(&"total"), "Expected total column"); - assert!(col_names.contains(&"max_id"), "Expected max_id column"); -} - -#[tokio::test] -#[ignore] -async fn test_get_materialized_view_definition() { - require_pg!(); - let params = pg_params(); - - let definition = - postgres::get_materialized_view_definition(¶ms, "user_stats", "test_schema") - .await - .expect("get_materialized_view_definition should succeed"); - - assert!( - definition.contains("CREATE MATERIALIZED VIEW"), - "Expected CREATE MATERIALIZED VIEW in definition, got: {}", - definition - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_materialized_view_definition_rejects_regular_view() { - require_pg!(); - let params = pg_params(); - - // `active_users` is a regular view (relkind = 'v'), not a materialized - // view. Passing it to get_materialized_view_definition must error instead - // of returning the regular view's DDL labeled as a materialized view. - let result = - postgres::get_materialized_view_definition(¶ms, "active_users", "test_schema").await; - assert!( - result.is_err(), - "get_materialized_view_definition should reject a regular view name, \ - but it returned: {:?}", - result - ); -} - -#[tokio::test] -#[ignore] -async fn test_refresh_materialized_view() { - require_pg!(); - let params = pg_params(); - - // Refresh should succeed without error - postgres::refresh_materialized_view(¶ms, "user_stats", "test_schema") - .await - .expect("refresh_materialized_view should succeed"); - - // Verify the MV still has data after refresh - let result = postgres::execute_query( - ¶ms, - "SELECT total FROM test_schema.user_stats", - None, - 1, - None, - ) - .await - .expect("SELECT from MV should work after refresh"); - - assert_eq!(result.rows.len(), 1); - // total should be >= 2 (we seeded 2 rows in all_types) - let total = result.rows[0][0].as_i64().unwrap_or(0); - assert!(total >= 2, "Expected total >= 2, got: {}", total); -} diff --git a/src-tauri/tests/postgres_integration/multi_database.rs b/src-tauri/tests/postgres_integration/multi_database.rs deleted file mode 100644 index a2392a7b6..000000000 --- a/src-tauri/tests/postgres_integration/multi_database.rs +++ /dev/null @@ -1,271 +0,0 @@ -//! Multi-database tests (exercises per-database pool routing). - -use crate::helpers::{pg_params, pg_params_secondary}; -use tabularis_lib::drivers::postgres; -use tabularis_lib::models::DatabaseSelection; - -// --- new: test the params.database override pattern used by Stage 1 Tauri -// commands (get_schemas, get_tables, etc. with database: Option) ---- - -#[tokio::test] -#[ignore] -async fn test_database_override_routes_to_secondary() { - require_pg!(); - // Start from testdb params, then switch database via the same - // params.database = Single(db) override the Tauri commands apply. - let mut params = pg_params(); - params.database = DatabaseSelection::Single("tabularis_test_secondary".to_string()); - - let schemas = postgres::get_schemas(¶ms) - .await - .expect("get_schemas with overridden database should succeed"); - - assert!( - schemas.contains(&"secondary_schema".to_string()), - "Override to tabularis_test_secondary should expose secondary_schema, got: {:?}", - schemas - ); - assert!( - !schemas.contains(&"test_schema".to_string()), - "Override should NOT see testdb's test_schema, got: {:?}", - schemas - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_tables_with_database_and_schema_override() { - require_pg!(); - // Start from testdb/public, override to secondary's schema — this is - // the exact path `get_tables` takes when called with `database` + `schema` - // params from the nested multi-db sidebar. - let mut params = pg_params(); - params.database = DatabaseSelection::Single("tabularis_test_secondary".to_string()); - - let tables = postgres::get_tables(¶ms, "secondary_schema") - .await - .expect("get_tables with overridden database+schema should succeed"); - - let names: Vec<&str> = tables.iter().map(|t| t.name.as_str()).collect(); - assert!( - names.contains(&"remote_data"), - "Expected remote_data in tabularis_test_secondary.secondary_schema, got: {:?}", - names - ); -} - -#[tokio::test] -#[ignore] -async fn test_empty_string_filter_prevents_maintenance_db_override() { - require_pg!(); - // The .filter(|d| !d.is_empty()) guard in Stage 1 Tauri commands means - // passing Some("") must NOT override params.database. Confirm the existing - // testdb connection still sees testdb's schemas when a blank override is - // simulated (we do NOT override — just verify testdb baseline is intact). - let params = pg_params(); - - let schemas = postgres::get_schemas(¶ms) - .await - .expect("testdb schemas should be accessible"); - - assert!( - schemas.contains(&"test_schema".to_string()), - "testdb should have test_schema, got: {:?}", - schemas - ); - assert!( - !schemas.contains(&"secondary_schema".to_string()), - "testdb should NOT see secondary_schema, got: {:?}", - schemas - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_databases_lists_both() { - require_pg!(); - let params = pg_params(); - - let databases = postgres::get_databases(¶ms) - .await - .expect("get_databases should succeed"); - - assert!(databases.contains(&"testdb".to_string())); - assert!(databases.contains(&"tabularis_test_secondary".to_string())); -} - -#[tokio::test] -#[ignore] -async fn test_get_schemas_on_secondary_database() { - require_pg!(); - let params = pg_params_secondary(); - - let schemas = postgres::get_schemas(¶ms) - .await - .expect("get_schemas on secondary should succeed"); - - assert!( - schemas.contains(&"secondary_schema".to_string()), - "Expected secondary_schema, got: {:?}", - schemas - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_tables_on_secondary_database() { - require_pg!(); - let params = pg_params_secondary(); - - let tables = postgres::get_tables(¶ms, "secondary_schema") - .await - .expect("get_tables on secondary should succeed"); - - let table_names: Vec<&str> = tables.iter().map(|t| t.name.as_str()).collect(); - assert!( - table_names.contains(&"remote_data"), - "Expected remote_data table in secondary, got: {:?}", - table_names - ); -} - -#[tokio::test] -#[ignore] -async fn test_execute_query_on_secondary_database() { - require_pg!(); - let params = pg_params_secondary(); - - let result = postgres::execute_query( - ¶ms, - "SELECT COUNT(*) AS cnt FROM secondary_schema.remote_data", - None, - 1, - None, - ) - .await - .expect("query on secondary should succeed"); - - let count = result.rows[0][0].as_i64().unwrap_or(0); - assert_eq!(count, 5, "Expected 5 seeded rows in secondary"); -} - -#[tokio::test] -#[ignore] -async fn test_pool_isolation_between_databases() { - require_pg!(); - let primary = pg_params(); - let secondary = pg_params_secondary(); - - // Query primary — should see test_schema tables - let primary_tables = crate::helpers::retry(|| { - let p = primary.clone(); - async move { postgres::get_tables(&p, "test_schema").await } - }) - .await - .expect("primary tables"); - assert!(!primary_tables.is_empty()); - - // Query secondary — should NOT see test_schema (it doesn't exist there) - let secondary_schemas = crate::helpers::retry(|| { - let s = secondary.clone(); - async move { postgres::get_schemas(&s).await } - }) - .await - .expect("secondary schemas"); - assert!( - !secondary_schemas.contains(&"test_schema".to_string()), - "test_schema should not exist in secondary database" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_columns_on_secondary_database() { - require_pg!(); - let params = pg_params_secondary(); - - let columns = postgres::get_columns(¶ms, "remote_data", "secondary_schema") - .await - .expect("get_columns on secondary"); - - let col_names: Vec<&str> = columns.iter().map(|c| c.name.as_str()).collect(); - assert!(col_names.contains(&"id")); - assert!(col_names.contains(&"value")); - assert_eq!(columns.len(), 2); -} - -#[tokio::test] -#[ignore] -async fn test_fallback_to_postgres_maintenance_db() { - require_pg!(); - - // Connect with empty database — should fall back to "postgres" maintenance DB - let mut params = pg_params(); - params.database = tabularis_lib::models::DatabaseSelection::Single("postgres".to_string()); - - let databases = postgres::get_databases(¶ms) - .await - .expect("should connect to maintenance DB"); - - // The maintenance DB can list all databases - assert!(databases.contains(&"testdb".to_string())); -} - -#[tokio::test] -#[ignore] -async fn test_export_rejects_database_mismatch_on_pinned_session() { - // An export on a tab with an open transaction on database A must not - // silently stream rows from A when the tab has switched to database B (#1067). - require_pg!(); - let primary = pg_params(); - let secondary = pg_params_secondary(); - let session = "test-export-pinned-session-db-mismatch"; - - // Start a transaction on the primary database and leave it open. - let (_results, pinned) = postgres::execute_batch_in_session( - &primary, - &["BEGIN".into()], - None, - 1, - None, - Some(session), - None, - ) - .await - .expect("BEGIN should succeed"); - assert!(pinned, "BEGIN should leave a pinned transaction"); - - // An export targeting the secondary database on the same session must be - // rejected rather than silently streaming from the primary connection. - let err = postgres::export::stream_query( - &secondary, - "SELECT 1", - Some(session), - |_headers, _values| Ok(()), - ) - .await - .expect_err("database mismatch should be rejected"); - assert!( - err.contains("open transaction on database") && err.contains("testdb"), - "error should name the pinned database, got: {err}" - ); - assert!( - err.contains("tabularis_test_secondary"), - "error should name the requested database, got: {err}" - ); - - // Clean up: roll back the open transaction on the primary. This also - // confirms the pinned session survived the rejected export (the slot - // was only borrowed via slot.client(), never consumed). - postgres::execute_batch_in_session( - &primary, - &["ROLLBACK".into()], - None, - 1, - None, - Some(session), - None, - ) - .await - .expect("ROLLBACK should succeed"); -} diff --git a/src-tauri/tests/postgres_integration/parity.rs b/src-tauri/tests/postgres_integration/parity.rs deleted file mode 100644 index 3d1cdc12b..000000000 --- a/src-tauri/tests/postgres_integration/parity.rs +++ /dev/null @@ -1,339 +0,0 @@ -//! Parity test harness — runs identical assertions against multiple driver -//! implementations to prove behavioral equivalence. -//! -//! # Phase 0 -//! -//! Only `DriverTarget::Builtin` is registered. Tests pass trivially (single -//! result, nothing to compare), but the harness infrastructure is ready for -//! Phase 1 to add `DriverTarget::Plugin`. -//! -//! # Phase 1 -//! -//! Both targets are registered. Tests now run against both drivers and assert -//! that their outputs are identical — proving parity by construction. -//! -//! # Comparison Strategy -//! -//! Since model structs don't derive `PartialEq`, the harness serializes results -//! to `serde_json::Value` and compares those. This also catches subtle -//! differences in field ordering or null handling that direct struct comparison -//! might miss. - -use std::collections::HashMap; -use std::fmt::Debug; -use std::path::PathBuf; -use std::sync::Arc; - -use serde::Serialize; -use serde_json::Value as JsonValue; - -use tabularis_lib::drivers::driver_trait::{ - DatabaseDriver, DriverCapabilities, PluginManifest, SqlDialect, -}; -use tabularis_lib::drivers::postgres::PostgresDriver; -use tabularis_lib::models::{ConnectionParams, DataTypeInfo}; -use tabularis_lib::plugins::driver::RpcDriver; - -use crate::helpers::{pg_params, pg_params_secondary, retry_transient}; - -/// Identifies which driver implementation to test. -#[derive(Debug, Clone)] -pub enum DriverTarget { - /// The built-in PostgreSQL driver (direct sqlx implementation). - Builtin, - /// A plugin driver communicating over JSON-RPC stdio. - /// The string is the plugin id (e.g. "postgres-plugin"). - Plugin(String), -} - -impl std::fmt::Display for DriverTarget { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Builtin => write!(f, "builtin"), - Self::Plugin(id) => write!(f, "plugin:{}", id), - } - } -} - -/// The parity harness. Holds configured driver targets and connection params. -pub struct ParityHarness { - targets: Vec<(DriverTarget, Arc)>, - pub params: ConnectionParams, - pub params_secondary: ConnectionParams, -} - -impl ParityHarness { - /// Create a harness with only the built-in driver (Phase 0 fallback). - pub fn builtin_only() -> Self { - let driver = Arc::new(PostgresDriver::new()) as Arc; - Self { - targets: vec![(DriverTarget::Builtin, driver)], - params: pg_params(), - params_secondary: pg_params_secondary(), - } - } - - /// Create a harness, optionally including the plugin driver if - /// `POSTGRES_PLUGIN_BIN` is set. This is the primary constructor for - /// Phase 1+ parity tests. - pub async fn new() -> Self { - let mut harness = Self::builtin_only(); - if let Some(plugin_driver) = try_plugin_driver().await { - harness = harness.with_plugin("postgres-plugin", plugin_driver); - } - harness - } - - /// Add a plugin driver target. - pub fn with_plugin(mut self, id: &str, driver: Arc) -> Self { - self.targets - .push((DriverTarget::Plugin(id.to_string()), driver)); - self - } - - /// Returns a reference to the list of configured targets. - pub fn targets(&self) -> &[(DriverTarget, Arc)] { - &self.targets - } - - /// Run a test function against all configured targets and assert identical - /// results (compared via JSON serialization). The `method_name` is used in - /// assertion messages for diagnostics. - /// - /// With a single target (Phase 0), this simply runs the function once and - /// returns the JSON value. With multiple targets (Phase 1+), it compares all - /// serialized results pairwise. - pub async fn assert_parity(&self, method_name: &str, test_fn: F) -> JsonValue - where - T: Debug + Serialize, - F: Fn(Arc, ConnectionParams) -> Fut, - Fut: std::future::Future>, - { - self.run_parity_inner(method_name, &self.params, test_fn) - .await - } - - /// Same as `assert_parity` but uses `params_secondary` for multi-database tests. - pub async fn assert_parity_secondary( - &self, - method_name: &str, - test_fn: F, - ) -> JsonValue - where - T: Debug + Serialize, - F: Fn(Arc, ConnectionParams) -> Fut, - Fut: std::future::Future>, - { - self.run_parity_inner(method_name, &self.params_secondary, test_fn) - .await - } - - async fn run_parity_inner( - &self, - method_name: &str, - params: &ConnectionParams, - test_fn: F, - ) -> JsonValue - where - T: Debug + Serialize, - F: Fn(Arc, ConnectionParams) -> Fut, - Fut: std::future::Future>, - { - let mut results: Vec<(String, JsonValue)> = Vec::new(); - - for (target, driver) in &self.targets { - let result = retry_transient(3, || test_fn(Arc::clone(driver), params.clone())) - .await - .unwrap_or_else(|e| { - panic!( - "Parity test '{}' failed on target {}: {}", - method_name, target, e - ) - }); - let json = serde_json::to_value(&result).unwrap_or_else(|e| { - panic!( - "Parity test '{}': failed to serialize result from {}: {}", - method_name, target, e - ) - }); - results.push((target.to_string(), json)); - } - - // Compare all results pairwise - for window in results.windows(2) { - let (ref name_a, ref val_a) = window[0]; - let (ref name_b, ref val_b) = window[1]; - assert_eq!( - val_a, - val_b, - "Parity failure in '{}': {} and {} returned different results.\n\ - Left: {}\n\ - Right: {}", - method_name, - name_a, - name_b, - serde_json::to_string_pretty(val_a).unwrap(), - serde_json::to_string_pretty(val_b).unwrap() - ); - } - - // Return the first result (all are equal) - results.into_iter().next().unwrap().1 - } - - /// Assert that a method produces the same error semantics across targets. - /// For methods expected to fail, this checks that all targets either succeed - /// with equal results or fail (error messages may differ between drivers, - /// so only the success/failure outcome is compared). - #[allow(dead_code)] - pub async fn assert_error_parity(&self, method_name: &str, test_fn: F) - where - T: Debug + Serialize, - F: Fn(Arc, ConnectionParams) -> Fut, - Fut: std::future::Future>, - { - let mut results: Vec<(String, Result)> = Vec::new(); - - for (target, driver) in &self.targets { - let result = test_fn(Arc::clone(driver), self.params.clone()).await; - let mapped = result.map(|v| { - serde_json::to_value(&v) - .unwrap_or_else(|e| panic!("Failed to serialize result from {}: {}", target, e)) - }); - results.push((target.to_string(), mapped)); - } - - for window in results.windows(2) { - let (ref name_a, ref res_a) = window[0]; - let (ref name_b, ref res_b) = window[1]; - match (res_a, res_b) { - (Ok(a), Ok(b)) => assert_eq!( - a, b, - "Parity failure in '{}': {} and {} returned different success values", - method_name, name_a, name_b - ), - (Err(_), Err(_)) => { - // Both failed — parity holds (error messages may differ between drivers) - } - _ => panic!( - "Parity failure in '{}': {} {} but {} {}", - method_name, - name_a, - if res_a.is_ok() { "succeeded" } else { "failed" }, - name_b, - if res_b.is_ok() { "succeeded" } else { "failed" } - ), - } - } - } -} - -/// Attempt to construct a plugin driver from the `POSTGRES_PLUGIN_BIN` env var. -/// Returns `None` if the env var is unset (Phase 0 / no plugin available). -/// Panics if the env var is set but the path doesn't exist or the plugin -/// fails to start — an explicit `POSTGRES_PLUGIN_BIN` is a request to run -/// against a real plugin, so a bad path must fail loud rather than silently -/// falling back to builtin-only parity (which would trivially "pass"). -async fn try_plugin_driver() -> Option> { - let bin_path = std::env::var("POSTGRES_PLUGIN_BIN").ok()?; - let path = PathBuf::from(&bin_path); - - if !path.exists() { - panic!( - "POSTGRES_PLUGIN_BIN is set to '{}' but the file does not exist — \ - fix the path or unset the variable to run builtin-only parity", - bin_path - ); - } - - eprintln!(" [parity] Spawning plugin driver from: {}", bin_path); - - let manifest = plugin_manifest(); - let data_types = plugin_data_types(); - - let driver = RpcDriver::new(manifest, path, None, data_types, HashMap::new()) - .await - .unwrap_or_else(|e| panic!("Failed to start plugin driver: {}", e)); - - Some(Arc::new(driver) as Arc) -} - -/// Build the PluginManifest matching the plugin's .tabularium file. -fn plugin_manifest() -> PluginManifest { - PluginManifest { - id: "postgres-plugin".to_string(), - name: "PostgreSQL Plugin".to_string(), - version: "0.1.0".to_string(), - description: "PostgreSQL plugin driver for Tabularis".to_string(), - default_port: Some(5432), - capabilities: DriverCapabilities { - schemas: true, - single_database: false, - views: true, - materialized_views: true, - routines: true, - routine_management: true, - routine_debug: None, - file_based: false, - folder_based: false, - in_memory: false, - data_files: Vec::new(), - connection_string: true, - connection_string_example: "postgres://user:pass@localhost:5432/db".into(), - connection_string_examples: Vec::new(), - connection_uri: false, - connection_uri_schemes: Vec::new(), - socks5_proxy: false, - identifier_quote: "\"".into(), - alter_primary_key: true, - auto_increment_keyword: String::new(), - serial_type: "SERIAL".into(), - inline_pk: false, - table_query_templates: false, - column_comments: false, - drop_table_sql: false, - column_stats: false, - query_classification: false, - read_only_queries: false, - query_timeout: false, - alter_column: true, - create_foreign_keys: true, - no_connection_required: false, - unix_socket: false, - manage_tables: true, - explain: true, - readonly: false, - triggers: true, - supports_ssl: true, - user_management: false, - sql_dialect: Some(SqlDialect::Postgres), - sql_syntax: None, - table_export: None, - table_import: None, - }, - is_builtin: false, - engine: Some("postgresql".to_string()), - paradigms: vec!["relational".to_string()], - default_username: "postgres".to_string(), - color: "#3b82f6".to_string(), - icon: "postgres".to_string(), - settings: vec![], - ui_extensions: None, - explain_parsers: None, - connection_fields: None, - type_mappings: { - let mut m = HashMap::new(); - m.insert("DATETIME".to_string(), "TIMESTAMP".to_string()); - m.insert("JSON".to_string(), "JSONB".to_string()); - m - }, - deprecated: None, - } -} - -/// Data types the plugin supports (matches .tabularium data_types array). -fn plugin_data_types() -> Vec { - // For the parity harness, data types are used for display only. - // Return an empty vec — the RpcDriver doesn't use these for query execution. - Vec::new() -} diff --git a/src-tauri/tests/postgres_integration/parity_batch.rs b/src-tauri/tests/postgres_integration/parity_batch.rs deleted file mode 100644 index 6fc7e92f9..000000000 --- a/src-tauri/tests/postgres_integration/parity_batch.rs +++ /dev/null @@ -1,187 +0,0 @@ -//! Parity tests for `execute_batch` — ensures plugin handles multi-statement -//! batch execution identically to the built-in driver. -//! -//! `execute_batch` returns `Vec`, and each entry -//! carries `execution_time_ms: Option` — a genuinely non-deterministic -//! wall-clock value that can never byte-match between two separate driver -//! processes. `assert_parity`'s exact JSON comparison is the wrong tool here -//! (same class of issue as `explain_query`'s volatile cost/timing output in -//! `parity_explain.rs`). Instead, call each target directly and compare only -//! the deterministic fields (`error`, `result`), ignoring `execution_time_ms`. - -use serde_json::Value; - -use crate::parity::ParityHarness; - -/// Strip the non-deterministic `execution_time_ms` field from each batch -/// entry so the remaining structure (`error`, `result`) can be compared -/// exactly across targets. -fn normalize_batch_result(v: &Value) -> Value { - let arr = v.as_array().expect("batch result should be an array"); - Value::Array( - arr.iter() - .map(|entry| json_without_key(entry, "execution_time_ms")) - .collect(), - ) -} - -fn json_without_key(v: &Value, key: &str) -> Value { - match v.as_object() { - Some(obj) => { - let mut filtered = serde_json::Map::new(); - for (k, val) in obj { - if k != key { - filtered.insert(k.clone(), val.clone()); - } - } - Value::Object(filtered) - } - None => v.clone(), - } -} - -#[tokio::test] -#[ignore] -async fn parity_batch_session_state() { - require_pg!(); - let harness = ParityHarness::new().await; - - let queries = vec![ - "SET search_path TO test_schema".to_string(), - "SELECT current_schema() AS current_schema".to_string(), - ]; - - let mut normalized_results = Vec::new(); - for (target, driver) in harness.targets() { - let result = driver - .execute_batch( - &harness.params, - &queries, - Some(100), - 1, - Some("test_schema"), - None, - ) - .await - .unwrap_or_else(|e| panic!("execute_batch failed on {}: {}", target, e)); - let json = serde_json::to_value(&result).expect("serialize batch result"); - normalized_results.push((target.to_string(), normalize_batch_result(&json))); - } - - for window in normalized_results.windows(2) { - assert_eq!( - window[0].1, window[1].1, - "execute_batch:session_state parity failure between {} and {}", - window[0].0, window[1].0 - ); - } - - let arr = normalized_results[0].1.as_array().unwrap(); - assert_eq!(arr.len(), 2, "should have results for both statements"); - let second = &arr[1]; - let succeeded = second.get("error").map(Value::is_null).unwrap_or(false); - assert!( - succeeded, - "SELECT current_schema() should succeed, got: {:?}", - second - ); -} - -#[tokio::test] -#[ignore] -async fn parity_batch_mixed_statements() { - require_pg!(); - let harness = ParityHarness::new().await; - - let queries = vec![ - "SELECT id FROM test_schema.all_types ORDER BY id LIMIT 2".to_string(), - "INSERT INTO test_schema.crud_scratch(name, value) VALUES ('batch_parity', 42)".to_string(), - ]; - - let mut normalized_results = Vec::new(); - for (target, driver) in harness.targets() { - let result = driver - .execute_batch( - &harness.params, - &queries, - Some(100), - 1, - Some("test_schema"), - None, - ) - .await - .unwrap_or_else(|e| panic!("execute_batch failed on {}: {}", target, e)); - let json = serde_json::to_value(&result).expect("serialize batch result"); - normalized_results.push((target.to_string(), normalize_batch_result(&json))); - } - - for window in normalized_results.windows(2) { - assert_eq!( - window[0].1, window[1].1, - "execute_batch:mixed_statements parity failure between {} and {}", - window[0].0, window[1].0 - ); - } - - let arr = normalized_results[0].1.as_array().unwrap(); - assert_eq!(arr.len(), 2, "should have results for both statements"); - let first_ok = arr[0].get("error").map(Value::is_null).unwrap_or(false); - assert!(first_ok, "SELECT should succeed, got: {:?}", arr[0]); - let second_ok = arr[1].get("error").map(Value::is_null).unwrap_or(false); - assert!(second_ok, "INSERT should succeed, got: {:?}", arr[1]); -} - -#[tokio::test] -#[ignore] -async fn parity_batch_error_handling() { - require_pg!(); - let harness = ParityHarness::new().await; - - let queries = vec![ - "SELECT 1 AS ok".to_string(), - "SELECT * FROM test_schema.this_table_does_not_exist".to_string(), - ]; - - let mut normalized_results = Vec::new(); - for (target, driver) in harness.targets() { - let result = driver - .execute_batch( - &harness.params, - &queries, - Some(100), - 1, - Some("test_schema"), - None, - ) - .await - .unwrap_or_else(|e| panic!("execute_batch failed on {}: {}", target, e)); - let json = serde_json::to_value(&result).expect("serialize batch result"); - normalized_results.push((target.to_string(), normalize_batch_result(&json))); - } - - // Do not assert_eq the error message text across targets — the builtin - // and plugin surface different underlying driver error strings for the - // same failure (e.g. differing wording from sqlx vs tokio-postgres). - // Compare only the success/failure shape. - for (target, json) in &normalized_results { - let arr = json.as_array().unwrap(); - assert_eq!( - arr.len(), - 2, - "{}: should have results for both statements", - target - ); - let first_ok = arr[0].get("error").map(Value::is_null).unwrap_or(false); - assert!( - first_ok, - "{}: valid SELECT should succeed, got: {:?}", - target, arr[0] - ); - let second_failed = arr[1].get("error").map(|e| !e.is_null()).unwrap_or(false); - assert!( - second_failed, - "{}: query on non-existent table should fail, got: {:?}", - target, arr[1] - ); - } -} diff --git a/src-tauri/tests/postgres_integration/parity_blob.rs b/src-tauri/tests/postgres_integration/parity_blob.rs deleted file mode 100644 index 55380aa9c..000000000 --- a/src-tauri/tests/postgres_integration/parity_blob.rs +++ /dev/null @@ -1,171 +0,0 @@ -//! Parity tests for BLOB (bytea) handling — covers ALL 3 baseline tests from -//! `blob.rs`. None of these were previously covered by parity tests. -//! -//! The `save_blob_to_file` test verifies both drivers can write to a file without -//! error. The `fetch_blob_as_data_url` test verifies both drivers return -//! identical wire-format strings for the same row. - -use std::collections::HashMap; - -use serde_json::json; - -use crate::parity::ParityHarness; - -/// Parity equivalent of `test_insert_and_query_bytea`. -/// Verifies inserting a BLOB-wire-encoded bytea value and querying it back. -/// Both drivers must handle the "BLOB:::" wire format -/// identically on insert and produce identical query results. -#[tokio::test] -#[ignore] -async fn parity_blob_insert_and_query() { - require_pg!(); - let harness = ParityHarness::new().await; - - // insert_record is destructive against the one shared physical database - // both targets point at — assert_parity calls each target in sequence, - // and col_text has no unique constraint, so inserting the same marker - // value from both targets produces TWO rows in the shared table (not - // one row inserted "the same way twice"). Run insert+query+cleanup - // directly per target so each target's row is isolated and cleaned up - // before the next target runs. - for (target, driver) in harness.targets() { - // 4 bytes (0xCA 0xFE 0xBA 0xBE) encoded as base64 = "yv66vg==" - let blob_wire = "BLOB:4:application/octet-stream:yv66vg=="; - let mut data = HashMap::new(); - data.insert("col_bytea".to_string(), json!(blob_wire)); - data.insert("col_text".to_string(), json!("parity_blob_test")); - driver - .insert_record( - &harness.params, - "all_types", - data, - Some("test_schema"), - 10_000_000, - ) - .await - .unwrap_or_else(|e| panic!("insert_record failed on {}: {}", target, e)); - - let query_result = driver - .execute_query( - &harness.params, - "SELECT col_bytea FROM test_schema.all_types WHERE col_text = 'parity_blob_test'", - None, - 1, - Some("test_schema"), - ) - .await - .unwrap_or_else(|e| panic!("execute_query failed on {}: {}", target, e)); - - assert_eq!( - query_result.rows.len(), - 1, - "{}: should find exactly the inserted blob row", - target - ); - assert!( - !query_result.rows[0][0].is_null(), - "{}: bytea column should not be null", - target - ); - - driver - .execute_query( - &harness.params, - "DELETE FROM test_schema.all_types WHERE col_text = 'parity_blob_test'", - None, - 1, - Some("test_schema"), - ) - .await - .unwrap_or_else(|e| panic!("cleanup delete failed on {}: {}", target, e)); - } -} - -/// Parity equivalent of `test_save_blob_to_file`. -/// Verifies both drivers can export a blob column to a file without error. -/// The seeded row (id=1) has col_bytea = '\xDEADBEEF'. -#[tokio::test] -#[ignore] -async fn parity_blob_save_to_file() { - require_pg!(); - let harness = ParityHarness::new().await; - - let tmp_path = std::env::temp_dir().join("tabularis_parity_blob_test.bin"); - let path_str = tmp_path.to_str().unwrap().to_string(); - - let result = harness - .assert_parity("save_blob_to_file:basic", |driver, params| { - let path = path_str.clone(); - async move { - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), json!(1)); - driver - .save_blob_to_file( - ¶ms, - "all_types", - "col_bytea", - &pk_map, - Some("test_schema"), - &path, - ) - .await - } - }) - .await; - - // Both drivers should succeed (result is null/() serialized) - assert!( - result.is_null(), - "save_blob_to_file returns () which serializes to null" - ); - - // Verify file was written and has content - let metadata = std::fs::metadata(&tmp_path); - assert!( - metadata.is_ok(), - "File should exist after save_blob_to_file" - ); - assert!(metadata.unwrap().len() > 0, "File should have content"); - - // Clean up - let _ = std::fs::remove_file(&tmp_path); -} - -/// Parity equivalent of `test_fetch_blob_as_data_url`. -/// Verifies both drivers return identical BLOB wire format strings for the -/// same row. The seeded row (id=1) has col_bytea = '\xDEADBEEF'. -#[tokio::test] -#[ignore] -async fn parity_blob_fetch_as_data_url() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "fetch_blob_as_data_url:basic", - |driver, params| async move { - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), json!(1)); - driver - .fetch_blob_as_data_url( - ¶ms, - "all_types", - "col_bytea", - &pk_map, - Some("test_schema"), - ) - .await - }, - ) - .await; - - let data_url = result - .as_str() - .expect("fetch_blob_as_data_url should return a string"); - // Should be in BLOB wire format: "BLOB:::" or data URL - assert!( - data_url.starts_with("BLOB:") || data_url.starts_with("data:"), - "Should return BLOB wire format or data URL, got: {}", - &data_url[..data_url.len().min(50)] - ); -} diff --git a/src-tauri/tests/postgres_integration/parity_column_metadata.rs b/src-tauri/tests/postgres_integration/parity_column_metadata.rs deleted file mode 100644 index e4480bc76..000000000 --- a/src-tauri/tests/postgres_integration/parity_column_metadata.rs +++ /dev/null @@ -1,277 +0,0 @@ -//! Parity tests for column metadata — covers baseline tests from -//! `column_metadata.rs` that are NOT already covered in `parity_tests.rs`. -//! -//! Already covered by `parity_tests.rs`: -//! - parity_get_columns (basic: all_types table, checks id is PK) -//! -//! New in this file — each test calls `get_columns` through the trait via the -//! harness and uses `assert_parity()` for byte-perfect JSON comparison, then -//! adds structural assertions on the shared result. - -use serde_json::Value; - -use crate::parity::ParityHarness; - -/// Parity equivalent of `test_get_columns_all_types_count`. -/// Verifies the all_types table returns exactly 27 columns from both drivers. -#[tokio::test] -#[ignore] -async fn parity_get_columns_all_types_count() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_columns:all_types:count", |driver, params| async move { - driver - .get_columns(¶ms, "all_types", Some("test_schema")) - .await - }) - .await; - - let arr = result.as_array().expect("columns should be an array"); - assert_eq!(arr.len(), 27, "Expected 27 columns in all_types"); -} - -/// Parity equivalent of `test_get_columns_pk_detection`. -/// Verifies primary key detection and auto-increment flag match between drivers. -#[tokio::test] -#[ignore] -async fn parity_get_columns_pk_detection() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_columns:all_types:pk_detection", - |driver, params| async move { - driver - .get_columns(¶ms, "all_types", Some("test_schema")) - .await - }, - ) - .await; - - let arr = result.as_array().expect("columns should be an array"); - - let id_col = arr - .iter() - .find(|c| c.get("name").and_then(|n| n.as_str()) == Some("id")) - .expect("id column should exist"); - assert_eq!( - id_col.get("is_pk").and_then(|v| v.as_bool()), - Some(true), - "id should be primary key" - ); - assert_eq!( - id_col.get("is_auto_increment").and_then(|v| v.as_bool()), - Some(true), - "SERIAL id should be auto_increment" - ); - assert_eq!( - id_col.get("data_type").and_then(|v| v.as_str()), - Some("integer"), - "SERIAL resolves to integer" - ); - - // Non-PK columns should not be marked as PK - let text_col = arr - .iter() - .find(|c| c.get("name").and_then(|n| n.as_str()) == Some("col_text")) - .expect("col_text should exist"); - assert_eq!( - text_col.get("is_pk").and_then(|v| v.as_bool()), - Some(false), - "col_text should not be PK" - ); - assert_eq!( - text_col.get("is_auto_increment").and_then(|v| v.as_bool()), - Some(false), - "col_text should not be auto_increment" - ); -} - -/// Parity equivalent of `test_get_columns_nullable_detection`. -/// Verifies nullable flag matches between drivers. -#[tokio::test] -#[ignore] -async fn parity_get_columns_nullable_detection() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_columns:all_types:nullable", - |driver, params| async move { - driver - .get_columns(¶ms, "all_types", Some("test_schema")) - .await - }, - ) - .await; - - let arr = result.as_array().expect("columns should be an array"); - - // id (SERIAL PRIMARY KEY) is NOT NULL - let id_col = arr - .iter() - .find(|c| c.get("name").and_then(|n| n.as_str()) == Some("id")) - .unwrap(); - assert_eq!( - id_col.get("is_nullable").and_then(|v| v.as_bool()), - Some(false), - "PK should not be nullable" - ); - - // col_text has no NOT NULL constraint - let text_col = arr - .iter() - .find(|c| c.get("name").and_then(|n| n.as_str()) == Some("col_text")) - .unwrap(); - assert_eq!( - text_col.get("is_nullable").and_then(|v| v.as_bool()), - Some(true), - "col_text should be nullable" - ); -} - -/// Parity equivalent of `test_get_columns_type_detection`. -/// Verifies data type strings match between drivers for multiple column types. -#[tokio::test] -#[ignore] -async fn parity_get_columns_type_detection() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_columns:all_types:type_detection", - |driver, params| async move { - driver - .get_columns(¶ms, "all_types", Some("test_schema")) - .await - }, - ) - .await; - - let arr = result.as_array().expect("columns should be an array"); - let find = |name: &str| -> &Value { - arr.iter() - .find(|c| c.get("name").and_then(|n| n.as_str()) == Some(name)) - .unwrap_or_else(|| panic!("column '{}' should exist", name)) - }; - - assert_eq!( - find("col_text").get("data_type").and_then(|v| v.as_str()), - Some("text") - ); - assert_eq!( - find("col_int").get("data_type").and_then(|v| v.as_str()), - Some("integer") - ); - assert_eq!( - find("col_bigint").get("data_type").and_then(|v| v.as_str()), - Some("bigint") - ); - assert_eq!( - find("col_bool").get("data_type").and_then(|v| v.as_str()), - Some("boolean") - ); - assert_eq!( - find("col_uuid").get("data_type").and_then(|v| v.as_str()), - Some("uuid") - ); - assert_eq!( - find("col_jsonb").get("data_type").and_then(|v| v.as_str()), - Some("jsonb") - ); - assert_eq!( - find("col_bytea").get("data_type").and_then(|v| v.as_str()), - Some("bytea") - ); - assert_eq!( - find("col_timestamptz") - .get("data_type") - .and_then(|v| v.as_str()), - Some("timestamp with time zone") - ); -} - -/// Parity equivalent of `test_get_columns_character_max_length`. -/// Verifies that character_maximum_length is reported identically. -#[tokio::test] -#[ignore] -async fn parity_get_columns_character_max_length() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_columns:all_types:char_max_length", - |driver, params| async move { - driver - .get_columns(¶ms, "all_types", Some("test_schema")) - .await - }, - ) - .await; - - let arr = result.as_array().expect("columns should be an array"); - - let varchar_col = arr - .iter() - .find(|c| c.get("name").and_then(|n| n.as_str()) == Some("col_varchar")) - .expect("col_varchar should exist"); - assert_eq!( - varchar_col.get("character_maximum_length"), - Some(&serde_json::Value::from(255)), - "PG driver returns character_maximum_length for varchar(n)" - ); - - let text_col = arr - .iter() - .find(|c| c.get("name").and_then(|n| n.as_str()) == Some("col_text")) - .expect("col_text should exist"); - assert!( - text_col.get("character_maximum_length").is_none() - || text_col.get("character_maximum_length") == Some(&Value::Null), - "TEXT has no max length" - ); -} - -/// Parity equivalent of `test_get_columns_enum_type`. -/// Verifies enum type representation matches between drivers. -#[tokio::test] -#[ignore] -async fn parity_get_columns_enum_type() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_columns:with_enum", |driver, params| async move { - driver - .get_columns(¶ms, "with_enum", Some("test_schema")) - .await - }) - .await; - - let arr = result.as_array().expect("columns should be an array"); - let mood_col = arr - .iter() - .find(|c| c.get("name").and_then(|n| n.as_str()) == Some("current_mood")) - .expect("current_mood column should exist"); - - let data_type = mood_col - .get("data_type") - .and_then(|v| v.as_str()) - .expect("data_type should be a string"); - // The PG driver resolves enum types — the plugin must match exactly. - // The assert_parity() already guarantees the strings are equal; - // this structural check just documents the expected format. - assert!( - data_type.contains("mood") - || data_type.starts_with("enum(") - || data_type == "USER-DEFINED", - "Enum column data_type should contain 'mood', start with 'enum(', or be 'USER-DEFINED', got: {}", - data_type - ); -} diff --git a/src-tauri/tests/postgres_integration/parity_crud.rs b/src-tauri/tests/postgres_integration/parity_crud.rs deleted file mode 100644 index 895ee0b7b..000000000 --- a/src-tauri/tests/postgres_integration/parity_crud.rs +++ /dev/null @@ -1,166 +0,0 @@ -//! Parity tests for CRUD operations — insert_record, update_record, delete_record. -//! -//! All tests use the `crud_scratch` table which is truncated by the seed script. - -use std::collections::HashMap; - -use serde_json::json; - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_insert_record() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("insert_record:basic", |driver, params| async move { - let mut data = HashMap::new(); - data.insert("name".to_string(), json!("parity_insert")); - data.insert("value".to_string(), json!(100)); - driver - .insert_record(¶ms, "crud_scratch", data, Some("test_schema"), 0) - .await - }) - .await; - - let affected = result.as_u64().expect("insert should return affected rows"); - assert_eq!(affected, 1, "inserting one row should affect 1 row"); -} - -#[tokio::test] -#[ignore] -async fn parity_update_record() { - require_pg!(); - let harness = ParityHarness::new().await; - - // Setup: insert a row to update (use execute_query for deterministic PK) - for (_target, driver) in harness.targets() { - let _ = driver - .execute_query( - &harness.params, - "INSERT INTO test_schema.crud_scratch(id, name, value) VALUES (9000, 'update_target', 1) ON CONFLICT (id) DO NOTHING", - None, - 1, - Some("test_schema"), - ) - .await; - } - - let result = harness - .assert_parity("update_record:basic", |driver, params| async move { - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), json!(9000)); - driver - .update_record( - ¶ms, - "crud_scratch", - &pk_map, - "value", - json!(999), - Some("test_schema"), - 0, - ) - .await - }) - .await; - - let affected = result.as_u64().expect("update should return affected rows"); - assert_eq!(affected, 1, "updating one matching row should affect 1 row"); -} - -#[tokio::test] -#[ignore] -async fn parity_delete_record() { - require_pg!(); - let harness = ParityHarness::new().await; - - // DELETE is destructive against the one shared physical database both - // targets point at — assert_parity calls each target in sequence, so a - // row inserted once and deleted by the first target would legitimately - // report 0 rows affected for the second target (it's already gone). - // Re-insert the row before each target's delete attempt instead of - // sharing a single setup pass, and compare only the deterministic - // affected_rows count directly (matches the direct-per-target pattern - // used in parity_batch.rs for the same class of issue). - let mut affected_by_target = Vec::new(); - for (target, driver) in harness.targets() { - driver - .execute_query( - &harness.params, - "INSERT INTO test_schema.crud_scratch(id, name, value) VALUES (9001, 'delete_target', 1) ON CONFLICT (id) DO UPDATE SET name = 'delete_target', value = 1", - None, - 1, - Some("test_schema"), - ) - .await - .unwrap_or_else(|e| panic!("setup insert failed on {}: {}", target, e)); - - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), json!(9001)); - let affected = driver - .delete_record( - &harness.params, - "crud_scratch", - &pk_map, - Some("test_schema"), - ) - .await - .unwrap_or_else(|e| panic!("delete_record failed on {}: {}", target, e)); - affected_by_target.push((target.to_string(), affected)); - } - - for (target, affected) in &affected_by_target { - assert_eq!( - *affected, 1, - "{}: deleting one matching row should affect 1 row", - target - ); - } -} - -#[tokio::test] -#[ignore] -async fn parity_insert_types() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("insert_record:types", |driver, params| async move { - let mut data = HashMap::new(); - data.insert("name".to_string(), json!("typed_insert")); - data.insert("value".to_string(), json!(42)); - driver - .insert_record(¶ms, "crud_scratch", data, Some("test_schema"), 0) - .await - }) - .await; - - let affected = result.as_u64().expect("insert should return affected rows"); - assert_eq!(affected, 1); -} - -#[tokio::test] -#[ignore] -async fn parity_delete_nonexistent() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("delete_record:nonexistent", |driver, params| async move { - let mut pk_map = HashMap::new(); - // Use an ID that definitely doesn't exist - pk_map.insert("id".to_string(), json!(999999)); - driver - .delete_record(¶ms, "crud_scratch", &pk_map, Some("test_schema")) - .await - }) - .await; - - let affected = result.as_u64().expect("delete should return affected rows"); - assert_eq!( - affected, 0, - "deleting a non-existent row should affect 0 rows" - ); -} diff --git a/src-tauri/tests/postgres_integration/parity_crud_extra.rs b/src-tauri/tests/postgres_integration/parity_crud_extra.rs deleted file mode 100644 index a50d5de05..000000000 --- a/src-tauri/tests/postgres_integration/parity_crud_extra.rs +++ /dev/null @@ -1,475 +0,0 @@ -//! Extra parity tests for CRUD — composite PK, NULL update, insert_with_default, -//! enum column binding. - -use std::collections::HashMap; - -use serde_json::{json, Value}; - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_keyless_real_two_column_update_accepts_string_identity() { - require_pg!(); - let harness = ParityHarness::new().await; - for (target, driver) in harness.targets() { - for query in [ - "DROP TABLE IF EXISTS test_schema.float4_keyless_edit", - "CREATE TABLE test_schema.float4_keyless_edit (price real, label text)", - "INSERT INTO test_schema.float4_keyless_edit VALUES (89.9, 'a')", - ] { - driver - .execute_query(&harness.params, query, None, 1, Some("test_schema")) - .await - .unwrap(); - } - let mut identity = HashMap::from([ - ("price".to_string(), json!(89.9)), - ("label".to_string(), json!("a")), - ]); - let edited_price = json!("59.99"); - let first = driver - .update_record( - &harness.params, - "float4_keyless_edit", - &identity, - "price", - edited_price.clone(), - Some("test_schema"), - 0, - ) - .await - .unwrap(); - assert_eq!(first, 1, "{target}: price update"); - // The next keyless step carries the editor's string without re-reading the row. - identity.insert("price".to_string(), edited_price); - let second = driver - .update_record( - &harness.params, - "float4_keyless_edit", - &identity, - "label", - json!("b"), - Some("test_schema"), - 0, - ) - .await - .unwrap(); - assert_eq!( - second, 1, - "{target}: label update with string REAL identity" - ); - let result = driver - .execute_query( - &harness.params, - "SELECT price, label FROM test_schema.float4_keyless_edit", - None, - 1, - Some("test_schema"), - ) - .await - .unwrap(); - assert_eq!( - result.rows, - vec![vec![json!(59.99), json!("b")]], - "{target}" - ); - driver - .execute_query( - &harness.params, - "DROP TABLE test_schema.float4_keyless_edit", - None, - 1, - Some("test_schema"), - ) - .await - .unwrap(); - } -} - -#[tokio::test] -#[ignore] -async fn parity_real_primary_keys_round_trip_through_json() { - require_pg!(); - let harness = ParityHarness::new().await; - for (target, driver) in harness.targets() { - for primary_key in ["price", "price, id"] { - driver - .execute_query( - &harness.params, - "DROP TABLE IF EXISTS test_schema.float4_pk_review", - None, - 1, - Some("test_schema"), - ) - .await - .unwrap(); - driver - .execute_query( - &harness.params, - &format!( - "CREATE TABLE test_schema.float4_pk_review \ - (price real, id integer, label text, PRIMARY KEY ({primary_key}))" - ), - None, - 1, - Some("test_schema"), - ) - .await - .unwrap(); - for price in [ - 89.9f32, - f32::from_bits(0x15ae43fd), - -f32::from_bits(0x15ae43fd), - ] { - let data = HashMap::from([ - ("price".to_string(), json!(price)), - ("id".to_string(), json!(1)), - ("label".to_string(), json!("before")), - ]); - driver - .insert_record( - &harness.params, - "float4_pk_review", - data, - Some("test_schema"), - 0, - ) - .await - .unwrap(); - let result = driver - .execute_query( - &harness.params, - "SELECT price FROM test_schema.float4_pk_review", - None, - 1, - Some("test_schema"), - ) - .await - .unwrap(); - let encoded = serde_json::to_string(&result.rows[0][0]).unwrap(); - let decoded: Value = serde_json::from_str(&encoded).unwrap(); - assert_eq!( - (decoded.as_f64().unwrap() as f32).to_bits(), - price.to_bits(), - "{target}" - ); - let mut pk_map = HashMap::from([("price".to_string(), decoded)]); - if primary_key == "price, id" { - pk_map.insert("id".to_string(), json!(1)); - } - let updated = driver - .update_record( - &harness.params, - "float4_pk_review", - &pk_map, - "label", - json!("after"), - Some("test_schema"), - 0, - ) - .await - .unwrap(); - assert_eq!(updated, 1, "{target}: {primary_key}, {price}"); - let deleted = driver - .delete_record( - &harness.params, - "float4_pk_review", - &pk_map, - Some("test_schema"), - ) - .await - .unwrap(); - assert_eq!(deleted, 1, "{target}: {primary_key}, {price}"); - } - driver - .execute_query( - &harness.params, - "DROP TABLE test_schema.float4_pk_review", - None, - 1, - Some("test_schema"), - ) - .await - .unwrap(); - } - } -} - -#[tokio::test] -#[ignore] -async fn parity_update_composite_pk() { - require_pg!(); - let harness = ParityHarness::new().await; - - // order_items has composite PK (order_id, item_no) and order_id has an FK - // to orders(id). The seed only creates order id=1, so reuse it here with - // a distinct item_no to avoid colliding with the seeded (1, 1) row. - for (_target, driver) in harness.targets() { - let _ = driver - .execute_query( - &harness.params, - "INSERT INTO test_schema.order_items(order_id, item_no, product) \ - VALUES (1, 99, 'Parity Widget') ON CONFLICT (order_id, item_no) DO NOTHING", - None, - 1, - Some("test_schema"), - ) - .await; - } - - // Update using composite PK - let result = harness - .assert_parity("update_record:composite_pk", |driver, params| async move { - let mut pk_map = HashMap::new(); - pk_map.insert("order_id".to_string(), json!(1)); - pk_map.insert("item_no".to_string(), json!(99)); - driver - .update_record( - ¶ms, - "order_items", - &pk_map, - "product", - json!("Parity Updated Widget"), - Some("test_schema"), - 0, - ) - .await - }) - .await; - - let affected = result.as_u64().expect("update should return affected rows"); - assert_eq!( - affected, 1, - "Composite PK update should affect exactly 1 row" - ); - - // Restore original value - for (_target, driver) in harness.targets() { - let mut pk_map = HashMap::new(); - pk_map.insert("order_id".to_string(), json!(1)); - pk_map.insert("item_no".to_string(), json!(99)); - let _ = driver - .update_record( - &harness.params, - "order_items", - &pk_map, - "product", - json!("Parity Widget"), - Some("test_schema"), - 0, - ) - .await; - } -} - -#[tokio::test] -#[ignore] -async fn parity_update_to_null() { - require_pg!(); - let harness = ParityHarness::new().await; - - // Setup: insert a row with a non-null value - for (_target, driver) in harness.targets() { - let _ = driver - .execute_query( - &harness.params, - "INSERT INTO test_schema.crud_scratch(id, name, value) \ - VALUES (9010, 'parity_null_update', 42) \ - ON CONFLICT (id) DO UPDATE SET value = 42", - None, - 1, - Some("test_schema"), - ) - .await; - } - - // Update the value column to NULL - let result = harness - .assert_parity("update_record:set_null", |driver, params| async move { - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), json!(9010)); - driver - .update_record( - ¶ms, - "crud_scratch", - &pk_map, - "value", - json!(null), - Some("test_schema"), - 0, - ) - .await - }) - .await; - - let affected = result.as_u64().expect("update should return affected rows"); - assert_eq!(affected, 1, "NULL update should affect 1 row"); - - // Verify the value is now NULL - let verify = harness - .assert_parity( - "execute_query:verify_null_update", - |driver, params| async move { - driver - .execute_query( - ¶ms, - "SELECT value FROM test_schema.crud_scratch WHERE id = 9010", - Some(100), - 1, - Some("test_schema"), - ) - .await - }, - ) - .await; - - let rows = verify.get("rows").and_then(Value::as_array).unwrap(); - assert_eq!(rows.len(), 1); - let value = rows[0] - .as_array() - .and_then(|arr| arr.first()) - .unwrap_or(&Value::Null); - assert!( - value.is_null(), - "Value should be NULL after update, got: {:?}", - value - ); -} - -#[tokio::test] -#[ignore] -async fn parity_insert_with_default() { - require_pg!(); - let harness = ParityHarness::new().await; - - // Insert only the name column — let `id` use its DEFAULT (serial/auto-increment) - // and `value` default to NULL. - let result = harness - .assert_parity("insert_record:with_default", |driver, params| async move { - let mut data = HashMap::new(); - data.insert("name".to_string(), json!("parity_default_test")); - driver - .insert_record(¶ms, "crud_scratch", data, Some("test_schema"), 0) - .await - }) - .await; - - let affected = result.as_u64().expect("insert should return affected rows"); - assert_eq!( - affected, 1, - "Insert with defaults should affect exactly 1 row" - ); - - // Verify the row was inserted (value should be NULL since we didn't set it) - let verify = harness - .assert_parity( - "execute_query:verify_default_insert", - |driver, params| async move { - driver - .execute_query( - ¶ms, - "SELECT name, value FROM test_schema.crud_scratch \ - WHERE name = 'parity_default_test' LIMIT 1", - Some(100), - 1, - Some("test_schema"), - ) - .await - }, - ) - .await; - - let rows = verify.get("rows").and_then(Value::as_array).unwrap(); - assert!(!rows.is_empty(), "Inserted row should be queryable"); -} - -#[tokio::test] -#[ignore] -async fn parity_insert_enum_value() { - require_pg!(); - let harness = ParityHarness::new().await; - - // with_enum.current_mood is a PostgreSQL enum (test_schema.mood). Binding - // an enum column requires a CAST($N AS ) — without it, the - // driver sends a plain TEXT parameter and PostgreSQL rejects it with - // "column current_mood is of type mood but expression is of type text". - // insert_record is destructive (adds a row neither target can attribute - // to a stable id), so clean up per target inside the loop. - for (target, driver) in harness.targets() { - let mut data = HashMap::new(); - data.insert("current_mood".to_string(), json!("sad")); - - let affected = driver - .insert_record(&harness.params, "with_enum", data, Some("test_schema"), 0) - .await - .unwrap_or_else(|e| { - panic!("insert_record with enum value failed on {}: {}", target, e) - }); - assert_eq!( - affected, 1, - "{}: inserting one enum row should affect 1 row", - target - ); - - driver - .execute_query( - &harness.params, - "DELETE FROM test_schema.with_enum WHERE current_mood = 'sad'", - None, - 1, - Some("test_schema"), - ) - .await - .unwrap_or_else(|e| panic!("cleanup delete failed on {}: {}", target, e)); - } -} - -#[tokio::test] -#[ignore] -async fn parity_update_enum_value() { - require_pg!(); - let harness = ParityHarness::new().await; - - // Same enum-CAST requirement as parity_insert_enum_value, exercised via - // update_record instead. Seed row id=1 always exists (see - // tests/fixtures/postgres_seed.sql) with current_mood = 'happy'. - for (target, driver) in harness.targets() { - let mut pk_map = HashMap::new(); - pk_map.insert("id".to_string(), json!(1)); - - let affected = driver - .update_record( - &harness.params, - "with_enum", - &pk_map, - "current_mood", - json!("neutral"), - Some("test_schema"), - 0, - ) - .await - .unwrap_or_else(|e| { - panic!("update_record with enum value failed on {}: {}", target, e) - }); - assert_eq!( - affected, 1, - "{}: updating the enum column should affect 1 row", - target - ); - - // Restore the seeded value so later tests see the original state. - driver - .update_record( - &harness.params, - "with_enum", - &pk_map, - "current_mood", - json!("happy"), - Some("test_schema"), - 0, - ) - .await - .unwrap_or_else(|e| panic!("restore failed on {}: {}", target, e)); - } -} diff --git a/src-tauri/tests/postgres_integration/parity_ddl.rs b/src-tauri/tests/postgres_integration/parity_ddl.rs deleted file mode 100644 index 7affcf12d..000000000 --- a/src-tauri/tests/postgres_integration/parity_ddl.rs +++ /dev/null @@ -1,389 +0,0 @@ -//! Parity tests for DDL generation — covers ALL 7 baseline tests from -//! `ddl_generation.rs`. None of these were previously covered by parity tests. -//! -//! DDL methods generate SQL without connecting to the database. The parity -//! comparison ensures the plugin generates IDENTICAL DDL strings to the builtin. - -use tabularis_lib::models::ColumnDefinition; - -use crate::parity::ParityHarness; - -/// Parity equivalent of `test_get_create_table_sql`. -/// Verifies CREATE TABLE DDL generation matches between drivers. -#[tokio::test] -#[ignore] -async fn parity_ddl_create_table() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_create_table_sql:basic", |driver, _params| async move { - let columns = vec![ - ColumnDefinition { - name: "id".to_string(), - data_type: "SERIAL".to_string(), - is_nullable: false, - is_pk: true, - is_auto_increment: true, - default_value: None, - comment: None, - on_update: None, - }, - ColumnDefinition { - name: "name".to_string(), - data_type: "TEXT".to_string(), - is_nullable: false, - is_pk: false, - is_auto_increment: false, - default_value: None, - comment: None, - on_update: None, - }, - ColumnDefinition { - name: "email".to_string(), - data_type: "VARCHAR(255)".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: Some("'unknown@example.com'".to_string()), - comment: None, - on_update: None, - }, - ]; - driver - .get_create_table_sql("parity_ddl_scratch_table", columns, Some("test_schema")) - .await - }) - .await; - - let arr = result - .as_array() - .expect("DDL should return array of statements"); - assert!(!arr.is_empty(), "Should return at least one SQL statement"); - - let sql: String = arr - .iter() - .filter_map(|v| v.as_str()) - .collect::>() - .join("; "); - let lower = sql.to_lowercase(); - - assert!( - lower.contains("create table"), - "Should contain CREATE TABLE" - ); - assert!( - lower.contains("parity_ddl_scratch_table"), - "Should contain table name" - ); - assert!( - lower.contains("serial") || lower.contains("generated"), - "Should handle auto-increment" - ); - assert!(lower.contains("not null"), "Should contain NOT NULL"); - assert!( - lower.contains("varchar(255)") || lower.contains("character varying(255)"), - "Should preserve varchar type" - ); -} - -/// Parity equivalent of `test_get_add_column_sql`. -/// Verifies ADD COLUMN DDL generation matches between drivers. -#[tokio::test] -#[ignore] -async fn parity_ddl_add_column() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_add_column_sql:basic", |driver, _params| async move { - let column = ColumnDefinition { - name: "new_col".to_string(), - data_type: "INTEGER".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: Some("0".to_string()), - comment: None, - on_update: None, - }; - driver - .get_add_column_sql("all_types", column, Some("test_schema")) - .await - }) - .await; - - let arr = result - .as_array() - .expect("DDL should return array of statements"); - assert!(!arr.is_empty()); - - let sql: String = arr - .iter() - .filter_map(|v| v.as_str()) - .collect::>() - .join("; "); - let lower = sql.to_lowercase(); - - assert!(lower.contains("alter table"), "Should contain ALTER TABLE"); - assert!(lower.contains("add column"), "Should contain ADD COLUMN"); - assert!(lower.contains("new_col"), "Should contain column name"); - assert!(lower.contains("integer"), "Should contain type"); -} - -/// Parity equivalent of `test_get_alter_column_rename`. -/// Verifies RENAME COLUMN DDL generation matches between drivers. -#[tokio::test] -#[ignore] -async fn parity_ddl_alter_column_rename() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_alter_column_sql:rename", - |driver, _params| async move { - let old_column = ColumnDefinition { - name: "old_name".to_string(), - data_type: "TEXT".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: None, - comment: None, - on_update: None, - }; - let new_column = ColumnDefinition { - name: "new_name".to_string(), - data_type: "TEXT".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: None, - comment: None, - on_update: None, - }; - driver - .get_alter_column_sql("all_types", old_column, new_column, Some("test_schema")) - .await - }, - ) - .await; - - let arr = result - .as_array() - .expect("DDL should return array of statements"); - assert!(!arr.is_empty()); - - let sql: String = arr - .iter() - .filter_map(|v| v.as_str()) - .collect::>() - .join("; "); - let lower = sql.to_lowercase(); - - assert!( - lower.contains("rename column") || lower.contains("alter column"), - "Should rename" - ); - assert!(lower.contains("old_name"), "Should reference old name"); - assert!(lower.contains("new_name"), "Should reference new name"); -} - -/// Parity equivalent of `test_get_alter_column_type_change`. -/// Verifies ALTER COLUMN TYPE DDL generation matches between drivers. -#[tokio::test] -#[ignore] -async fn parity_ddl_alter_column_type_change() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_alter_column_sql:type_change", - |driver, _params| async move { - let old_column = ColumnDefinition { - name: "col_text".to_string(), - data_type: "TEXT".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: None, - comment: None, - on_update: None, - }; - let new_column = ColumnDefinition { - name: "col_text".to_string(), - data_type: "VARCHAR(500)".to_string(), - is_nullable: true, - is_pk: false, - is_auto_increment: false, - default_value: None, - comment: None, - on_update: None, - }; - driver - .get_alter_column_sql("all_types", old_column, new_column, Some("test_schema")) - .await - }, - ) - .await; - - let arr = result - .as_array() - .expect("DDL should return array of statements"); - assert!(!arr.is_empty()); - - let sql: String = arr - .iter() - .filter_map(|v| v.as_str()) - .collect::>() - .join("; "); - let lower = sql.to_lowercase(); - - assert!( - lower.contains("type") || lower.contains("alter column"), - "Should change type, got: {}", - sql - ); -} - -/// Parity equivalent of `test_get_create_index_sql`. -/// Verifies CREATE INDEX DDL generation matches between drivers. -#[tokio::test] -#[ignore] -async fn parity_ddl_create_index() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_create_index_sql:multi_column", - |driver, _params| async move { - driver - .get_create_index_sql( - "all_types", - "idx_parity_ddl_test", - vec!["col_text".to_string(), "col_int".to_string()], - false, // not unique - Some("test_schema"), - ) - .await - }, - ) - .await; - - let arr = result - .as_array() - .expect("DDL should return array of statements"); - assert!(!arr.is_empty()); - - let sql: String = arr - .iter() - .filter_map(|v| v.as_str()) - .collect::>() - .join("; "); - let lower = sql.to_lowercase(); - - assert!( - lower.contains("create index"), - "Should contain CREATE INDEX" - ); - assert!( - lower.contains("idx_parity_ddl_test"), - "Should contain index name" - ); - assert!(lower.contains("col_text"), "Should contain first column"); - assert!(lower.contains("col_int"), "Should contain second column"); -} - -/// Parity equivalent of `test_get_create_index_sql_unique`. -/// Verifies CREATE UNIQUE INDEX DDL generation matches between drivers. -#[tokio::test] -#[ignore] -async fn parity_ddl_create_index_unique() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_create_index_sql:unique", - |driver, _params| async move { - driver - .get_create_index_sql( - "all_types", - "idx_parity_ddl_unique_test", - vec!["col_varchar".to_string()], - true, // unique - Some("test_schema"), - ) - .await - }, - ) - .await; - - let arr = result - .as_array() - .expect("DDL should return array of statements"); - let sql: String = arr - .iter() - .filter_map(|v| v.as_str()) - .collect::>() - .join("; "); - let lower = sql.to_lowercase(); - - assert!( - lower.contains("create unique index"), - "Should contain CREATE UNIQUE INDEX" - ); -} - -/// Parity equivalent of `test_get_create_foreign_key_sql`. -/// Verifies ADD CONSTRAINT FOREIGN KEY DDL generation matches between drivers. -#[tokio::test] -#[ignore] -async fn parity_ddl_create_foreign_key() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_create_foreign_key_sql:basic", - |driver, params| async move { - driver - .get_create_foreign_key_sql( - ¶ms, - "crud_scratch", - "fk_parity_ddl_test", - "value", - "all_types", - "id", - None, - None, - Some("test_schema"), - ) - .await - }, - ) - .await; - - let arr = result - .as_array() - .expect("DDL should return array of statements"); - assert!(!arr.is_empty()); - - let sql: String = arr - .iter() - .filter_map(|v| v.as_str()) - .collect::>() - .join("; "); - let lower = sql.to_lowercase(); - - assert!(lower.contains("alter table"), "Should contain ALTER TABLE"); - assert!( - lower.contains("add constraint"), - "Should contain ADD CONSTRAINT" - ); - assert!(lower.contains("foreign key"), "Should contain FOREIGN KEY"); - assert!(lower.contains("references"), "Should contain REFERENCES"); -} diff --git a/src-tauri/tests/postgres_integration/parity_explain.rs b/src-tauri/tests/postgres_integration/parity_explain.rs deleted file mode 100644 index 8354e6804..000000000 --- a/src-tauri/tests/postgres_integration/parity_explain.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! Parity tests for `explain_query` — verifies both drivers succeed on EXPLAIN. -//! -//! Note: ExplainQueryOutput differs structurally between built-in (Raw variant) -//! and plugin (Plan variant). These tests verify that both drivers return Ok -//! (no error) rather than comparing exact output, since EXPLAIN output contains -//! volatile runtime values (cost estimates, actual times, buffers). - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_explain_simple() { - require_pg!(); - let harness = ParityHarness::new().await; - - // We cannot use assert_parity here because the output format differs. - // Instead, verify that each target returns Ok (non-error) for EXPLAIN. - for (target, driver) in harness.targets() { - let result = driver - .explain_query( - &harness.params, - "SELECT id, col_text FROM test_schema.all_types WHERE id < 5", - false, - Some("test_schema"), - ) - .await; - - assert!( - result.is_ok(), - "EXPLAIN (no analyze) failed on target {}: {:?}", - target, - result.err() - ); - } -} - -#[tokio::test] -#[ignore] -async fn parity_explain_analyze() { - require_pg!(); - let harness = ParityHarness::new().await; - - // EXPLAIN ANALYZE actually executes the query and reports timing. - for (target, driver) in harness.targets() { - let result = driver - .explain_query( - &harness.params, - "SELECT id FROM test_schema.all_types ORDER BY id LIMIT 3", - true, - Some("test_schema"), - ) - .await; - - assert!( - result.is_ok(), - "EXPLAIN ANALYZE failed on target {}: {:?}", - target, - result.err() - ); - } -} diff --git a/src-tauri/tests/postgres_integration/parity_foreign_keys.rs b/src-tauri/tests/postgres_integration/parity_foreign_keys.rs deleted file mode 100644 index 6d4d8df3b..000000000 --- a/src-tauri/tests/postgres_integration/parity_foreign_keys.rs +++ /dev/null @@ -1,112 +0,0 @@ -//! Parity tests for foreign key introspection — covers baseline tests from -//! `foreign_keys.rs` that are NOT already covered in `parity_tests.rs`. -//! -//! Already covered by `parity_tests.rs`: -//! - parity_get_foreign_keys (basic: orders table, checks user_id FK) -//! -//! New in this file — each test calls `get_foreign_keys` through the trait via -//! the harness and uses `assert_parity()` for byte-perfect JSON comparison. - -use crate::parity::ParityHarness; - -/// Parity equivalent of `test_get_foreign_keys_composite_table`. -/// Verifies FK introspection on order_items (FK to orders). -#[tokio::test] -#[ignore] -async fn parity_get_foreign_keys_composite_table() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_foreign_keys:order_items", - |driver, params| async move { - driver - .get_foreign_keys(¶ms, "order_items", Some("test_schema")) - .await - }, - ) - .await; - - let arr = result.as_array().expect("foreign keys should be an array"); - let order_fk = arr - .iter() - .find(|f| f.get("column_name").and_then(|v| v.as_str()) == Some("order_id")) - .expect("Expected FK on order_id"); - - assert_eq!( - order_fk.get("ref_table").and_then(|v| v.as_str()), - Some("orders"), - "order_id FK should reference orders" - ); - assert_eq!( - order_fk.get("ref_column").and_then(|v| v.as_str()), - Some("id"), - "order_id FK should reference id column" - ); - assert_eq!( - order_fk.get("on_delete").and_then(|v| v.as_str()), - Some("CASCADE"), - "Expected ON DELETE CASCADE" - ); -} - -/// Parity equivalent of `test_get_foreign_keys_cross_schema`. -/// Verifies FK introspection on a table referencing another schema. -#[tokio::test] -#[ignore] -async fn parity_get_foreign_keys_cross_schema() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_foreign_keys:with_cross_schema_fk", - |driver, params| async move { - driver - .get_foreign_keys(¶ms, "with_cross_schema_fk", Some("test_schema")) - .await - }, - ) - .await; - - let arr = result.as_array().expect("foreign keys should be an array"); - let lookup_fk = arr - .iter() - .find(|f| f.get("column_name").and_then(|v| v.as_str()) == Some("lookup_code")) - .expect("Expected FK on lookup_code"); - - assert_eq!( - lookup_fk.get("ref_table").and_then(|v| v.as_str()), - Some("lookup"), - "lookup_code FK should reference lookup table" - ); - assert_eq!( - lookup_fk.get("ref_column").and_then(|v| v.as_str()), - Some("code"), - "lookup_code FK should reference code column" - ); -} - -/// Parity equivalent of `test_get_foreign_keys_table_without_fks`. -/// Verifies a table with no foreign keys returns an empty array from both drivers. -#[tokio::test] -#[ignore] -async fn parity_get_foreign_keys_table_without_fks() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_foreign_keys:crud_scratch:empty", - |driver, params| async move { - driver - .get_foreign_keys(¶ms, "crud_scratch", Some("test_schema")) - .await - }, - ) - .await; - - let arr = result.as_array().expect("foreign keys should be an array"); - assert!(arr.is_empty(), "crud_scratch has no foreign keys"); -} diff --git a/src-tauri/tests/postgres_integration/parity_indexes.rs b/src-tauri/tests/postgres_integration/parity_indexes.rs deleted file mode 100644 index 66188cf1e..000000000 --- a/src-tauri/tests/postgres_integration/parity_indexes.rs +++ /dev/null @@ -1,178 +0,0 @@ -//! Parity tests for index introspection — covers baseline tests from -//! `indexes.rs` that are NOT already covered in `parity_tests.rs`. -//! -//! Already covered by `parity_tests.rs`: -//! - parity_get_indexes (basic: all_types table, checks non-empty) -//! -//! New in this file — each test calls `get_indexes` through the trait via the -//! harness and uses `assert_parity()` for byte-perfect JSON comparison. - -use serde_json::Value; - -use crate::parity::ParityHarness; - -/// Parity equivalent of `test_get_indexes_btree`. -/// Verifies a specific btree index is present with correct attributes. -#[tokio::test] -#[ignore] -async fn parity_get_indexes_btree() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_indexes:all_types:btree", |driver, params| async move { - driver - .get_indexes(¶ms, "all_types", Some("test_schema")) - .await - }) - .await; - - let arr = result.as_array().expect("indexes should be an array"); - let idx = arr - .iter() - .find(|i| i.get("name").and_then(|n| n.as_str()) == Some("idx_all_types_text")) - .expect("Expected idx_all_types_text index"); - - assert_eq!( - idx.get("column_name").and_then(|v| v.as_str()), - Some("col_text"), - "idx_all_types_text should be on col_text" - ); - assert_eq!( - idx.get("is_unique").and_then(|v| v.as_bool()), - Some(false), - "idx_all_types_text should not be unique" - ); - assert_eq!( - idx.get("is_primary").and_then(|v| v.as_bool()), - Some(false), - "idx_all_types_text should not be primary" - ); -} - -/// Parity equivalent of `test_get_indexes_unique`. -/// Verifies a unique index is reported with correct flags. -#[tokio::test] -#[ignore] -async fn parity_get_indexes_unique() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_indexes:all_types:unique", - |driver, params| async move { - driver - .get_indexes(¶ms, "all_types", Some("test_schema")) - .await - }, - ) - .await; - - let arr = result.as_array().expect("indexes should be an array"); - let idx = arr - .iter() - .find(|i| i.get("name").and_then(|n| n.as_str()) == Some("idx_all_types_uuid")) - .expect("Expected idx_all_types_uuid unique index"); - - assert_eq!( - idx.get("column_name").and_then(|v| v.as_str()), - Some("col_uuid"), - "idx_all_types_uuid should be on col_uuid" - ); - assert_eq!( - idx.get("is_unique").and_then(|v| v.as_bool()), - Some(true), - "idx_all_types_uuid should be unique" - ); -} - -/// Parity equivalent of `test_get_indexes_composite`. -/// Verifies a composite (multi-column) index is reported with correct seq_in_index. -#[tokio::test] -#[ignore] -async fn parity_get_indexes_composite() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_indexes:order_items:composite", - |driver, params| async move { - driver - .get_indexes(¶ms, "order_items", Some("test_schema")) - .await - }, - ) - .await; - - let arr = result.as_array().expect("indexes should be an array"); - - // The composite index idx_order_items_composite covers (order_id, product) - let idx_entries: Vec<&Value> = arr - .iter() - .filter(|i| i.get("name").and_then(|n| n.as_str()) == Some("idx_order_items_composite")) - .collect(); - - assert_eq!( - idx_entries.len(), - 2, - "Composite index should have 2 entries (one per column)" - ); - - // Verify seq_in_index ordering - let first = idx_entries - .iter() - .find(|i| i.get("seq_in_index").and_then(|v| v.as_u64()) == Some(1)) - .expect("should have entry with seq_in_index=1"); - assert_eq!( - first.get("column_name").and_then(|v| v.as_str()), - Some("order_id") - ); - - let second = idx_entries - .iter() - .find(|i| i.get("seq_in_index").and_then(|v| v.as_u64()) == Some(2)) - .expect("should have entry with seq_in_index=2"); - assert_eq!( - second.get("column_name").and_then(|v| v.as_str()), - Some("product") - ); -} - -/// Parity equivalent of `test_get_indexes_primary_key`. -/// Verifies the primary key index is correctly reported. -#[tokio::test] -#[ignore] -async fn parity_get_indexes_primary_key() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_indexes:all_types:primary_key", - |driver, params| async move { - driver - .get_indexes(¶ms, "all_types", Some("test_schema")) - .await - }, - ) - .await; - - let arr = result.as_array().expect("indexes should be an array"); - let pk = arr - .iter() - .find(|i| i.get("is_primary").and_then(|v| v.as_bool()) == Some(true)) - .expect("Expected primary key index"); - - assert_eq!( - pk.get("column_name").and_then(|v| v.as_str()), - Some("id"), - "PK should be on id column" - ); - assert_eq!( - pk.get("is_unique").and_then(|v| v.as_bool()), - Some(true), - "PK index should also be unique" - ); -} diff --git a/src-tauri/tests/postgres_integration/parity_multi_db.rs b/src-tauri/tests/postgres_integration/parity_multi_db.rs deleted file mode 100644 index 8e80fa5ff..000000000 --- a/src-tauri/tests/postgres_integration/parity_multi_db.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! Parity tests for multi-database operations — using the secondary database -//! (tabularis_test_secondary) with its `secondary_schema.remote_data` table. - -use serde_json::Value; - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_get_schemas_secondary() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity_secondary("get_schemas:secondary", |driver, params| async move { - driver.get_schemas(¶ms).await - }) - .await; - - let schemas: Vec = serde_json::from_value(result).unwrap(); - assert!( - schemas.contains(&"secondary_schema".to_string()), - "secondary database should contain secondary_schema, got: {:?}", - schemas - ); -} - -#[tokio::test] -#[ignore] -async fn parity_get_columns_secondary() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity_secondary("get_columns:remote_data", |driver, params| async move { - driver - .get_columns(¶ms, "remote_data", Some("secondary_schema")) - .await - }) - .await; - - let columns = result.as_array().expect("columns should be an array"); - assert!(!columns.is_empty(), "remote_data table should have columns"); - - let col_names: Vec<&str> = columns - .iter() - .filter_map(|c| c.get("name").and_then(Value::as_str)) - .collect(); - assert!( - col_names.contains(&"id"), - "remote_data should have an id column, got: {:?}", - col_names - ); - assert!( - col_names.contains(&"value"), - "remote_data should have a value column, got: {:?}", - col_names - ); -} - -#[tokio::test] -#[ignore] -async fn parity_execute_query_secondary() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity_secondary("execute_query:secondary", |driver, params| async move { - driver - .execute_query( - ¶ms, - "SELECT id, value FROM secondary_schema.remote_data ORDER BY id LIMIT 5", - Some(100), - 1, - Some("secondary_schema"), - ) - .await - }) - .await; - - let rows = result.get("rows").and_then(Value::as_array).unwrap(); - assert!(!rows.is_empty(), "secondary query should return rows"); -} diff --git a/src-tauri/tests/postgres_integration/parity_multi_db_extra.rs b/src-tauri/tests/postgres_integration/parity_multi_db_extra.rs deleted file mode 100644 index ad9d5647d..000000000 --- a/src-tauri/tests/postgres_integration/parity_multi_db_extra.rs +++ /dev/null @@ -1,118 +0,0 @@ -//! Extra parity tests for multi-database operations — get_databases_lists_both, -//! get_tables_secondary, pool_isolation, fallback_to_maintenance_db. - -use serde_json::Value; -use tabularis_lib::models::DatabaseSelection; - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_get_databases_lists_both() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_databases:lists_both", |driver, params| async move { - driver.get_databases(¶ms).await - }) - .await; - - let databases: Vec = serde_json::from_value(result).unwrap(); - assert!( - databases.contains(&"testdb".to_string()), - "Should list testdb, got: {:?}", - databases - ); - assert!( - databases.contains(&"tabularis_test_secondary".to_string()), - "Should list tabularis_test_secondary, got: {:?}", - databases - ); -} - -#[tokio::test] -#[ignore] -async fn parity_get_tables_secondary_schema() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity_secondary("get_tables:secondary_extra", |driver, params| async move { - driver.get_tables(¶ms, Some("secondary_schema")).await - }) - .await; - - let tables = result.as_array().expect("tables should be an array"); - let table_names: Vec<&str> = tables - .iter() - .filter_map(|t| t.get("name").and_then(Value::as_str)) - .collect(); - assert!( - table_names.contains(&"remote_data"), - "Expected remote_data table in secondary, got: {:?}", - table_names - ); -} - -#[tokio::test] -#[ignore] -async fn parity_pool_isolation_between_databases() { - require_pg!(); - let harness = ParityHarness::new().await; - - // Primary database should see test_schema tables - let primary_result = harness - .assert_parity( - "get_tables:primary_pool_isolation", - |driver, params| async move { driver.get_tables(¶ms, Some("test_schema")).await }, - ) - .await; - - let primary_tables = primary_result.as_array().expect("tables should be array"); - assert!( - !primary_tables.is_empty(), - "Primary db should have test_schema tables" - ); - - // Secondary database should NOT have test_schema - let secondary_result = harness - .assert_parity_secondary( - "get_schemas:pool_isolation_secondary", - |driver, params| async move { driver.get_schemas(¶ms).await }, - ) - .await; - - let secondary_schemas: Vec = serde_json::from_value(secondary_result).unwrap(); - assert!( - !secondary_schemas.contains(&"test_schema".to_string()), - "test_schema should not exist in secondary database, got: {:?}", - secondary_schemas - ); -} - -#[tokio::test] -#[ignore] -async fn parity_fallback_to_maintenance_db() { - require_pg!(); - let harness = ParityHarness::new().await; - - // Connect with "postgres" maintenance database — should be able to list databases - let result = harness - .assert_parity( - "get_databases:maintenance_db", - |driver, params| async move { - let mut maint_params = params.clone(); - maint_params.database = DatabaseSelection::Single("postgres".to_string()); - driver.get_databases(&maint_params).await - }, - ) - .await; - - let databases: Vec = serde_json::from_value(result).unwrap(); - assert!( - databases.contains(&"testdb".to_string()), - "Maintenance db should list testdb, got: {:?}", - databases - ); -} diff --git a/src-tauri/tests/postgres_integration/parity_mv_extra.rs b/src-tauri/tests/postgres_integration/parity_mv_extra.rs deleted file mode 100644 index 6b9c05a0a..000000000 --- a/src-tauri/tests/postgres_integration/parity_mv_extra.rs +++ /dev/null @@ -1,29 +0,0 @@ -//! Extra parity tests for materialized views — MV definition retrieval. -//! -//! Both the built-in PostgreSQL driver and the plugin driver must return the -//! same materialized view definition. The built-in driver failed on PG 16 -//! ("error serializing parameter 0") when it bound a `String` directly to -//! `regclass`. It now resolves the MV by a `pg_class`/`pg_namespace` join -//! with `relkind = 'm'`, binding schema/name as text — which also avoids -//! the regclass serialization failure. See `get_view_definition` for the -//! plain-view variant. - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_get_materialized_view_definition() { - require_pg!(); - let harness = ParityHarness::new().await; - - harness - .assert_parity( - "get_materialized_view_definition:user_stats", - |driver, params| async move { - driver - .get_materialized_view_definition(¶ms, "user_stats", Some("test_schema")) - .await - }, - ) - .await; -} diff --git a/src-tauri/tests/postgres_integration/parity_query.rs b/src-tauri/tests/postgres_integration/parity_query.rs deleted file mode 100644 index 159897ce1..000000000 --- a/src-tauri/tests/postgres_integration/parity_query.rs +++ /dev/null @@ -1,261 +0,0 @@ -//! Parity tests for `execute_query` — ensures plugin produces identical query -//! results to the built-in driver. - -use serde_json::Value; - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_execute_query_basic_select() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("execute_query:basic_select", |driver, params| async move { - driver - .execute_query( - ¶ms, - "SELECT id, col_text FROM test_schema.all_types ORDER BY id LIMIT 5", - Some(100), - 1, - Some("test_schema"), - ) - .await - }) - .await; - - let rows = result.get("rows").and_then(Value::as_array).unwrap(); - assert!(!rows.is_empty()); - assert!(rows.len() <= 5); -} - -#[tokio::test] -#[ignore] -async fn parity_execute_query_all_types() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("execute_query:all_types", |driver, params| async move { - driver - .execute_query( - ¶ms, - "SELECT * FROM test_schema.all_types WHERE id = 1", - Some(100), - 1, - Some("test_schema"), - ) - .await - }) - .await; - - let rows = result.get("rows").and_then(Value::as_array).unwrap(); - assert_eq!(rows.len(), 1, "expected exactly one row for id = 1"); -} - -#[tokio::test] -#[ignore] -async fn parity_execute_query_with_pagination() { - require_pg!(); - let harness = ParityHarness::new().await; - - // The seed only guarantees 2 rows in all_types, so paginate with limit=1 - // across 2 pages rather than limit=2 (which would leave page 2 empty). - let page1 = harness - .assert_parity( - "execute_query:pagination_page1", - |driver, params| async move { - driver - .execute_query( - ¶ms, - "SELECT id, col_text FROM test_schema.all_types ORDER BY id", - Some(1), - 1, - Some("test_schema"), - ) - .await - }, - ) - .await; - - let rows_p1 = page1.get("rows").and_then(Value::as_array).unwrap(); - assert_eq!(rows_p1.len(), 1, "page 1 should have exactly 1 row"); - - // Page 2 with limit 1 — should return a different row - let page2 = harness - .assert_parity( - "execute_query:pagination_page2", - |driver, params| async move { - driver - .execute_query( - ¶ms, - "SELECT id, col_text FROM test_schema.all_types ORDER BY id", - Some(1), - 2, - Some("test_schema"), - ) - .await - }, - ) - .await; - - let rows_p2 = page2.get("rows").and_then(Value::as_array).unwrap(); - assert_eq!(rows_p2.len(), 1, "page 2 should have exactly 1 row"); - assert_ne!(rows_p1, rows_p2, "pages should return different rows"); -} - -#[tokio::test] -#[ignore] -async fn parity_execute_query_dml() { - require_pg!(); - let harness = ParityHarness::new().await; - - // Use UPDATE on a known scratch row to verify affected_rows handling. - // First insert a row to update. - let _ = harness - .assert_parity("execute_query:dml_setup", |driver, params| async move { - driver - .execute_query( - ¶ms, - "INSERT INTO test_schema.crud_scratch(name, value) VALUES ('dml_parity', 0) ON CONFLICT DO NOTHING", - Some(100), - 1, - Some("test_schema"), - ) - .await - }) - .await; - - let result = harness - .assert_parity("execute_query:dml_update", |driver, params| async move { - driver - .execute_query( - ¶ms, - "UPDATE test_schema.crud_scratch SET value = value + 1 WHERE name = 'dml_parity'", - Some(100), - 1, - Some("test_schema"), - ) - .await - }) - .await; - - // DML queries should report affected_rows - let affected = result.get("affected_rows").and_then(Value::as_u64); - assert!( - affected.is_some(), - "DML result should include affected_rows field" - ); - assert!(affected.unwrap() >= 1); -} - -#[tokio::test] -#[ignore] -async fn parity_execute_query_null_handling() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("execute_query:null_handling", |driver, params| async move { - driver - .execute_query( - ¶ms, - "SELECT NULL AS null_col, id FROM test_schema.all_types WHERE id = 1", - Some(100), - 1, - Some("test_schema"), - ) - .await - }) - .await; - - let rows = result.get("rows").and_then(Value::as_array).unwrap(); - assert_eq!(rows.len(), 1); - let row = &rows[0]; - // The null column should be present and null - let null_val = row.get("null_col").or_else(|| { - // Some drivers return rows as arrays - row.as_array().and_then(|arr| arr.first()) - }); - assert!( - null_val.is_some(), - "null column should be present in result" - ); -} - -#[tokio::test] -#[ignore] -async fn parity_execute_query_count() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("execute_query:count", |driver, params| async move { - driver - .execute_query( - ¶ms, - "SELECT COUNT(*) AS cnt FROM test_schema.all_types", - Some(100), - 1, - Some("test_schema"), - ) - .await - }) - .await; - - let rows = result.get("rows").and_then(Value::as_array).unwrap(); - assert_eq!(rows.len(), 1, "COUNT query should return exactly one row"); -} - -/// Regression test for a real bug caught by manual smoke testing (issue #614 -/// follow-up, filed as tabularis-postgresql-plugin#7): the plugin's -/// `extract_value` had no explicit case for PostgreSQL enum columns, so -/// SELECTing an enum value returned `null` instead of the real label — while -/// the builtin driver (confirmed here, and independently via `psql`) returns -/// the correct string. `assert_parity` alone would have failed loudly on this -/// exact mismatch had it existed; it didn't, because no parity test read an -/// enum value back through `execute_query` — only `get_columns` (metadata) -/// and `insert_record`/`update_record` (binding) exercised enums before this. -#[tokio::test] -#[ignore] -async fn parity_execute_query_enum_value() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("execute_query:enum_value", |driver, params| async move { - driver - .execute_query( - ¶ms, - "SELECT id, current_mood FROM test_schema.with_enum ORDER BY id LIMIT 1", - Some(100), - 1, - Some("test_schema"), - ) - .await - }) - .await; - - let rows = result.get("rows").and_then(Value::as_array).unwrap(); - assert_eq!(rows.len(), 1, "expected exactly one row"); - let row = &rows[0]; - - // Seed data (tests/fixtures/postgres_seed.sql) inserts current_mood = - // 'happy' for the one seeded row and never updates it in any other - // integration test, so this value is stable — a real, non-null enum - // label, not a placeholder. Handles both row shapes (object keyed by - // column name, or positional array) the same way parity_execute_query_ - // null_handling above does. - let mood_val = row - .get("current_mood") - .or_else(|| row.as_array().and_then(|arr| arr.get(1))) - .expect("current_mood should be present in the result row"); - - assert_eq!( - mood_val.as_str(), - Some("happy"), - "current_mood should be the real enum label 'happy', not null — \ - got: {mood_val:?}" - ); -} diff --git a/src-tauri/tests/postgres_integration/parity_query_extra.rs b/src-tauri/tests/postgres_integration/parity_query_extra.rs deleted file mode 100644 index 9b92cf4e3..000000000 --- a/src-tauri/tests/postgres_integration/parity_query_extra.rs +++ /dev/null @@ -1,125 +0,0 @@ -//! Extra parity tests for query execution — affected_rows_for_dml, batch_session_state. - -use serde_json::Value; - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_execute_query_affected_rows_for_dml() { - require_pg!(); - let harness = ParityHarness::new().await; - - // Insert into scratch table — DML should report affected_rows = 1 - // and return no columns/rows. - let result = harness - .assert_parity( - "execute_query:affected_rows_dml", - |driver, params| async move { - driver - .execute_query( - ¶ms, - "INSERT INTO test_schema.crud_scratch (name, value) \ - VALUES ('parity_affected_rows', 1)", - None, - 1, - Some("test_schema"), - ) - .await - }, - ) - .await; - - // DML returns affected_rows = 1 - let affected = result - .get("affected_rows") - .and_then(Value::as_u64) - .unwrap_or(0); - assert_eq!(affected, 1, "INSERT should affect exactly 1 row"); - - // DML returns no columns - let columns = result - .get("columns") - .and_then(Value::as_array) - .map(|a| a.len()) - .unwrap_or(0); - assert_eq!(columns, 0, "DML should return no columns"); - - // DML returns no rows - let rows = result - .get("rows") - .and_then(Value::as_array) - .map(|a| a.len()) - .unwrap_or(0); - assert_eq!(rows, 0, "DML should return no rows"); -} - -#[tokio::test] -#[ignore] -async fn parity_execute_batch_session_state() { - require_pg!(); - let harness = ParityHarness::new().await; - - // execute_batch returns Vec, and each entry - // carries execution_time_ms: Option — a genuine wall-clock value - // that can never byte-match between two separate driver processes. - // assert_parity's exact comparison is the wrong tool here (same class - // of issue fixed in parity_batch.rs) — call each target directly and - // check only the deterministic fields. - let statements = vec![ - "BEGIN".to_string(), - "CREATE TEMP TABLE _parity_batch_test (x INT)".to_string(), - "INSERT INTO _parity_batch_test VALUES (42)".to_string(), - "SELECT x FROM _parity_batch_test".to_string(), - "COMMIT".to_string(), - ]; - - for (target, driver) in harness.targets() { - let result = driver - .execute_batch( - &harness.params, - &statements, - Some(100), - 1, - Some("test_schema"), - None, - ) - .await - .unwrap_or_else(|e| panic!("execute_batch failed on {}: {}", target, e)); - let arr = serde_json::to_value(&result).expect("serialize batch result"); - let arr = arr.as_array().expect("batch result should be an array"); - - assert!( - arr.len() >= 4, - "{}: expected at least 4 results, got: {}", - target, - arr.len() - ); - - // The SELECT result (4th statement, index 3) should return the inserted value - let select_result = &arr[3]; - let succeeded = select_result - .get("error") - .map(Value::is_null) - .unwrap_or(false); - assert!( - succeeded, - "{}: SELECT from temp table should succeed, got: {:?}", - target, select_result - ); - - if let Some(result_obj) = select_result.get("result") { - if let Some(rows) = result_obj.get("rows").and_then(Value::as_array) { - assert_eq!(rows.len(), 1, "{}: SELECT should return 1 row", target); - if let Some(row) = rows.first().and_then(Value::as_array) { - assert_eq!( - row.first().and_then(Value::as_i64), - Some(42), - "{}: temp table should contain value 42", - target - ); - } - } - } - } -} diff --git a/src-tauri/tests/postgres_integration/parity_routines_extra.rs b/src-tauri/tests/postgres_integration/parity_routines_extra.rs deleted file mode 100644 index 11071c04b..000000000 --- a/src-tauri/tests/postgres_integration/parity_routines_extra.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! Extra parity tests for routines — overloaded functions, procedures, drop_routine. - -use serde_json::Value; - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_get_routines_overloaded_functions() { - require_pg!(); - let harness = ParityHarness::new().await; - - // add_numbers is overloaded: (int, int) and (int, int, int). - // Both drivers must return the same number of overloaded entries. - let result = harness - .assert_parity("get_routines:overloaded", |driver, params| async move { - driver.get_routines(¶ms, Some("test_schema")).await - }) - .await; - - let routines = result.as_array().expect("routines should be an array"); - let add_numbers_count = routines - .iter() - .filter(|r| r.get("name").and_then(Value::as_str) == Some("add_numbers")) - .count(); - assert_eq!( - add_numbers_count, 2, - "Expected 2 overloaded add_numbers functions, got: {}", - add_numbers_count - ); -} - -#[tokio::test] -#[ignore] -async fn parity_get_routines_lists_procedures() { - require_pg!(); - let harness = ParityHarness::new().await; - - // Verify that procedures (not just functions) appear in get_routines. - let result = harness - .assert_parity("get_routines:procedures", |driver, params| async move { - driver.get_routines(¶ms, Some("test_schema")).await - }) - .await; - - let routines = result.as_array().expect("routines should be an array"); - let proc_names: Vec<&str> = routines - .iter() - .filter(|r| r.get("routine_type").and_then(Value::as_str) == Some("PROCEDURE")) - .filter_map(|r| r.get("name").and_then(Value::as_str)) - .collect(); - - assert!( - proc_names.contains(&"reset_orders"), - "Expected reset_orders procedure in routine list, got: {:?}", - proc_names - ); -} - -#[tokio::test] -#[ignore] -async fn parity_drop_routine() { - require_pg!(); - let harness = ParityHarness::new().await; - - // drop_routine is destructive against the one shared physical database - // both targets point at — assert_parity calls each target in sequence, - // so the second target's drop would legitimately fail with "function - // does not exist" once the first target already dropped it. Re-create - // (idempotent via CREATE OR REPLACE) before each target's drop attempt. - for (target, driver) in harness.targets() { - driver - .execute_query( - &harness.params, - "CREATE OR REPLACE FUNCTION test_schema.parity_drop_fn(a INT) \ - RETURNS INT LANGUAGE SQL AS $$ SELECT a $$", - None, - 1, - Some("test_schema"), - ) - .await - .unwrap_or_else(|e| panic!("setup create function failed on {}: {}", target, e)); - - driver - .drop_routine( - &harness.params, - "parity_drop_fn", - "FUNCTION", - Some("test_schema"), - None, - ) - .await - .unwrap_or_else(|e| panic!("drop_routine failed on {}: {}", target, e)); - } - - // Verify it's gone by checking that the routine no longer appears - let result = harness - .assert_parity("get_routines:after_drop", |driver, params| async move { - driver.get_routines(¶ms, Some("test_schema")).await - }) - .await; - - let routines = result.as_array().expect("routines should be an array"); - let found = routines - .iter() - .any(|r| r.get("name").and_then(Value::as_str) == Some("parity_drop_fn")); - assert!( - !found, - "Dropped function parity_drop_fn should not appear in routine list" - ); -} diff --git a/src-tauri/tests/postgres_integration/parity_routines_full.rs b/src-tauri/tests/postgres_integration/parity_routines_full.rs deleted file mode 100644 index 53f3b2a96..000000000 --- a/src-tauri/tests/postgres_integration/parity_routines_full.rs +++ /dev/null @@ -1,107 +0,0 @@ -//! Parity tests for routine (function/procedure) and trigger introspection. - -use serde_json::Value; - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_get_routine_parameters() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_routine_parameters:add_numbers", - |driver, params| async move { - driver - .get_routine_parameters(¶ms, "add_numbers", Some("test_schema"), None) - .await - }, - ) - .await; - - let params_arr = result - .as_array() - .expect("routine parameters should be an array"); - assert!(!params_arr.is_empty(), "add_numbers should have parameters"); - - // Verify parameter names are present - let names: Vec<&str> = params_arr - .iter() - .filter_map(|p| p.get("name").and_then(Value::as_str)) - .collect(); - assert!( - names.contains(&"a") || names.contains(&"b"), - "add_numbers parameters should include a and/or b, got: {:?}", - names - ); -} - -#[tokio::test] -#[ignore] -async fn parity_get_routine_definition() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_routine_definition:add_numbers", - |driver, params| async move { - driver - .get_routine_definition( - ¶ms, - "add_numbers", - "function", - Some("test_schema"), - None, - ) - .await - }, - ) - .await; - - let definition = result - .as_str() - .expect("routine definition should be a string"); - assert!( - !definition.is_empty(), - "add_numbers definition should not be empty" - ); - // The function body should reference addition - assert!( - definition.contains('+') || definition.to_lowercase().contains("return"), - "add_numbers definition should contain arithmetic or RETURN" - ); -} - -#[tokio::test] -#[ignore] -async fn parity_get_trigger_definition() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_trigger_definition:trg_audit", - |driver, params| async move { - driver - .get_trigger_definition(¶ms, "trg_audit", "all_types", Some("test_schema")) - .await - }, - ) - .await; - - let definition = result - .as_str() - .expect("trigger definition should be a string"); - assert!( - !definition.is_empty(), - "trg_audit definition should not be empty" - ); - assert!( - definition.to_lowercase().contains("trigger") - || definition.to_lowercase().contains("execute"), - "trigger definition should reference TRIGGER or EXECUTE" - ); -} diff --git a/src-tauri/tests/postgres_integration/parity_schema_discovery.rs b/src-tauri/tests/postgres_integration/parity_schema_discovery.rs deleted file mode 100644 index 722e5985d..000000000 --- a/src-tauri/tests/postgres_integration/parity_schema_discovery.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! Parity tests for schema discovery — covers baseline tests from -//! `schema_discovery.rs` that are NOT already covered in `parity_tests.rs`. -//! -//! Already covered by `parity_tests.rs`: -//! - parity_get_schemas (covers test_get_schemas_returns_test_schema) -//! - parity_get_databases (covers test_get_databases_returns_testdb) -//! - parity_get_tables (covers test_get_tables_returns_seeded_tables) -//! -//! New in this file: -//! - parity_get_tables_other_schema (covers test_get_tables_other_schema) - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_get_tables_other_schema() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_tables:other_schema", |driver, params| async move { - driver.get_tables(¶ms, Some("other_schema")).await - }) - .await; - - let arr = result.as_array().expect("tables should be an array"); - let names: Vec<&str> = arr.iter().filter_map(|t| t.get("name")?.as_str()).collect(); - assert!( - names.contains(&"lookup"), - "Expected lookup table in other_schema, got: {:?}", - names - ); -} diff --git a/src-tauri/tests/postgres_integration/parity_tests.rs b/src-tauri/tests/postgres_integration/parity_tests.rs deleted file mode 100644 index 6c4565b18..000000000 --- a/src-tauri/tests/postgres_integration/parity_tests.rs +++ /dev/null @@ -1,265 +0,0 @@ -//! Parity integration tests — run driver methods through the harness to prove -//! equivalence across driver implementations. -//! -//! In Phase 0 these serve as a structural validation that the harness works -//! correctly with the built-in driver. In Phase 1 they become the gate: the -//! plugin must produce identical outputs. - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_get_schemas() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_schemas", |driver, params| async move { - driver.get_schemas(¶ms).await - }) - .await; - - let schemas: Vec = serde_json::from_value(result).unwrap(); - assert!(schemas.contains(&"test_schema".to_string())); - assert!(schemas.contains(&"public".to_string())); -} - -#[tokio::test] -#[ignore] -async fn parity_get_databases() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_databases", |driver, params| async move { - driver.get_databases(¶ms).await - }) - .await; - - let databases: Vec = serde_json::from_value(result).unwrap(); - assert!(databases.contains(&"testdb".to_string())); -} - -#[tokio::test] -#[ignore] -async fn parity_get_tables() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_tables", |driver, params| async move { - driver.get_tables(¶ms, Some("test_schema")).await - }) - .await; - - let arr = result.as_array().expect("tables should be an array"); - let names: Vec<&str> = arr.iter().filter_map(|t| t.get("name")?.as_str()).collect(); - assert!(names.contains(&"all_types")); - assert!(names.contains(&"orders")); -} - -#[tokio::test] -#[ignore] -async fn parity_get_columns() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_columns:all_types", |driver, params| async move { - driver - .get_columns(¶ms, "all_types", Some("test_schema")) - .await - }) - .await; - - let arr = result.as_array().expect("columns should be an array"); - assert!(!arr.is_empty()); - let id_col = arr - .iter() - .find(|c| c.get("name").and_then(|n| n.as_str()) == Some("id")); - assert!(id_col.is_some(), "should have an 'id' column"); - assert_eq!( - id_col.unwrap().get("is_pk").and_then(|v| v.as_bool()), - Some(true) - ); -} - -#[tokio::test] -#[ignore] -async fn parity_get_foreign_keys() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_foreign_keys:orders", |driver, params| async move { - driver - .get_foreign_keys(¶ms, "orders", Some("test_schema")) - .await - }) - .await; - - let arr = result.as_array().expect("foreign keys should be an array"); - assert!(!arr.is_empty()); - let fk = &arr[0]; - assert_eq!( - fk.get("column_name").and_then(|v| v.as_str()), - Some("user_id") - ); -} - -#[tokio::test] -#[ignore] -async fn parity_get_indexes() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_indexes:all_types", |driver, params| async move { - driver - .get_indexes(¶ms, "all_types", Some("test_schema")) - .await - }) - .await; - - let arr = result.as_array().expect("indexes should be an array"); - assert!(!arr.is_empty()); -} - -#[tokio::test] -#[ignore] -async fn parity_get_views() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_views", |driver, params| async move { - driver.get_views(¶ms, Some("test_schema")).await - }) - .await; - - let arr = result.as_array().expect("views should be an array"); - let names: Vec<&str> = arr.iter().filter_map(|v| v.get("name")?.as_str()).collect(); - assert!(names.contains(&"active_users")); -} - -#[tokio::test] -#[ignore] -async fn parity_get_view_definition() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_view_definition:active_users", - |driver, params| async move { - driver - .get_view_definition(¶ms, "active_users", Some("test_schema")) - .await - }, - ) - .await; - - let def = result.as_str().expect("view definition should be a string"); - assert!(def.to_lowercase().contains("select")); -} - -#[tokio::test] -#[ignore] -async fn parity_get_materialized_views() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_materialized_views", |driver, params| async move { - driver - .get_materialized_views(¶ms, Some("test_schema")) - .await - }) - .await; - - let arr = result - .as_array() - .expect("materialized views should be an array"); - let names: Vec<&str> = arr.iter().filter_map(|v| v.get("name")?.as_str()).collect(); - assert!(names.contains(&"user_stats")); -} - -#[tokio::test] -#[ignore] -async fn parity_get_routines() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_routines", |driver, params| async move { - driver.get_routines(¶ms, Some("test_schema")).await - }) - .await; - - let arr = result.as_array().expect("routines should be an array"); - let names: Vec<&str> = arr.iter().filter_map(|r| r.get("name")?.as_str()).collect(); - assert!(names.contains(&"add_numbers")); -} - -#[tokio::test] -#[ignore] -async fn parity_get_triggers() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity("get_triggers", |driver, params| async move { - driver.get_triggers(¶ms, Some("test_schema")).await - }) - .await; - - let arr = result.as_array().expect("triggers should be an array"); - let names: Vec<&str> = arr.iter().filter_map(|t| t.get("name")?.as_str()).collect(); - assert!(names.contains(&"trg_audit")); -} - -#[tokio::test] -#[ignore] -async fn parity_get_tables_secondary() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity_secondary("get_tables:secondary", |driver, params| async move { - driver.get_tables(¶ms, Some("secondary_schema")).await - }) - .await; - - let arr = result.as_array().expect("tables should be an array"); - let names: Vec<&str> = arr.iter().filter_map(|t| t.get("name")?.as_str()).collect(); - assert!(names.contains(&"remote_data")); -} - -#[tokio::test] -#[ignore] -async fn parity_map_inferred_type() { - require_pg!(); - let harness = ParityHarness::new().await; - - // map_inferred_type is synchronous — test it directly on each target - for (target, driver) in harness.targets() { - assert_eq!( - driver.map_inferred_type("DATETIME"), - "TIMESTAMP", - "map_inferred_type(DATETIME) failed on {}", - target - ); - assert_eq!( - driver.map_inferred_type("JSON"), - "JSONB", - "map_inferred_type(JSON) failed on {}", - target - ); - assert_eq!( - driver.map_inferred_type("TEXT"), - "TEXT", - "map_inferred_type(TEXT) passthrough failed on {}", - target - ); - } -} diff --git a/src-tauri/tests/postgres_integration/parity_triggers_extra.rs b/src-tauri/tests/postgres_integration/parity_triggers_extra.rs deleted file mode 100644 index 2bbb0e3bc..000000000 --- a/src-tauri/tests/postgres_integration/parity_triggers_extra.rs +++ /dev/null @@ -1,96 +0,0 @@ -//! Extra parity tests for triggers — create/drop trigger and empty schema. - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_create_and_drop_trigger() { - require_pg!(); - let harness = ParityHarness::new().await; - - let trigger_name = "trg_parity_temp"; - let table_name = "crud_scratch"; - let schema = Some("test_schema"); - - // Cleanup from any prior failed run - for (_target, driver) in harness.targets() { - let _ = driver - .drop_trigger(&harness.params, trigger_name, table_name, schema) - .await; - } - - // create_trigger/drop_trigger are destructive against the one shared - // physical database both targets point at — assert_parity calls each - // target in sequence, so the second target's CREATE would legitimately - // fail with "trigger already exists" (created by the first target) and - // its DROP would legitimately fail with "trigger does not exist" (already - // dropped by the first target). Run create+drop directly per target - // instead, so each target creates its own copy and drops its own copy. - let create_sql = format!( - "CREATE TRIGGER {} BEFORE INSERT ON test_schema.{} \ - FOR EACH ROW EXECUTE FUNCTION test_schema.audit_trigger_fn()", - trigger_name, table_name - ); - - for (target, driver) in harness.targets() { - driver - .create_trigger(&harness.params, &create_sql, Some("test_schema")) - .await - .unwrap_or_else(|e| panic!("create_trigger failed on {}: {}", target, e)); - - // Verify the trigger exists by listing triggers (read-only, safe to - // check per-target since both point at the same live state). - let triggers = driver - .get_triggers(&harness.params, Some("test_schema")) - .await - .unwrap_or_else(|e| panic!("get_triggers failed on {}: {}", target, e)); - let found = triggers.iter().any(|t| t.name == trigger_name); - assert!( - found, - "{}: created trigger {} should appear in list", - target, trigger_name - ); - - driver - .drop_trigger( - &harness.params, - trigger_name, - table_name, - Some("test_schema"), - ) - .await - .unwrap_or_else(|e| panic!("drop_trigger failed on {}: {}", target, e)); - - let triggers = driver - .get_triggers(&harness.params, Some("test_schema")) - .await - .unwrap_or_else(|e| panic!("get_triggers (after drop) failed on {}: {}", target, e)); - let still_found = triggers.iter().any(|t| t.name == trigger_name); - assert!( - !still_found, - "{}: dropped trigger {} should not appear in list", - target, trigger_name - ); - } -} - -#[tokio::test] -#[ignore] -async fn parity_get_triggers_empty_schema() { - require_pg!(); - let harness = ParityHarness::new().await; - - // other_schema has no triggers — both drivers should return an empty list - let result = harness - .assert_parity("get_triggers:empty_schema", |driver, params| async move { - driver.get_triggers(¶ms, Some("other_schema")).await - }) - .await; - - let triggers = result.as_array().expect("triggers should be an array"); - assert!( - triggers.is_empty(), - "other_schema should have no triggers, got: {:?}", - triggers - ); -} diff --git a/src-tauri/tests/postgres_integration/parity_views_extra.rs b/src-tauri/tests/postgres_integration/parity_views_extra.rs deleted file mode 100644 index 09ff612fb..000000000 --- a/src-tauri/tests/postgres_integration/parity_views_extra.rs +++ /dev/null @@ -1,76 +0,0 @@ -//! Extra parity tests for views — alter_view and empty schema scenarios. - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_alter_view() { - require_pg!(); - let harness = ParityHarness::new().await; - - let view_name = "parity_alter_view"; - let schema = Some("test_schema"); - let def1 = "SELECT id FROM test_schema.all_types"; - let def2 = "SELECT id, col_text FROM test_schema.all_types"; - - // create_view/drop_view are destructive against the one shared physical - // database both targets point at — assert_parity calls each target in - // sequence, so the second target's plain CREATE VIEW would legitimately - // fail with "view already exists" and its DROP would legitimately fail - // with "view does not exist" once the first target already did so. - // alter_view itself uses CREATE OR REPLACE (idempotent), so it's safe - // under assert_parity — but the surrounding create/drop are not. Run the - // whole create->alter->verify->drop sequence directly per target. - for (target, driver) in harness.targets() { - // Cleanup from any prior failed run. - let _ = driver.drop_view(&harness.params, view_name, schema).await; - - driver - .create_view(&harness.params, view_name, def1, schema) - .await - .unwrap_or_else(|e| panic!("create_view failed on {}: {}", target, e)); - - driver - .alter_view(&harness.params, view_name, def2, schema) - .await - .unwrap_or_else(|e| panic!("alter_view failed on {}: {}", target, e)); - - let columns = driver - .get_view_columns(&harness.params, view_name, schema) - .await - .unwrap_or_else(|e| panic!("get_view_columns failed on {}: {}", target, e)); - assert_eq!( - columns.len(), - 2, - "{}: altered view should have 2 columns, got: {}", - target, - columns.len() - ); - - driver - .drop_view(&harness.params, view_name, schema) - .await - .unwrap_or_else(|e| panic!("drop_view (cleanup) failed on {}: {}", target, e)); - } -} - -#[tokio::test] -#[ignore] -async fn parity_get_views_empty_schema() { - require_pg!(); - let harness = ParityHarness::new().await; - - // other_schema has no views — both drivers should return an empty list - let result = harness - .assert_parity("get_views:empty_schema", |driver, params| async move { - driver.get_views(¶ms, Some("other_schema")).await - }) - .await; - - let views = result.as_array().expect("views should be an array"); - assert!( - views.is_empty(), - "other_schema should have no views, got: {:?}", - views - ); -} diff --git a/src-tauri/tests/postgres_integration/parity_views_full.rs b/src-tauri/tests/postgres_integration/parity_views_full.rs deleted file mode 100644 index 6cbe1a922..000000000 --- a/src-tauri/tests/postgres_integration/parity_views_full.rs +++ /dev/null @@ -1,131 +0,0 @@ -//! Parity tests for view and materialized view lifecycle operations. - -use crate::parity::ParityHarness; - -#[tokio::test] -#[ignore] -async fn parity_get_view_columns() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_view_columns:active_users", - |driver, params| async move { - driver - .get_view_columns(¶ms, "active_users", Some("test_schema")) - .await - }, - ) - .await; - - let columns = result.as_array().expect("view columns should be an array"); - assert!(!columns.is_empty(), "active_users view should have columns"); -} - -#[tokio::test] -#[ignore] -async fn parity_create_drop_view() { - require_pg!(); - let harness = ParityHarness::new().await; - - let view_name = "parity_temp_view"; - let definition = "SELECT id, col_text FROM test_schema.all_types WHERE id < 10"; - - // create_view/drop_view are destructive against the one shared physical - // database both targets point at — assert_parity calls each target in - // sequence, so the second target's plain CREATE VIEW would legitimately - // fail with "view already exists" (created by the first target) and its - // DROP would legitimately fail with "view does not exist" (already - // dropped by the first target). Run create+verify+drop directly per - // target instead, so each target creates and drops its own view. - for (target, driver) in harness.targets() { - // Cleanup from any prior failed run. - let _ = driver - .drop_view(&harness.params, view_name, Some("test_schema")) - .await; - - driver - .create_view(&harness.params, view_name, definition, Some("test_schema")) - .await - .unwrap_or_else(|e| panic!("create_view failed on {}: {}", target, e)); - - let columns = driver - .get_view_columns(&harness.params, view_name, Some("test_schema")) - .await - .unwrap_or_else(|e| panic!("get_view_columns failed on {}: {}", target, e)); - assert!( - !columns.is_empty(), - "{}: temp view should have columns", - target - ); - - driver - .drop_view(&harness.params, view_name, Some("test_schema")) - .await - .unwrap_or_else(|e| panic!("drop_view failed on {}: {}", target, e)); - - // get_view_columns queries information_schema.columns filtered by - // table name, so a dropped view returns Ok(empty), not Err. - let columns_after_drop = driver - .get_view_columns(&harness.params, view_name, Some("test_schema")) - .await - .unwrap_or_else(|e| { - panic!( - "get_view_columns on dropped view should return Ok(empty), not Err, on {}: {}", - target, e - ) - }); - assert!( - columns_after_drop.is_empty(), - "{}: view should have no columns after drop, got: {:?}", - target, - columns_after_drop - ); - } -} - -#[tokio::test] -#[ignore] -async fn parity_get_materialized_view_columns() { - require_pg!(); - let harness = ParityHarness::new().await; - - let result = harness - .assert_parity( - "get_materialized_view_columns:user_stats", - |driver, params| async move { - driver - .get_materialized_view_columns(¶ms, "user_stats", Some("test_schema")) - .await - }, - ) - .await; - - let columns = result - .as_array() - .expect("materialized view columns should be an array"); - assert!( - !columns.is_empty(), - "user_stats materialized view should have columns" - ); -} - -#[tokio::test] -#[ignore] -async fn parity_refresh_materialized_view() { - require_pg!(); - let harness = ParityHarness::new().await; - - // refresh_materialized_view returns () on success — verify no error - harness - .assert_parity( - "refresh_materialized_view:user_stats", - |driver, params| async move { - driver - .refresh_materialized_view(¶ms, "user_stats", Some("test_schema")) - .await - }, - ) - .await; -} diff --git a/src-tauri/tests/postgres_integration/query_execution.rs b/src-tauri/tests/postgres_integration/query_execution.rs deleted file mode 100644 index 0bc1ec4d9..000000000 --- a/src-tauri/tests/postgres_integration/query_execution.rs +++ /dev/null @@ -1,242 +0,0 @@ -//! Query execution tests. - -use crate::helpers::{pg_params, pg_params_secondary}; -use tabularis_lib::drivers::postgres; - -#[tokio::test] -#[ignore] -async fn test_execute_query_basic_select() { - require_pg!(); - let params = pg_params(); - - let result = postgres::execute_query( - ¶ms, - "SELECT id, col_text, col_int FROM test_schema.all_types ORDER BY id LIMIT 1", - Some(100), - 1, - None, - ) - .await - .expect("execute_query should succeed"); - - assert_eq!(result.columns, vec!["id", "col_text", "col_int"]); - assert!(!result.rows.is_empty(), "Should have at least one row"); - - // First row should have id=1 from seed - let first_row = &result.rows[0]; - assert_eq!(first_row[0], serde_json::json!(1)); // id - assert_eq!(first_row[1], serde_json::json!("hello")); // col_text - assert_eq!(first_row[2], serde_json::json!(42)); // col_int -} - -#[tokio::test] -#[ignore] -async fn test_execute_query_with_pagination() { - require_pg!(); - let params = pg_params(); - - // Page 1 with limit 1 - let page1 = postgres::execute_query( - ¶ms, - "SELECT id FROM test_schema.all_types ORDER BY id", - Some(1), - 1, - None, - ) - .await - .expect("page 1"); - - assert_eq!(page1.rows.len(), 1); - assert_eq!(page1.rows[0][0], serde_json::json!(1)); - assert!( - page1.pagination.as_ref().map_or(false, |p| p.has_more), - "Should have more pages" - ); - - // Page 2 - let page2 = postgres::execute_query( - ¶ms, - "SELECT id FROM test_schema.all_types ORDER BY id", - Some(1), - 2, - None, - ) - .await - .expect("page 2"); - - assert_eq!(page2.rows.len(), 1); - assert_eq!(page2.rows[0][0], serde_json::json!(2)); -} - -#[tokio::test] -#[ignore] -async fn test_execute_query_all_types_roundtrip() { - require_pg!(); - let params = pg_params(); - - let result = postgres::execute_query( - ¶ms, - "SELECT * FROM test_schema.all_types WHERE id = 1", - None, - 1, - None, - ) - .await - .expect("execute_query should succeed"); - - assert_eq!(result.rows.len(), 1, "Expected exactly 1 row"); - let row = &result.rows[0]; - - // Verify key type extractions produce valid JSON values (not null for seeded data) - let col_idx = |name: &str| result.columns.iter().position(|c| c == name).unwrap(); - - assert!(!row[col_idx("col_text")].is_null()); - assert!(!row[col_idx("col_int")].is_null()); - assert!(!row[col_idx("col_bool")].is_null()); - assert!(!row[col_idx("col_uuid")].is_null()); - assert!(!row[col_idx("col_jsonb")].is_null()); - assert!(!row[col_idx("col_int_array")].is_null()); - assert!(!row[col_idx("col_timestamptz")].is_null()); -} - -#[tokio::test] -#[ignore] -async fn test_execute_query_null_handling() { - require_pg!(); - let params = pg_params(); - - // Row 2 was seeded with only col_text (NULL) — most columns are null - // except col_uuid which has DEFAULT gen_random_uuid() - let result = postgres::execute_query( - ¶ms, - "SELECT col_text, col_int, col_bool, col_bytea FROM test_schema.all_types WHERE id = 2", - None, - 1, - None, - ) - .await - .expect("execute_query should succeed"); - - assert_eq!(result.rows.len(), 1); - let row = &result.rows[0]; - // These columns have no default and weren't set — should be null - for (i, val) in row.iter().enumerate() { - assert!( - val.is_null(), - "Column {} expected null, got: {:?}", - result.columns[i], - val - ); - } -} - -#[tokio::test] -#[ignore] -async fn test_execute_query_affected_rows_for_dml() { - require_pg!(); - let params = pg_params(); - - // Insert into scratch table - let result = postgres::execute_query( - ¶ms, - "INSERT INTO test_schema.crud_scratch (name, value) VALUES ('test', 1)", - None, - 1, - None, - ) - .await - .expect("INSERT should succeed"); - - assert_eq!(result.affected_rows, 1); - assert!(result.columns.is_empty(), "DML returns no columns"); - assert!(result.rows.is_empty(), "DML returns no rows"); -} - -#[tokio::test] -#[ignore] -async fn test_execute_batch_session_state() { - require_pg!(); - let params = pg_params(); - - // Batch with transaction + temp table — session state must persist - let statements: Vec = vec![ - "BEGIN".into(), - "CREATE TEMP TABLE _batch_test (x INT)".into(), - "INSERT INTO _batch_test VALUES (42)".into(), - "SELECT x FROM _batch_test".into(), - "COMMIT".into(), - ]; - - let results = postgres::execute_batch(¶ms, &statements, Some(100), 1, None, None) - .await - .expect("execute_batch should succeed"); - - // The SELECT result (4th statement, index 3) should return the inserted value - assert!(results.len() >= 4, "Expected at least 4 results"); - let select_result = results[3] - .result - .as_ref() - .expect("SELECT should produce a result"); - assert_eq!(select_result.rows.len(), 1); - assert_eq!(select_result.rows[0][0], serde_json::json!(42)); -} - -#[tokio::test] -#[ignore] -async fn test_pinned_session_rejects_database_mismatch() { - // A transaction started on one database must not silently run on another - // when the tab switches databases mid-transaction (#947). - require_pg!(); - let primary = pg_params(); - let secondary = pg_params_secondary(); - let session = "test-pinned-session-db-mismatch"; - - // Start a transaction on the primary database and leave it open. - let (_results, pinned) = postgres::execute_batch_in_session( - &primary, - &["BEGIN".into()], - None, - 1, - None, - Some(session), - None, - ) - .await - .expect("BEGIN should succeed"); - assert!(pinned, "BEGIN should leave a pinned transaction"); - - // The same session, now targeting the secondary database, must be rejected - // rather than silently running on the primary connection. - let err = postgres::execute_batch_in_session( - &secondary, - &["SELECT 1".into()], - None, - 1, - None, - Some(session), - None, - ) - .await - .expect_err("database mismatch should be rejected"); - assert!( - err.contains("open transaction on database") && err.contains("testdb"), - "error should name the pinned database, got: {err}" - ); - assert!( - err.contains("tabularis_test_secondary"), - "error should name the requested database, got: {err}" - ); - - // Clean up: roll back the open transaction on the primary. - postgres::execute_batch_in_session( - &primary, - &["ROLLBACK".into()], - None, - 1, - None, - Some(session), - None, - ) - .await - .expect("ROLLBACK should succeed"); -} diff --git a/src-tauri/tests/postgres_integration/read_only.rs b/src-tauri/tests/postgres_integration/read_only.rs deleted file mode 100644 index 968393114..000000000 --- a/src-tauri/tests/postgres_integration/read_only.rs +++ /dev/null @@ -1,100 +0,0 @@ -//! `execute_read_only_query`: the database refuses writes that keyword -//! classification can miss (MCP read-only mode and approval gate). - -use crate::helpers::pg_params; -use tabularis_lib::drivers::postgres; - -async fn table_exists(name: &str) -> bool { - let result = postgres::execute_query( - &pg_params(), - &format!("SELECT to_regclass('public.{name}') IS NOT NULL"), - None, - 1, - None, - ) - .await - .expect("check table"); - result.rows[0][0] == serde_json::json!(true) -} - -#[tokio::test] -#[ignore] -async fn test_read_only_query_returns_rows() { - require_pg!(); - let result = postgres::execute_read_only_query(&pg_params(), "SELECT 1 AS x", None, 1, None) - .await - .expect("a read runs in read-only mode"); - assert_eq!(result.rows[0][0], serde_json::json!(1)); -} - -#[tokio::test] -#[ignore] -async fn test_read_only_query_rejects_select_into() { - require_pg!(); - let outcome = postgres::execute_read_only_query( - &pg_params(), - "SELECT 1 AS x INTO ro_bypass_probe", - None, - 1, - None, - ) - .await; - assert!(outcome.is_err(), "SELECT INTO must be rejected"); - assert!(!table_exists("ro_bypass_probe").await); -} - -#[tokio::test] -#[ignore] -async fn test_read_only_query_rejects_volatile_writes() { - require_pg!(); - let params = pg_params(); - postgres::execute_query( - ¶ms, - "CREATE SEQUENCE IF NOT EXISTS ro_probe_seq", - None, - 1, - None, - ) - .await - .expect("create sequence"); - for write in [ - "SELECT setval('ro_probe_seq', 42)", - "SELECT nextval('ro_probe_seq')", - ] { - assert!( - postgres::execute_read_only_query(¶ms, write, None, 1, None) - .await - .is_err(), - "{write} must be rejected" - ); - } - postgres::execute_query(¶ms, "DROP SEQUENCE ro_probe_seq", None, 1, None) - .await - .expect("drop sequence"); -} - -#[tokio::test] -#[ignore] -async fn test_read_only_query_does_not_leak_into_the_pool() { - require_pg!(); - let params = pg_params(); - let _ = - postgres::execute_read_only_query(¶ms, "SELECT 1 INTO ro_leak_probe", None, 1, None) - .await; - let _ = postgres::execute_read_only_query(¶ms, "SELECT 1", None, 1, None).await; - // Ordinary writes on the next pooled connections are not read-only. - for _ in 0..3 { - postgres::execute_query( - ¶ms, - "CREATE TABLE ro_leak_probe (id int)", - None, - 1, - None, - ) - .await - .expect("writes still work after a read-only query"); - postgres::execute_query(¶ms, "DROP TABLE ro_leak_probe", None, 1, None) - .await - .expect("drop probe table"); - } -} diff --git a/src-tauri/tests/postgres_integration/routines.rs b/src-tauri/tests/postgres_integration/routines.rs deleted file mode 100644 index ae70a6342..000000000 --- a/src-tauri/tests/postgres_integration/routines.rs +++ /dev/null @@ -1,158 +0,0 @@ -//! Routine (function/procedure) management tests. - -use crate::helpers::pg_params; -use tabularis_lib::drivers::postgres; - -#[tokio::test] -#[ignore] -async fn test_get_routines_lists_functions() { - require_pg!(); - let params = pg_params(); - - let routines = postgres::get_routines(¶ms, "test_schema") - .await - .expect("get_routines should succeed"); - - let routine_names: Vec<&str> = routines.iter().map(|r| r.name.as_str()).collect(); - assert!( - routine_names.contains(&"add_numbers"), - "Expected add_numbers function, got: {:?}", - routine_names - ); - assert!( - routine_names.contains(&"get_user"), - "Expected get_user function" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_routines_lists_procedures() { - require_pg!(); - let params = pg_params(); - - let routines = postgres::get_routines(¶ms, "test_schema") - .await - .expect("get_routines should succeed"); - - let proc_names: Vec<&str> = routines - .iter() - .filter(|r| r.routine_type == "PROCEDURE") - .map(|r| r.name.as_str()) - .collect(); - - assert!( - proc_names.contains(&"reset_orders"), - "Expected reset_orders procedure, got: {:?}", - proc_names - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_routines_overloaded_functions() { - require_pg!(); - let params = pg_params(); - - let routines = postgres::get_routines(¶ms, "test_schema") - .await - .expect("get_routines should succeed"); - - // add_numbers is overloaded: (int, int) and (int, int, int) - let add_numbers_count = routines.iter().filter(|r| r.name == "add_numbers").count(); - assert_eq!( - add_numbers_count, 2, - "Expected 2 overloaded add_numbers functions" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_routine_parameters() { - require_pg!(); - let params = pg_params(); - - // Signature-less: still the pre-#893 read, whose list may carry the - // parameters of every overload at once. That is what this assertion has - // always tolerated, and the arm below is the one that does not. - let routine_params = - postgres::get_routine_parameters(¶ms, "add_numbers", "test_schema", None) - .await - .expect("get_routine_parameters should succeed"); - - assert!( - routine_params.len() >= 2, - "add_numbers should have at least 2 parameters, got: {}", - routine_params.len() - ); - - // Asked for one overload by its signature, the list is that overload's own. - // `add_numbers` is seeded with a two-argument and a three-argument version, - // so without the filter this came back with every overload's parameters in - // one list, two of them at ordinal_position 1 (#893). - let two_arg = postgres::get_routine_parameters( - ¶ms, - "add_numbers", - "test_schema", - Some("a integer, b integer"), - ) - .await - .expect("get_routine_parameters for the two-argument overload"); - - let named: Vec<&str> = two_arg - .iter() - .filter(|p| !p.name.is_empty()) - .map(|p| p.name.as_str()) - .collect(); - assert_eq!( - named, - vec!["a", "b"], - "the two-argument overload takes exactly a and b, got: {named:?}" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_routine_definition() { - require_pg!(); - let params = pg_params(); - - let def = - postgres::get_routine_definition(¶ms, "get_user", "FUNCTION", "test_schema", None) - .await - .expect("get_routine_definition should succeed"); - - assert!( - def.to_lowercase().contains("select") || def.to_lowercase().contains("function"), - "Function definition should contain SQL, got: {}", - def - ); -} - -#[tokio::test] -#[ignore] -async fn test_drop_routine() { - require_pg!(); - let params = pg_params(); - - // Create a temporary function to test drop - postgres::execute_query( - ¶ms, - "CREATE OR REPLACE FUNCTION test_schema.temp_drop_test(a INT) RETURNS INT LANGUAGE SQL AS $$ SELECT a $$", - None, - 1, - None, - ) - .await - .expect("create function"); - - // Drop it - let drop_result = - postgres::drop_routine(¶ms, "temp_drop_test", "FUNCTION", "test_schema", None).await; - - assert!( - drop_result.is_ok(), - "drop_routine should succeed: {:?}", - drop_result.err() - ); -} diff --git a/src-tauri/tests/postgres_integration/schema_discovery.rs b/src-tauri/tests/postgres_integration/schema_discovery.rs deleted file mode 100644 index 018c9e30d..000000000 --- a/src-tauri/tests/postgres_integration/schema_discovery.rs +++ /dev/null @@ -1,98 +0,0 @@ -//! Schema discovery tests: get_schemas, get_databases, get_tables. - -use crate::helpers::pg_params; -use tabularis_lib::drivers::postgres; - -#[tokio::test] -#[ignore] -async fn test_get_schemas_returns_test_schema() { - require_pg!(); - let params = pg_params(); - - let schemas = postgres::get_schemas(¶ms) - .await - .expect("get_schemas should succeed"); - - assert!( - schemas.contains(&"test_schema".to_string()), - "Expected test_schema in schemas list, got: {:?}", - schemas - ); - assert!( - schemas.contains(&"other_schema".to_string()), - "Expected other_schema in schemas list" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_databases_returns_testdb() { - require_pg!(); - let params = pg_params(); - - let databases = postgres::get_databases(¶ms) - .await - .expect("get_databases should succeed"); - - assert!( - databases.contains(&"testdb".to_string()), - "Expected testdb in databases list, got: {:?}", - databases - ); - assert!( - databases.contains(&"tabularis_test_secondary".to_string()), - "Expected tabularis_test_secondary in databases list" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_tables_returns_seeded_tables() { - require_pg!(); - let params = pg_params(); - - let tables = postgres::get_tables(¶ms, "test_schema") - .await - .expect("get_tables should succeed"); - - let table_names: Vec<&str> = tables.iter().map(|t| t.name.as_str()).collect(); - - assert!( - table_names.contains(&"all_types"), - "Expected all_types table" - ); - assert!( - table_names.contains(&"with_enum"), - "Expected with_enum table" - ); - assert!(table_names.contains(&"orders"), "Expected orders table"); - assert!( - table_names.contains(&"order_items"), - "Expected order_items table" - ); - assert!( - table_names.contains(&"with_cross_schema_fk"), - "Expected with_cross_schema_fk table" - ); - assert!( - table_names.contains(&"crud_scratch"), - "Expected crud_scratch table" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_tables_other_schema() { - require_pg!(); - let params = pg_params(); - - let tables = postgres::get_tables(¶ms, "other_schema") - .await - .expect("get_tables for other_schema should succeed"); - - let table_names: Vec<&str> = tables.iter().map(|t| t.name.as_str()).collect(); - assert!( - table_names.contains(&"lookup"), - "Expected lookup table in other_schema" - ); -} diff --git a/src-tauri/tests/postgres_integration/table_transfer.rs b/src-tauri/tests/postgres_integration/table_transfer.rs deleted file mode 100644 index 348be03ba..000000000 --- a/src-tauri/tests/postgres_integration/table_transfer.rs +++ /dev/null @@ -1,388 +0,0 @@ -//! "Export table to SQL" and "Import table from SQL" (#709) against a real -//! PostgreSQL server: a table exported from one schema and imported into -//! another comes back with the same values, for types whose driver-extracted -//! form would not survive (arrays, `bytea` past the preview size, -//! `timestamptz` offsets, `numeric` precision, JSON). - -use std::path::Path; -use std::sync::Arc; - -use crate::helpers::pg_params; -use serde_json::Value; -use tabularis_lib::application::database_transfers::DumpCancellationState; -use tabularis_lib::application::table_transfers::{ - export_table, import_table, IfTableExists, TableExportDestination, TableExportOptions, - TableImportOptions, TableImportSource, -}; -use tabularis_lib::drivers::postgres; -use tabularis_lib::export::ExportCancellationState; -use tabularis_lib::models::{ConnectionsFile, SavedConnection}; -use tabularis_lib::runtime::events::NoopRuntimeEvents; -use tabularis_lib::runtime::paths::FixedRuntimePaths; -use tabularis_lib::runtime::RuntimeContext; -use tabularis_lib::table_sql::TableSqlContent; - -struct NoSecrets; - -impl tabularis_lib::runtime::secrets::RuntimeSecrets for NoSecrets { - fn get(&self, _account: &str) -> Result, String> { - Ok(None) - } - - fn set(&self, _account: &str, _value: &str) -> Result<(), String> { - Ok(()) - } - - fn delete(&self, _account: &str) -> Result<(), String> { - Ok(()) - } -} - -/// A runtime whose only saved connection, `pg`, is the test server. -fn runtime(dir: &Path) -> RuntimeContext { - let runtime = RuntimeContext::new( - Arc::new(FixedRuntimePaths::new(dir.to_path_buf(), dir.to_path_buf())), - Arc::new(NoopRuntimeEvents), - Arc::new(NoSecrets), - ); - let connection = SavedConnection { - id: "pg".to_string(), - name: "pg".to_string(), - params: pg_params(), - plugin_secret_keys: Vec::new(), - group_id: None, - sort_order: None, - detect_json_in_text_columns: None, - appearance: None, - tag_ids: None, - environment: None, - managed: false, - }; - tabularis_lib::persistence::save_connections_file( - &runtime.paths.connections_file(), - &ConnectionsFile { - connections: vec![connection], - ..Default::default() - }, - ) - .expect("save the test connection"); - runtime -} - -async fn run(sql: &str) -> Vec> { - postgres::execute_query(&pg_params(), sql, None, 1, None) - .await - .unwrap_or_else(|error| panic!("fixture SQL failed: {error}; SQL: {sql}")) - .rows -} - -const COLUMNS: &str = "id, customer, note, price::text, paid, at::text, meta::text, \ - encode(raw, 'hex'), tags::text, d::text"; - -#[tokio::test] -#[ignore] -async fn test_table_round_trips_into_another_schema() { - require_pg!(); - tabularis_lib::drivers::registry::register_driver(postgres::PostgresDriver::new()).await; - let suffix = uuid::Uuid::new_v4().simple().to_string(); - let source = format!("table_transfer_src_{suffix}"); - let target = format!("table_transfer_dst_{suffix}"); - run(&format!("CREATE SCHEMA {source}")).await; - run(&format!("CREATE SCHEMA {target}")).await; - for schema in [&source, &target] { - run(&format!( - "CREATE TABLE {schema}.customers (id integer PRIMARY KEY, name text)" - )) - .await; - run(&format!( - "INSERT INTO {schema}.customers VALUES (1, 'a'), (2, 'b')" - )) - .await; - } - run(&format!( - "CREATE TABLE {source}.orders (id integer PRIMARY KEY, \ - customer integer REFERENCES {source}.customers (id), note text, \ - price numeric(10,2), paid boolean, at timestamptz, meta jsonb, raw bytea, \ - tags text[], d date)" - )) - .await; - run(&format!( - "CREATE INDEX orders_note ON {source}.orders (note)" - )) - .await; - run(&format!( - "CREATE UNIQUE INDEX orders_customer ON {source}.orders (customer, id) WHERE paid" - )) - .await; - run(&format!( - "INSERT INTO {source}.orders VALUES \ - (1, 1, E'it''s; a \\\\ back\\nslash', 12.50, true, '2026-01-02 03:04:05+00', \ - '{{\"k\": [1, \"x\"]}}', '\\xdeadbeef', ARRAY['a', 'b;c'], '2026-02-03'), \ - (2, 2, NULL, NULL, false, NULL, NULL, NULL, NULL, NULL), \ - (3, 1, '', 0, NULL, '2026-06-01 10:00:00+05:30', '\"text\"', \ - decode(repeat('ab', 20000), 'hex'), '{{}}', NULL), \ - (4, 2, 'caf\u{e9} \u{1f600} \u{4e2d}\u{6587}', NULL, NULL, NULL, NULL, NULL, \ - ARRAY['\u{1f600}', NULL], NULL)" - )) - .await; - - let temp = tempfile::tempdir().unwrap(); - let runtime = runtime(temp.path()); - let path = temp.path().join("orders.sql"); - let exported = export_table( - &runtime, - &ExportCancellationState::default(), - None, - "pg".to_string(), - TableExportOptions { - table: "orders".to_string(), - content: TableSqlContent::StructureAndData, - schema: Some(source.clone()), - database: None, - }, - TableExportDestination::ServerPath(path.clone()), - ) - .await; - let imported = import_table( - &runtime, - &DumpCancellationState::default(), - None, - "pg".to_string(), - TableImportSource::ServerPath(path), - TableImportOptions { - if_exists: IfTableExists::Fail, - schema: Some(target.clone()), - database: None, - }, - ) - .await; - let source_rows = run(&format!( - "SELECT {COLUMNS} FROM {source}.orders ORDER BY id" - )) - .await; - let target_rows = imported - .as_ref() - .ok() - .map(|_| format!("SELECT {COLUMNS} FROM {target}.orders ORDER BY id")); - let target_rows = match target_rows { - Some(sql) => Some(run(&sql).await), - None => None, - }; - let indexes = |schema: &str| { - format!( - "SELECT indexname, replace(indexdef, '{schema}.', '') FROM pg_indexes \ - WHERE schemaname = '{schema}' AND tablename = 'orders' ORDER BY indexname" - ) - }; - let source_indexes = run(&indexes(&source)).await; - let target_indexes = run(&indexes(&target)).await; - run(&format!("DROP SCHEMA {source} CASCADE")).await; - run(&format!("DROP SCHEMA {target} CASCADE")).await; - - assert_eq!(exported.expect("export").rows, 4); - assert_eq!(imported.expect("import").rows, 4); - assert_eq!(target_rows.unwrap(), source_rows); - assert_eq!(source_indexes.len(), 3, "the primary key and two indexes"); - assert_eq!(target_indexes, source_indexes); -} - -/// UNIQUE and EXCLUDE constraints stay constraints (with `DEFERRABLE`), and -/// an index on a schema-qualified function keeps naming that function. -#[tokio::test] -#[ignore] -async fn test_constraints_and_function_indexes_round_trip() { - require_pg!(); - tabularis_lib::drivers::registry::register_driver(postgres::PostgresDriver::new()).await; - let suffix = uuid::Uuid::new_v4().simple().to_string(); - let source = format!("table_transfer_con_src_{suffix}"); - let target = format!("table_transfer_con_dst_{suffix}"); - run(&format!("CREATE SCHEMA {source}")).await; - run(&format!("CREATE SCHEMA {target}")).await; - run(&format!( - "CREATE FUNCTION {source}.norm(text) RETURNS text LANGUAGE sql IMMUTABLE \ - AS 'SELECT lower(trim($1))'" - )) - .await; - run(&format!( - "CREATE TABLE {source}.slots (id integer PRIMARY KEY, code text, area circle, \ - CONSTRAINT slots_code UNIQUE (code) DEFERRABLE INITIALLY DEFERRED, \ - CONSTRAINT slots_area EXCLUDE USING gist (area WITH &&))" - )) - .await; - run(&format!( - "CREATE INDEX slots_norm ON {source}.slots ({source}.norm(code))" - )) - .await; - run(&format!( - "INSERT INTO {source}.slots VALUES (1, 'A', '<(0,0),1>'), (2, 'B', '<(5,5),1>')" - )) - .await; - - let imported = round_trip("slots", &source, &target).await; - let constraints = |schema: &str| { - format!( - "SELECT conname, contype::text, condeferrable, condeferred, \ - pg_get_constraintdef(c.oid) FROM pg_constraint c \ - JOIN pg_class t ON t.oid = c.conrelid JOIN pg_namespace n ON n.oid = t.relnamespace \ - WHERE n.nspname = '{schema}' AND t.relname = 'slots' ORDER BY conname" - ) - }; - let indexes = |schema: &str| { - format!( - "SELECT indexname, replace(indexdef, 'ON {schema}.slots', 'ON slots') FROM pg_indexes \ - WHERE schemaname = '{schema}' AND tablename = 'slots' ORDER BY indexname" - ) - }; - let source_constraints = run(&constraints(&source)).await; - let target_constraints = run(&constraints(&target)).await; - let source_indexes = run(&indexes(&source)).await; - let target_indexes = run(&indexes(&target)).await; - run(&format!("DROP SCHEMA {target} CASCADE")).await; - run(&format!("DROP SCHEMA {source} CASCADE")).await; - - assert_eq!(imported.expect("round trip"), 2); - assert_eq!( - source_constraints.len(), - 3, - "the primary key, UNIQUE and EXCLUDE" - ); - assert_eq!(target_constraints, source_constraints); - assert_eq!(source_indexes.len(), 4); - assert_eq!(target_indexes, source_indexes); - assert!( - format!("{target_indexes:?}").contains(&format!("{source}.norm(code)")), - "{target_indexes:?}" - ); -} - -/// Exports `{source}.{table}` and imports it into `target`. -async fn round_trip(table: &str, source: &str, target: &str) -> Result { - round_trip_file(table, source, target) - .await - .map(|(rows, _)| rows) -} - -/// The first value of each exported row, in file order. -fn exported_keys(file: &str) -> Vec { - file.lines() - .filter_map(|line| line.strip_prefix('(')) - .map(|line| { - line.split(',') - .next() - .unwrap() - .trim_matches('\'') - .to_string() - }) - .collect() -} - -/// [`round_trip`], also returning the exported file. -async fn round_trip_file(table: &str, source: &str, target: &str) -> Result<(u64, String), String> { - let temp = tempfile::tempdir().unwrap(); - let runtime = runtime(temp.path()); - let path = temp.path().join(format!("{table}.sql")); - export_table( - &runtime, - &ExportCancellationState::default(), - None, - "pg".to_string(), - TableExportOptions { - table: table.to_string(), - content: TableSqlContent::StructureAndData, - schema: Some(source.to_string()), - database: None, - }, - TableExportDestination::ServerPath(path.clone()), - ) - .await?; - let file = std::fs::read_to_string(&path).map_err(|e| e.to_string())?; - import_table( - &runtime, - &DumpCancellationState::default(), - None, - "pg".to_string(), - TableImportSource::ServerPath(path), - TableImportOptions { - if_exists: IfTableExists::Fail, - schema: Some(target.to_string()), - database: None, - }, - ) - .await - .map(|imported| (imported.rows, file)) -} - -/// Integer limits, `numeric` with more digits than a double holds, and the -/// float edge values (infinities, NaN, negative zero, the smallest and -/// largest doubles) come back bit for bit. -#[tokio::test] -#[ignore] -async fn test_numeric_extremes_round_trip() { - require_pg!(); - tabularis_lib::drivers::registry::register_driver(postgres::PostgresDriver::new()).await; - let suffix = uuid::Uuid::new_v4().simple().to_string(); - let source = format!("table_transfer_num_src_{suffix}"); - let target = format!("table_transfer_num_dst_{suffix}"); - run(&format!("CREATE SCHEMA {source}")).await; - run(&format!("CREATE SCHEMA {target}")).await; - run(&format!( - "CREATE TABLE {source}.numbers (id integer PRIMARY KEY, small smallint, \ - big bigint, exact numeric, scaled numeric(60,30), double float8, single float4)" - )) - .await; - run(&format!( - "INSERT INTO {source}.numbers VALUES \ - (1, 32767, 9223372036854775807, \ - '123456789012345678901234567890.123456789012345678901234567890', \ - '-123456789012345678901234567890.123456789012345678901234567890', \ - 'Infinity', 'Infinity'), \ - (2, -32768, -9223372036854775808, 'NaN', 0, '-Infinity', '-Infinity'), \ - (3, 0, 9007199254740993, '-0.000000000000000000000000000001', NULL, 'NaN', 'NaN'), \ - (4, NULL, -9007199254740993, 1e-130, 1, '-0', '-0'), \ - (5, 1, NULL, NULL, NULL, 1.7976931348623157e308, 3.4028235e38), \ - (6, 2, 0, 0.1, 0.1, 5e-324, 1.4e-45), \ - (7, 3, 1, 0, NULL, 0.30000000000000004, 0.1)" - )) - .await; - - // The export dialog's estimate: none before the first ANALYZE. - let unanalyzed = postgres::get_approximate_row_count(&pg_params(), "numbers", &source).await; - run(&format!("ANALYZE {source}.numbers")).await; - let analyzed = postgres::get_approximate_row_count(&pg_params(), "numbers", &source).await; - let imported = round_trip("numbers", &source, &target).await; - // Rows come out in key order, not in the order of the key's text. - run(&format!( - "CREATE TABLE {source}.keyed (id integer PRIMARY KEY, v text)" - )) - .await; - run(&format!( - "INSERT INTO {source}.keyed SELECT g, g::text FROM generate_series(12, 1, -1) g" - )) - .await; - let keyed = round_trip_file("keyed", &source, &target).await; - let compare = |schema: &str| { - format!( - "SELECT id, small, big::text, exact::text, scaled::text, double::text, \ - encode(float8send(double), 'hex'), single::text, \ - encode(float4send(single), 'hex') FROM {schema}.numbers ORDER BY id" - ) - }; - let source_rows = run(&compare(&source)).await; - let target_rows = match imported { - Ok(_) => Some(run(&compare(&target)).await), - Err(_) => None, - }; - run(&format!("DROP SCHEMA {source} CASCADE")).await; - run(&format!("DROP SCHEMA {target} CASCADE")).await; - - assert_eq!(unanalyzed, Ok(None)); - assert_eq!(analyzed, Ok(Some(7))); - assert_eq!(imported.expect("round trip"), 7); - assert_eq!(target_rows.unwrap(), source_rows); - let (rows, file) = keyed.expect("keyed round trip"); - assert_eq!(rows, 12); - assert_eq!( - exported_keys(&file), - (1..=12).map(|id| id.to_string()).collect::>() - ); -} diff --git a/src-tauri/tests/postgres_integration/triggers.rs b/src-tauri/tests/postgres_integration/triggers.rs deleted file mode 100644 index a3f4a5134..000000000 --- a/src-tauri/tests/postgres_integration/triggers.rs +++ /dev/null @@ -1,98 +0,0 @@ -//! Trigger management tests. - -use crate::helpers::pg_params; -use tabularis_lib::drivers::postgres; - -#[tokio::test] -#[ignore] -async fn test_get_triggers() { - require_pg!(); - let params = pg_params(); - - let triggers = postgres::get_triggers(¶ms, "test_schema") - .await - .expect("get_triggers should succeed"); - - let trigger_names: Vec<&str> = triggers.iter().map(|t| t.name.as_str()).collect(); - assert!( - trigger_names.contains(&"trg_audit"), - "Expected trg_audit trigger, got: {:?}", - trigger_names - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_trigger_definition() { - require_pg!(); - let params = pg_params(); - - let def = postgres::get_trigger_definition(¶ms, "trg_audit", "all_types", "test_schema") - .await - .expect("get_trigger_definition should succeed"); - - assert!( - def.to_lowercase().contains("after update"), - "Trigger definition should indicate AFTER UPDATE, got: {}", - def - ); - assert!( - def.to_lowercase().contains("all_types"), - "Trigger definition should reference all_types table" - ); -} - -#[tokio::test] -#[ignore] -async fn test_create_and_drop_trigger() { - require_pg!(); - let params = pg_params(); - - let trigger_name = "trg_test_temp"; - let schema = "test_schema"; - - // Cleanup from any prior failed run - let _ = postgres::drop_trigger(¶ms, trigger_name, "crud_scratch", schema).await; - - // Create trigger (reuse existing trigger function) - let create_sql = format!( - "CREATE TRIGGER {} BEFORE INSERT ON {}.crud_scratch \ - FOR EACH ROW EXECUTE FUNCTION {}.audit_trigger_fn()", - trigger_name, schema, schema - ); - postgres::create_trigger(¶ms, &create_sql, schema) - .await - .expect("create_trigger should succeed"); - - // Verify exists - let triggers = postgres::get_triggers(¶ms, schema).await.unwrap(); - assert!( - triggers.iter().any(|t| t.name == trigger_name), - "Created trigger should appear in list" - ); - - // Drop - postgres::drop_trigger(¶ms, trigger_name, "crud_scratch", schema) - .await - .expect("drop_trigger should succeed"); - - // Verify gone - let triggers = postgres::get_triggers(¶ms, schema).await.unwrap(); - assert!( - !triggers.iter().any(|t| t.name == trigger_name), - "Dropped trigger should not appear in list" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_triggers_empty_schema() { - require_pg!(); - let params = pg_params(); - - let triggers = postgres::get_triggers(¶ms, "other_schema") - .await - .expect("get_triggers should succeed for schema with no triggers"); - - assert!(triggers.is_empty(), "other_schema should have no triggers"); -} diff --git a/src-tauri/tests/postgres_integration/views.rs b/src-tauri/tests/postgres_integration/views.rs deleted file mode 100644 index 862f811f3..000000000 --- a/src-tauri/tests/postgres_integration/views.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! View management tests. - -use crate::helpers::pg_params; -use tabularis_lib::drivers::postgres; - -#[tokio::test] -#[ignore] -async fn test_get_views() { - require_pg!(); - let params = pg_params(); - - let views = postgres::get_views(¶ms, "test_schema") - .await - .expect("get_views should succeed"); - - let view_names: Vec<&str> = views.iter().map(|v| v.name.as_str()).collect(); - assert!( - view_names.contains(&"active_users"), - "Expected active_users view, got: {:?}", - view_names - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_view_definition() { - require_pg!(); - let params = pg_params(); - - let def = postgres::get_view_definition(¶ms, "active_users", "test_schema") - .await - .expect("get_view_definition should succeed"); - - assert!( - def.to_lowercase().contains("select"), - "View definition should contain SELECT, got: {}", - def - ); - assert!( - def.to_lowercase().contains("all_types"), - "View definition should reference all_types table" - ); -} - -#[tokio::test] -#[ignore] -async fn test_get_view_columns() { - require_pg!(); - let params = pg_params(); - - let columns = postgres::get_view_columns(¶ms, "active_users", "test_schema") - .await - .expect("get_view_columns should succeed"); - - let col_names: Vec<&str> = columns.iter().map(|c| c.name.as_str()).collect(); - assert!(col_names.contains(&"id"), "Expected id column in view"); - assert!(col_names.contains(&"name"), "Expected name column in view"); - assert!( - col_names.contains(&"is_active"), - "Expected is_active column in view" - ); -} - -#[tokio::test] -#[ignore] -async fn test_create_and_drop_view() { - require_pg!(); - let params = pg_params(); - - let view_name = "test_temp_view"; - let schema = "test_schema"; - let definition = "SELECT id, col_text FROM test_schema.all_types WHERE id < 10"; - - // Create - postgres::create_view(¶ms, view_name, definition, schema) - .await - .expect("create_view should succeed"); - - // Verify exists - let views = postgres::get_views(¶ms, schema).await.unwrap(); - assert!( - views.iter().any(|v| v.name == view_name), - "Created view should appear in list" - ); - - // Drop - postgres::drop_view(¶ms, view_name, schema) - .await - .expect("drop_view should succeed"); - - // Verify gone - let views = postgres::get_views(¶ms, schema).await.unwrap(); - assert!( - !views.iter().any(|v| v.name == view_name), - "Dropped view should not appear in list" - ); -} - -#[tokio::test] -#[ignore] -async fn test_alter_view() { - require_pg!(); - let params = pg_params(); - - let view_name = "test_alter_view"; - let schema = "test_schema"; - - // Cleanup from any prior failed run - let _ = postgres::drop_view(¶ms, view_name, schema).await; - - // Create initial view - let def1 = "SELECT id FROM test_schema.all_types"; - crate::helpers::retry(|| { - let p = params.clone(); - async move { postgres::create_view(&p, view_name, def1, schema).await } - }) - .await - .expect("create_view should succeed"); - - // Alter (replace) with new definition - let def2 = "SELECT id, col_text FROM test_schema.all_types"; - crate::helpers::retry(|| { - let p = params.clone(); - async move { postgres::alter_view(&p, view_name, def2, schema).await } - }) - .await - .expect("alter_view should succeed"); - - // Verify new definition has both columns - let columns = crate::helpers::retry(|| { - let p = params.clone(); - async move { postgres::get_view_columns(&p, view_name, schema).await } - }) - .await - .unwrap(); - assert_eq!(columns.len(), 2, "Altered view should have 2 columns"); - - // Cleanup - postgres::drop_view(¶ms, view_name, schema) - .await - .unwrap(); -} - -#[tokio::test] -#[ignore] -async fn test_get_views_empty_schema() { - require_pg!(); - let params = pg_params(); - - // other_schema has no views - let views = postgres::get_views(¶ms, "other_schema") - .await - .expect("get_views should succeed for schema with no views"); - - assert!(views.is_empty(), "other_schema should have no views"); -} diff --git a/src-tauri/tests/postgres_plugin_table_copy.rs b/src-tauri/tests/postgres_plugin_table_copy.rs new file mode 100644 index 000000000..79a252a94 --- /dev/null +++ b/src-tauri/tests/postgres_plugin_table_copy.rs @@ -0,0 +1,500 @@ +//! Opt-in end-to-end coverage of table copy through the real PostgreSQL plugin +//! (a release with `table_copy`), against a disposable local PostgreSQL. +//! +//! Run with: +//! `TABULARIS_TEST_PG_PLUGIN_DIR=

\ +//! cargo test --test postgres_plugin_table_copy -- --ignored --nocapture` +//! Optional: TABULARIS_TEST_PG_HOST (127.0.0.1), _PORT (54320), _USER (postgres), +//! _PASSWORD (password), _DATABASE (testdb). The role must be able to create +//! schemas. Each run creates two UUID-named schemas and drops only those. +//! Needs `psql` reachable as `podman exec pg-tabularis-test psql` or on PATH; +//! set TABULARIS_TEST_PSQL to a full command prefix to override. + +use std::path::Path; +use std::process::Command; +use std::sync::Arc; +use tabularis_lib::application::database_transfers::DumpCancellationState; +use tabularis_lib::application::table_row_transfers::{ + get_capabilities, plan, run, TransferStatus, +}; +use tabularis_lib::models::{ + ConnectionParams, ConnectionsFile, DatabaseSelection, SavedConnection, +}; +use tabularis_lib::runtime::bootstrap::{ + bootstrap_application, install_process_prerequisites, BootstrapOptions, +}; +use tabularis_lib::runtime::events::NoopRuntimeEvents; +use tabularis_lib::runtime::paths::FixedRuntimePaths; +use tabularis_lib::runtime::RuntimeContext; +use tabularis_lib::table_transfer::{ + ColumnMappingRequest, ConflictMode, TableSelection, TableTransferRequest, +}; + +fn env(name: &str, default: &str) -> String { + std::env::var(format!("TABULARIS_TEST_PG_{name}")).unwrap_or_else(|_| default.to_string()) +} + +fn psql(sql: &str) -> String { + let prefix = std::env::var("TABULARIS_TEST_PSQL") + .unwrap_or_else(|_| "podman exec pg-tabularis-test psql -U postgres -d testdb".to_string()); + let mut parts = prefix.split_whitespace(); + let output = Command::new(parts.next().unwrap()) + .args(parts) + .args(["-At", "-F", "|", "-v", "ON_ERROR_STOP=1", "-c", sql]) + .output() + .expect("run psql"); + assert!( + output.status.success(), + "psql failed: {}\nSQL: {sql}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8_lossy(&output.stdout).trim().to_string() +} + +struct NoSecrets; + +impl tabularis_lib::runtime::secrets::RuntimeSecrets for NoSecrets { + fn get(&self, _account: &str) -> Result, String> { + Ok(None) + } + fn set(&self, _account: &str, _value: &str) -> Result<(), String> { + Ok(()) + } + fn delete(&self, _account: &str) -> Result<(), String> { + Ok(()) + } +} + +fn saved(id: &str, params: ConnectionParams) -> SavedConnection { + SavedConnection { + id: id.to_string(), + name: id.to_string(), + params, + plugin_secret_keys: Vec::new(), + group_id: None, + sort_order: None, + detect_json_in_text_columns: None, + appearance: None, + tag_ids: None, + environment: None, + managed: false, + } +} + +fn pg_params() -> ConnectionParams { + ConnectionParams { + driver: "postgresql".to_string(), + host: Some(env("HOST", "127.0.0.1")), + port: Some(env("PORT", "54320").parse().unwrap()), + username: Some(env("USER", "postgres")), + password: Some(env("PASSWORD", "password")), + database: DatabaseSelection::Single(env("DATABASE", "testdb")), + ssl_mode: Some("disable".to_string()), + ..Default::default() + } +} + +fn copy_plugin_into(plugins: &Path) { + let source = std::env::var("TABULARIS_TEST_PG_PLUGIN_DIR") + .expect("set TABULARIS_TEST_PG_PLUGIN_DIR to a directory with .tabularium and the binary"); + std::fs::create_dir_all(plugins).unwrap(); + for entry in std::fs::read_dir(source).unwrap() { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_file() { + std::fs::copy(entry.path(), plugins.join(entry.file_name())).unwrap(); + } + } +} + +fn request( + source: &str, + target: &str, + source_schema: &str, + target_schema: &str, + table: &str, + conflict: ConflictMode, +) -> TableTransferRequest { + TableTransferRequest { + source_connection_id: source.to_string(), + source_database: None, + source_schema: Some(source_schema.to_string()), + target_connection_id: target.to_string(), + target_database: None, + target_schema: Some(target_schema.to_string()), + tables: vec![TableSelection { + source_table: table.to_string(), + target_table: table.to_string(), + columns: Vec::::new(), + }], + conflict, + batch_rows: Some(7), + transfer_id: Some(format!("e2e-{}", uuid::Uuid::new_v4())), + } +} + +const COLUMNS: &str = "id bigint primary key, flag boolean, small smallint, big bigint, \ + r4 real, r8 double precision, n numeric(30,10), v varchar(40), t text, u uuid, \ + j jsonb, d date, tm time(3), ts timestamp(6), tz timestamptz, b bytea"; + +const SEED: &str = "INSERT INTO {s}.items SELECT i, i % 2 = 0, (i % 100)::smallint, \ + i::bigint * 1000000000, i / 8.0, i / 3.0, (i || '.1234567891')::numeric(30,10), 'v' || i, \ + CASE WHEN i % 5 = 0 THEN NULL ELSE 'text ''quoted'' ' || i END, \ + gen_random_uuid(), jsonb_build_object('i', i, 'a', jsonb_build_array(1, 2)), \ + date '2024-01-01' + i, time '01:02:03.123' + (i || ' minutes')::interval, \ + timestamp '2024-01-02 03:04:05.123456' + (i || ' seconds')::interval, \ + timestamptz '2024-01-02 03:04:05.123456+00' + (i || ' hours')::interval, \ + decode(lpad(to_hex(i), 4, '0'), 'hex') \ + FROM generate_series(1, 30) i"; + +/// The driver registry is process-wide, so the two tests must not overlap; +/// each one starts by stopping any plugin the other left registered. +static REGISTRY_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +/// Drops the schemas even when an assertion panics. +struct DropSchemas(Vec); + +impl Drop for DropSchemas { + fn drop(&mut self) { + for schema in &self.0 { + let _ = std::panic::catch_unwind(|| { + psql(&format!("DROP SCHEMA IF EXISTS {schema} CASCADE")) + }); + } + } +} + +const WIDE_SEED: &str = "INSERT INTO {s}.wide SELECT i, decode(repeat('ab', 100000), 'hex') \ + FROM generate_series(1, 400) i"; + +const DIGEST: &str = "SELECT md5(string_agg(x::text, '|' ORDER BY id)) FROM {s}.items x"; + +#[tokio::test] +#[ignore = "requires TABULARIS_TEST_PG_PLUGIN_DIR and a disposable PostgreSQL"] +async fn copies_a_table_between_postgres_connections_and_into_sqlite_through_the_plugin() { + let _serial = REGISTRY_LOCK.lock().await; + // A plugin left registered by the other test belongs to a finished runtime. + tabularis_lib::drivers::registry::shutdown_external_drivers().await; + let dir = tempfile::tempdir().unwrap(); + copy_plugin_into(&dir.path().join("plugins").join("postgresql")); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + dir.path().to_path_buf(), + dir.path().to_path_buf(), + )), + Arc::new(NoopRuntimeEvents), + Arc::new(NoSecrets), + ); + let sqlite_file = dir.path().join("target.db"); + std::fs::File::create(&sqlite_file).unwrap(); + tabularis_lib::persistence::save_connections_file( + &runtime.paths.connections_file(), + &ConnectionsFile { + connections: vec![ + saved("pg", pg_params()), + saved( + "lite", + ConnectionParams { + driver: "sqlite".to_string(), + database: DatabaseSelection::Single(sqlite_file.to_string_lossy().into()), + ..Default::default() + }, + ), + ], + ..Default::default() + }, + ) + .unwrap(); + + install_process_prerequisites(); + bootstrap_application( + runtime.clone(), + BootstrapOptions { + load_external_plugins: true, + run_connection_migrations: false, + }, + ) + .await + .expect("bootstrap"); + + let capabilities = get_capabilities().await; + assert!( + capabilities + .pairs + .iter() + .any(|p| p.source == "postgresql" && p.target == "postgresql"), + "the plugin must advertise table_copy: {:?}", + capabilities.pairs + ); + assert!(capabilities + .pairs + .iter() + .any(|p| p.source == "postgresql" && p.target == "sqlite")); + + let tag = uuid::Uuid::new_v4().simple().to_string(); + let (src, dst) = (format!("xs_{tag}"), format!("xd_{tag}")); + let _cleanup = DropSchemas(vec![src.clone(), dst.clone()]); + for schema in [&src, &dst] { + psql(&format!( + "CREATE SCHEMA {schema}; CREATE TABLE {schema}.items ({COLUMNS})" + )); + } + psql(&SEED.replace("{s}", &src)); + let state = DumpCancellationState::default(); + + { + // Plan is clean for identical tables. + let planned = plan( + &runtime, + None, + request("pg", "pg", &src, &dst, "items", ConflictMode::Fail), + ) + .await + .unwrap(); + assert!( + !planned.blocking, + "{:?} {:?}", + planned.issues, planned.tables + ); + + // PG -> PG, then compare every column through the server. + let result = run( + &runtime, + &state, + None, + request("pg", "pg", &src, &dst, "items", ConflictMode::Fail), + ) + .await + .unwrap(); + let table = &result.tables[0]; + assert_eq!(table.error, None); + assert_eq!(result.status, TransferStatus::Completed); + assert_eq!((table.rows_read, table.rows_written), (30, 30)); + assert_eq!( + psql(&DIGEST.replace("{s}", &dst)), + psql(&DIGEST.replace("{s}", &src)), + "every value must arrive exactly" + ); + + // Skip mode over the same rows writes nothing and reports them skipped. + let again = run( + &runtime, + &state, + None, + request("pg", "pg", &src, &dst, "items", ConflictMode::Skip), + ) + .await + .unwrap(); + let table = &again.tables[0]; + assert_eq!(table.error, None); + assert_eq!((table.rows_written, table.rows_skipped), (0, 30)); + + // Fail mode over the same rows stops and leaves the target as it was. + let failed = run( + &runtime, + &state, + None, + request("pg", "pg", &src, &dst, "items", ConflictMode::Fail), + ) + .await + .unwrap(); + assert_eq!(failed.tables[0].status, TransferStatus::Failed); + assert_eq!(psql(&format!("SELECT count(*) FROM {dst}.items")), "30"); + + // The source cannot be written into itself, even by another connection id. + let same = plan( + &runtime, + None, + request("pg", "pg", &src, &src, "items", ConflictMode::Fail), + ) + .await + .unwrap(); + assert!(same.blocking); + } + + // PG -> SQLite: values arrive exactly in a table with compatible types. + let pool = tabularis_lib::pool_manager::get_sqlite_pool(&ConnectionParams { + driver: "sqlite".to_string(), + database: DatabaseSelection::Single(sqlite_file.to_string_lossy().into()), + ..Default::default() + }) + .await + .unwrap(); + sqlx::query( + "CREATE TABLE items (id INTEGER PRIMARY KEY, flag BOOLEAN, small INTEGER, big INTEGER, \ + r4 REAL, r8 REAL, n NUMERIC, v TEXT, t TEXT, u TEXT, j JSON, d DATE, tm TIME, \ + ts DATETIME, tz DATETIME, b BLOB)", + ) + .execute(&pool) + .await + .unwrap(); + let to_sqlite = run( + &runtime, + &state, + None, + request("pg", "lite", &src, "", "items", ConflictMode::Fail), + ) + .await + .unwrap(); + let table = &to_sqlite.tables[0]; + assert_eq!(table.error, None, "{table:?}"); + assert_eq!((table.rows_read, table.rows_written), (30, 30)); + let (count, bytes, tz): (i64, Vec, String) = + sqlx::query_as("SELECT count(*), (SELECT b FROM items WHERE id = 30), (SELECT tz FROM items WHERE id = 1) FROM items") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(count, 30); + assert_eq!(bytes, vec![0x00, 0x1e]); + assert_eq!( + tz, + psql(&format!("SELECT tz::text FROM {src}.items WHERE id = 1")) + ); +} + +/// Rows of ~100 KB make the plugin cut a page at its response-size budget. +/// A plugin that rewinds one row too far repeats a row after such a page; the +/// copy must then stop loudly rather than write rows twice, and a plugin that +/// rewinds correctly must copy every row exactly once. +#[tokio::test] +#[ignore = "requires TABULARIS_TEST_PG_PLUGIN_DIR and a disposable PostgreSQL"] +async fn wide_rows_never_arrive_twice() { + let _serial = REGISTRY_LOCK.lock().await; + // A plugin left registered by the other test belongs to a finished runtime. + tabularis_lib::drivers::registry::shutdown_external_drivers().await; + let dir = tempfile::tempdir().unwrap(); + copy_plugin_into(&dir.path().join("plugins").join("postgresql")); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + dir.path().to_path_buf(), + dir.path().to_path_buf(), + )), + Arc::new(NoopRuntimeEvents), + Arc::new(NoSecrets), + ); + tabularis_lib::persistence::save_connections_file( + &runtime.paths.connections_file(), + &ConnectionsFile { + connections: vec![saved("pg", pg_params())], + ..Default::default() + }, + ) + .unwrap(); + install_process_prerequisites(); + bootstrap_application( + runtime.clone(), + BootstrapOptions { + load_external_plugins: true, + run_connection_migrations: false, + }, + ) + .await + .expect("bootstrap"); + + let tag = uuid::Uuid::new_v4().simple().to_string(); + let (src, dst) = (format!("ws_{tag}"), format!("wd_{tag}")); + let _cleanup = DropSchemas(vec![src.clone(), dst.clone()]); + for schema in [&src, &dst] { + psql(&format!( + "CREATE SCHEMA {schema}; CREATE TABLE {schema}.wide (id bigint primary key, b bytea)" + )); + } + psql(&WIDE_SEED.replace("{s}", &src)); + + let mut wide = request("pg", "pg", &src, &dst, "wide", ConflictMode::Fail); + wide.batch_rows = Some(500); + let result = run(&runtime, &DumpCancellationState::default(), None, wide) + .await + .unwrap(); + let table = &result.tables[0]; + let copied: i64 = psql(&format!("SELECT count(*) FROM {dst}.wide")) + .parse() + .unwrap(); + let distinct: i64 = psql(&format!("SELECT count(DISTINCT id) FROM {dst}.wide")) + .parse() + .unwrap(); + assert_eq!(copied, distinct, "a row was written twice: {table:?}"); + println!( + "wide copy: status={:?} written={} error={:?}", + table.status, table.rows_written, table.error + ); + if table.status == TransferStatus::Completed { + assert_eq!(copied, 400, "{table:?}"); + } else { + let error = table.error.clone().unwrap_or_default(); + assert!(error.contains("response size limit"), "{error}"); + } +} + +/// An identity column that is `BY DEFAULT` accepts the copied value, so a table +/// keyed by one must copy; an `ALWAYS` identity column cannot take a value and +/// is left for the planner to refuse. +#[tokio::test] +#[ignore = "requires TABULARIS_TEST_PG_PLUGIN_DIR and a disposable PostgreSQL"] +async fn a_by_default_identity_key_copies_with_its_values() { + let _serial = REGISTRY_LOCK.lock().await; + tabularis_lib::drivers::registry::shutdown_external_drivers().await; + let dir = tempfile::tempdir().unwrap(); + copy_plugin_into(&dir.path().join("plugins").join("postgresql")); + let runtime = RuntimeContext::new( + Arc::new(FixedRuntimePaths::new( + dir.path().to_path_buf(), + dir.path().to_path_buf(), + )), + Arc::new(NoopRuntimeEvents), + Arc::new(NoSecrets), + ); + tabularis_lib::persistence::save_connections_file( + &runtime.paths.connections_file(), + &ConnectionsFile { + connections: vec![saved("pg", pg_params())], + ..Default::default() + }, + ) + .unwrap(); + install_process_prerequisites(); + bootstrap_application( + runtime.clone(), + BootstrapOptions { + load_external_plugins: true, + run_connection_migrations: false, + }, + ) + .await + .expect("bootstrap"); + + let tag = uuid::Uuid::new_v4().simple().to_string(); + let (src, dst) = (format!("is_{tag}"), format!("id_{tag}")); + let _cleanup = DropSchemas(vec![src.clone(), dst.clone()]); + for schema in [&src, &dst] { + psql(&format!( + "CREATE SCHEMA {schema}; CREATE TABLE {schema}.t (id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, v text)" + )); + } + psql(&format!( + "INSERT INTO {src}.t (id, v) SELECT i * 10, 'v' || i FROM generate_series(1, 5) i" + )); + + let result = plan( + &runtime, + None, + request("pg", "pg", &src, &dst, "t", ConflictMode::Fail), + ) + .await + .unwrap(); + assert!(!result.blocking, "{:?} {:?}", result.issues, result.tables); + let run = run( + &runtime, + &DumpCancellationState::default(), + None, + request("pg", "pg", &src, &dst, "t", ConflictMode::Fail), + ) + .await + .unwrap(); + assert_eq!(run.tables[0].error, None); + assert_eq!( + psql(&format!( + "SELECT string_agg(id::text, ',' ORDER BY id) FROM {dst}.t" + )), + "10,20,30,40,50" + ); +} diff --git a/src-tauri/tests/socket_integration.rs b/src-tauri/tests/socket_integration.rs index 25b20264f..121ad78a2 100644 --- a/src-tauri/tests/socket_integration.rs +++ b/src-tauri/tests/socket_integration.rs @@ -2,11 +2,24 @@ #![cfg(unix)] use tabularis_lib::drivers::driver_trait::DatabaseDriver; -use tabularis_lib::drivers::{mysql::MysqlDriver, postgres::PostgresDriver}; +use tabularis_lib::drivers::mysql::MysqlDriver; +use tabularis_lib::drivers::registry; use tabularis_lib::models::{ConnectionParams, DatabaseSelection}; -use tabularis_lib::pool_manager::{ - close_pool_with_id, get_mysql_pool_with_id, get_postgres_pool_with_id, -}; +use tabularis_lib::pool_manager::{close_pool_with_id, get_mysql_pool_with_id}; + +struct NoSecrets; + +impl tabularis_lib::runtime::secrets::RuntimeSecrets for NoSecrets { + fn get(&self, _account: &str) -> Result, String> { + Ok(None) + } + fn set(&self, _account: &str, _value: &str) -> Result<(), String> { + Ok(()) + } + fn delete(&self, _account: &str) -> Result<(), String> { + Ok(()) + } +} fn params(driver: &str, port: u16) -> ConnectionParams { ConnectionParams { @@ -95,48 +108,105 @@ async fn mysql_socket_auth_and_tcp_regression() { close_pool_with_id(&tcp, Some("socket-regression-admin")).await; } +/// Verifies the `postgresql` plugin honors `unix_socket_path`: when a socket +/// path is set, the plugin must dial the socket (not TCP) and ignore the +/// `host`/`port` fields. The built-in postgres driver did this in +/// `pool_manager.rs` (`split_postgres_socket_path` + `build_postgres_configurations`); +/// the plugin must mirror that logic. +/// +/// Needs a plugin release that honors `unix_socket_path` (1.0.0-rc.15 or +/// later); rc.14 and earlier dial TCP from `host`/`port` instead and fail the +/// socket half of this test. CI runs it against the pinned release in +/// `.github/workflows/postgres-integration.yml`. +/// +/// Run with: +/// PG_UNIX_SOCKET=/var/run/postgresql cargo test --test socket_integration \ +/// postgresql_plugin_honors_unix_socket -- --ignored --nocapture #[tokio::test] -#[ignore = "requires disposable PostgreSQL on port 54320 and PG_UNIX_SOCKET"] -async fn postgres_socket_tls_and_tcp_regression() { - let driver = PostgresDriver::new(); - let mut tcp = params("postgres", 54320); - driver - .test_connection(&tcp) +#[ignore = "requires disposable PostgreSQL on port 54320, PG_UNIX_SOCKET, and the postgresql plugin installed"] +async fn postgresql_plugin_honors_unix_socket_path() { + // Bootstrap with external plugins so the postgresql plugin registers. A + // plugin directory given in TABULARIS_TEST_PG_PLUGIN_DIR is copied into a + // scratch app directory; otherwise the installed plugin is used. + tabularis_lib::runtime::bootstrap::install_process_prerequisites(); + let scratch = tempfile::tempdir().expect("scratch app directory"); + let runtime = match std::env::var("TABULARIS_TEST_PG_PLUGIN_DIR") { + Ok(plugin_dir) => { + let target = scratch + .path() + .join("plugins") + .join("drivers") + .join("postgresql"); + std::fs::create_dir_all(&target).unwrap(); + for entry in std::fs::read_dir(plugin_dir).unwrap() { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_file() { + std::fs::copy(entry.path(), target.join(entry.file_name())).unwrap(); + } + } + tabularis_lib::runtime::RuntimeContext::new( + std::sync::Arc::new(tabularis_lib::runtime::paths::FixedRuntimePaths::new( + scratch.path().to_path_buf(), + scratch.path().to_path_buf(), + )), + std::sync::Arc::new(tabularis_lib::runtime::events::NoopRuntimeEvents), + std::sync::Arc::new(NoSecrets), + ) + } + Err(_) => tabularis_lib::runtime::RuntimeContext::system(), + }; + let _ = tabularis_lib::runtime::bootstrap::bootstrap_application( + runtime, + tabularis_lib::runtime::bootstrap::BootstrapOptions { + load_external_plugins: true, + run_connection_migrations: false, + }, + ) + .await; + + let drv = registry::get_driver("postgresql") .await - .expect("TCP authentication"); - let missing = tempfile::tempdir().unwrap(); - tcp.ssl_mode = Some("verify-full".to_string()); - tcp.ssl_ca = Some(missing.path().join("ca.pem").display().to_string()); - tcp.ssl_cert = Some(missing.path().join("cert.pem").display().to_string()); - tcp.ssl_key = Some(missing.path().join("key.pem").display().to_string()); - assert!( - driver.test_connection(&tcp).await.is_err(), - "TCP must validate TLS files" - ); + .expect("postgresql plugin must be registered"); + + // TCP works (sanity check). + let tcp = ConnectionParams { + driver: "postgresql".to_string(), + host: Some("127.0.0.1".to_string()), + port: Some( + std::env::var("PG_PORT") + .ok() + .and_then(|port| port.parse().ok()) + .unwrap_or(54320), + ), + username: Some("postgres".to_string()), + password: Some("password".to_string()), + database: DatabaseSelection::Single("testdb".to_string()), + ssl_mode: Some("disable".to_string()), + ..Default::default() + }; + drv.test_connection(&tcp) + .await + .expect("TCP authentication via postgresql plugin"); + + // Socket: set unix_socket_path + a bogus host. If the plugin honors the + // socket, test_connection succeeds despite the unreachable host. If it + // dials TCP, it fails to resolve ignored.invalid. The port stays at the + // server's: for a socket directory the port names the socket file + // (`.s.PGSQL.`), so changing it would probe a different socket. + let socket_path = std::env::var("PG_UNIX_SOCKET") + .expect("PG_UNIX_SOCKET env var must point at the socket dir"); let mut socket = tcp.clone(); - socket.unix_socket_path = Some(std::env::var("PG_UNIX_SOCKET").expect("PG_UNIX_SOCKET")); + socket.unix_socket_path = Some(socket_path); socket.host = Some("ignored.invalid".to_string()); - socket.port = Some(1); - socket.startup_script = Some("SET application_name = 'socket_probe'".to_string()); - driver - .test_connection(&socket) - .await - .expect("socket ignores inactive TLS files"); - for _ in 0..2 { - let pool = get_postgres_pool_with_id(&socket, Some("socket-regression")) - .await - .expect("socket pool"); - let client = pool.get().await.expect("socket checkout"); - let row = client - .query_one("SELECT current_setting('application_name')", &[]) - .await - .expect("startup script on socket pool"); - assert_eq!(row.get::<_, String>(0), "socket_probe"); - drop(client); - close_pool_with_id(&socket, Some("socket-regression")).await; - } - driver - .test_connection(¶ms("postgres", 54320)) + socket.ssl_mode = Some("disable".to_string()); + + drv.test_connection(&socket).await.expect( + "postgresql plugin must dial the Unix socket, not TCP — \ + if this fails, the plugin is ignoring unix_socket_path", + ); + + // TCP still works after the socket test (no state corruption). + drv.test_connection(&tcp) .await .expect("TCP still works after socket use"); }