From b0b027a9aa08f00090bc49b0d30a297fd0c423ec Mon Sep 17 00:00:00 2001 From: James Maes Date: Mon, 12 Oct 2026 17:05:36 -0500 Subject: [PATCH 1/4] docs: name 1.0.0-RC.4 as the snake_case rename release 1.0.0-RC.3 on Maven Central is an accidental republish of RC.2, so the rename shipped in 1.0.0-RC.4. Point UPGRADE.md, the @Deprecated(since) annotations, their javadoc, the RC.4 changelog wording, the README upgrade row and the naming test comment at RC.4, and note that upgrading from RC.3 is the same as upgrading from RC.2. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- README.md | 2 +- UPGRADE.md | 8 +++++--- .../sqlworkbench/SqlWorkbenchQBitConfig.java | 16 ++++++++-------- .../sqlworkbench/model/ShareAudienceType.java | 4 ++-- .../sqlworkbench/model/SqlWorkbenchCell.java | 4 ++-- .../model/SqlWorkbenchExecution.java | 4 ++-- .../sqlworkbench/model/SqlWorkbenchNotebook.java | 4 ++-- .../model/SqlWorkbenchNotebookShare.java | 4 ++-- .../model/SqlWorkbenchNotebookVersion.java | 4 ++-- .../model/SqlWorkbenchResultSnapshot.java | 4 ++-- .../SqlWorkbenchQBitProducerTest.java | 4 ++-- 12 files changed, 32 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b621b47..6c9db14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,9 +21,9 @@ All notable changes to this project are documented here. The format follows Keep - **Pinning a result works with QQQ core permission enforcement on.** `getUserPermissionNames()` now includes `sql_workbench_result_snapshot.insert`: pinning is a top-level insert, which core enforcement checks, so hosts no longer need to grant it by hand. Record locks still limit snapshots to the user's own notebooks. ### Deprecated -- `LEGACY_TABLE_NAME` on each entity, `ShareAudienceType.LEGACY_NAME` and `SqlWorkbenchQBitConfig.LEGACY_*` hold the pre-RC.3 names, for migrating stored references only. +- `LEGACY_TABLE_NAME` on each entity, `ShareAudienceType.LEGACY_NAME` and `SqlWorkbenchQBitConfig.LEGACY_*` hold the pre-RC.4 names, for migrating stored references only. -### Upgrade from RC.2 +### Upgrade from RC.2 (or RC.3, a copy of RC.2) - Follow [UPGRADE.md](UPGRADE.md): grant the renamed permissions and rename stored table names (audit, saved views and reports). No DDL. ## [1.0.0-RC.3] - 2026-10-12 diff --git a/README.md b/README.md index 46d2af8..06c6b6c 100644 --- a/README.md +++ b/README.md @@ -244,7 +244,7 @@ A checklist for adding the workbench to a QQQ application. Each row points to th | ESB and search | Optional: wire `SqlWorkbenchIntegrations.esbTableNames` and `quickSearchTables` into your ESB and Quick Search config ([ESB and Quick Search](#esb-and-quick-search)). | | Turning writes off | `withWriteModeEnabled(false)` disables write mode for everyone. | | Known limitations | Raw SQL bypasses QQQ security, audits, listeners and automations ([Safety model](#safety-model)). H2 and generic backends have no enforced read-only transaction. Only PostgreSQL DDL ships. Shares are read-only (no shared editing). | -| Upgrading | From RC.2: the QQQ names became snake_case (`sql_workbench_*`; no DDL). See [UPGRADE.md](UPGRADE.md) for permissions and stored table names. From RC.1: also run the share-table DDL and backfill, grant the new permission lists (the tables no longer rely on the admin `hasAccess` permission alone), call `applyToSession`, and use QQQ `4.1.0-RC.4` or later. | +| Upgrading | From RC.2 (or RC.3, a copy of RC.2): the QQQ names became snake_case (`sql_workbench_*`; no DDL). See [UPGRADE.md](UPGRADE.md) for permissions and stored table names. From RC.1: also run the share-table DDL and backfill, grant the new permission lists (the tables no longer rely on the admin `hasAccess` permission alone), call `applyToSession`, and use QQQ `4.1.0-RC.4` or later. | Nothing in the qbit is specific to one host application. diff --git a/UPGRADE.md b/UPGRADE.md index 127c606..9ba915c 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -1,10 +1,12 @@ # Upgrading -## To 1.0.0-RC.3: snake_case names (metadata only) +## To 1.0.0-RC.4: snake_case names (metadata only) -The owner naming rule now applies to every QRun-IO qbit: table names are lowercase snake_case, prefixed with the qbit's name. In 1.0.0-RC.3 the SQL Workbench's QQQ names change to match. **The database does not change**: the physical tables were already `sql_workbench_*` (`docs/ddl/postgres.sql`), so no DDL runs. What changes is the names QQQ uses, and anything your app stored under the old names. +The rename shipped in 1.0.0-RC.4. 1.0.0-RC.3 on Maven Central is an accidental republish of the RC.2 code (see CHANGELOG.md), so upgrading from RC.3 is the same as upgrading from RC.2. -| Kind | Before (RC.1, RC.2) | From RC.3 | +The owner naming rule now applies to every QRun-IO qbit: table names are lowercase snake_case, prefixed with the qbit's name. In 1.0.0-RC.4 the SQL Workbench's QQQ names change to match. **The database does not change**: the physical tables were already `sql_workbench_*` (`docs/ddl/postgres.sql`), so no DDL runs. What changes is the names QQQ uses, and anything your app stored under the old names. + +| Kind | Before (RC.1, RC.2, RC.3) | From RC.4 | |---|---|---| | Tables (and the notebook possible-value source) | `sqlWorkbenchNotebook`, `sqlWorkbenchCell`, `sqlWorkbenchNotebookVersion`, `sqlWorkbenchResultSnapshot`, `sqlWorkbenchNotebookShare`, `sqlWorkbenchExecution` | `sql_workbench_notebook`, `sql_workbench_cell`, `sql_workbench_notebook_version`, `sql_workbench_result_snapshot`, `sql_workbench_notebook_share`, `sql_workbench_execution` | | Enum possible-value source | `sqlWorkbenchShareAudienceType` | `sql_workbench_share_audience_type` | diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitConfig.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitConfig.java index 0a080ac..3a479d0 100644 --- a/src/main/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitConfig.java +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitConfig.java @@ -71,23 +71,23 @@ public class SqlWorkbenchQBitConfig implements QBitConfig public static final String ALL_ACCESS_SECURITY_KEY_NAME = "sql_workbench_all_access"; /////////////////////////////////////////////////////////////////////////// - // names before 1.0.0-RC.3, when the owner rule (lowercase snake_case, // + // names before 1.0.0-RC.4, when the owner rule (lowercase snake_case, // // prefixed with the qbit name) was applied; kept only so hosts can // // migrate stored references (see UPGRADE.md) // /////////////////////////////////////////////////////////////////////////// - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_ACCESS_PERMISSION_BASE_NAME = "sqlWorkbench"; - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_WRITE_PERMISSION_NAME = "sqlWorkbench.write"; - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_SHARE_PERMISSION_NAME = "sqlWorkbench.share"; - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_ADMIN_PERMISSION_BASE_NAME = "sqlWorkbenchAdmin"; - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_USER_SECURITY_KEY_TYPE_NAME = "sqlWorkbenchUser"; - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_AUDIENCE_SECURITY_KEY_TYPE_NAME = "sqlWorkbenchAudience"; - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_ALL_ACCESS_SECURITY_KEY_NAME = "sqlWorkbenchAllAccess"; private String backendName; diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/ShareAudienceType.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/ShareAudienceType.java index d169843..b8de203 100644 --- a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/ShareAudienceType.java +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/ShareAudienceType.java @@ -33,9 +33,9 @@ public enum ShareAudienceType implements PossibleValueEnum public static final String NAME = "sql_workbench_share_audience_type"; /******************************************************************************* - ** The possible-value source name before 1.0.0-RC.3. + ** The possible-value source name before 1.0.0-RC.4. *******************************************************************************/ - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_NAME = "sqlWorkbenchShareAudienceType"; private final String label; diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchCell.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchCell.java index 48b3d5e..b936dbc 100644 --- a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchCell.java +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchCell.java @@ -32,10 +32,10 @@ public class SqlWorkbenchCell extends QRecordEntity public static final String TABLE_NAME = "sql_workbench_cell"; /******************************************************************************* - ** The table name before 1.0.0-RC.3 (owner rule: lowercase snake_case, + ** The table name before 1.0.0-RC.4 (owner rule: lowercase snake_case, ** prefixed with the qbit name). Kept for migrating stored references only. *******************************************************************************/ - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_TABLE_NAME = "sqlWorkbenchCell"; @QField(isEditable = false, isPrimaryKey = true) diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchExecution.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchExecution.java index 57b25f3..8bb000d 100644 --- a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchExecution.java +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchExecution.java @@ -34,10 +34,10 @@ public class SqlWorkbenchExecution extends QRecordEntity public static final String TABLE_NAME = "sql_workbench_execution"; /******************************************************************************* - ** The table name before 1.0.0-RC.3 (owner rule: lowercase snake_case, + ** The table name before 1.0.0-RC.4 (owner rule: lowercase snake_case, ** prefixed with the qbit name). Kept for migrating stored references only. *******************************************************************************/ - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_TABLE_NAME = "sqlWorkbenchExecution"; @QField(isEditable = false, isPrimaryKey = true) diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebook.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebook.java index 24b3c7f..a19d6bc 100644 --- a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebook.java +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebook.java @@ -33,10 +33,10 @@ public class SqlWorkbenchNotebook extends QRecordEntity public static final String TABLE_NAME = "sql_workbench_notebook"; /******************************************************************************* - ** The table name before 1.0.0-RC.3 (owner rule: lowercase snake_case, + ** The table name before 1.0.0-RC.4 (owner rule: lowercase snake_case, ** prefixed with the qbit name). Kept for migrating stored references only. *******************************************************************************/ - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_TABLE_NAME = "sqlWorkbenchNotebook"; @QField(isEditable = false, isPrimaryKey = true) diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebookShare.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebookShare.java index c858d3a..e36a363 100644 --- a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebookShare.java +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebookShare.java @@ -36,10 +36,10 @@ public class SqlWorkbenchNotebookShare extends QRecordEntity public static final String TABLE_NAME = "sql_workbench_notebook_share"; /******************************************************************************* - ** The table name before 1.0.0-RC.3 (owner rule: lowercase snake_case, + ** The table name before 1.0.0-RC.4 (owner rule: lowercase snake_case, ** prefixed with the qbit name). Kept for migrating stored references only. *******************************************************************************/ - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_TABLE_NAME = "sqlWorkbenchNotebookShare"; @QField(isEditable = false, isPrimaryKey = true) diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebookVersion.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebookVersion.java index 5e2665e..bb57985 100644 --- a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebookVersion.java +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchNotebookVersion.java @@ -32,10 +32,10 @@ public class SqlWorkbenchNotebookVersion extends QRecordEntity public static final String TABLE_NAME = "sql_workbench_notebook_version"; /******************************************************************************* - ** The table name before 1.0.0-RC.3 (owner rule: lowercase snake_case, + ** The table name before 1.0.0-RC.4 (owner rule: lowercase snake_case, ** prefixed with the qbit name). Kept for migrating stored references only. *******************************************************************************/ - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_TABLE_NAME = "sqlWorkbenchNotebookVersion"; @QField(isEditable = false, isPrimaryKey = true) diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchResultSnapshot.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchResultSnapshot.java index bf30969..add76cc 100644 --- a/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchResultSnapshot.java +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/model/SqlWorkbenchResultSnapshot.java @@ -33,10 +33,10 @@ public class SqlWorkbenchResultSnapshot extends QRecordEntity public static final String TABLE_NAME = "sql_workbench_result_snapshot"; /******************************************************************************* - ** The table name before 1.0.0-RC.3 (owner rule: lowercase snake_case, + ** The table name before 1.0.0-RC.4 (owner rule: lowercase snake_case, ** prefixed with the qbit name). Kept for migrating stored references only. *******************************************************************************/ - @Deprecated(since = "1.0.0-RC.3") + @Deprecated(since = "1.0.0-RC.4") public static final String LEGACY_TABLE_NAME = "sqlWorkbenchResultSnapshot"; @QField(isEditable = false, isPrimaryKey = true) diff --git a/src/test/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducerTest.java b/src/test/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducerTest.java index 8e083aa..e06bbad 100644 --- a/src/test/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducerTest.java +++ b/src/test/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducerTest.java @@ -178,9 +178,9 @@ class SqlWorkbenchQBitProducerTest extends BaseSqlWorkbenchTest /******************************************************************************* - ** Owner naming rule (1.0.0-RC.3): table, possible-value source, permission + ** Owner naming rule (1.0.0-RC.4): table, possible-value source, permission ** and security key names are lowercase snake_case prefixed with the qbit's - ** name; the pre-RC.3 names stay available only as deprecated constants. + ** name; the pre-RC.4 names stay available only as deprecated constants. *******************************************************************************/ @Test @SuppressWarnings("deprecation") From 236fa901cf0a2006e0bf7b8043953251861a2737 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 13 Oct 2026 14:31:10 -0500 Subject: [PATCH 2/4] ci: automate RC releases; hotfix/* pushes no longer publish Removes publish_hotfix_release: a hotfix/* branch push published a GA release to Maven Central with no tag or review (QRun-IO/qbit-cdn#12, QRun-IO/qqq#1121). hotfix/* branches now run test_only; a hotfix release publishes from a reviewed vX.Y.Z tag through publish_release. Adds .github/workflows/release-rc.yml (reusable QRun-IO/.github qbit-release-rc): a manual dispatch, or merging a develop PR labelled release:rc, merges develop into the release line and the release/* push runs the existing CircleCI RC publish. Co-Authored-By: Claude Opus 5.5 --- .circleci/config.yml | 13 +------------ .github/workflows/release-rc.yml | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/release-rc.yml diff --git a/.circleci/config.yml b/.circleci/config.yml index 2b9734e..a4d1a07 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -22,7 +22,7 @@ workflows: context: [qqq-maven-registry-credentials] filters: branches: - ignore: /(develop|release\/.*|hotfix\/.*)/ + ignore: /(develop|release\/.*)/ publish_snapshot: jobs: @@ -58,14 +58,3 @@ workflows: ignore: /.*/ tags: only: [/^v\d+\.\d+\.\d+$/] - - publish_hotfix_release: - jobs: - - qqq-orb/mvn_publish: - pre-steps: - - configure-package-install - context: [qqq-maven-registry-credentials] - branch_type: hotfix - filters: - branches: - only: [/hotfix\/.*/] diff --git a/.github/workflows/release-rc.yml b/.github/workflows/release-rc.yml new file mode 100644 index 0000000..dd332a0 --- /dev/null +++ b/.github/workflows/release-rc.yml @@ -0,0 +1,25 @@ +# Cut the next release candidate (QRun-IO/qqq docs/QRUN-QBIT-REPO-STANDARD.md, C6): +# run this workflow by hand, or merge a develop PR labelled `release:rc`. It merges develop into +# the release line and the release/* push runs CircleCI publish_release_candidate. +name: Release candidate + +on: + workflow_dispatch: + inputs: + dry_run: + description: Print the plan without merging or creating branches + type: boolean + default: false + pull_request: + types: [closed] + branches: [develop] + +permissions: + contents: write + +jobs: + release-rc: + if: github.event_name == 'workflow_dispatch' || (github.event.pull_request.merged == true && contains(github.event.pull_request.labels.*.name, 'release:rc')) + uses: QRun-IO/.github/.github/workflows/qbit-release-rc.yml@main + with: + dry_run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }} From 84a7033ae4e2789c46aea4ba809280a9791373d9 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 13 Oct 2026 19:48:18 -0500 Subject: [PATCH 3/4] feat(api): serve the sql-workbench routes as spec'd UI API extension endpoints Replace SqlWorkbenchRouteProvider (21 raw /qqq/v1/sql-workbench Javalin routes) with one MiddlewareSpecExtension "sql-workbench" (prefix /sql-workbench). JSON operations use AbstractJsonEndpointSpec; the result export stream extends AbstractEndpointSpec. Paths, methods and payloads are unchanged, and so are the permission checks, read-only gates, limits and audit. The generated fragment is committed at openapi/qqq-v1/sql-workbench.yaml and checked by a contract test. The server tests run in strict raw-route mode. The core baseline becomes 4.1.0-RC.6, the first RC with the extension point (QRun-IO/qqq#1128). Closes #20 (architecture review QRun-IO/qqq#1150, finding F2). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 +- CHANGELOG.md | 2 + README.md | 6 +- docs/DESIGN.md | 6 +- docs/UI-API.md | 93 + pom.xml | 6 +- .../SqlWorkbenchQBitProducer.java | 6 +- .../sqlworkbench/api/CancelExecutionSpec.java | 87 + .../sqlworkbench/api/CreateNotebookSpec.java | 87 + .../sqlworkbench/api/CreateSnapshotSpec.java | 87 + .../sqlworkbench/api/DeleteNotebookSpec.java | 77 + .../sqlworkbench/api/DeleteSnapshotSpec.java | 77 + .../api/DuplicateNotebookSpec.java | 87 + .../qbits/sqlworkbench/api/ExecuteSpec.java | 87 + .../qbits/sqlworkbench/api/ExplainSpec.java | 87 + .../sqlworkbench/api/ExportResultSpec.java | 165 ++ .../sqlworkbench/api/GetCapabilitiesSpec.java | 89 + .../sqlworkbench/api/GetHistorySpec.java | 75 + .../sqlworkbench/api/GetNotebookSpec.java | 75 + .../qbits/sqlworkbench/api/GetRowsSpec.java | 75 + .../qbits/sqlworkbench/api/GetSchemaSpec.java | 75 + .../sqlworkbench/api/GetVersionSpec.java | 75 + .../sqlworkbench/api/ListNotebooksSpec.java | 76 + .../sqlworkbench/api/ListSnapshotsSpec.java | 76 + .../sqlworkbench/api/ListVersionsSpec.java | 76 + .../sqlworkbench/api/PublishNotebookSpec.java | 87 + .../sqlworkbench/api/RestoreVersionSpec.java | 87 + .../api/SqlWorkbenchEndpoints.java | 69 + .../api/SqlWorkbenchJsonSpec.java | 335 +++ .../api/SqlWorkbenchRouteProvider.java | 268 --- .../sqlworkbench/api/SqlWorkbenchRoutes.java | 49 - .../sqlworkbench/api/SqlWorkbenchSchemas.java | 329 +++ .../sqlworkbench/api/UpdateNotebookSpec.java | 87 + .../openapi/qqq-v1/sql-workbench.yaml | 2005 +++++++++++++++++ .../SqlWorkbenchQBitProducerTest.java | 6 +- .../api/SqlWorkbenchApiContractTest.java | 72 + .../api/SqlWorkbenchEndpointSpecTest.java | 349 +++ .../api/SqlWorkbenchRouteProviderTest.java | 203 -- 38 files changed, 5066 insertions(+), 538 deletions(-) create mode 100644 docs/UI-API.md create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/CancelExecutionSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/CreateNotebookSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/CreateSnapshotSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/DeleteNotebookSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/DeleteSnapshotSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/DuplicateNotebookSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExecuteSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExplainSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExportResultSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetCapabilitiesSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetHistorySpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetNotebookSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetRowsSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetSchemaSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetVersionSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListNotebooksSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListSnapshotsSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListVersionsSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/PublishNotebookSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/RestoreVersionSpec.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchEndpoints.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchJsonSpec.java delete mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRouteProvider.java delete mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRoutes.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchSchemas.java create mode 100644 src/main/java/com/kingsrook/qbits/sqlworkbench/api/UpdateNotebookSpec.java create mode 100644 src/main/resources/openapi/qqq-v1/sql-workbench.yaml create mode 100644 src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchApiContractTest.java create mode 100644 src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchEndpointSpecTest.java delete mode 100644 src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRouteProviderTest.java diff --git a/AGENTS.md b/AGENTS.md index 8d91acb..ac4d851 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,7 +24,7 @@ How tests are split: **Entry point:** `SqlWorkbenchQBitProducer implements QBitMetaDataProducer`. - Component producers are found in the `metadata` package only (`getPackageNameForFindingMetaDataProducers`), because `api` needs the optional Javalin dependency. -- `postProduceActions` builds `SqlWorkbenchRuntime` and calls `api.SqlWorkbenchRoutes.register` when Javalin is on the classpath. +- `postProduceActions` builds `SqlWorkbenchRuntime` and calls `api.SqlWorkbenchEndpoints.register` when Javalin is on the classpath. **Packages:** - `sql/`: `SqlScanner` (dialect-aware lexer), `SqlClassifier` (split, then classify as READ, EXPLAIN_ANALYZE, WRITE, DDL, or FORBIDDEN), `NamedParameterSql` (`:name` → `?`). Pure Java. @@ -38,7 +38,7 @@ How tests are split: - `explain/`: `PlanParser` (Postgres JSON, MySQL JSON/text, SQLite rows, text) and `PlanNode`. - `schema/`: `SchemaIntrospector` (JDBC `DatabaseMetaData` plus the QQQ table and field to SQL name mapping), cached in the runtime. - `notebook/`: `NotebookService` (CRUD, sharing, versions in one transaction, snapshots), run as the caller's session through the standard table actions; `NotebookVersioning` (one version per change, as the system user). -- `api/`: `SqlWorkbenchApi` (transport-agnostic, permission checks), `SqlWorkbenchRouteProvider` (Javalin 7 routes under `/qqq/v1/sql-workbench`), `ResultExporter` (CSV/JSON/XLSX via fastexcel), and `SqlWorkbenchRoutes`. +- `api/`: `SqlWorkbenchApi` (transport-agnostic, permission checks), `SqlWorkbenchJsonSpec` and concrete endpoint specs (the UI API extension under `/qqq/v1/sql-workbench`), `ResultExporter` (CSV/JSON/XLSX via fastexcel), and `SqlWorkbenchEndpoints`. - `metadata/`: the 6 tables (record locks, joins, child-list widgets), the security key types, the PVSs, the record actions, the `SQL_WORKBENCH` widget and its renderer, the home dashboard widgets, the Runner child app, and the `sqlWorkbench` app (nav: Runner, then the main tables only). - `home/`: the dashboard data (`SqlWorkbenchHome`, read through core actions in the viewer's session so locks apply), its renderer, and inline-styled HTML helpers. - `SqlWorkbenchIntegrations`: opt-in ESB and Quick Search hooks for the main tables. @@ -65,7 +65,7 @@ How tests are split: ## Dependencies - Java 21. -- Parent `com.kingsrook:qbit-build-parent:2.0.0` (qqq 4.0.0). The default-active `qqq-snapshot` profile imports `qqq-bom-pom:4.1.0-RC.4` ahead of it (RC.4 brings the record developer panel contract), as in qbit-quick-search (ADR-0007). Remove that activation when the parent moves to 4.1. +- Parent `com.kingsrook:qbit-build-parent:2.0.0` (qqq 4.0.0). The default-active `qqq-snapshot` profile imports `qqq-bom-pom:4.1.0-RC.6` ahead of it (RC.6 brings the UI API extension contract), as in qbit-quick-search (ADR-0007). Remove that activation when the parent moves to 4.1. - `qqq-backend-core`, `qqq-backend-module-rdbms`, and `qqq-middleware-javalin` (optional). - Tests: JUnit 5, AssertJ, Mockito, H2, `qqq-backend-module-sqlite`/`-postgres` (drivers), Testcontainers 1.21.4. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c9db14..6511b2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to this project are documented here. The format follows Keep ## [1.0.0-RC.4] - Unreleased ### Added +- OpenAPI coverage for all 21 SQL Workbench UI API operations, including streaming CSV/JSON/XLSX export. The `sql-workbench` extension preserves `/qqq/v1/sql-workbench`, existing request/response shapes, permission and ownership checks, exact decimal parameters, execution limits and audit. The generated fragment is in `src/main/resources/openapi/qqq-v1/sql-workbench.yaml`; strict-server security tests and a fragment contract test guard it. - **App home dashboard.** The `sqlWorkbench` app's home is now an information dashboard of real data, read in the viewer's session (permissions and record locks apply): summary tiles and links, runs per day, recent notebooks, recent runs, slowest and failed queries, most-used notebooks, shared notebooks, committed writes, and (workbench admins only) activity by user. Each widget has an honest empty state. - **Runner.** The notebook editor (`SQL_WORKBENCH` widget) moves to its own nav entry: the `sqlWorkbenchRunner` child app, labeled Runner. Open a notebook with `/app/sqlWorkbenchRunner?notebook=`. - On a notebook's record view: an Open in Runner widget, and a Runs child list (its executions the viewer may see) through the new join `sql_workbench_notebook_join_sql_workbench_execution`. @@ -12,6 +13,7 @@ All notable changes to this project are documented here. The format follows Keep - **Record developer panel** "SQL Workbench" (`SqlWorkbenchDeveloperPanelProvider`, registered by `SqlWorkbenchDeveloperPanelsMetaDataProducer`): read-only `SELECT`s for the record and its table in the backend's own names, backend details, and links that open them in the Runner as a new cell (`/app/sqlWorkbenchRunner?sql=&backend=`, never run). Requires QQQ 4.1.0-RC.4 (the developer panel contract) and a Next UI with the Runner `?sql=` support. ### Changed +- Require QQQ `4.1.0-RC.6` for the UI API extension contract. Replace the raw Javalin route provider with endpoint specs registered by the qbit producer. `registerRoutes=false` still disables HTTP registration. No existing operation wire changes. - **The nav lists only the main tables**: Notebooks and the execution audit, after the Runner. Cells, versions, pinned results and shares are child lists on a notebook (still standard tables, reachable by URL and API). The app's widget list is now the dashboard, not the `SQL_WORKBENCH` widget; links to `/app/sqlWorkbench` that expected the editor should point at `/app/sqlWorkbenchRunner`. - The notebook record's header shows the description. - **Names follow the owner rule: lowercase snake_case, prefixed with the qbit's name (metadata only, no DDL).** Tables `sql_workbench_notebook`, `sql_workbench_cell`, `sql_workbench_notebook_version`, `sql_workbench_result_snapshot`, `sql_workbench_notebook_share`, `sql_workbench_execution` (they now equal their backend table names); possible-value source `sql_workbench_share_audience_type`; permissions `sql_workbench.*`, `sql_workbench_admin.hasAccess` and `.read` etc.; security key types `sql_workbench_user` (all-access `sql_workbench_all_access`) and `sql_workbench_audience`; joins `sql_workbench_notebook_join_sql_workbench_*`. diff --git a/README.md b/README.md index 06c6b6c..e714068 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ The full design (architecture, data model, security model, limits, API contract, ## Requirements -- Java 21 and QQQ 4.1 (built against `4.1.0-RC.4`, which is required: it lets partial edits of child rows pass joined record locks, [qqq#1073](https://github.com/QRun-IO/qqq/issues/1073)). +- Java 21 and QQQ `4.1.0-RC.6` or later (the UI API extension contract, qqq#1128). - `qqq-backend-module-rdbms` for the targets. `qqq-middleware-javalin` for the REST routes; it is optional, and without it the engine still works but no routes are registered. - A Next UI release that renders the `SQL_WORKBENCH` widget. @@ -51,7 +51,7 @@ The producer adds the following to the instance: - **The `sqlWorkbenchWidget` widget** (type `SQL_WORKBENCH`): the notebook editor. - **The home dashboard widgets** ([App home](#app-home)). - **The `sqlWorkbench` app.** Its home page is the dashboard. Its nav lists the **Runner** (`sqlWorkbenchRunner`, a child app whose page is the `SQL_WORKBENCH` widget), then the main tables: Notebooks (`sql_workbench_notebook`) and the execution audit (`sql_workbench_execution`). Cells, versions, pinned results and shares are not in the nav; they are child lists on a notebook. -- **The `/qqq/v1/sql-workbench/*` routes**, registered through `QJavalinMetaData`, as `qqq-esb` does. +- **All 21 `/qqq/v1/sql-workbench/*` operations**, registered as the `sql-workbench` UI API extension. The producer preserves the established prefix; strict UI API route checking is supported. The generated [OpenAPI fragment](src/main/resources/openapi/qqq-v1/sql-workbench.yaml) covers JSON and streaming exports. See [the contract and operation catalog](docs/UI-API.md). To move the app under another app (for example an Admin app), re-parent `SqlWorkbenchQBitProducer.APP_NAME` after producing; the Runner moves with it. Open a notebook in the Runner with `/app/sqlWorkbenchRunner?notebook=`. @@ -231,7 +231,7 @@ A checklist for adding the workbench to a QQQ application. Each row points to th | Item | What to do | |---|---| | Coordinates | `com.kingsrook.qbits:qbit-sql-workbench`. Current release candidate: `1.0.0-RC.2` (Maven Central, published from `release/1.0`). | -| QQQ version | QQQ 4.1, `4.1.0-RC.4` or later (qqq#1073: partial edits of child rows under joined locks). Java 21. | +| QQQ version | QQQ `4.1.0-RC.6` or later (qqq#1128: UI API extension specs). Java 21. | | Dependencies | `qqq-backend-module-rdbms` comes in transitively. Add `qqq-middleware-javalin` yourself for the REST routes; it is optional in this qbit's POM, and without it no routes are registered. | | Frontend | A Next UI (`qqq-frontend-next`) release that renders the `SQL_WORKBENCH` widget: `v1.0.0-RC.13` or later. Other frontends show the app and tables but not the notebook. | | Registration | `new SqlWorkbenchQBitProducer().withQBitConfig(config).produce(qInstance)` after your backends are in the instance. The producer registers its own QBit metadata; don't add it by hand. To nest the app (for example under Admin), re-parent `SqlWorkbenchQBitProducer.APP_NAME` after producing. | diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 7e394d0..9738c15 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -42,7 +42,7 @@ SQL Workbench is a super-user SQL notebook for any QQQ application. Users write │ └ WidgetRenderer │◄───────────────►│ /qqq/v1/metaData (app + widget, filtered │ │ case 'SQL_WORKBENCH' │ │ by sql_workbench.hasAccess)│ │ └ SqlWorkbenchWidget (lazy) │ │ │ - │ ├ NotebookList │ /qqq/v1/ │ SqlWorkbenchRouteProvider │ + │ ├ NotebookList │ /qqq/v1/ │ SQL Workbench endpoint specs │ │ ├ NotebookEditor │ sql-workbench/*│ └ SqlWorkbenchApi (session, perms, JSON) │ │ │ ├ SqlCell (CM6) │◄───────────────►│ ├ SqlExecutionEngine ──► ConnectionMgr │ │ │ ├ MarkdownCell │ │ │ ├ SqlClassifier / NamedParameterSql│ @@ -73,8 +73,8 @@ SQL Workbench is a super-user SQL notebook for any QQQ application. Users write | `explain/*` | `ExplainService` (per-dialect EXPLAIN syntax) and `PlanParser`, which normalizes Postgres JSON, MySQL JSON, SQLite `EXPLAIN QUERY PLAN` rows, and H2 text into one `PlanNode` tree. | | `notebook/NotebookService` | Notebook CRUD, visibility, versions, and snapshots through QQQ actions on the qbit tables. | | `api/SqlWorkbenchApi` | Transport-agnostic API: map in, map out. Checks permissions and throws QQQ exceptions. Unit-testable without HTTP. | -| `api/SqlWorkbenchRouteProvider` | `QJavalinRouteProviderInterface`. Sets up the session (`ExecutorSessionUtils.setupSession`), calls the API, writes JSON, and maps errors through `QJavalinUtils.handleException`. Clears the context in `finally`. | -| `api/SqlWorkbenchJavalinMetaDataProducer` | Adds the route provider to `QJavalinMetaData` once (the ESB pattern). Called from `postProduceActions` when the class is loadable. | +| `api/SqlWorkbenchEndpoints` and `*Spec` | One `MiddlewareSpecExtension`, `sql-workbench`, at `/sql-workbench`. Twenty JSON specs extend `AbstractJsonEndpointSpec`; export extends `AbstractEndpointSpec` directly. Core sets up and clears the session. The shared JSON transport checks access before parsing and keeps exact decimal parameters and 409 duplicate-execution errors. Existing services retain permission checks, limits and audit. See [UI API contract](UI-API.md). | +| `api/SqlWorkbenchSchemas` | Versioned request and response component schemas, declared once by the capabilities spec for the complete extension. The committed fragment is checked by `SqlWorkbenchApiContractTest`. | ### 2.2 Frontend (Next UI) diff --git a/docs/UI-API.md b/docs/UI-API.md new file mode 100644 index 0000000..f42bed6 --- /dev/null +++ b/docs/UI-API.md @@ -0,0 +1,93 @@ +# SQL Workbench UI API contract + +All 21 operations are registered by `SqlWorkbenchQBitProducer` through +`SqlWorkbenchEndpoints` as one `MiddlewareSpecExtension` named `sql-workbench`, +version `1.0.0`, with the established `/sql-workbench` prefix. Full URLs remain +`/qqq/v1/sql-workbench/...`. QQQ `4.1.0-RC.6` is the minimum core version. +`registerRoutes=false` disables extension registration; middleware remains optional. + +The producer registers no raw routes. Twenty JSON operations extend +`AbstractJsonEndpointSpec` through `SqlWorkbenchJsonSpec`; `ExportResultSpec` +extends `AbstractEndpointSpec` directly and streams CSV, JSON or XLSX with the +existing attachment filename and `Cache-Control: no-store` headers. + +The checked-in fragment is +[`src/main/resources/openapi/qqq-v1/sql-workbench.yaml`](../src/main/resources/openapi/qqq-v1/sql-workbench.yaml). +It is also included in a host's `/qqq/v1/openapi.yaml` and `.json`, and the +extension appears in `/qqq/v1/version`. All component names begin with +`SqlWorkbench`. Schemas explicitly describe the existing map payloads rather +than changing their serialization. SQL results include nullable scalar values, +binary previews and nested arrays; execute responses vary by execution status. + +## Compatibility and security + +No existing operation paths, methods, request or response shapes, status codes, +or export headers change. Next UI can vendor the fragment without adapting its +existing calls. New metadata consists of the extension/version advertisement, +OpenAPI schemas and stable operation identifiers. + +Core authenticates the caller before each spec runs and clears `QContext` after +the request. Workbench access is checked before parsing bodies, path integers or +export formats. JSON object parsing retains `BigDecimal` precision, JSON-only +content-type checks, empty/null-body behavior, and existing error messages. +Duplicate execution UUIDs still return 409. SQL failures remain HTTP 200 with a +`FAILED`, `TIMED_OUT` or `CANCELLED` execution status. + +Specs call the same `SqlWorkbenchApi`, notebook service and execution engine. +Write/EXPLAIN ANALYZE gates, sharing permissions, caller record locks, notebook +ownership, cached-result ownership, cancellation ownership, per-user concurrency +limits, audit-before-SQL and deferred audit updates remain in place. Client IPs +continue into execution audits. No request bodies or result data are logged by +the transport. + +## Operations + +| Method | Path (after `/qqq/v1/sql-workbench`) | operationId | +|---|---|---| +| GET | `/capabilities` | `sqlWorkbenchGetCapabilities` | +| POST | `/execute` | `sqlWorkbenchExecute` | +| POST | `/executions/{uuid}/cancel` | `sqlWorkbenchCancelExecution` | +| GET | `/executions/{uuid}/export` | `sqlWorkbenchExportResult` | +| GET | `/executions/{uuid}/rows` | `sqlWorkbenchGetRows` | +| POST | `/explain` | `sqlWorkbenchExplain` | +| GET | `/history` | `sqlWorkbenchGetHistory` | +| GET | `/notebooks` | `sqlWorkbenchListNotebooks` | +| POST | `/notebooks` | `sqlWorkbenchCreateNotebook` | +| DELETE | `/notebooks/{id}` | `sqlWorkbenchDeleteNotebook` | +| GET | `/notebooks/{id}` | `sqlWorkbenchGetNotebook` | +| PUT | `/notebooks/{id}` | `sqlWorkbenchUpdateNotebook` | +| POST | `/notebooks/{id}/duplicate` | `sqlWorkbenchDuplicateNotebook` | +| POST | `/notebooks/{id}/publish` | `sqlWorkbenchPublishNotebook` | +| GET | `/notebooks/{id}/snapshots` | `sqlWorkbenchListSnapshots` | +| POST | `/notebooks/{id}/snapshots` | `sqlWorkbenchCreateSnapshot` | +| DELETE | `/notebooks/{id}/snapshots/{snapshotId}` | `sqlWorkbenchDeleteSnapshot` | +| GET | `/notebooks/{id}/versions` | `sqlWorkbenchListVersions` | +| GET | `/notebooks/{id}/versions/{n}` | `sqlWorkbenchGetVersion` | +| POST | `/notebooks/{id}/versions/{n}/restore` | `sqlWorkbenchRestoreVersion` | +| GET | `/schema/{backendName}` | `sqlWorkbenchGetSchema` | + +## Verification and regeneration + +`SqlWorkbenchApiContractTest` regenerates the fragment in memory and checks it +against the checked-in file using core's deterministic `UiApiContract` tooling. +It also checks the namespace, secured specs, prefix, media types and 21 unique +operation IDs. Intentional contract changes can regenerate the file with: + +```sh +./mvnw -B test -Dtest=SqlWorkbenchApiContractTest -DsqlWorkbench.openapi.update=true +``` + +Before RC.6 is released, local verification uses the separately installed core: + +```sh +./mvnw -B verify -Dqqq.snapshot.version=4.1.0-ARCHRC6-SNAPSHOT +``` + +The POM must continue to name `4.1.0-RC.6`; the local override is never a release +dependency. On PowerShell, quote each `-D...` argument and use `mvnw.cmd`. + +`SqlWorkbenchEndpointSpecTest` runs real HTTP through +`QApplicationJavalinServer.withStrictUiApiRoutes(true)`. It preserves the former +route-provider tests and adds 401/403 coverage for every operation, mutation +denials, execution limits, audited rejection, exact decimals, SQL failures and +all three exports. Engine tests continue to verify audit and transaction safety. diff --git a/pom.xml b/pom.xml index ebcc563..df7cabb 100644 --- a/pom.xml +++ b/pom.xml @@ -250,9 +250,9 @@ - + - + qqq-snapshot @@ -260,7 +260,7 @@ true - 4.1.0-RC.4 + 4.1.0-RC.6 diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducer.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducer.java index 53a134d..557d8f6 100644 --- a/src/main/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducer.java +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducer.java @@ -42,7 +42,7 @@ import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair; ** SQL_WORKBENCH widget, sqlWorkbench app), applies the config's table ** customizer and default backend, stamps sourceQBitName, then calls ** {@link #postProduceActions}, which builds the runtime and registers the - ** /qqq/v1/sql-workbench Javalin routes. + ** /qqq/v1/sql-workbench UI API extension. ** ** Host usage: ** new SqlWorkbenchQBitProducer().withQBitConfig(config).produce(qInstance); @@ -188,7 +188,7 @@ public class SqlWorkbenchQBitProducer implements QBitMetaDataProducer defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchCancelledV1"); + } + + + + /******************************************************************************* + ** Describe the JSON body. + *******************************************************************************/ + @Override + protected Schema defineRequestBodySchema() + { + return (SqlWorkbenchSchemas.ref("EmptyRequest")); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.cancel(caller, input.getPathParam("uuid"))); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/CreateNotebookSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/CreateNotebookSpec.java new file mode 100644 index 0000000..8e7c50b --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/CreateNotebookSpec.java @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; +import com.kingsrook.qqq.openapi.model.Schema; + + +/******************************************************************************* + ** Create a personal notebook. + *******************************************************************************/ +public class CreateNotebookSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.POST, "/notebooks", "Create a personal notebook")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchNotebookV1"); + } + + + + /******************************************************************************* + ** Describe the JSON body. + *******************************************************************************/ + @Override + protected Schema defineRequestBodySchema() + { + return (SqlWorkbenchSchemas.ref("NotebookRequest")); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.notebooks().create(input.getBody(), caller)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/CreateSnapshotSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/CreateSnapshotSpec.java new file mode 100644 index 0000000..0dce782 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/CreateSnapshotSpec.java @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; +import com.kingsrook.qqq.openapi.model.Schema; + + +/******************************************************************************* + ** Pin the caller's cached result to an owned notebook. + *******************************************************************************/ +public class CreateSnapshotSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.POST, "/notebooks/{id}/snapshots", "Pin the caller's cached result to an owned notebook")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchSnapshotV1"); + } + + + + /******************************************************************************* + ** Describe the JSON body. + *******************************************************************************/ + @Override + protected Schema defineRequestBodySchema() + { + return (SqlWorkbenchSchemas.ref("SnapshotRequest")); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.createSnapshot(caller, pathInt(input, "id"), input.getBody())); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/DeleteNotebookSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/DeleteNotebookSpec.java new file mode 100644 index 0000000..5227c62 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/DeleteNotebookSpec.java @@ -0,0 +1,77 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import java.util.Map; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; + + +/******************************************************************************* + ** Delete an owned notebook. + *******************************************************************************/ +public class DeleteNotebookSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.DELETE, "/notebooks/{id}", "Delete an owned notebook")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchDeletedV1"); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + api.notebooks().delete(pathInt(input, "id"), caller); + return (Map.of("deleted", true)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/DeleteSnapshotSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/DeleteSnapshotSpec.java new file mode 100644 index 0000000..20c3728 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/DeleteSnapshotSpec.java @@ -0,0 +1,77 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import java.util.Map; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; + + +/******************************************************************************* + ** Delete a snapshot from an owned notebook. + *******************************************************************************/ +public class DeleteSnapshotSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.DELETE, "/notebooks/{id}/snapshots/{snapshotId}", "Delete a snapshot from an owned notebook")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchDeletedV1"); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + api.notebooks().deleteSnapshot(pathInt(input, "id"), pathInt(input, "snapshotId"), caller); + return (Map.of("deleted", true)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/DuplicateNotebookSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/DuplicateNotebookSpec.java new file mode 100644 index 0000000..0838dcd --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/DuplicateNotebookSpec.java @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; +import com.kingsrook.qqq.openapi.model.Schema; + + +/******************************************************************************* + ** Make a personal copy of a visible notebook. + *******************************************************************************/ +public class DuplicateNotebookSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.POST, "/notebooks/{id}/duplicate", "Make a personal copy of a visible notebook")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchNotebookV1"); + } + + + + /******************************************************************************* + ** Describe the JSON body. + *******************************************************************************/ + @Override + protected Schema defineRequestBodySchema() + { + return (SqlWorkbenchSchemas.ref("EmptyRequest")); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.notebooks().duplicate(pathInt(input, "id"), caller)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExecuteSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExecuteSpec.java new file mode 100644 index 0000000..fb1ceb1 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExecuteSpec.java @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; +import com.kingsrook.qqq.openapi.model.Schema; + + +/******************************************************************************* + ** Execute read-only SQL or preview and confirm a gated write. + *******************************************************************************/ +public class ExecuteSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.POST, "/execute", "Execute read-only SQL or preview and confirm a gated write")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchExecutionV1"); + } + + + + /******************************************************************************* + ** Describe the JSON body. + *******************************************************************************/ + @Override + protected Schema defineRequestBodySchema() + { + return (SqlWorkbenchSchemas.ref("ExecuteRequest")); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.execute(caller, input.getBody())); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExplainSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExplainSpec.java new file mode 100644 index 0000000..b72ca26 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExplainSpec.java @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; +import com.kingsrook.qqq.openapi.model.Schema; + + +/******************************************************************************* + ** Explain SQL; ANALYZE remains subject to write gates. + *******************************************************************************/ +public class ExplainSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.POST, "/explain", "Explain SQL; ANALYZE remains subject to write gates")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchExplainV1"); + } + + + + /******************************************************************************* + ** Describe the JSON body. + *******************************************************************************/ + @Override + protected Schema defineRequestBodySchema() + { + return (SqlWorkbenchSchemas.ref("ExplainRequest")); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.explain(caller, input.getBody())); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExportResultSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExportResultSpec.java new file mode 100644 index 0000000..0eb79bc --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ExportResultSpec.java @@ -0,0 +1,165 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.ArrayList; +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qbits.sqlworkbench.engine.ResultCache; +import com.kingsrook.qqq.backend.core.exceptions.QException; +import com.kingsrook.qqq.backend.core.utils.StringUtils; +import com.kingsrook.qqq.middleware.javalin.executors.AbstractMiddlewareExecutor; +import com.kingsrook.qqq.middleware.javalin.executors.io.AbstractMiddlewareInput; +import com.kingsrook.qqq.middleware.javalin.executors.io.AbstractMiddlewareOutputInterface; +import com.kingsrook.qqq.middleware.javalin.specs.AbstractEndpointSpec; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.middleware.javalin.specs.BasicResponse; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Method; +import com.kingsrook.qqq.openapi.model.Parameter; +import io.javalin.http.Context; +import io.javalin.http.HttpStatus; + + +/******************************************************************************* + ** Stream a caller-owned cached result without buffering it as a JSON response. + *******************************************************************************/ +public class ExportResultSpec extends AbstractEndpointSpec +{ + /******************************************************************************* + ** Describe the existing download endpoint. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (SqlWorkbenchJsonSpec.operation(HttpMethod.GET, "/executions/{uuid}/export", "Export the caller's cached result as CSV, JSON or XLSX")); + } + + + + /******************************************************************************* + ** Stable identifier for generated clients. + *******************************************************************************/ + @Override + protected void customizeMethod(Method method) + { + method.setOperationId("sqlWorkbenchExportResult"); + } + + + + /******************************************************************************* + ** Describe UUID and format selection. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (SqlWorkbenchJsonSpec.parametersFor(defineBasicOperation().getPath(), "format")); + } + + + + /******************************************************************************* + ** All three media types are served by the same operation. + *******************************************************************************/ + @Override + public List defineAdditionalBasicResponses() + { + List responses = new ArrayList<>(SqlWorkbenchJsonSpec.errors()); + for(ResultExporter.Format format : ResultExporter.Format.values()) + { + responses.add(new BasicResponse(format.getContentType(), HttpStatus.OK, + "Attachment named sql-result-{short UUID}.{format}; Cache-Control: no-store", + format == ResultExporter.Format.JSON ? "SqlWorkbenchExportJsonV1" : "SqlWorkbenchExportFileV1", null)); + } + return (responses); + } + + + + /******************************************************************************* + ** Check access before parsing format, just as the previous route did. + *******************************************************************************/ + @Override + public ExportInput buildInput(Context context) throws Exception + { + ExportInput input = new ExportInput(); + input.caller = new SqlWorkbenchApi().caller(context.ip()); + input.uuid = context.pathParam("uuid"); + input.format = ResultExporter.Format.of(StringUtils.hasContent(context.queryParam("format")) ? context.queryParam("format") : "csv"); + return (input); + } + + + + /******************************************************************************* + ** Stream only after the executor authorizes access to the cached result. + *******************************************************************************/ + @Override + public void handleOutput(Context context, ExportOutput output) throws Exception + { + String shortId = output.uuid.length() > 8 ? output.uuid.substring(0, 8) : output.uuid; + context.contentType(output.format.getContentType()); + context.header("Content-Disposition", "attachment; filename=\"sql-result-" + shortId.replaceAll("[^A-Za-z0-9-]", "") + "." + output.format.getExtension() + "\""); + context.header("Cache-Control", "no-store"); + ResultExporter.write(output.entry.result(), output.format, context.outputStream()); + } + + + + /******************************************************************************* + ** Request state populated after session authentication. + *******************************************************************************/ + public static class ExportInput extends AbstractMiddlewareInput + { + private Caller caller; + private String uuid; + private ResultExporter.Format format; + } + + + + /******************************************************************************* + ** Authorized cached data and download metadata. + *******************************************************************************/ + public static class ExportOutput implements AbstractMiddlewareOutputInterface + { + private ResultCache.Entry entry; + private String uuid; + private ResultExporter.Format format; + } + + + + /******************************************************************************* + ** Service authorization stays identical to JSON result paging. + *******************************************************************************/ + public static class ExportExecutor extends AbstractMiddlewareExecutor + { + /******************************************************************************* + ** Resolve only the caller's cached execution. + *******************************************************************************/ + @Override + public void execute(ExportInput input, ExportOutput output) throws QException + { + output.entry = new SqlWorkbenchApi().exportable(input.caller, input.uuid); + output.uuid = input.uuid; + output.format = input.format; + } + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetCapabilitiesSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetCapabilitiesSpec.java new file mode 100644 index 0000000..a172913 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetCapabilitiesSpec.java @@ -0,0 +1,89 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import java.util.Map; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; +import com.kingsrook.qqq.openapi.model.Schema; + + +/******************************************************************************* + ** Get caller capabilities and configured limits. + *******************************************************************************/ +public class GetCapabilitiesSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Declare shared components once. The extension registers all specs together. + *******************************************************************************/ + @Override + public Map defineComponentSchemas() + { + return (SqlWorkbenchSchemas.components()); + } + + + + + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.GET, "/capabilities", "Get caller capabilities and configured limits")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchCapabilitiesV1"); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.capabilities(caller)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetHistorySpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetHistorySpec.java new file mode 100644 index 0000000..c029cd6 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetHistorySpec.java @@ -0,0 +1,75 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; + + +/******************************************************************************* + ** List the caller's recent audited executions. + *******************************************************************************/ +public class GetHistorySpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.GET, "/history", "List the caller's recent audited executions")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters("limit", "backendName")); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchHistoryV1"); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.history(caller, input.getQueryParamInteger("limit"), input.getQueryParam("backendName"))); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetNotebookSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetNotebookSpec.java new file mode 100644 index 0000000..ae0c818 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetNotebookSpec.java @@ -0,0 +1,75 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; + + +/******************************************************************************* + ** Get a visible notebook and its cells. + *******************************************************************************/ +public class GetNotebookSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.GET, "/notebooks/{id}", "Get a visible notebook and its cells")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchNotebookV1"); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.notebooks().get(pathInt(input, "id"), caller)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetRowsSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetRowsSpec.java new file mode 100644 index 0000000..ac09806 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetRowsSpec.java @@ -0,0 +1,75 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; + + +/******************************************************************************* + ** Page or sort the caller's cached result. + *******************************************************************************/ +public class GetRowsSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.GET, "/executions/{uuid}/rows", "Page or sort the caller's cached result")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters("offset", "limit", "sort", "dir")); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchRowsV1"); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.rows(caller, input.getPathParam("uuid"), input.getQueryParamInteger("offset"), input.getQueryParamInteger("limit"), input.getQueryParamInteger("sort"), input.getQueryParam("dir"))); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetSchemaSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetSchemaSpec.java new file mode 100644 index 0000000..73e2614 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetSchemaSpec.java @@ -0,0 +1,75 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; + + +/******************************************************************************* + ** Inspect a target backend schema. + *******************************************************************************/ +public class GetSchemaSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.GET, "/schema/{backendName}", "Inspect a target backend schema")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters("refresh")); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchSchemaV1"); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.schema(caller, input.getPathParam("backendName"), "true".equalsIgnoreCase(input.getQueryParam("refresh")))); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetVersionSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetVersionSpec.java new file mode 100644 index 0000000..3e47610 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/GetVersionSpec.java @@ -0,0 +1,75 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; + + +/******************************************************************************* + ** Get a visible notebook version and saved content. + *******************************************************************************/ +public class GetVersionSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.GET, "/notebooks/{id}/versions/{n}", "Get a visible notebook version and saved content")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchVersionV1"); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.notebooks().version(pathInt(input, "id"), pathInt(input, "n"), caller)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListNotebooksSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListNotebooksSpec.java new file mode 100644 index 0000000..ee877f9 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListNotebooksSpec.java @@ -0,0 +1,76 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import java.util.Map; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; + + +/******************************************************************************* + ** List visible personal or shared notebooks. + *******************************************************************************/ +public class ListNotebooksSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.GET, "/notebooks", "List visible personal or shared notebooks")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters("scope")); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchNotebooksV1"); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (Map.of("notebooks", api.notebooks().list(input.getQueryParam("scope"), caller))); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListSnapshotsSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListSnapshotsSpec.java new file mode 100644 index 0000000..ffa7fa3 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListSnapshotsSpec.java @@ -0,0 +1,76 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import java.util.Map; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; + + +/******************************************************************************* + ** List snapshots of a visible notebook. + *******************************************************************************/ +public class ListSnapshotsSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.GET, "/notebooks/{id}/snapshots", "List snapshots of a visible notebook")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchSnapshotsV1"); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (Map.of("snapshots", api.notebooks().snapshots(pathInt(input, "id"), caller))); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListVersionsSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListVersionsSpec.java new file mode 100644 index 0000000..bf06077 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/ListVersionsSpec.java @@ -0,0 +1,76 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import java.util.Map; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; + + +/******************************************************************************* + ** List versions of a visible notebook. + *******************************************************************************/ +public class ListVersionsSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.GET, "/notebooks/{id}/versions", "List versions of a visible notebook")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchVersionsV1"); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (Map.of("versions", api.notebooks().versions(pathInt(input, "id"), caller))); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/PublishNotebookSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/PublishNotebookSpec.java new file mode 100644 index 0000000..efd72ef --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/PublishNotebookSpec.java @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; +import com.kingsrook.qqq.openapi.model.Schema; + + +/******************************************************************************* + ** Publish or withdraw an owned notebook with share permission. + *******************************************************************************/ +public class PublishNotebookSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.POST, "/notebooks/{id}/publish", "Publish or withdraw an owned notebook with share permission")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchNotebookV1"); + } + + + + /******************************************************************************* + ** Describe the JSON body. + *******************************************************************************/ + @Override + protected Schema defineRequestBodySchema() + { + return (SqlWorkbenchSchemas.ref("PublishRequest")); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.notebooks().publish(pathInt(input, "id"), Boolean.TRUE.equals(input.getBody().get("shared")), caller)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/RestoreVersionSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/RestoreVersionSpec.java new file mode 100644 index 0000000..49d1e49 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/RestoreVersionSpec.java @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; +import com.kingsrook.qqq.openapi.model.Schema; + + +/******************************************************************************* + ** Restore an owned notebook version as a new version. + *******************************************************************************/ +public class RestoreVersionSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.POST, "/notebooks/{id}/versions/{n}/restore", "Restore an owned notebook version as a new version")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchNotebookV1"); + } + + + + /******************************************************************************* + ** Describe the JSON body. + *******************************************************************************/ + @Override + protected Schema defineRequestBodySchema() + { + return (SqlWorkbenchSchemas.ref("EmptyRequest")); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.notebooks().restore(pathInt(input, "id"), pathInt(input, "n"), caller)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchEndpoints.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchEndpoints.java new file mode 100644 index 0000000..4e95475 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchEndpoints.java @@ -0,0 +1,69 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import com.kingsrook.qqq.backend.core.model.metadata.QInstance; +import com.kingsrook.qqq.middleware.javalin.specs.extensions.MiddlewareSpecExtension; +import com.kingsrook.qqq.middleware.javalin.specs.extensions.MiddlewareSpecExtensionsMetaData; + + +/******************************************************************************* + ** Registers all SQL Workbench operations as UI API specs. + *******************************************************************************/ +public class SqlWorkbenchEndpoints +{ + /******************************************************************************* + ** Register the extension idempotently. + *******************************************************************************/ + public static void register(QInstance qInstance) + { + MiddlewareSpecExtensionsMetaData.ofOrWithNew(qInstance).withExtension(extension()); + } + + + + /******************************************************************************* + ** The complete UI API extension at its established prefix. + *******************************************************************************/ + public static MiddlewareSpecExtension extension() + { + return (new MiddlewareSpecExtension().withName("sql-workbench").withPathPrefix("/sql-workbench") + .withSemanticVersion("1.0.0").withDescription("Audited SQL execution and notebooks") + .withSpec(GetCapabilitiesSpec.class) + .withSpec(GetSchemaSpec.class) + .withSpec(ExecuteSpec.class) + .withSpec(ExplainSpec.class) + .withSpec(GetRowsSpec.class) + .withSpec(CancelExecutionSpec.class) + .withSpec(GetHistorySpec.class) + .withSpec(ListNotebooksSpec.class) + .withSpec(CreateNotebookSpec.class) + .withSpec(GetNotebookSpec.class) + .withSpec(UpdateNotebookSpec.class) + .withSpec(DeleteNotebookSpec.class) + .withSpec(PublishNotebookSpec.class) + .withSpec(DuplicateNotebookSpec.class) + .withSpec(ListVersionsSpec.class) + .withSpec(GetVersionSpec.class) + .withSpec(RestoreVersionSpec.class) + .withSpec(ListSnapshotsSpec.class) + .withSpec(CreateSnapshotSpec.class) + .withSpec(DeleteSnapshotSpec.class) + .withSpec(ExportResultSpec.class)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchJsonSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchJsonSpec.java new file mode 100644 index 0000000..5271775 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchJsonSpec.java @@ -0,0 +1,335 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qbits.sqlworkbench.engine.DuplicateExecutionException; +import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException; +import com.kingsrook.qqq.backend.core.utils.JsonUtils; +import com.kingsrook.qqq.backend.core.utils.StringUtils; +import com.kingsrook.qqq.middleware.javalin.QJavalinUtils; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.middleware.javalin.specs.BasicResponse; +import com.kingsrook.qqq.middleware.javalin.specs.extensions.AbstractJsonEndpointSpec; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.In; +import com.kingsrook.qqq.openapi.model.Method; +import com.kingsrook.qqq.openapi.model.Parameter; +import com.kingsrook.qqq.openapi.model.RequestBody; +import com.kingsrook.qqq.openapi.model.Schema; +import com.kingsrook.qqq.openapi.model.Type; +import io.javalin.http.Context; +import io.javalin.http.HttpStatus; + + +/******************************************************************************* + ** Shared transport; the existing services retain authorization, limits and audit. + *******************************************************************************/ +public abstract class SqlWorkbenchJsonSpec extends AbstractJsonEndpointSpec +{ + /******************************************************************************* + ** Check access before parsing; preserve exact decimal parameters. + *******************************************************************************/ + @Override + public JsonInput buildInput(Context context) throws Exception + { + Caller caller = new SqlWorkbenchApi().caller(context.ip()); + WorkbenchInput input = new WorkbenchInput(this, caller); + input.getPathParams().putAll(context.pathParamMap()); + context.queryParamMap().forEach((name, values) -> input.getQueryParams().put(name, values == null || values.isEmpty() ? null : values.get(0))); + if(defineRequestBodySchema() != null) + { + input.getBody().putAll(readExactBody(context)); + } + return (input); + } + + + + /******************************************************************************* + ** Parse the established JSON object shape without losing decimal precision. + *******************************************************************************/ + private static Map readExactBody(Context context) throws QBadRequestException + { + if(!StringUtils.hasContent(context.body())) + { + return (Map.of()); + } + if(context.contentType() == null || !context.contentType().toLowerCase().startsWith("application/json")) + { + throw (new QBadRequestException("Request bodies must be JSON (Content-Type: application/json).")); + } + try + { + Map body = JsonUtils.toObject(context.body(), new TypeReference>() {}, mapper -> mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)); + return (body == null ? Map.of() : body); + } + catch(Exception e) + { + throw (new QBadRequestException("The request body is not a JSON object.")); + } + } + + + + /******************************************************************************* + ** Preserve duplicate execution UUID conflicts. + *******************************************************************************/ + @Override + protected void handleException(Context context, Exception e) + { + QJavalinUtils.handleException(e instanceof DuplicateExecutionException ? org.eclipse.jetty.http.HttpStatus.Code.CONFLICT : null, context, e); + } + + + + /******************************************************************************* + ** Bodies remain optional; empty bodies retain their existing service semantics. + *******************************************************************************/ + @Override + public RequestBody defineRequestBody() + { + RequestBody body = super.defineRequestBody(); + return (body == null ? null : body.withRequired(false)); + } + + + + /******************************************************************************* + ** Stable operation identifiers for generated clients. + *******************************************************************************/ + @Override + protected void customizeMethod(Method method) + { + method.setOperationId("sqlWorkbench" + getClass().getSimpleName().replace("Spec", "")); + } + + + + /******************************************************************************* + ** Keep the established extension prefix. + *******************************************************************************/ + static BasicOperation operation(HttpMethod method, String path, String summary) + { + return (new BasicOperation().withHttpMethod(method).withPath("/sql-workbench" + path) + .withShortSummary(summary).withLongDescription(summary + ". Requires SQL Workbench access; services enforce caller permissions, ownership, execution limits and audit.")); + } + + + + /******************************************************************************* + ** Document existing request error statuses. + *******************************************************************************/ + @Override + public List defineAdditionalBasicResponses() + { + return (errors()); + } + + + + /******************************************************************************* + ** Share error schemas with the export stream. + *******************************************************************************/ + static List errors() + { + return (List.of(new BasicResponse(HttpStatus.BAD_REQUEST, "Invalid input or execution limit exceeded", "SqlWorkbenchErrorV1"), + new BasicResponse(HttpStatus.UNAUTHORIZED, "Sign in required", "SqlWorkbenchErrorV1"), + new BasicResponse(HttpStatus.FORBIDDEN, "Permission denied", "SqlWorkbenchErrorV1"), + new BasicResponse(HttpStatus.NOT_FOUND, "Missing or invisible resource", "SqlWorkbenchErrorV1"), + new BasicResponse(HttpStatus.CONFLICT, "Execution UUID already used", "SqlWorkbenchErrorV1"))); + } + + + + /******************************************************************************* + ** Path and query parameter declarations. + *******************************************************************************/ + protected List parameters(String... queries) + { + return (parametersFor(defineBasicOperation().getPath(), queries)); + } + + + + /******************************************************************************* + ** Share parameter declarations with the export stream. + *******************************************************************************/ + static List parametersFor(String path, String... queries) + { + List parameters = new ArrayList<>(); + Matcher matcher = Pattern.compile("\\{([^}]+)}").matcher(path); + while(matcher.find()) + { + parameters.add(parameter(matcher.group(1), In.PATH)); + } + for(String query : queries) + { + parameters.add(parameter(query, In.QUERY)); + } + return (parameters); + } + + + + /******************************************************************************* + ** Document parameter types and default behavior. + *******************************************************************************/ + private static Parameter parameter(String name, In location) + { + Type type = Type.STRING; + if(List.of("id", "n", "snapshotId", "offset", "limit", "sort").contains(name)) + { + type = Type.INTEGER; + } + else if("refresh".equals(name)) + { + type = Type.BOOLEAN; + } + return (new Parameter().withName(name).withIn(location).withRequired(location == In.PATH) + .withDescription(parameterDescription(name)).withSchema(new Schema().withType(type))); + } + + + + /******************************************************************************* + ** Parameter help for generated clients. + *******************************************************************************/ + private static String parameterDescription(String name) + { + switch(name) + { + case "id": + return ("Notebook identifier."); + case "n": + return ("Notebook version number."); + case "snapshotId": + return ("Snapshot identifier."); + case "uuid": + return ("Execution UUID; case insensitive."); + case "backendName": + return ("Configured target backend name."); + case "offset": + return ("Rows to skip; default zero; negative values become zero."); + case "limit": + return ("Page size; nonpositive or absent uses the default. Rows cap at maxPageSize; history caps at 200 (default 50)."); + case "sort": + return ("Optional zero-based result column index."); + case "dir": + return ("Sort direction: desc (case insensitive) or asc (default)."); + case "refresh": + return ("True to bypass the schema cache; default false."); + case "scope": + return ("mine (default) or shared notebook library."); + case "format": + return ("csv (default), json or xlsx; case insensitive."); + default: + return (name); + } + } + + + + /******************************************************************************* + ** Preserve integer path validation. + *******************************************************************************/ + protected static Integer pathInt(JsonInput input, String name) throws QBadRequestException + { + try + { + return (Integer.parseInt(input.getPathParam(name))); + } + catch(NumberFormatException e) + { + throw (new QBadRequestException(name + " must be an integer.")); + } + } + + + + /******************************************************************************* + ** Caller captured before body parsing, including the audit client IP. + *******************************************************************************/ + protected static Caller caller(JsonInput input) + { + return (((WorkbenchInput) input).caller); + } + + + + /******************************************************************************* + ** Per-request state; spec instances themselves are shared across requests. + *******************************************************************************/ + private static class WorkbenchInput extends JsonInput + { + private final SqlWorkbenchJsonSpec spec; + private final Caller caller; + + + + /******************************************************************************* + ** Capture the spec and authorized caller. + *******************************************************************************/ + private WorkbenchInput(SqlWorkbenchJsonSpec spec, Caller caller) + { + this.spec = spec; + this.caller = caller; + } + + + + /******************************************************************************* + ** Supply the spec to the framework's JSON executor. + *******************************************************************************/ + @Override + public AbstractJsonEndpointSpec getSpec() + { + return (spec); + } + + + + /******************************************************************************* + ** Preserve the established integer-query error message. + *******************************************************************************/ + @Override + public Integer getQueryParamInteger(String name) throws QBadRequestException + { + String value = getQueryParam(name); + if(!StringUtils.hasContent(value)) + { + return (null); + } + try + { + return (Integer.parseInt(value.trim())); + } + catch(NumberFormatException e) + { + throw (new QBadRequestException(name + " must be an integer.")); + } + } + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRouteProvider.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRouteProvider.java deleted file mode 100644 index 2b3e7e2..0000000 --- a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRouteProvider.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Copyright 2026 Kingsrook, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.kingsrook.qbits.sqlworkbench.api; - - -import java.util.LinkedHashMap; -import java.util.Map; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.kingsrook.qqq.backend.core.context.QContext; -import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException; -import com.kingsrook.qqq.backend.core.exceptions.QException; -import com.kingsrook.qqq.backend.core.model.metadata.QInstance; -import com.kingsrook.qqq.backend.core.utils.JsonUtils; -import com.kingsrook.qqq.backend.core.utils.StringUtils; -import com.kingsrook.qbits.sqlworkbench.SqlWorkbenchRuntime; -import com.kingsrook.qbits.sqlworkbench.engine.Caller; -import com.kingsrook.qbits.sqlworkbench.engine.DuplicateExecutionException; -import com.kingsrook.qbits.sqlworkbench.engine.ResultCache; -import com.kingsrook.qqq.middleware.javalin.QJavalinRouteProviderInterface; -import com.kingsrook.qqq.middleware.javalin.QJavalinUtils; -import com.kingsrook.qqq.middleware.javalin.executors.ExecutorSessionUtils; -import io.javalin.config.JavalinConfig; -import io.javalin.http.ContentType; -import io.javalin.http.Context; -import org.eclipse.jetty.http.HttpStatus; - - -/******************************************************************************* - ** Javalin routes for the SQL Workbench under /qqq/v1/sql-workbench (see - ** docs/DESIGN.md section 5 for the contract). - ** - ** Each request gets a session from the instance's authentication module - ** (ExecutorSessionUtils), then SqlWorkbenchApi checks permissions and does - ** the work. Errors map through QJavalinUtils.handleException: 400 bad - ** request, 401 unauthenticated, 403 not permitted, 404 unknown, 409 a - ** re-used executionUuid. POST / PUT - ** bodies must be JSON (Content-Type application/json): a cross-site form - ** cannot send that without a CORS preflight. Request and response bodies - ** are never logged. - *******************************************************************************/ -public class SqlWorkbenchRouteProvider implements QJavalinRouteProviderInterface -{ - public static final String BASE_PATH = "/qqq/v1/sql-workbench"; - - private QInstance qInstance; - - - - /******************************************************************************* - ** - *******************************************************************************/ - @Override - public void setQInstance(QInstance qInstance) - { - this.qInstance = qInstance; - } - - - - /******************************************************************************* - ** - *******************************************************************************/ - @Override - public void acceptJavalinConfig(JavalinConfig config) - { - config.routes.get(BASE_PATH + "/capabilities", ctx -> respond(ctx, false, (api, caller, body) -> api.capabilities(caller))); - config.routes.get(BASE_PATH + "/schema/{backendName}", ctx -> respond(ctx, false, (api, caller, body) -> api.schema(caller, ctx.pathParam("backendName"), "true".equalsIgnoreCase(ctx.queryParam("refresh"))))); - config.routes.post(BASE_PATH + "/execute", ctx -> respond(ctx, true, (api, caller, body) -> api.execute(caller, body))); - config.routes.post(BASE_PATH + "/explain", ctx -> respond(ctx, true, (api, caller, body) -> api.explain(caller, body))); - config.routes.get(BASE_PATH + "/executions/{uuid}/rows", ctx -> respond(ctx, false, (api, caller, body) -> api.rows(caller, ctx.pathParam("uuid"), - intParam(ctx, "offset"), intParam(ctx, "limit"), intParam(ctx, "sort"), ctx.queryParam("dir")))); - config.routes.get(BASE_PATH + "/executions/{uuid}/export", this::export); - config.routes.post(BASE_PATH + "/executions/{uuid}/cancel", ctx -> respond(ctx, true, (api, caller, body) -> api.cancel(caller, ctx.pathParam("uuid")))); - config.routes.get(BASE_PATH + "/history", ctx -> respond(ctx, false, (api, caller, body) -> api.history(caller, intParam(ctx, "limit"), ctx.queryParam("backendName")))); - - config.routes.get(BASE_PATH + "/notebooks", ctx -> respond(ctx, false, (api, caller, body) -> Map.of("notebooks", api.notebooks().list(ctx.queryParam("scope"), caller)))); - config.routes.post(BASE_PATH + "/notebooks", ctx -> respond(ctx, true, (api, caller, body) -> api.notebooks().create(body, caller))); - config.routes.get(BASE_PATH + "/notebooks/{id}", ctx -> respond(ctx, false, (api, caller, body) -> api.notebooks().get(id(ctx), caller))); - config.routes.put(BASE_PATH + "/notebooks/{id}", ctx -> respond(ctx, true, (api, caller, body) -> api.notebooks().update(id(ctx), body, caller))); - config.routes.delete(BASE_PATH + "/notebooks/{id}", ctx -> respond(ctx, false, (api, caller, body) -> - { - api.notebooks().delete(id(ctx), caller); - return (Map.of("deleted", true)); - })); - config.routes.post(BASE_PATH + "/notebooks/{id}/publish", ctx -> respond(ctx, true, (api, caller, body) -> api.notebooks().publish(id(ctx), Boolean.TRUE.equals(body.get("shared")), caller))); - config.routes.post(BASE_PATH + "/notebooks/{id}/duplicate", ctx -> respond(ctx, true, (api, caller, body) -> api.notebooks().duplicate(id(ctx), caller))); - config.routes.get(BASE_PATH + "/notebooks/{id}/versions", ctx -> respond(ctx, false, (api, caller, body) -> Map.of("versions", api.notebooks().versions(id(ctx), caller)))); - config.routes.get(BASE_PATH + "/notebooks/{id}/versions/{n}", ctx -> respond(ctx, false, (api, caller, body) -> api.notebooks().version(id(ctx), pathInt(ctx, "n"), caller))); - config.routes.post(BASE_PATH + "/notebooks/{id}/versions/{n}/restore", ctx -> respond(ctx, true, (api, caller, body) -> api.notebooks().restore(id(ctx), pathInt(ctx, "n"), caller))); - config.routes.get(BASE_PATH + "/notebooks/{id}/snapshots", ctx -> respond(ctx, false, (api, caller, body) -> Map.of("snapshots", api.notebooks().snapshots(id(ctx), caller)))); - config.routes.post(BASE_PATH + "/notebooks/{id}/snapshots", ctx -> respond(ctx, true, (api, caller, body) -> api.createSnapshot(caller, id(ctx), body))); - config.routes.delete(BASE_PATH + "/notebooks/{id}/snapshots/{snapshotId}", ctx -> respond(ctx, false, (api, caller, body) -> - { - api.notebooks().deleteSnapshot(id(ctx), pathInt(ctx, "snapshotId"), caller); - return (Map.of("deleted", true)); - })); - } - - - - /******************************************************************************* - ** Session, permission check, body, handler, JSON - or the error's status. - *******************************************************************************/ - private void respond(Context context, boolean readsBody, Handler handler) - { - try - { - ExecutorSessionUtils.setupSession(context, qInstance); - SqlWorkbenchApi api = new SqlWorkbenchApi(qInstance, SqlWorkbenchRuntime.get(qInstance)); - Caller caller = api.caller(context.ip()); - Map body = readsBody ? readJsonBody(context) : Map.of(); - Object result = handler.handle(api, caller, body); - - context.contentType(ContentType.APPLICATION_JSON); - context.result(JsonUtils.toJsonCustomized(result, builder -> builder.serializationInclusion(JsonInclude.Include.ALWAYS))); - } - catch(Exception e) - { - QJavalinUtils.handleException(e instanceof DuplicateExecutionException ? HttpStatus.Code.CONFLICT : null, context, e); - } - finally - { - QContext.clear(); - } - } - - - - /******************************************************************************* - ** GET /executions/{uuid}/export?format=csv|json|xlsx - *******************************************************************************/ - private void export(Context context) - { - try - { - ExecutorSessionUtils.setupSession(context, qInstance); - SqlWorkbenchApi api = new SqlWorkbenchApi(qInstance, SqlWorkbenchRuntime.get(qInstance)); - Caller caller = api.caller(context.ip()); - ResultExporter.Format format = ResultExporter.Format.of(StringUtils.hasContent(context.queryParam("format")) ? context.queryParam("format") : "csv"); - String uuid = context.pathParam("uuid"); - ResultCache.Entry entry = api.exportable(caller, uuid); - - String shortId = uuid.length() > 8 ? uuid.substring(0, 8) : uuid; - context.contentType(format.getContentType()); - context.header("Content-Disposition", "attachment; filename=\"sql-result-" + shortId.replaceAll("[^A-Za-z0-9-]", "") + "." + format.getExtension() + "\""); - context.header("Cache-Control", "no-store"); - ResultExporter.write(entry.result(), format, context.outputStream()); - } - catch(Exception e) - { - QJavalinUtils.handleException(null, context, e); - } - finally - { - QContext.clear(); - } - } - - - - /******************************************************************************* - ** A JSON object body. Decimals stay exact (BigDecimal). - *******************************************************************************/ - static Map readJsonBody(Context context) throws QBadRequestException - { - String body = context.body(); - if(!StringUtils.hasContent(body)) - { - return (new LinkedHashMap<>()); - } - - String contentType = context.contentType(); - if(contentType == null || !contentType.toLowerCase().startsWith("application/json")) - { - throw (new QBadRequestException("Request bodies must be JSON (Content-Type: application/json).")); - } - - try - { - Map map = JsonUtils.toObject(body, new TypeReference>() {}, mapper -> mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)); - return (map == null ? new LinkedHashMap<>() : map); - } - catch(Exception e) - { - throw (new QBadRequestException("The request body is not a JSON object.")); - } - } - - - - /******************************************************************************* - ** - *******************************************************************************/ - private static Integer id(Context context) throws QBadRequestException - { - return (pathInt(context, "id")); - } - - - - /******************************************************************************* - ** - *******************************************************************************/ - private static Integer pathInt(Context context, String name) throws QBadRequestException - { - try - { - return (Integer.parseInt(context.pathParam(name))); - } - catch(NumberFormatException e) - { - throw (new QBadRequestException(name + " must be an integer.")); - } - } - - - - /******************************************************************************* - ** - *******************************************************************************/ - private static Integer intParam(Context context, String name) throws QBadRequestException - { - String value = context.queryParam(name); - if(!StringUtils.hasContent(value)) - { - return (null); - } - try - { - return (Integer.parseInt(value.trim())); - } - catch(NumberFormatException e) - { - throw (new QBadRequestException(name + " must be an integer.")); - } - } - - - - /******************************************************************************* - ** One endpoint's work. - *******************************************************************************/ - @FunctionalInterface - private interface Handler - { - /******************************************************************************* - ** - *******************************************************************************/ - Object handle(SqlWorkbenchApi api, Caller caller, Map body) throws QException; - } - -} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRoutes.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRoutes.java deleted file mode 100644 index feb2ac3..0000000 --- a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRoutes.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2026 Kingsrook, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.kingsrook.qbits.sqlworkbench.api; - - -import com.kingsrook.qqq.backend.core.model.metadata.QInstance; -import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference; -import com.kingsrook.qqq.backend.core.utils.CollectionUtils; -import com.kingsrook.qqq.middleware.javalin.QJavalinMetaData; - - -/******************************************************************************* - ** Registers SqlWorkbenchRouteProvider (the /qqq/v1/sql-workbench routes) - ** with the Javalin server through the instance's QJavalinMetaData - as - ** qqq-esb's EsbJavalinMetaDataProducer does. Only touched when - ** qqq-middleware-javalin is on the classpath (the producer checks first). - *******************************************************************************/ -public class SqlWorkbenchRoutes -{ - - /******************************************************************************* - ** Add the route provider reference, once. - *******************************************************************************/ - public static void register(QInstance qInstance) - { - QJavalinMetaData javalinMetaData = QJavalinMetaData.ofOrWithNew(qInstance); - boolean registered = CollectionUtils.nonNullList(javalinMetaData.getAdditionalRouteProviderReferences()).stream() - .anyMatch(reference -> reference != null && SqlWorkbenchRouteProvider.class.getName().equals(reference.getName())); - if(!registered) - { - javalinMetaData.withAdditionalRouteProviderReference(new QCodeReference(SqlWorkbenchRouteProvider.class)); - } - } - -} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchSchemas.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchSchemas.java new file mode 100644 index 0000000..d885f7b --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchSchemas.java @@ -0,0 +1,329 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import com.kingsrook.qqq.openapi.model.Schema; +import com.kingsrook.qqq.openapi.model.Type; + + +/******************************************************************************* + ** Versioned wire schemas shared by SQL Workbench specs. + *******************************************************************************/ +public class SqlWorkbenchSchemas +{ + /******************************************************************************* + ** Explicit schemas for the existing map payloads; no serialization changes. + *******************************************************************************/ + public static Map components() + { + Map schemas = new LinkedHashMap<>(); + schemas.put("SqlWorkbenchErrorV1", new Schema().withType(Type.OBJECT) + .withProperty("error", new Schema().withType(Type.STRING))); + schemas.put("SqlWorkbenchEmptyRequestV1", new Schema().withType(Type.OBJECT)); + schemas.put("SqlWorkbenchDeletedV1", new Schema().withType(Type.OBJECT) + .withProperty("deleted", new Schema().withType(Type.BOOLEAN))); + schemas.put("SqlWorkbenchCancelledV1", new Schema().withType(Type.OBJECT) + .withProperty("cancelled", new Schema().withType(Type.BOOLEAN))); + schemas.put("SqlWorkbenchLimitsV1", new Schema().withType(Type.OBJECT) + .withProperty("maxRows", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("pageSize", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("maxPageSize", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("maxResultBytes", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("statementTimeoutSeconds", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("writeStatementTimeoutSeconds", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("maxAffectedRowsWithoutAcknowledgement", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("maxAffectedRows", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("maxSqlLength", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("maxStatementsPerRun", new Schema().withType(Type.INTEGER).withFormat("int64"))); + schemas.put("SqlWorkbenchBackendV1", new Schema().withType(Type.OBJECT) + .withProperty("name", new Schema().withType(Type.STRING)) + .withProperty("label", new Schema().withType(Type.STRING)) + .withProperty("vendor", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("dialect", ref("Dialect")) + .withProperty("readOnlyCredentials", new Schema().withType(Type.BOOLEAN)) + .withProperty("readOnlyEnforced", new Schema().withType(Type.BOOLEAN)) + .withProperty("transactionalDdl", new Schema().withType(Type.BOOLEAN)) + .withProperty("writeAllowed", new Schema().withType(Type.BOOLEAN))); + schemas.put("SqlWorkbenchCapabilitiesV1", new Schema().withType(Type.OBJECT) + .withProperty("version", new Schema().withType(Type.STRING)) + .withProperty("canWrite", new Schema().withType(Type.BOOLEAN)) + .withProperty("canShare", new Schema().withType(Type.BOOLEAN)) + .withProperty("writeModeEnabled", new Schema().withType(Type.BOOLEAN)) + .withProperty("limits", ref("Limits")) + .withProperty("backends", array(ref("Backend")))); + schemas.put("SqlWorkbenchColumnV1", new Schema().withType(Type.OBJECT) + .withProperty("name", new Schema().withType(Type.STRING)) + .withProperty("label", new Schema().withType(Type.STRING)) + .withProperty("typeName", new Schema().withType(Type.STRING)) + .withProperty("jdbcType", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("kind", ref("ColumnKind"))); + schemas.put("SqlWorkbenchBinaryValueV1", new Schema().withType(Type.OBJECT) + .withProperty("$binary", new Schema().withType(Type.BOOLEAN)) + .withProperty("length", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("hexPreview", new Schema().withType(Type.STRING))); + schemas.put("SqlWorkbenchStatementV1", new Schema().withType(Type.OBJECT) + .withProperty("index", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("kind", ref("StatementKind")) + .withProperty("leadingKeyword", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("text", new Schema().withType(Type.STRING)) + .withProperty("affectedRows", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true))); + schemas.put("SqlWorkbenchExecuteRequestV1", new Schema().withType(Type.OBJECT) + .withProperty("backendName", new Schema().withType(Type.STRING)) + .withProperty("sql", new Schema().withType(Type.STRING)) + .withProperty("params", ref("Parameters")) + .withProperty("mode", new Schema().withType(Type.STRING)) + .withProperty("notebookId", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true)) + .withProperty("cellKey", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("pageSize", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true)) + .withProperty("confirmToken", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("acknowledgeRowGuard", new Schema().withType(Type.BOOLEAN)) + .withProperty("executionUuid", new Schema().withType(Type.STRING).withNullable(true))); + schemas.put("SqlWorkbenchExplainRequestV1", new Schema().withType(Type.OBJECT) + .withProperty("backendName", new Schema().withType(Type.STRING)) + .withProperty("sql", new Schema().withType(Type.STRING)) + .withProperty("params", ref("Parameters")) + .withProperty("analyze", new Schema().withType(Type.BOOLEAN))); + schemas.put("SqlWorkbenchExecutionV1", new Schema().withType(Type.OBJECT) + .withProperty("executionUuid", new Schema().withType(Type.STRING)) + .withProperty("status", ref("Status")) + .withProperty("mode", new Schema().withType(Type.STRING)) + .withProperty("backendName", new Schema().withType(Type.STRING)) + .withProperty("durationMs", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true)) + .withProperty("statements", array(ref("Statement"))) + .withProperty("columns", array(ref("Column"))) + .withProperty("rows", ref("RowsData")) + .withProperty("rowCount", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("hasMore", new Schema().withType(Type.BOOLEAN)) + .withProperty("truncated", new Schema().withType(Type.BOOLEAN)) + .withProperty("truncatedReason", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("rowsAffected", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("error", new Schema().withType(Type.STRING)) + .withProperty("sqlState", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("dryRunSupported", new Schema().withType(Type.BOOLEAN)) + .withProperty("dryRunNote", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("totalAffectedRows", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true)) + .withProperty("rowGuardExceeded", new Schema().withType(Type.BOOLEAN)) + .withProperty("rowGuardLimit", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("confirmToken", new Schema().withType(Type.STRING)) + .withProperty("expiresAt", new Schema().withType(Type.STRING)) + .withProperty("previewAffectedRows", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("actualAffectedRows", new Schema().withType(Type.INTEGER).withFormat("int64"))); + schemas.put("SqlWorkbenchRowsV1", new Schema().withType(Type.OBJECT) + .withProperty("executionUuid", new Schema().withType(Type.STRING)) + .withProperty("columns", array(ref("Column"))) + .withProperty("rows", ref("RowsData")) + .withProperty("offset", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("rowCount", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("truncated", new Schema().withType(Type.BOOLEAN)) + .withProperty("truncatedReason", new Schema().withType(Type.STRING).withNullable(true))); + schemas.put("SqlWorkbenchPlanNodeV1", new Schema().withType(Type.OBJECT) + .withProperty("label", new Schema().withType(Type.STRING)) + .withProperty("detail", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("startupCost", new Schema().withType(Type.NUMBER).withNullable(true)) + .withProperty("totalCost", new Schema().withType(Type.NUMBER).withNullable(true)) + .withProperty("planRows", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true)) + .withProperty("actualTimeMs", new Schema().withType(Type.NUMBER).withNullable(true)) + .withProperty("actualRows", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true)) + .withProperty("loops", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true)) + .withProperty("extra", ref("FreeObject")) + .withProperty("children", array(ref("PlanNode")))); + schemas.put("SqlWorkbenchExplainV1", new Schema().withType(Type.OBJECT) + .withProperty("executionUuid", new Schema().withType(Type.STRING)) + .withProperty("status", ref("Status")) + .withProperty("mode", new Schema().withType(Type.STRING)) + .withProperty("backendName", new Schema().withType(Type.STRING)) + .withProperty("dialect", ref("Dialect")) + .withProperty("analyze", new Schema().withType(Type.BOOLEAN)) + .withProperty("plan", ref("PlanNode")) + .withProperty("raw", new Schema().withType(Type.STRING)) + .withProperty("error", new Schema().withType(Type.STRING)) + .withProperty("sqlState", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("durationMs", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true))); + schemas.put("SqlWorkbenchSchemaColumnV1", new Schema().withType(Type.OBJECT) + .withProperty("name", new Schema().withType(Type.STRING)) + .withProperty("typeName", new Schema().withType(Type.STRING)) + .withProperty("nullable", new Schema().withType(Type.BOOLEAN))); + schemas.put("SqlWorkbenchSchemaTableV1", new Schema().withType(Type.OBJECT) + .withProperty("name", new Schema().withType(Type.STRING)) + .withProperty("type", new Schema().withType(Type.STRING)) + .withProperty("columns", array(ref("SchemaColumn")))); + schemas.put("SqlWorkbenchDatabaseSchemaV1", new Schema().withType(Type.OBJECT) + .withProperty("name", new Schema().withType(Type.STRING)) + .withProperty("tables", array(ref("SchemaTable")))); + schemas.put("SqlWorkbenchQqqFieldV1", new Schema().withType(Type.OBJECT) + .withProperty("name", new Schema().withType(Type.STRING)) + .withProperty("label", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("sqlName", new Schema().withType(Type.STRING)) + .withProperty("type", new Schema().withType(Type.STRING).withNullable(true))); + schemas.put("SqlWorkbenchQqqTableV1", new Schema().withType(Type.OBJECT) + .withProperty("name", new Schema().withType(Type.STRING)) + .withProperty("label", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("sqlName", new Schema().withType(Type.STRING)) + .withProperty("fields", array(ref("QqqField")))); + schemas.put("SqlWorkbenchSchemaV1", new Schema().withType(Type.OBJECT) + .withProperty("backendName", new Schema().withType(Type.STRING)) + .withProperty("dialect", ref("Dialect")) + .withProperty("schemas", array(ref("DatabaseSchema"))) + .withProperty("truncated", new Schema().withType(Type.BOOLEAN)) + .withProperty("keywords", array(new Schema().withType(Type.STRING))) + .withProperty("functions", array(new Schema().withType(Type.STRING))) + .withProperty("qqqTables", array(ref("QqqTable"))) + .withProperty("cachedAt", new Schema().withType(Type.STRING))); + schemas.put("SqlWorkbenchHistoryEntryV1", new Schema().withType(Type.OBJECT) + .withProperty("executionUuid", new Schema().withType(Type.STRING)) + .withProperty("backendName", new Schema().withType(Type.STRING)) + .withProperty("mode", new Schema().withType(Type.STRING)) + .withProperty("status", new Schema().withType(Type.STRING)) + .withProperty("sqlText", new Schema().withType(Type.STRING)) + .withProperty("notebookId", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true)) + .withProperty("cellKey", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("startTime", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("durationMs", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true)) + .withProperty("rowsReturned", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true)) + .withProperty("rowsAffected", new Schema().withType(Type.INTEGER).withFormat("int64").withNullable(true)) + .withProperty("errorMessage", new Schema().withType(Type.STRING).withNullable(true))); + schemas.put("SqlWorkbenchHistoryV1", new Schema().withType(Type.OBJECT) + .withProperty("executions", array(ref("HistoryEntry")))); + schemas.put("SqlWorkbenchNotebookParameterV1", new Schema().withType(Type.OBJECT) + .withProperty("name", new Schema().withType(Type.STRING)) + .withProperty("type", new Schema().withType(Type.STRING)) + .withProperty("defaultValue", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("label", new Schema().withType(Type.STRING).withNullable(true))); + schemas.put("SqlWorkbenchCellV1", new Schema().withType(Type.OBJECT) + .withProperty("cellKey", new Schema().withType(Type.STRING)) + .withProperty("cellType", new Schema().withType(Type.STRING)) + .withProperty("title", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("content", new Schema().withType(Type.STRING)) + .withProperty("backendName", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("sortOrder", new Schema().withType(Type.INTEGER).withFormat("int64"))); + schemas.put("SqlWorkbenchNotebookSummaryV1", new Schema().withType(Type.OBJECT) + .withProperty("id", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("title", new Schema().withType(Type.STRING)) + .withProperty("description", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("visibility", new Schema().withType(Type.STRING)) + .withProperty("ownerUserId", new Schema().withType(Type.STRING)) + .withProperty("ownerName", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("defaultBackendName", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("currentVersion", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("canEdit", new Schema().withType(Type.BOOLEAN)) + .withProperty("createDate", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("modifyDate", new Schema().withType(Type.STRING).withNullable(true))); + schemas.put("SqlWorkbenchNotebookV1", new Schema().withType(Type.OBJECT) + .withProperty("id", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("title", new Schema().withType(Type.STRING)) + .withProperty("description", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("visibility", new Schema().withType(Type.STRING)) + .withProperty("ownerUserId", new Schema().withType(Type.STRING)) + .withProperty("ownerName", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("defaultBackendName", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("currentVersion", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("canEdit", new Schema().withType(Type.BOOLEAN)) + .withProperty("createDate", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("modifyDate", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("parameters", array(ref("NotebookParameter"))) + .withProperty("cells", array(ref("Cell")))); + schemas.put("SqlWorkbenchNotebookContentV1", new Schema().withType(Type.OBJECT) + .withProperty("title", new Schema().withType(Type.STRING)) + .withProperty("description", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("defaultBackendName", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("parameters", array(ref("NotebookParameter"))) + .withProperty("cells", array(ref("Cell")))); + schemas.put("SqlWorkbenchNotebookRequestV1", new Schema().withType(Type.OBJECT) + .withProperty("title", new Schema().withType(Type.STRING)) + .withProperty("description", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("defaultBackendName", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("parameters", array(ref("NotebookParameter"))) + .withProperty("cells", array(ref("Cell"))) + .withProperty("comment", new Schema().withType(Type.STRING))); + schemas.put("SqlWorkbenchNotebooksV1", new Schema().withType(Type.OBJECT) + .withProperty("notebooks", array(ref("NotebookSummary")))); + schemas.put("SqlWorkbenchPublishRequestV1", new Schema().withType(Type.OBJECT) + .withProperty("shared", new Schema().withType(Type.BOOLEAN))); + schemas.put("SqlWorkbenchVersionSummaryV1", new Schema().withType(Type.OBJECT) + .withProperty("versionNumber", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("savedByName", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("comment", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("createDate", new Schema().withType(Type.STRING))); + schemas.put("SqlWorkbenchVersionV1", new Schema().withType(Type.OBJECT) + .withProperty("versionNumber", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("savedByName", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("comment", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("createDate", new Schema().withType(Type.STRING)) + .withProperty("notebook", ref("NotebookContent"))); + schemas.put("SqlWorkbenchVersionsV1", new Schema().withType(Type.OBJECT) + .withProperty("versions", array(ref("VersionSummary")))); + schemas.put("SqlWorkbenchSnapshotRequestV1", new Schema().withType(Type.OBJECT) + .withProperty("executionUuid", new Schema().withType(Type.STRING)) + .withProperty("cellKey", new Schema().withType(Type.STRING)) + .withProperty("label", new Schema().withType(Type.STRING).withNullable(true))); + schemas.put("SqlWorkbenchSnapshotResultV1", new Schema().withType(Type.OBJECT) + .withProperty("columns", array(ref("Column"))) + .withProperty("rows", ref("RowsData"))); + schemas.put("SqlWorkbenchSnapshotV1", new Schema().withType(Type.OBJECT) + .withProperty("id", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("cellKey", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("executionUuid", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("label", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("backendName", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("rowCount", new Schema().withType(Type.INTEGER).withFormat("int64")) + .withProperty("truncated", new Schema().withType(Type.BOOLEAN)) + .withProperty("createDate", new Schema().withType(Type.STRING).withNullable(true)) + .withProperty("result", ref("SnapshotResult"))); + schemas.put("SqlWorkbenchSnapshotsV1", new Schema().withType(Type.OBJECT) + .withProperty("snapshots", array(ref("Snapshot")))); + schemas.put("SqlWorkbenchDialectV1", new Schema().withType(Type.STRING).withEnumValues(List.of("postgresql", "mysql", "sqlite", "h2", "sql"))); + schemas.put("SqlWorkbenchColumnKindV1", new Schema().withType(Type.STRING).withEnumValues(List.of("number", "string", "boolean", "date", "datetime", "time", "json", "binary", "array", "other"))); + schemas.put("SqlWorkbenchStatementKindV1", new Schema().withType(Type.STRING).withEnumValues(List.of("READ", "EXPLAIN_ANALYZE", "WRITE", "DDL", "FORBIDDEN"))); + schemas.put("SqlWorkbenchStatusV1", new Schema().withType(Type.STRING).withEnumValues(List.of("SUCCEEDED", "FAILED", "TIMED_OUT", "CANCELLED", "REJECTED", "PREVIEW", "DRIFTED"))); + schemas.put("SqlWorkbenchParametersV1", new Schema().withType(Type.OBJECT).withAdditionalProperties(new Schema()) + .withDescription("Named SQL parameter values. JSON decimals are parsed exactly as BigDecimal.")); + schemas.put("SqlWorkbenchFreeObjectV1", new Schema().withType(Type.OBJECT).withAdditionalProperties(true)); + schemas.put("SqlWorkbenchValueV1", new Schema().withAnyOf(List.of( + new Schema().withType(Type.STRING).withNullable(true), new Schema().withType(Type.NUMBER), new Schema().withType(Type.BOOLEAN), + ref("BinaryValue"), array(ref("Value")), ref("FreeObject"))) + .withDescription("JSON-safe JDBC value; null, scalar, binary preview, nested array or vendor JSON object.")); + schemas.put("SqlWorkbenchRowsDataV1", array(array(ref("Value")))); + schemas.put("SqlWorkbenchExportFileV1", new Schema().withType(Type.STRING).withFormat("binary")); + schemas.put("SqlWorkbenchExportJsonV1", array(new Schema().withType(Type.OBJECT).withAdditionalProperties(ref("Value"))) + .withDescription("Rows keyed by unique column labels, with duplicate labels suffixed.")); + return (schemas); + } + + + + /******************************************************************************* + ** Reference a component in this extension's namespace. + *******************************************************************************/ + public static Schema ref(String name) + { + return (new Schema().withRefToSchema("SqlWorkbench" + name + "V1")); + } + + + + /******************************************************************************* + ** An array with explicitly described items. + *******************************************************************************/ + private static Schema array(Schema items) + { + return (new Schema().withType(Type.ARRAY).withItems(items)); + } +} diff --git a/src/main/java/com/kingsrook/qbits/sqlworkbench/api/UpdateNotebookSpec.java b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/UpdateNotebookSpec.java new file mode 100644 index 0000000..f228ea0 --- /dev/null +++ b/src/main/java/com/kingsrook/qbits/sqlworkbench/api/UpdateNotebookSpec.java @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.util.List; +import com.kingsrook.qbits.sqlworkbench.engine.Caller; +import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation; +import com.kingsrook.qqq.openapi.model.HttpMethod; +import com.kingsrook.qqq.openapi.model.Parameter; +import com.kingsrook.qqq.openapi.model.Schema; + + +/******************************************************************************* + ** Update an owned notebook and record a version. + *******************************************************************************/ +public class UpdateNotebookSpec extends SqlWorkbenchJsonSpec +{ + /******************************************************************************* + ** Describe the operation. + *******************************************************************************/ + @Override + public BasicOperation defineBasicOperation() + { + return (operation(HttpMethod.PUT, "/notebooks/{id}", "Update an owned notebook and record a version")); + } + + + + /******************************************************************************* + ** Describe path and query parameters. + *******************************************************************************/ + @Override + public List defineRequestParameters() + { + return (parameters()); + } + + + + /******************************************************************************* + ** Name the response schema. + *******************************************************************************/ + @Override + protected String getResponseSchemaName() + { + return ("SqlWorkbenchNotebookV1"); + } + + + + /******************************************************************************* + ** Describe the JSON body. + *******************************************************************************/ + @Override + protected Schema defineRequestBodySchema() + { + return (SqlWorkbenchSchemas.ref("NotebookRequest")); + } + + + + /******************************************************************************* + ** Invoke the existing service with the authenticated caller. + *******************************************************************************/ + @Override + protected Object handle(JsonInput input) throws Exception + { + SqlWorkbenchApi api = new SqlWorkbenchApi(); + Caller caller = caller(input); + return (api.notebooks().update(pathInt(input, "id"), input.getBody(), caller)); + } +} diff --git a/src/main/resources/openapi/qqq-v1/sql-workbench.yaml b/src/main/resources/openapi/qqq-v1/sql-workbench.yaml new file mode 100644 index 0000000..6da936c --- /dev/null +++ b/src/main/resources/openapi/qqq-v1/sql-workbench.yaml @@ -0,0 +1,2005 @@ +components: + schemas: + SqlWorkbenchBackendV1: + properties: + name: + type: "string" + label: + type: "string" + vendor: + nullable: true + type: "string" + dialect: + $ref: "#/components/schemas/SqlWorkbenchDialectV1" + readOnlyCredentials: + type: "boolean" + readOnlyEnforced: + type: "boolean" + transactionalDdl: + type: "boolean" + writeAllowed: + type: "boolean" + type: "object" + SqlWorkbenchBinaryValueV1: + properties: + $binary: + type: "boolean" + length: + format: "int64" + type: "integer" + hexPreview: + type: "string" + type: "object" + SqlWorkbenchCancelledV1: + properties: + cancelled: + type: "boolean" + type: "object" + SqlWorkbenchCapabilitiesV1: + properties: + version: + type: "string" + canWrite: + type: "boolean" + canShare: + type: "boolean" + writeModeEnabled: + type: "boolean" + limits: + $ref: "#/components/schemas/SqlWorkbenchLimitsV1" + backends: + items: + $ref: "#/components/schemas/SqlWorkbenchBackendV1" + type: "array" + type: "object" + SqlWorkbenchCellV1: + properties: + cellKey: + type: "string" + cellType: + type: "string" + title: + nullable: true + type: "string" + content: + type: "string" + backendName: + nullable: true + type: "string" + sortOrder: + format: "int64" + type: "integer" + type: "object" + SqlWorkbenchColumnKindV1: + enum: + - "number" + - "string" + - "boolean" + - "date" + - "datetime" + - "time" + - "json" + - "binary" + - "array" + - "other" + type: "string" + SqlWorkbenchColumnV1: + properties: + name: + type: "string" + label: + type: "string" + typeName: + type: "string" + jdbcType: + format: "int64" + type: "integer" + kind: + $ref: "#/components/schemas/SqlWorkbenchColumnKindV1" + type: "object" + SqlWorkbenchDatabaseSchemaV1: + properties: + name: + type: "string" + tables: + items: + $ref: "#/components/schemas/SqlWorkbenchSchemaTableV1" + type: "array" + type: "object" + SqlWorkbenchDeletedV1: + properties: + deleted: + type: "boolean" + type: "object" + SqlWorkbenchDialectV1: + enum: + - "postgresql" + - "mysql" + - "sqlite" + - "h2" + - "sql" + type: "string" + SqlWorkbenchEmptyRequestV1: + type: "object" + SqlWorkbenchErrorV1: + properties: + error: + type: "string" + type: "object" + SqlWorkbenchExecuteRequestV1: + properties: + backendName: + type: "string" + sql: + type: "string" + params: + $ref: "#/components/schemas/SqlWorkbenchParametersV1" + mode: + type: "string" + notebookId: + format: "int64" + nullable: true + type: "integer" + cellKey: + nullable: true + type: "string" + pageSize: + format: "int64" + nullable: true + type: "integer" + confirmToken: + nullable: true + type: "string" + acknowledgeRowGuard: + type: "boolean" + executionUuid: + nullable: true + type: "string" + type: "object" + SqlWorkbenchExecutionV1: + properties: + executionUuid: + type: "string" + status: + $ref: "#/components/schemas/SqlWorkbenchStatusV1" + mode: + type: "string" + backendName: + type: "string" + durationMs: + format: "int64" + nullable: true + type: "integer" + statements: + items: + $ref: "#/components/schemas/SqlWorkbenchStatementV1" + type: "array" + columns: + items: + $ref: "#/components/schemas/SqlWorkbenchColumnV1" + type: "array" + rows: + $ref: "#/components/schemas/SqlWorkbenchRowsDataV1" + rowCount: + format: "int64" + type: "integer" + hasMore: + type: "boolean" + truncated: + type: "boolean" + truncatedReason: + nullable: true + type: "string" + rowsAffected: + format: "int64" + type: "integer" + error: + type: "string" + sqlState: + nullable: true + type: "string" + dryRunSupported: + type: "boolean" + dryRunNote: + nullable: true + type: "string" + totalAffectedRows: + format: "int64" + nullable: true + type: "integer" + rowGuardExceeded: + type: "boolean" + rowGuardLimit: + format: "int64" + type: "integer" + confirmToken: + type: "string" + expiresAt: + type: "string" + previewAffectedRows: + format: "int64" + type: "integer" + actualAffectedRows: + format: "int64" + type: "integer" + type: "object" + SqlWorkbenchExplainRequestV1: + properties: + backendName: + type: "string" + sql: + type: "string" + params: + $ref: "#/components/schemas/SqlWorkbenchParametersV1" + analyze: + type: "boolean" + type: "object" + SqlWorkbenchExplainV1: + properties: + executionUuid: + type: "string" + status: + $ref: "#/components/schemas/SqlWorkbenchStatusV1" + mode: + type: "string" + backendName: + type: "string" + dialect: + $ref: "#/components/schemas/SqlWorkbenchDialectV1" + analyze: + type: "boolean" + plan: + $ref: "#/components/schemas/SqlWorkbenchPlanNodeV1" + raw: + type: "string" + error: + type: "string" + sqlState: + nullable: true + type: "string" + durationMs: + format: "int64" + nullable: true + type: "integer" + type: "object" + SqlWorkbenchExportFileV1: + format: "binary" + type: "string" + SqlWorkbenchExportJsonV1: + description: "Rows keyed by unique column labels, with duplicate labels suffixed." + items: + additionalProperties: + $ref: "#/components/schemas/SqlWorkbenchValueV1" + type: "object" + type: "array" + SqlWorkbenchFreeObjectV1: + additionalProperties: true + type: "object" + SqlWorkbenchHistoryEntryV1: + properties: + executionUuid: + type: "string" + backendName: + type: "string" + mode: + type: "string" + status: + type: "string" + sqlText: + type: "string" + notebookId: + format: "int64" + nullable: true + type: "integer" + cellKey: + nullable: true + type: "string" + startTime: + nullable: true + type: "string" + durationMs: + format: "int64" + nullable: true + type: "integer" + rowsReturned: + format: "int64" + nullable: true + type: "integer" + rowsAffected: + format: "int64" + nullable: true + type: "integer" + errorMessage: + nullable: true + type: "string" + type: "object" + SqlWorkbenchHistoryV1: + properties: + executions: + items: + $ref: "#/components/schemas/SqlWorkbenchHistoryEntryV1" + type: "array" + type: "object" + SqlWorkbenchLimitsV1: + properties: + maxRows: + format: "int64" + type: "integer" + pageSize: + format: "int64" + type: "integer" + maxPageSize: + format: "int64" + type: "integer" + maxResultBytes: + format: "int64" + type: "integer" + statementTimeoutSeconds: + format: "int64" + type: "integer" + writeStatementTimeoutSeconds: + format: "int64" + type: "integer" + maxAffectedRowsWithoutAcknowledgement: + format: "int64" + type: "integer" + maxAffectedRows: + format: "int64" + type: "integer" + maxSqlLength: + format: "int64" + type: "integer" + maxStatementsPerRun: + format: "int64" + type: "integer" + type: "object" + SqlWorkbenchNotebookContentV1: + properties: + title: + type: "string" + description: + nullable: true + type: "string" + defaultBackendName: + nullable: true + type: "string" + parameters: + items: + $ref: "#/components/schemas/SqlWorkbenchNotebookParameterV1" + type: "array" + cells: + items: + $ref: "#/components/schemas/SqlWorkbenchCellV1" + type: "array" + type: "object" + SqlWorkbenchNotebookParameterV1: + properties: + name: + type: "string" + type: + type: "string" + defaultValue: + nullable: true + type: "string" + label: + nullable: true + type: "string" + type: "object" + SqlWorkbenchNotebookRequestV1: + properties: + title: + type: "string" + description: + nullable: true + type: "string" + defaultBackendName: + nullable: true + type: "string" + parameters: + items: + $ref: "#/components/schemas/SqlWorkbenchNotebookParameterV1" + type: "array" + cells: + items: + $ref: "#/components/schemas/SqlWorkbenchCellV1" + type: "array" + comment: + type: "string" + type: "object" + SqlWorkbenchNotebookSummaryV1: + properties: + id: + format: "int64" + type: "integer" + title: + type: "string" + description: + nullable: true + type: "string" + visibility: + type: "string" + ownerUserId: + type: "string" + ownerName: + nullable: true + type: "string" + defaultBackendName: + nullable: true + type: "string" + currentVersion: + format: "int64" + type: "integer" + canEdit: + type: "boolean" + createDate: + nullable: true + type: "string" + modifyDate: + nullable: true + type: "string" + type: "object" + SqlWorkbenchNotebookV1: + properties: + id: + format: "int64" + type: "integer" + title: + type: "string" + description: + nullable: true + type: "string" + visibility: + type: "string" + ownerUserId: + type: "string" + ownerName: + nullable: true + type: "string" + defaultBackendName: + nullable: true + type: "string" + currentVersion: + format: "int64" + type: "integer" + canEdit: + type: "boolean" + createDate: + nullable: true + type: "string" + modifyDate: + nullable: true + type: "string" + parameters: + items: + $ref: "#/components/schemas/SqlWorkbenchNotebookParameterV1" + type: "array" + cells: + items: + $ref: "#/components/schemas/SqlWorkbenchCellV1" + type: "array" + type: "object" + SqlWorkbenchNotebooksV1: + properties: + notebooks: + items: + $ref: "#/components/schemas/SqlWorkbenchNotebookSummaryV1" + type: "array" + type: "object" + SqlWorkbenchParametersV1: + additionalProperties: {} + description: "Named SQL parameter values. JSON decimals are parsed exactly as\ + \ BigDecimal." + type: "object" + SqlWorkbenchPlanNodeV1: + properties: + label: + type: "string" + detail: + nullable: true + type: "string" + startupCost: + nullable: true + type: "number" + totalCost: + nullable: true + type: "number" + planRows: + format: "int64" + nullable: true + type: "integer" + actualTimeMs: + nullable: true + type: "number" + actualRows: + format: "int64" + nullable: true + type: "integer" + loops: + format: "int64" + nullable: true + type: "integer" + extra: + $ref: "#/components/schemas/SqlWorkbenchFreeObjectV1" + children: + items: + $ref: "#/components/schemas/SqlWorkbenchPlanNodeV1" + type: "array" + type: "object" + SqlWorkbenchPublishRequestV1: + properties: + shared: + type: "boolean" + type: "object" + SqlWorkbenchQqqFieldV1: + properties: + name: + type: "string" + label: + nullable: true + type: "string" + sqlName: + type: "string" + type: + nullable: true + type: "string" + type: "object" + SqlWorkbenchQqqTableV1: + properties: + name: + type: "string" + label: + nullable: true + type: "string" + sqlName: + type: "string" + fields: + items: + $ref: "#/components/schemas/SqlWorkbenchQqqFieldV1" + type: "array" + type: "object" + SqlWorkbenchRowsDataV1: + items: + items: + $ref: "#/components/schemas/SqlWorkbenchValueV1" + type: "array" + type: "array" + SqlWorkbenchRowsV1: + properties: + executionUuid: + type: "string" + columns: + items: + $ref: "#/components/schemas/SqlWorkbenchColumnV1" + type: "array" + rows: + $ref: "#/components/schemas/SqlWorkbenchRowsDataV1" + offset: + format: "int64" + type: "integer" + rowCount: + format: "int64" + type: "integer" + truncated: + type: "boolean" + truncatedReason: + nullable: true + type: "string" + type: "object" + SqlWorkbenchSchemaColumnV1: + properties: + name: + type: "string" + typeName: + type: "string" + nullable: + type: "boolean" + type: "object" + SqlWorkbenchSchemaTableV1: + properties: + name: + type: "string" + type: + type: "string" + columns: + items: + $ref: "#/components/schemas/SqlWorkbenchSchemaColumnV1" + type: "array" + type: "object" + SqlWorkbenchSchemaV1: + properties: + backendName: + type: "string" + dialect: + $ref: "#/components/schemas/SqlWorkbenchDialectV1" + schemas: + items: + $ref: "#/components/schemas/SqlWorkbenchDatabaseSchemaV1" + type: "array" + truncated: + type: "boolean" + keywords: + items: + type: "string" + type: "array" + functions: + items: + type: "string" + type: "array" + qqqTables: + items: + $ref: "#/components/schemas/SqlWorkbenchQqqTableV1" + type: "array" + cachedAt: + type: "string" + type: "object" + SqlWorkbenchSnapshotRequestV1: + properties: + executionUuid: + type: "string" + cellKey: + type: "string" + label: + nullable: true + type: "string" + type: "object" + SqlWorkbenchSnapshotResultV1: + properties: + columns: + items: + $ref: "#/components/schemas/SqlWorkbenchColumnV1" + type: "array" + rows: + $ref: "#/components/schemas/SqlWorkbenchRowsDataV1" + type: "object" + SqlWorkbenchSnapshotV1: + properties: + id: + format: "int64" + type: "integer" + cellKey: + nullable: true + type: "string" + executionUuid: + nullable: true + type: "string" + label: + nullable: true + type: "string" + backendName: + nullable: true + type: "string" + rowCount: + format: "int64" + type: "integer" + truncated: + type: "boolean" + createDate: + nullable: true + type: "string" + result: + $ref: "#/components/schemas/SqlWorkbenchSnapshotResultV1" + type: "object" + SqlWorkbenchSnapshotsV1: + properties: + snapshots: + items: + $ref: "#/components/schemas/SqlWorkbenchSnapshotV1" + type: "array" + type: "object" + SqlWorkbenchStatementKindV1: + enum: + - "READ" + - "EXPLAIN_ANALYZE" + - "WRITE" + - "DDL" + - "FORBIDDEN" + type: "string" + SqlWorkbenchStatementV1: + properties: + index: + format: "int64" + type: "integer" + kind: + $ref: "#/components/schemas/SqlWorkbenchStatementKindV1" + leadingKeyword: + nullable: true + type: "string" + text: + type: "string" + affectedRows: + format: "int64" + nullable: true + type: "integer" + type: "object" + SqlWorkbenchStatusV1: + enum: + - "SUCCEEDED" + - "FAILED" + - "TIMED_OUT" + - "CANCELLED" + - "REJECTED" + - "PREVIEW" + - "DRIFTED" + type: "string" + SqlWorkbenchValueV1: + anyOf: + - nullable: true + type: "string" + - type: "number" + - type: "boolean" + - $ref: "#/components/schemas/SqlWorkbenchBinaryValueV1" + - items: + $ref: "#/components/schemas/SqlWorkbenchValueV1" + type: "array" + - $ref: "#/components/schemas/SqlWorkbenchFreeObjectV1" + description: "JSON-safe JDBC value; null, scalar, binary preview, nested array\ + \ or vendor JSON object." + SqlWorkbenchVersionSummaryV1: + properties: + versionNumber: + format: "int64" + type: "integer" + savedByName: + nullable: true + type: "string" + comment: + nullable: true + type: "string" + createDate: + type: "string" + type: "object" + SqlWorkbenchVersionV1: + properties: + versionNumber: + format: "int64" + type: "integer" + savedByName: + nullable: true + type: "string" + comment: + nullable: true + type: "string" + createDate: + type: "string" + notebook: + $ref: "#/components/schemas/SqlWorkbenchNotebookContentV1" + type: "object" + SqlWorkbenchVersionsV1: + properties: + versions: + items: + $ref: "#/components/schemas/SqlWorkbenchVersionSummaryV1" + type: "array" + type: "object" + securitySchemes: + sessionUuidCookie: + in: "cookie" + name: "sessionUUID" + type: "apiKey" +info: + contact: + email: "contact@kingsrook.com" + description: "Audited SQL execution and notebooks" + title: "QQQ Middleware API extension: sql-workbench" + version: "1.0.0" +openapi: "3.0.3" +paths: + /qqq/v1/sql-workbench/capabilities: + get: + description: "Get caller capabilities and configured limits. Requires SQL Workbench\ + \ access; services enforce caller permissions, ownership, execution limits\ + \ and audit." + operationId: "sqlWorkbenchGetCapabilities" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchCapabilitiesV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Get caller capabilities and configured limits" + /qqq/v1/sql-workbench/schema/{backendName}: + get: + description: "Inspect a target backend schema. Requires SQL Workbench access;\ + \ services enforce caller permissions, ownership, execution limits and audit." + operationId: "sqlWorkbenchGetSchema" + parameters: + - description: "Configured target backend name." + in: "path" + name: "backendName" + required: true + schema: + type: "string" + - description: "True to bypass the schema cache; default false." + in: "query" + name: "refresh" + required: false + schema: + type: "boolean" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchSchemaV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Inspect a target backend schema" + /qqq/v1/sql-workbench/execute: + post: + description: "Execute read-only SQL or preview and confirm a gated write. Requires\ + \ SQL Workbench access; services enforce caller permissions, ownership, execution\ + \ limits and audit." + operationId: "sqlWorkbenchExecute" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchExecuteRequestV1" + required: false + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchExecutionV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Execute read-only SQL or preview and confirm a gated write" + /qqq/v1/sql-workbench/explain: + post: + description: "Explain SQL; ANALYZE remains subject to write gates. Requires\ + \ SQL Workbench access; services enforce caller permissions, ownership, execution\ + \ limits and audit." + operationId: "sqlWorkbenchExplain" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchExplainRequestV1" + required: false + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchExplainV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Explain SQL; ANALYZE remains subject to write gates" + /qqq/v1/sql-workbench/executions/{uuid}/rows: + get: + description: "Page or sort the caller's cached result. Requires SQL Workbench\ + \ access; services enforce caller permissions, ownership, execution limits\ + \ and audit." + operationId: "sqlWorkbenchGetRows" + parameters: + - description: "Execution UUID; case insensitive." + in: "path" + name: "uuid" + required: true + schema: + type: "string" + - description: "Rows to skip; default zero; negative values become zero." + in: "query" + name: "offset" + required: false + schema: + type: "integer" + - description: "Page size; nonpositive or absent uses the default. Rows cap\ + \ at maxPageSize; history caps at 200 (default 50)." + in: "query" + name: "limit" + required: false + schema: + type: "integer" + - description: "Optional zero-based result column index." + in: "query" + name: "sort" + required: false + schema: + type: "integer" + - description: "Sort direction: desc (case insensitive) or asc (default)." + in: "query" + name: "dir" + required: false + schema: + type: "string" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchRowsV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Page or sort the caller's cached result" + /qqq/v1/sql-workbench/executions/{uuid}/cancel: + post: + description: "Cancel the caller's running execution. Requires SQL Workbench\ + \ access; services enforce caller permissions, ownership, execution limits\ + \ and audit." + operationId: "sqlWorkbenchCancelExecution" + parameters: + - description: "Execution UUID; case insensitive." + in: "path" + name: "uuid" + required: true + schema: + type: "string" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchEmptyRequestV1" + required: false + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchCancelledV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Cancel the caller's running execution" + /qqq/v1/sql-workbench/history: + get: + description: "List the caller's recent audited executions. Requires SQL Workbench\ + \ access; services enforce caller permissions, ownership, execution limits\ + \ and audit." + operationId: "sqlWorkbenchGetHistory" + parameters: + - description: "Page size; nonpositive or absent uses the default. Rows cap\ + \ at maxPageSize; history caps at 200 (default 50)." + in: "query" + name: "limit" + required: false + schema: + type: "integer" + - description: "Configured target backend name." + in: "query" + name: "backendName" + required: false + schema: + type: "string" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchHistoryV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "List the caller's recent audited executions" + /qqq/v1/sql-workbench/notebooks: + get: + description: "List visible personal or shared notebooks. Requires SQL Workbench\ + \ access; services enforce caller permissions, ownership, execution limits\ + \ and audit." + operationId: "sqlWorkbenchListNotebooks" + parameters: + - description: "mine (default) or shared notebook library." + in: "query" + name: "scope" + required: false + schema: + type: "string" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchNotebooksV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "List visible personal or shared notebooks" + post: + description: "Create a personal notebook. Requires SQL Workbench access; services\ + \ enforce caller permissions, ownership, execution limits and audit." + operationId: "sqlWorkbenchCreateNotebook" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchNotebookRequestV1" + required: false + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchNotebookV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Create a personal notebook" + /qqq/v1/sql-workbench/notebooks/{id}: + delete: + description: "Delete an owned notebook. Requires SQL Workbench access; services\ + \ enforce caller permissions, ownership, execution limits and audit." + operationId: "sqlWorkbenchDeleteNotebook" + parameters: + - description: "Notebook identifier." + in: "path" + name: "id" + required: true + schema: + type: "integer" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchDeletedV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Delete an owned notebook" + get: + description: "Get a visible notebook and its cells. Requires SQL Workbench access;\ + \ services enforce caller permissions, ownership, execution limits and audit." + operationId: "sqlWorkbenchGetNotebook" + parameters: + - description: "Notebook identifier." + in: "path" + name: "id" + required: true + schema: + type: "integer" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchNotebookV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Get a visible notebook and its cells" + put: + description: "Update an owned notebook and record a version. Requires SQL Workbench\ + \ access; services enforce caller permissions, ownership, execution limits\ + \ and audit." + operationId: "sqlWorkbenchUpdateNotebook" + parameters: + - description: "Notebook identifier." + in: "path" + name: "id" + required: true + schema: + type: "integer" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchNotebookRequestV1" + required: false + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchNotebookV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Update an owned notebook and record a version" + /qqq/v1/sql-workbench/notebooks/{id}/publish: + post: + description: "Publish or withdraw an owned notebook with share permission. Requires\ + \ SQL Workbench access; services enforce caller permissions, ownership, execution\ + \ limits and audit." + operationId: "sqlWorkbenchPublishNotebook" + parameters: + - description: "Notebook identifier." + in: "path" + name: "id" + required: true + schema: + type: "integer" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchPublishRequestV1" + required: false + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchNotebookV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Publish or withdraw an owned notebook with share permission" + /qqq/v1/sql-workbench/notebooks/{id}/duplicate: + post: + description: "Make a personal copy of a visible notebook. Requires SQL Workbench\ + \ access; services enforce caller permissions, ownership, execution limits\ + \ and audit." + operationId: "sqlWorkbenchDuplicateNotebook" + parameters: + - description: "Notebook identifier." + in: "path" + name: "id" + required: true + schema: + type: "integer" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchEmptyRequestV1" + required: false + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchNotebookV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Make a personal copy of a visible notebook" + /qqq/v1/sql-workbench/notebooks/{id}/versions: + get: + description: "List versions of a visible notebook. Requires SQL Workbench access;\ + \ services enforce caller permissions, ownership, execution limits and audit." + operationId: "sqlWorkbenchListVersions" + parameters: + - description: "Notebook identifier." + in: "path" + name: "id" + required: true + schema: + type: "integer" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchVersionsV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "List versions of a visible notebook" + /qqq/v1/sql-workbench/notebooks/{id}/versions/{n}: + get: + description: "Get a visible notebook version and saved content. Requires SQL\ + \ Workbench access; services enforce caller permissions, ownership, execution\ + \ limits and audit." + operationId: "sqlWorkbenchGetVersion" + parameters: + - description: "Notebook identifier." + in: "path" + name: "id" + required: true + schema: + type: "integer" + - description: "Notebook version number." + in: "path" + name: "n" + required: true + schema: + type: "integer" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchVersionV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Get a visible notebook version and saved content" + /qqq/v1/sql-workbench/notebooks/{id}/versions/{n}/restore: + post: + description: "Restore an owned notebook version as a new version. Requires SQL\ + \ Workbench access; services enforce caller permissions, ownership, execution\ + \ limits and audit." + operationId: "sqlWorkbenchRestoreVersion" + parameters: + - description: "Notebook identifier." + in: "path" + name: "id" + required: true + schema: + type: "integer" + - description: "Notebook version number." + in: "path" + name: "n" + required: true + schema: + type: "integer" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchEmptyRequestV1" + required: false + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchNotebookV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Restore an owned notebook version as a new version" + /qqq/v1/sql-workbench/notebooks/{id}/snapshots: + get: + description: "List snapshots of a visible notebook. Requires SQL Workbench access;\ + \ services enforce caller permissions, ownership, execution limits and audit." + operationId: "sqlWorkbenchListSnapshots" + parameters: + - description: "Notebook identifier." + in: "path" + name: "id" + required: true + schema: + type: "integer" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchSnapshotsV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "List snapshots of a visible notebook" + post: + description: "Pin the caller's cached result to an owned notebook. Requires\ + \ SQL Workbench access; services enforce caller permissions, ownership, execution\ + \ limits and audit." + operationId: "sqlWorkbenchCreateSnapshot" + parameters: + - description: "Notebook identifier." + in: "path" + name: "id" + required: true + schema: + type: "integer" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchSnapshotRequestV1" + required: false + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchSnapshotV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Pin the caller's cached result to an owned notebook" + /qqq/v1/sql-workbench/notebooks/{id}/snapshots/{snapshotId}: + delete: + description: "Delete a snapshot from an owned notebook. Requires SQL Workbench\ + \ access; services enforce caller permissions, ownership, execution limits\ + \ and audit." + operationId: "sqlWorkbenchDeleteSnapshot" + parameters: + - description: "Notebook identifier." + in: "path" + name: "id" + required: true + schema: + type: "integer" + - description: "Snapshot identifier." + in: "path" + name: "snapshotId" + required: true + schema: + type: "integer" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchDeletedV1" + description: "Successful Response" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Delete a snapshot from an owned notebook" + /qqq/v1/sql-workbench/executions/{uuid}/export: + get: + description: "Export the caller's cached result as CSV, JSON or XLSX. Requires\ + \ SQL Workbench access; services enforce caller permissions, ownership, execution\ + \ limits and audit." + operationId: "sqlWorkbenchExportResult" + parameters: + - description: "Execution UUID; case insensitive." + in: "path" + name: "uuid" + required: true + schema: + type: "string" + - description: "csv (default), json or xlsx; case insensitive." + in: "query" + name: "format" + required: false + schema: + type: "string" + responses: + 400: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Invalid input or execution limit exceeded" + 401: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Sign in required" + 403: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Permission denied" + 404: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Missing or invisible resource" + 200: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchExportJsonV1" + application/vnd.openxmlformats-officedocument.spreadsheetml.sheet: + schema: + $ref: "#/components/schemas/SqlWorkbenchExportFileV1" + text/csv; charset=utf-8: + schema: + $ref: "#/components/schemas/SqlWorkbenchExportFileV1" + description: "Attachment named sql-result-{short UUID}.{format}; Cache-Control:\ + \ no-store" + 409: + content: + application/json: + schema: + $ref: "#/components/schemas/SqlWorkbenchErrorV1" + description: "Execution UUID already used" + security: + - sessionUuidCookie: + - "N/A" + summary: "Export the caller's cached result as CSV, JSON or XLSX" diff --git a/src/test/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducerTest.java b/src/test/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducerTest.java index e06bbad..011288b 100644 --- a/src/test/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducerTest.java +++ b/src/test/java/com/kingsrook/qbits/sqlworkbench/SqlWorkbenchQBitProducerTest.java @@ -47,7 +47,7 @@ import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData; import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData; import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryBackendModule; import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSTableBackendDetails; -import com.kingsrook.qqq.middleware.javalin.QJavalinMetaData; +import com.kingsrook.qqq.middleware.javalin.specs.extensions.MiddlewareSpecExtensionsMetaData; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -137,7 +137,7 @@ class SqlWorkbenchQBitProducerTest extends BaseSqlWorkbenchTest assertThat(runner.getPermissionRules().getPermissionBaseName()).isEqualTo("sql_workbench"); assertThat(app.getChildren()).noneMatch(child -> child instanceof QProcessMetaData); - assertThat(QJavalinMetaData.of(qInstance).getAdditionalRouteProviderReferences()).isNotEmpty(); + assertThat(MiddlewareSpecExtensionsMetaData.ofOrWithNew(qInstance).getExtensions()).isNotEmpty(); assertThat(SqlWorkbenchRuntime.get(qInstance)).isNotNull(); assertThat(new SqlWorkbenchWidgetRenderer().render(null).getWidgetData().getType()).isEqualTo("SQL_WORKBENCH"); assertThat(SqlWorkbenchQBitProducer.getVersion()).isNotBlank(); @@ -164,7 +164,7 @@ class SqlWorkbenchQBitProducerTest extends BaseSqlWorkbenchTest assertThat(instance.getPossibleValueSource("ns_sql_workbench_backend")).isNotNull(); assertThat(instance.getTable("ns_sql_workbench_cell").getField("cellType").getPossibleValueSourceName()).isEqualTo("ns_sql_workbench_cell_type"); assertThat(instance.getPossibleValueSource("ns_sql_workbench_cell_type")).isNotNull(); - assertThat(QJavalinMetaData.of(instance)).isNull(); + assertThat(MiddlewareSpecExtensionsMetaData.of(instance)).isNull(); SqlWorkbenchRuntime first = prefixed.getRuntime(); new SqlWorkbenchQBitProducer().withQBitConfig(prefixed).getQBitMetaData(); diff --git a/src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchApiContractTest.java b/src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchApiContractTest.java new file mode 100644 index 0000000..9610476 --- /dev/null +++ b/src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchApiContractTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashSet; +import java.util.Set; +import com.kingsrook.qqq.middleware.javalin.specs.v1.MiddlewareVersionV1; +import com.kingsrook.qqq.middleware.javalin.tools.UiApiContract; +import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; + + +/******************************************************************************* + ** The committed fragment describes exactly the shipped extension operations. + *******************************************************************************/ +class SqlWorkbenchApiContractTest +{ + /******************************************************************************* + ** Regenerate with -DsqlWorkbench.openapi.update=true after intentional changes. + *******************************************************************************/ + @Test + void contract() throws Exception + { + var extension = SqlWorkbenchEndpoints.extension(); + var version = new MiddlewareVersionV1(); + String generated = UiApiContract.generateExtensionYaml(version, extension); + Path path = Path.of("src/main/resources/openapi/qqq-v1/sql-workbench.yaml"); + if(Boolean.getBoolean("sqlWorkbench.openapi.update")) + { + Files.createDirectories(path.getParent()); + Files.writeString(path, generated); + } + assertThat(UiApiContract.check(generated, Files.readString(path), null, 1, + "./mvnw -Dtest=SqlWorkbenchApiContractTest -DsqlWorkbench.openapi.update=true test")).isEmpty(); + var model = version.generateExtensionOpenAPIModel("qqq", extension); + assertThat(model.getComponents().getSchemas().keySet()).allMatch(name -> name.startsWith("SqlWorkbench")); + assertThat(model.getPaths().keySet()).allMatch(name -> name.startsWith("/qqq/v1/sql-workbench/")); + assertThat(extension.getSpecs()).hasSize(21); + assertThat(extension.getEffectivePathPrefix()).isEqualTo("/sql-workbench"); + Set operationIds = new HashSet<>(); + Set componentNames = new HashSet<>(); + for(var reference : extension.getSpecs()) + { + var spec = (com.kingsrook.qqq.middleware.javalin.specs.AbstractEndpointSpec) Class.forName(reference.getName()).getConstructor().newInstance(); + assertThat(spec.isSecured()).isTrue(); + assertThat(spec.defineMethod().getOperationId()).startsWith("sqlWorkbench"); + assertThat(operationIds.add(spec.defineMethod().getOperationId())).isTrue(); + for(String name : spec.defineComponentSchemas().keySet()) + { + assertThat(componentNames.add(name)).as("Component declared once: " + name).isTrue(); + } + } + assertThat(generated).contains("text/csv; charset=utf-8", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "format: \"binary\""); + } +} diff --git a/src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchEndpointSpecTest.java b/src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchEndpointSpecTest.java new file mode 100644 index 0000000..28aadb4 --- /dev/null +++ b/src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchEndpointSpecTest.java @@ -0,0 +1,349 @@ +/* + * Copyright 2026 Kingsrook, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.kingsrook.qbits.sqlworkbench.api; + + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.List; +import java.util.Map; +import com.fasterxml.jackson.core.type.TypeReference; +import com.kingsrook.qbits.sqlworkbench.BaseSqlWorkbenchTest; +import com.kingsrook.qbits.sqlworkbench.SqlWorkbenchRuntime; +import com.kingsrook.qqq.backend.core.context.QContext; +import com.kingsrook.qqq.backend.core.instances.AbstractQQQApplication; +import com.kingsrook.qqq.backend.core.model.metadata.QInstance; +import com.kingsrook.qqq.backend.core.utils.JsonUtils; +import com.kingsrook.qqq.middleware.javalin.QApplicationJavalinServer; +import com.kingsrook.qqq.middleware.javalin.specs.AbstractEndpointSpec; +import com.kingsrook.qqq.middleware.javalin.specs.extensions.MiddlewareSpecExtensionsMetaData; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; + + +/******************************************************************************* + ** The routes over real HTTP (Javalin on a random port, MOCK authentication + ** with the sessionId cookie choosing the test user). + *******************************************************************************/ +class SqlWorkbenchEndpointSpecTest extends BaseSqlWorkbenchTest +{ + private QApplicationJavalinServer javalin; + private String base; + private HttpClient client = HttpClient.newHttpClient(); + + + + /******************************************************************************* + ** + *******************************************************************************/ + @BeforeEach + void startServer() throws Exception + { + QContext.clear(); + javalin = new QApplicationJavalinServer(new AbstractQQQApplication() + { + /******************************************************************************* + ** Serve the same instance and runtime prepared by the test fixture. + *******************************************************************************/ + @Override + public QInstance defineQInstance() + { + return (qInstance); + } + }).withPort(0).withServeFrontendNext(false).withServeFrontendMaterialDashboard(false) + .withServeLegacyUnversionedMiddlewareAPI(false).withStrictUiApiRoutes(true); + javalin.start(); + base = "http://localhost:" + javalin.getBoundPort() + "/qqq/v1/sql-workbench"; + } + + + + /******************************************************************************* + ** + *******************************************************************************/ + @AfterEach + void stopServer() + { + javalin.stop(); + } + + + + /******************************************************************************* + ** + *******************************************************************************/ + private HttpResponse send(String method, String path, String user, String body, String contentType) throws Exception + { + HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(base + path)).header("Cookie", "sessionId=" + user); + if(contentType != null) + { + builder.header("Content-Type", contentType); + } + builder.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body)); + return (client.send(builder.build(), HttpResponse.BodyHandlers.ofString())); + } + + + + /******************************************************************************* + ** + *******************************************************************************/ + private static Map json(HttpResponse response) throws Exception + { + return (JsonUtils.toObject(response.body(), new TypeReference>() {})); + } + + + + /******************************************************************************* + ** + *******************************************************************************/ + @Test + void testRegistration() + { + SqlWorkbenchEndpoints.register(qInstance); + var extensions = MiddlewareSpecExtensionsMetaData.ofOrWithNew(qInstance).getExtensions(); + assertThat(extensions).containsOnlyKeys("sql-workbench"); + assertThat(extensions.get("sql-workbench").getSpecs()).hasSize(21); + assertThat(javalin.isStrictUiApiRoutes()).isTrue(); + } + + + + /******************************************************************************* + ** + *******************************************************************************/ + @Test + @SuppressWarnings("unchecked") + void testEndToEnd() throws Exception + { + assertThat(send("GET", "/capabilities", "nobody", null, null).statusCode()).isEqualTo(403); + assertThat(send("GET", "/capabilities", READER, null, null).statusCode()).isEqualTo(200); + + //////////////////////////////////////////////////////////// + // JSON only - a form post (CSRF shape) is refused // + //////////////////////////////////////////////////////////// + assertThat(send("POST", "/execute", READER, "backendName=h2&sql=SELECT+1", "application/x-www-form-urlencoded").statusCode()).isEqualTo(400); + assertThat(send("POST", "/execute", READER, "not json", "application/json").statusCode()).isEqualTo(400); + + HttpResponse run = send("POST", "/execute", READER, "{\"backendName\":\"h2\",\"sql\":\"SELECT id, salary FROM person WHERE salary > :s ORDER BY id\",\"params\":{\"s\":25000.25}}", "application/json"); + assertThat(run.statusCode()).isEqualTo(200); + Map result = json(run); + assertThat(result.get("status")).isEqualTo("SUCCEEDED"); + assertThat(result.get("rowCount")).isEqualTo(2); + String uuid = (String) result.get("executionUuid"); + + assertThat(json(send("GET", "/executions/" + uuid + "/rows?offset=1&limit=1&sort=0&dir=desc", READER, null, null)).get("rows")).asList().hasSize(1); + assertThat(send("GET", "/executions/" + uuid + "/rows?offset=x", READER, null, null).statusCode()).isEqualTo(400); + assertThat(send("GET", "/executions/" + uuid + "/rows", OTHER_READER, null, null).statusCode()).isEqualTo(404); + + HttpResponse csv = send("GET", "/executions/" + uuid + "/export?format=csv", READER, null, null); + assertThat(csv.statusCode()).isEqualTo(200); + assertThat(csv.headers().firstValue("Content-Disposition").orElse("")).contains("attachment").contains(".csv"); + assertThat(csv.body()).contains("id,salary"); + assertThat(send("GET", "/executions/" + uuid + "/export?format=pdf", READER, null, null).statusCode()).isEqualTo(400); + assertThat(send("GET", "/executions/" + uuid + "/export", OTHER_READER, null, null).statusCode()).isEqualTo(404); + + assertThat(send("POST", "/execute", READER, "{\"backendName\":\"h2\",\"sql\":\"DELETE FROM person\",\"mode\":\"WRITE\"}", "application/json").statusCode()).isEqualTo(403); + assertThat(send("POST", "/execute", READER, "{\"backendName\":\"nope\",\"sql\":\"SELECT 1\"}", "application/json").statusCode()).isEqualTo(404); + assertThat(json(send("POST", "/explain", READER, "{\"backendName\":\"h2\",\"sql\":\"SELECT 1\"}", "application/json")).get("status")).isEqualTo("SUCCEEDED"); + assertThat(json(send("POST", "/executions/" + uuid + "/cancel", READER, "{}", "application/json")).get("cancelled")).isEqualTo(false); + assertThat((List) json(send("GET", "/history?limit=5", READER, null, null)).get("executions")).hasSize(3); + assertThat(json(send("GET", "/schema/h2", READER, null, null)).get("dialect")).isEqualTo("h2"); + + /////////////////////////////////////////////////////////////////// + // a client-chosen id: any case on the paths, single-use (409) // + /////////////////////////////////////////////////////////////////// + String clientUuid = "3F2504E0-4F89-11D3-9A0C-0305E82C3301"; + String body = "{\"backendName\":\"h2\",\"sql\":\"SELECT 1 AS one\",\"executionUuid\":\"" + clientUuid + "\"}"; + assertThat(json(send("POST", "/execute", READER, body, "application/json")).get("executionUuid")).isEqualTo(clientUuid.toLowerCase()); + assertThat(send("GET", "/executions/" + clientUuid + "/rows", READER, null, null).statusCode()).isEqualTo(200); + assertThat(send("GET", "/executions/" + clientUuid + "/export", READER, null, null).statusCode()).isEqualTo(200); + HttpResponse again = send("POST", "/execute", READER, body, "application/json"); + assertThat(again.statusCode()).isEqualTo(409); + assertThat(again.body()).contains("already used"); + } + + + + /******************************************************************************* + ** + *******************************************************************************/ + @Test + void testNotebookRoutes() throws Exception + { + Map created = json(send("POST", "/notebooks", WRITER, "{\"title\":\"N1\",\"cells\":[{\"cellKey\":\"a\",\"cellType\":\"SQL\",\"content\":\"SELECT 1\"}]}", "application/json")); + Integer id = (Integer) created.get("id"); + + assertThat((List) json(send("GET", "/notebooks?scope=mine", WRITER, null, null)).get("notebooks")).hasSize(1); + assertThat(json(send("GET", "/notebooks/" + id, WRITER, null, null)).get("title")).isEqualTo("N1"); + assertThat(send("GET", "/notebooks/" + id, READER, null, null).statusCode()).isEqualTo(404); + assertThat(send("GET", "/notebooks/abc", WRITER, null, null).statusCode()).isEqualTo(400); + + assertThat(json(send("PUT", "/notebooks/" + id, WRITER, "{\"title\":\"N2\"}", "application/json")).get("currentVersion")).isEqualTo(2); + assertThat(json(send("POST", "/notebooks/" + id + "/publish", WRITER, "{\"shared\":true}", "application/json")).get("visibility")).isEqualTo("SHARED"); + assertThat((List) json(send("GET", "/notebooks?scope=shared", READER, null, null)).get("notebooks")).hasSize(1); + assertThat(json(send("POST", "/notebooks/" + id + "/duplicate", READER, "{}", "application/json")).get("ownerUserId")).isEqualTo(READER); + assertThat((List) json(send("GET", "/notebooks/" + id + "/versions", WRITER, null, null)).get("versions")).hasSize(2); + assertThat(json(send("GET", "/notebooks/" + id + "/versions/1", WRITER, null, null)).get("versionNumber")).isEqualTo(1); + assertThat(json(send("POST", "/notebooks/" + id + "/versions/1/restore", WRITER, "{}", "application/json")).get("title")).isEqualTo("N1"); + + String uuid = (String) json(send("POST", "/execute", WRITER, "{\"backendName\":\"h2\",\"sql\":\"SELECT 1 AS one\"}", "application/json")).get("executionUuid"); + Map snapshot = json(send("POST", "/notebooks/" + id + "/snapshots", WRITER, "{\"executionUuid\":\"" + uuid + "\",\"cellKey\":\"a\"}", "application/json")); + assertThat((List) json(send("GET", "/notebooks/" + id + "/snapshots", WRITER, null, null)).get("snapshots")).hasSize(1); + assertThat(json(send("DELETE", "/notebooks/" + id + "/snapshots/" + snapshot.get("id"), WRITER, null, null)).get("deleted")).isEqualTo(true); + + assertThat(send("DELETE", "/notebooks/" + id, READER, null, null).statusCode()).isEqualTo(403); + assertThat(json(send("DELETE", "/notebooks/" + id, WRITER, null, null)).get("deleted")).isEqualTo(true); + } + + + + /******************************************************************************* + ** Every spec checks access before parsing bodies, identifiers or formats. + *******************************************************************************/ + @Test + void testEveryOperationDeniesMissingAccess() throws Exception + { + for(var reference : SqlWorkbenchEndpoints.extension().getSpecs()) + { + var spec = (AbstractEndpointSpec) Class.forName(reference.getName()).getConstructor().newInstance(); + var operation = spec.defineBasicOperation(); + String path = operation.getPath().substring("/sql-workbench".length()).replaceAll("\\{[^}]+}", "invalid"); + String method = operation.getHttpMethod().name(); + boolean body = method.equals("POST") || method.equals("PUT"); + HttpResponse response = send(method, path + "?format=invalid", "nobody", body ? "not json" : null, body ? "text/plain" : null); + assertThat(response.statusCode()).as(method + " " + path).isEqualTo(403); + assertThat(json(response)).containsEntry("error", "Permission denied."); + HttpRequest unauthenticated = HttpRequest.newBuilder(URI.create(base + path)) + .header("Authorization", "Bearer Deny") + .method(method, HttpRequest.BodyPublishers.noBody()).build(); + assertThat(client.send(unauthenticated, HttpResponse.BodyHandlers.ofString()).statusCode()).as(method + " authentication").isEqualTo(401); + } + assertThat(json(send("GET", "/history", READER, null, null)).get("executions")).asList().isEmpty(); + } + + + + /******************************************************************************* + ** Write gates, read-only classification and concurrency limits remain audited. + *******************************************************************************/ + @Test + void testExecutionGatesAndLimits() throws Exception + { + String write = "{\"backendName\":\"h2\",\"sql\":\"DELETE FROM person\",\"mode\":\"WRITE\"}"; + assertThat(send("POST", "/execute", READER, write, "application/json").statusCode()).isEqualTo(403); + config.setWriteModeEnabled(false); + assertThat(send("POST", "/execute", WRITER, write, "application/json").statusCode()).isEqualTo(403); + String analyze = "{\"backendName\":\"h2\",\"sql\":\"SELECT 1\",\"analyze\":true}"; + assertThat(send("POST", "/explain", WRITER, analyze, "application/json").statusCode()).isEqualTo(403); + config.setWriteModeEnabled(true); + assertThat(send("POST", "/explain", READER, analyze, "application/json").statusCode()).isEqualTo(403); + assertThat(send("POST", "/execute", WRITER, write.replace(",\"mode\":\"WRITE\"", ""), "application/json").statusCode()).isEqualTo(400); + + config.setMaxConcurrentExecutionsPerUser(1); + var running = SqlWorkbenchRuntime.get(qInstance).getRunningStatements(); + String uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3302"; + var registration = running.register(uuid, READER, 1); + try + { + HttpResponse limited = send("POST", "/execute", READER, "{\"backendName\":\"h2\",\"sql\":\"SELECT 1\"}", "application/json"); + assertThat(limited.statusCode()).isEqualTo(400); + assertThat(limited.body()).contains("executions running"); + assertThat(json(send("POST", "/executions/" + uuid + "/cancel", OTHER_READER, "{}", "application/json"))).containsEntry("cancelled", false); + assertThat(registration.isCancelled()).isFalse(); + assertThat(json(send("POST", "/executions/" + uuid + "/cancel", READER, "{}", "application/json"))).containsEntry("cancelled", true); + } + finally + { + running.unregister(uuid, registration); + } + List history = (List) json(send("GET", "/history", READER, null, null)).get("executions"); + assertThat(history).hasSize(3).allSatisfy(entry -> assertThat(((Map) entry).get("status")).isEqualTo("REJECTED")); + Map count = json(send("POST", "/execute", READER, "{\"backendName\":\"h2\",\"sql\":\"SELECT COUNT(*) AS n FROM person\"}", "application/json")); + assertThat(count.get("rows")).isEqualTo(List.of(List.of(5))); + } + + + + /******************************************************************************* + ** Share permission, ownership and cached-result ownership apply to mutations. + *******************************************************************************/ + @Test + void testNotebookMutationDenials() throws Exception + { + Integer id = (Integer) json(send("POST", "/notebooks", READER, "{\"title\":\"Private\"}", "application/json")).get("id"); + assertThat(send("POST", "/notebooks/" + id + "/publish", READER, "{\"shared\":true}", "application/json").statusCode()).isEqualTo(403); + for(String suffix : List.of("", "/versions", "/versions/1", "/snapshots")) + { + assertThat(send("GET", "/notebooks/" + id + suffix, OTHER_READER, null, null).statusCode()).isEqualTo(404); + } + assertThat(send("PUT", "/notebooks/" + id, OTHER_READER, "{\"title\":\"Stolen\"}", "application/json").statusCode()).isEqualTo(404); + assertThat(send("POST", "/notebooks/" + id + "/duplicate", OTHER_READER, "{}", "application/json").statusCode()).isEqualTo(404); + assertThat(send("POST", "/notebooks/" + id + "/versions/1/restore", OTHER_READER, "{}", "application/json").statusCode()).isEqualTo(404); + + Integer shared = (Integer) json(send("POST", "/notebooks", WRITER, "{\"title\":\"Shared\"}", "application/json")).get("id"); + send("POST", "/notebooks/" + shared + "/publish", WRITER, "{\"shared\":true}", "application/json"); + assertThat(send("PUT", "/notebooks/" + shared, READER, "{\"title\":\"Stolen\"}", "application/json").statusCode()).isEqualTo(403); + assertThat(send("POST", "/notebooks/" + shared + "/versions/1/restore", READER, "{}", "application/json").statusCode()).isEqualTo(403); + String uuid = (String) json(send("POST", "/execute", WRITER, "{\"backendName\":\"h2\",\"sql\":\"SELECT 1\"}", "application/json")).get("executionUuid"); + String snapshotBody = "{\"executionUuid\":\"" + uuid + "\",\"cellKey\":\"a\"}"; + assertThat(send("POST", "/notebooks/" + id + "/snapshots", READER, snapshotBody, "application/json").statusCode()).isEqualTo(404); + Integer snapshotId = (Integer) json(send("POST", "/notebooks/" + shared + "/snapshots", WRITER, snapshotBody, "application/json")).get("id"); + assertThat(send("DELETE", "/notebooks/" + shared + "/snapshots/" + snapshotId, READER, null, null).statusCode()).isEqualTo(403); + assertThat(json(send("GET", "/notebooks/" + id, READER, null, null))).containsEntry("title", "Private"); + } + + + + /******************************************************************************* + ** Keep decimal parameters, null bodies, SQL failures and all export formats. + *******************************************************************************/ + @Test + void testWireCompatibility() throws Exception + { + HttpResponse run = send("POST", "/execute", READER, + "{\"backendName\":\"h2\",\"sql\":\"SELECT CAST(:n AS DECIMAL(30,20)) AS n\",\"params\":{\"n\":0.12345678901234567890}}", "application/json"); + assertThat(run.statusCode()).isEqualTo(200); + assertThat(run.body()).contains("0.12345678901234567890"); + String uuid = (String) json(run).get("executionUuid"); + for(String format : List.of("csv", "json", "xlsx")) + { + HttpResponse export = send("GET", "/executions/" + uuid + "/export?format=" + format, READER, null, null); + assertThat(export.statusCode()).isEqualTo(200); + assertThat(export.headers().firstValue("Cache-Control")).contains("no-store"); + assertThat(export.headers().firstValue("Content-Disposition").orElseThrow()).endsWith("." + format + "\""); + if(format.equals("json")) + { + assertThat(export.body()).contains("0.12345678901234567890"); + } + } + assertThat(json(send("POST", "/executions/" + uuid + "/cancel", READER, "null", "application/json"))).containsEntry("cancelled", false); + assertThat(send("POST", "/execute", READER, "[]", "application/json").statusCode()).isEqualTo(400); + assertThat(send("POST", "/execute", READER, "{}", null).statusCode()).isEqualTo(400); + HttpResponse failed = send("POST", "/execute", READER, "{\"backendName\":\"h2\",\"sql\":\"SELECT * FROM nonexistent_table\"}", "application/json"); + assertThat(failed.statusCode()).isEqualTo(200); + assertThat(json(failed)).containsEntry("status", "FAILED"); + String served = client.send(HttpRequest.newBuilder(URI.create(base.replace("/sql-workbench", "/openapi.yaml"))).build(), HttpResponse.BodyHandlers.ofString()).body(); + assertThat(served).contains("sqlWorkbenchExecute", "sqlWorkbenchExportResult", "SqlWorkbenchNotebookV1"); + } + +} diff --git a/src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRouteProviderTest.java b/src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRouteProviderTest.java deleted file mode 100644 index db55de0..0000000 --- a/src/test/java/com/kingsrook/qbits/sqlworkbench/api/SqlWorkbenchRouteProviderTest.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 2026 Kingsrook, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.kingsrook.qbits.sqlworkbench.api; - - -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.List; -import java.util.Map; -import com.fasterxml.jackson.core.type.TypeReference; -import com.kingsrook.qqq.backend.core.context.QContext; -import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference; -import com.kingsrook.qqq.backend.core.utils.JsonUtils; -import com.kingsrook.qbits.sqlworkbench.BaseSqlWorkbenchTest; -import com.kingsrook.qqq.middleware.javalin.QJavalinMetaData; -import io.javalin.Javalin; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; - - -/******************************************************************************* - ** The routes over real HTTP (Javalin on a random port, MOCK authentication - ** with the sessionId cookie choosing the test user). - *******************************************************************************/ -class SqlWorkbenchRouteProviderTest extends BaseSqlWorkbenchTest -{ - private Javalin javalin; - private String base; - private HttpClient client = HttpClient.newHttpClient(); - - - - /******************************************************************************* - ** - *******************************************************************************/ - @BeforeEach - void startServer() - { - QContext.clear(); - SqlWorkbenchRouteProvider provider = new SqlWorkbenchRouteProvider(); - provider.setQInstance(qInstance); - javalin = Javalin.create(provider::acceptJavalinConfig).start(0); - base = "http://localhost:" + javalin.port() + SqlWorkbenchRouteProvider.BASE_PATH; - } - - - - /******************************************************************************* - ** - *******************************************************************************/ - @AfterEach - void stopServer() - { - javalin.stop(); - } - - - - /******************************************************************************* - ** - *******************************************************************************/ - private HttpResponse send(String method, String path, String user, String body, String contentType) throws Exception - { - HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(base + path)).header("Cookie", "sessionId=" + user); - if(contentType != null) - { - builder.header("Content-Type", contentType); - } - builder.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body)); - return (client.send(builder.build(), HttpResponse.BodyHandlers.ofString())); - } - - - - /******************************************************************************* - ** - *******************************************************************************/ - private static Map json(HttpResponse response) throws Exception - { - return (JsonUtils.toObject(response.body(), new TypeReference>() {})); - } - - - - /******************************************************************************* - ** - *******************************************************************************/ - @Test - void testRegistration() - { - com.kingsrook.qbits.sqlworkbench.api.SqlWorkbenchRoutes.register(qInstance); - List references = QJavalinMetaData.of(qInstance).getAdditionalRouteProviderReferences(); - assertThat(references).filteredOn(r -> r.getName().equals(SqlWorkbenchRouteProvider.class.getName())).hasSize(1); - } - - - - /******************************************************************************* - ** - *******************************************************************************/ - @Test - @SuppressWarnings("unchecked") - void testEndToEnd() throws Exception - { - assertThat(send("GET", "/capabilities", "nobody", null, null).statusCode()).isEqualTo(403); - assertThat(send("GET", "/capabilities", READER, null, null).statusCode()).isEqualTo(200); - - //////////////////////////////////////////////////////////// - // JSON only - a form post (CSRF shape) is refused // - //////////////////////////////////////////////////////////// - assertThat(send("POST", "/execute", READER, "backendName=h2&sql=SELECT+1", "application/x-www-form-urlencoded").statusCode()).isEqualTo(400); - assertThat(send("POST", "/execute", READER, "not json", "application/json").statusCode()).isEqualTo(400); - - HttpResponse run = send("POST", "/execute", READER, "{\"backendName\":\"h2\",\"sql\":\"SELECT id, salary FROM person WHERE salary > :s ORDER BY id\",\"params\":{\"s\":25000.25}}", "application/json"); - assertThat(run.statusCode()).isEqualTo(200); - Map result = json(run); - assertThat(result.get("status")).isEqualTo("SUCCEEDED"); - assertThat(result.get("rowCount")).isEqualTo(2); - String uuid = (String) result.get("executionUuid"); - - assertThat(json(send("GET", "/executions/" + uuid + "/rows?offset=1&limit=1&sort=0&dir=desc", READER, null, null)).get("rows")).asList().hasSize(1); - assertThat(send("GET", "/executions/" + uuid + "/rows?offset=x", READER, null, null).statusCode()).isEqualTo(400); - assertThat(send("GET", "/executions/" + uuid + "/rows", OTHER_READER, null, null).statusCode()).isEqualTo(404); - - HttpResponse csv = send("GET", "/executions/" + uuid + "/export?format=csv", READER, null, null); - assertThat(csv.statusCode()).isEqualTo(200); - assertThat(csv.headers().firstValue("Content-Disposition").orElse("")).contains("attachment").contains(".csv"); - assertThat(csv.body()).contains("id,salary"); - assertThat(send("GET", "/executions/" + uuid + "/export?format=pdf", READER, null, null).statusCode()).isEqualTo(400); - assertThat(send("GET", "/executions/" + uuid + "/export", OTHER_READER, null, null).statusCode()).isEqualTo(404); - - assertThat(send("POST", "/execute", READER, "{\"backendName\":\"h2\",\"sql\":\"DELETE FROM person\",\"mode\":\"WRITE\"}", "application/json").statusCode()).isEqualTo(403); - assertThat(send("POST", "/execute", READER, "{\"backendName\":\"nope\",\"sql\":\"SELECT 1\"}", "application/json").statusCode()).isEqualTo(404); - assertThat(json(send("POST", "/explain", READER, "{\"backendName\":\"h2\",\"sql\":\"SELECT 1\"}", "application/json")).get("status")).isEqualTo("SUCCEEDED"); - assertThat(json(send("POST", "/executions/" + uuid + "/cancel", READER, "{}", "application/json")).get("cancelled")).isEqualTo(false); - assertThat((List) json(send("GET", "/history?limit=5", READER, null, null)).get("executions")).hasSize(3); - assertThat(json(send("GET", "/schema/h2", READER, null, null)).get("dialect")).isEqualTo("h2"); - - /////////////////////////////////////////////////////////////////// - // a client-chosen id: any case on the paths, single-use (409) // - /////////////////////////////////////////////////////////////////// - String clientUuid = "3F2504E0-4F89-11D3-9A0C-0305E82C3301"; - String body = "{\"backendName\":\"h2\",\"sql\":\"SELECT 1 AS one\",\"executionUuid\":\"" + clientUuid + "\"}"; - assertThat(json(send("POST", "/execute", READER, body, "application/json")).get("executionUuid")).isEqualTo(clientUuid.toLowerCase()); - assertThat(send("GET", "/executions/" + clientUuid + "/rows", READER, null, null).statusCode()).isEqualTo(200); - assertThat(send("GET", "/executions/" + clientUuid + "/export", READER, null, null).statusCode()).isEqualTo(200); - HttpResponse again = send("POST", "/execute", READER, body, "application/json"); - assertThat(again.statusCode()).isEqualTo(409); - assertThat(again.body()).contains("already used"); - } - - - - /******************************************************************************* - ** - *******************************************************************************/ - @Test - void testNotebookRoutes() throws Exception - { - Map created = json(send("POST", "/notebooks", WRITER, "{\"title\":\"N1\",\"cells\":[{\"cellKey\":\"a\",\"cellType\":\"SQL\",\"content\":\"SELECT 1\"}]}", "application/json")); - Integer id = (Integer) created.get("id"); - - assertThat((List) json(send("GET", "/notebooks?scope=mine", WRITER, null, null)).get("notebooks")).hasSize(1); - assertThat(json(send("GET", "/notebooks/" + id, WRITER, null, null)).get("title")).isEqualTo("N1"); - assertThat(send("GET", "/notebooks/" + id, READER, null, null).statusCode()).isEqualTo(404); - assertThat(send("GET", "/notebooks/abc", WRITER, null, null).statusCode()).isEqualTo(400); - - assertThat(json(send("PUT", "/notebooks/" + id, WRITER, "{\"title\":\"N2\"}", "application/json")).get("currentVersion")).isEqualTo(2); - assertThat(json(send("POST", "/notebooks/" + id + "/publish", WRITER, "{\"shared\":true}", "application/json")).get("visibility")).isEqualTo("SHARED"); - assertThat((List) json(send("GET", "/notebooks?scope=shared", READER, null, null)).get("notebooks")).hasSize(1); - assertThat(json(send("POST", "/notebooks/" + id + "/duplicate", READER, "{}", "application/json")).get("ownerUserId")).isEqualTo(READER); - assertThat((List) json(send("GET", "/notebooks/" + id + "/versions", WRITER, null, null)).get("versions")).hasSize(2); - assertThat(json(send("GET", "/notebooks/" + id + "/versions/1", WRITER, null, null)).get("versionNumber")).isEqualTo(1); - assertThat(json(send("POST", "/notebooks/" + id + "/versions/1/restore", WRITER, "{}", "application/json")).get("title")).isEqualTo("N1"); - - String uuid = (String) json(send("POST", "/execute", WRITER, "{\"backendName\":\"h2\",\"sql\":\"SELECT 1 AS one\"}", "application/json")).get("executionUuid"); - Map snapshot = json(send("POST", "/notebooks/" + id + "/snapshots", WRITER, "{\"executionUuid\":\"" + uuid + "\",\"cellKey\":\"a\"}", "application/json")); - assertThat((List) json(send("GET", "/notebooks/" + id + "/snapshots", WRITER, null, null)).get("snapshots")).hasSize(1); - assertThat(json(send("DELETE", "/notebooks/" + id + "/snapshots/" + snapshot.get("id"), WRITER, null, null)).get("deleted")).isEqualTo(true); - - assertThat(send("DELETE", "/notebooks/" + id, READER, null, null).statusCode()).isEqualTo(403); - assertThat(json(send("DELETE", "/notebooks/" + id, WRITER, null, null)).get("deleted")).isEqualTo(true); - } - -} From 103ef543d138bf12576be777e88ca76120e5a223 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 14 Oct 2026 07:15:14 -0500 Subject: [PATCH 4/4] build: qbit-build-parent 2.1.0 with architecture guardrails enforced Enforce the qbit-bom#10 guardrails (G1, G3, G4, G7) and run tests in strict raw-route mode (G2). All pass on the released QQQ 4.1.0-RC.6. Co-Authored-By: Claude Opus 5.5 --- pom.xml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index df7cabb..8538d87 100644 --- a/pom.xml +++ b/pom.xml @@ -18,6 +18,8 @@ + true + true 1.0.0-SNAPSHOT 21 21 @@ -29,7 +31,7 @@ com.kingsrook qbit-build-parent - 2.0.0 + 2.1.0 com.kingsrook.qbits