Compare commits

..
Author SHA1 Message Date
james.maes ae57a9442b Merge pull request 'fix(filters): relative dates in an analysis filter no longer answer HTTP 500' (#44) from fix/relative-date-filters into develop
build / maven (push) Successful in 4m33s
maven / build (push) Successful in 4m33s
2026-11-11 13:11:49 +00:00
james.maesandClaude Fable 5.2 472fcbf8dd docs(changelog): file the relative-date fix under Unreleased / Fixed
build / maven (push) Successful in 3m15s
maven / build (push) Successful in 3m15s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 07:05:46 -06:00
james.maesandClaude Fable 5.2 a707215317 fix(filters): relative dates in an analysis filter no longer answer HTTP 500
build / maven (push) Successful in 4m20s
maven / build (push) Successful in 4m20s
A filter criterion whose value is a filter expression (NowWithOffset, ThisOrLastPeriod, Now)
on a date or date-time field failed in DrillFilters.restoreTypes with 'Unsupported class
...NowWithOffset for converting to Instant': the value was converted to the field's type
before the query. Expressions are now passed through for core to evaluate, so a pivot
'created in the last day' works directly, after the JSON round trip of the UI API and of a
saved definition, and its drill filters carry the expression.

PivotContractTest.pivotWithRelativeDateFilter fails without the change on the memory, H2
and PostgreSQL engines.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 07:05:30 -06:00
james.maes 0e9c4ec2b8 Merge pull request 'build(deps): align with Gitea registry (parent 2.2.1, QQQ 4.1.0-RC.26)' (#43) from deps/align-gitea into develop
build / maven (push) Successful in 5m34s
maven / build (push) Successful in 5m34s
2026-11-07 18:41:07 +00:00
james.maesandClaude Opus 5.5 a62834c089 test: regenerate OpenAPI contract for QQQ 4.1.0-RC.26
build / maven (push) Successful in 7m9s
maven / build (push) Successful in 7m9s
QQQ RC.26 adds the shared BasicErrorResponseV1 schema to extension models; regenerate the committed fragment and allow that core schema.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 12:30:29 -06:00
james.maesandClaude Opus 5.5 880977b19a build(deps): align with Gitea registry (parent 2.2.1, QQQ 4.1.0-RC.26)
build / maven (push) Canceled after 4m50s
maven / build (push) Canceled after 0s
pom.xml: parent -> 2.2.1
pom.xml: qqq.snapshot.version: 4.1.0-RC.19 -> 4.1.0-RC.26
pom.xml: added qqq.version=4.1.0-RC.26 (parent BOM import)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 17:59:06 +00:00
CI 53d17b784e Bump version to 0.3.0-SNAPSHOT [skip ci] 2026-11-06 17:21:57 +00:00
james.maes 4354239fd7 Merge pull request 'ci: pin shared workflow to v1' (#42) from ci/pin-v1-develop into develop
QRun-IO/ci-policy: native / dotnet-0 (push) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3 (push) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (push) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (push) Skipped
QRun-IO/ci-policy: ci / source-config-14 (push) Skipped
QRun-IO/ci-policy: ci / original-voyage (push) Skipped
QRun-IO/ci-policy: ci / original-cli (push) Skipped
QRun-IO/ci-policy: ci / ci-result (push) Successful in 11s
build / maven (push) Successful in 7m29s
QRun-IO/ci-policy: ci / fork-guard (push) Skipped
QRun-IO/ci-policy: native / fork-deny (push) Skipped
QRun-IO/ci-policy: ci / Scoped workflow [workflow 1e25bb5a243dfdcd95d4b9a4f780200ff8c8778a] (push) Successful in 18s
QRun-IO/ci-policy: ci / head-profile (push) Skipped
QRun-IO/ci-policy: ci / repository-policy (push) Skipped
QRun-IO/ci-policy: ci / application-template-0 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (push) Skipped
QRun-IO/ci-policy: ci / node-8 (push) Skipped
QRun-IO/ci-policy: ci / node-9 (push) Skipped
QRun-IO/ci-policy: ci / node-10 (push) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (push) Skipped
QRun-IO/ci-policy: ci / source-config-13 (push) Skipped
QRun-IO/ci-policy: ci / original-business (push) Skipped
QRun-IO/ci-policy: ci / shared-pipeline (push) Skipped
QRun-IO/ci-policy: native / native-result (push) Successful in 13s
QRun-IO/ci-policy: ci / gradle-1 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (push) Skipped
QRun-IO/ci-policy: ci / android-0 (push) Skipped
QRun-IO/ci-policy: ci / original-mcp (push) Skipped
QRun-IO/ci-policy: ci / not-enrolled (push) Skipped
maven / build (push) Successful in 7m29s
2026-11-06 16:06:08 +00:00
james.maesandClaude Opus 5.5 21ca0bb158 ci: pin shared workflow to v1
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-business (pull_request) Skipped
QRun-IO/ci-policy: ci / original-voyage (pull_request) Skipped
QRun-IO/ci-policy: ci / original-cli (pull_request) Skipped
QRun-IO/ci-policy: ci / ci-result (pull_request) Successful in 7s
build / maven (push) Successful in 6m49s
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / Scoped workflow [workflow 1e25bb5a243dfdcd95d4b9a4f780200ff8c8778a] (pull_request) Successful in 7s
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 6s
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / android-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-mcp (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: ci / shared-pipeline (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
maven / build (push) Successful in 6m49s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 14:08:22 +00:00
CI 0ec2b55f0f Bump version to 0.2.0-SNAPSHOT [skip ci] 2026-11-05 23:53:38 +00:00
james.maes 9c81be5223 Merge pull request 'ci: use shared ci-workflows Maven workflow' (#41) from ci/ci-workflows into develop
QRun-IO/ci-policy: native / dotnet-0 (push) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3 (push) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (push) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (push) Skipped
QRun-IO/ci-policy: ci / source-config-14 (push) Skipped
QRun-IO/ci-policy: ci / original-voyage (push) Skipped
QRun-IO/ci-policy: ci / original-cli (push) Skipped
QRun-IO/ci-policy: ci / ci-result (push) Successful in 5s
build / maven (push) Successful in 5m14s
QRun-IO/ci-policy: ci / fork-guard (push) Skipped
QRun-IO/ci-policy: native / fork-deny (push) Skipped
QRun-IO/ci-policy: ci / head-profile (push) Skipped
QRun-IO/ci-policy: ci / repository-policy (push) Skipped
QRun-IO/ci-policy: ci / application-template-0 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (push) Skipped
QRun-IO/ci-policy: native / native-result (push) Successful in 7s
QRun-IO/ci-policy: ci / node-8 (push) Skipped
QRun-IO/ci-policy: ci / node-9 (push) Skipped
QRun-IO/ci-policy: ci / node-10 (push) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (push) Skipped
QRun-IO/ci-policy: ci / source-config-13 (push) Skipped
QRun-IO/ci-policy: ci / original-business (push) Skipped
QRun-IO/ci-policy: ci / shared-pipeline (push) Skipped
QRun-IO/ci-policy: ci / Scoped workflow [workflow d20a578c7d818bc7ca32a2ac2c675da4e4f27385] (push) Successful in 8s
QRun-IO/ci-policy: ci / gradle-1 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (push) Skipped
QRun-IO/ci-policy: ci / android-0 (push) Skipped
QRun-IO/ci-policy: ci / original-mcp (push) Skipped
QRun-IO/ci-policy: ci / not-enrolled (push) Skipped
maven / build (push) Successful in 5m14s
2026-11-05 23:16:09 +00:00
james.maesandClaude Opus 5.5 0012d9b3fa ci: use shared ci-workflows Maven workflow
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / Scoped workflow [workflow 1b3648d9421543350067e95e54959dfb471b26d5] (pull_request) Successful in 11s
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-business (pull_request) Skipped
QRun-IO/ci-policy: ci / original-voyage (pull_request) Skipped
QRun-IO/ci-policy: ci / original-cli (pull_request) Skipped
build / maven (push) Successful in 5m6s
QRun-IO/ci-policy: ci / ci-result (pull_request) Failing after 8s
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 9s
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / android-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-mcp (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: ci / shared-pipeline (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Failing after 13s
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
maven / build (push) Successful in 5m6s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 4m52s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Failing after 2s
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Failing after 14m32s
Replace the platform-ci release callers with one caller of
KofTwentyTwo/ci-workflows maven.yaml (qqq-orb port).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 22:04:16 +00:00
james.maes f2fd8b1b0f Merge pull request 'ci: reconcile legacy release ancestry for normal RC cuts' (#39) from fix/reconcile-release-ci into develop
QRun-IO/ci-policy: ci / source-config-14 (push) Skipped
QRun-IO/ci-policy: ci / original-voyage (push) Skipped
qrun-release / postpublish (push) Successful in 2m5s
QRun-IO/ci-policy: native / dotnet-0 (push) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (push) Successful in 13s
Shared Java Maven CI with Docker / secrets (push) Successful in 13s
QRun-IO/ci-policy: ci / java-core-2-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (push) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3 (push) Successful in 4m40s
QRun-IO/ci-policy: ci / ci-result (push) Successful in 4s
Shared Java Maven CI with Docker / verify (push) Successful in 4m54s
QRun-IO/ci-policy: ci / node-playwright-11 (push) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (push) Skipped
QRun-IO/ci-policy: ci / source-config-13 (push) Skipped
qrun-release / release (push) Successful in 5m5s
QRun-IO/ci-policy: ci / original-business (push) Skipped
QRun-IO/ci-policy: native / fork-deny (push) Skipped
QRun-IO/ci-policy: ci / repository-policy (push) Skipped
QRun-IO/ci-policy: native / native-result (push) Successful in 3s
QRun-IO/ci-policy: ci / fork-guard (push) Skipped
QRun-IO/ci-policy: ci / head-profile (push) Skipped
QRun-IO/ci-policy: ci / application-template-0 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (push) Skipped
QRun-IO/ci-policy: ci / node-9 (push) Skipped
QRun-IO/ci-policy: ci / node-8 (push) Skipped
QRun-IO/ci-policy: ci / node-10 (push) Skipped
Shared Java Maven CI with Docker / gate (push) Successful in 10s
QRun-IO/ci-policy: ci / android-0 (push) Skipped
QRun-IO/ci-policy: ci / not-enrolled (push) Skipped
QRun-IO/ci-policy: ci / original-mcp (push) Skipped
Shared QRun source version / version (push) Successful in 2m5s
QRun-IO/ci-policy: ci / java-docker-3-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (push) Skipped
QRun-IO/ci-policy: ci / gradle-1 (push) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (push) Successful in 4m26s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (push) Successful in 10s
QRun-IO/ci-policy: ci / java-maven-7 (push) Skipped
2026-11-03 21:42:29 +00:00
35731a101d ci: reconcile legacy release ancestry with canonical develop
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
Shared Java Maven CI with Docker / secrets (push) Successful in 13s
Shared Java Maven CI with Docker / verify (push) Successful in 5m8s
qrun-release / postpublish (push) Skipped
QRun-IO/ci-policy: ci / ci-result (pull_request) Successful in 4s
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-business (pull_request) Skipped
QRun-IO/ci-policy: ci / original-voyage (pull_request) Skipped
Release candidate / release-rc (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Successful in 12s
qrun-release / release (push) Successful in 5m24s
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / android-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-mcp (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 6s
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 4m33s
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Successful in 4m50s
Shared Java Maven CI with Docker / gate (push) Successful in 12s
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Successful in 14s
Preserve current develop CI configuration and SNAPSHOT revision; application source is unchanged. Reconcile the prior release ancestry so normal Gitea RC cuts can merge without obsolete CI conflicts.

Co-Authored-By: Claude <noreply@anthropic.com>

Co-Authored-By: Codex <noreply@openai.com>
2026-11-03 15:36:08 -06:00
james.maes 1836afce45 Merge pull request 'docs: record Forge prerequisite fix for release' (#38) from docs/forge-release-notes into develop
QRun-IO/ci-policy: ci / java-frontend-browser-5 (push) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (push) Skipped
QRun-IO/ci-policy: ci / source-config-14 (push) Skipped
QRun-IO/ci-policy: ci / original-voyage (push) Skipped
QRun-IO/ci-policy: native / dotnet-0 (push) Skipped
Shared Java Maven CI with Docker / secrets (push) Successful in 15s
QRun-IO/ci-policy: ci / java-core-2-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (push) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (push) Successful in 15s
QRun-IO/ci-policy: ci / java-docker-3 (push) Successful in 4m31s
Shared Java Maven CI with Docker / verify (push) Successful in 4m40s
QRun-IO/ci-policy: ci / ci-result (push) Successful in 5s
qrun-release / postpublish (push) Successful in 1m6s
QRun-IO/ci-policy: ci / fork-guard (push) Skipped
QRun-IO/ci-policy: ci / head-profile (push) Skipped
QRun-IO/ci-policy: ci / application-template-0 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (push) Skipped
QRun-IO/ci-policy: ci / node-9 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (push) Skipped
QRun-IO/ci-policy: ci / node-8 (push) Skipped
QRun-IO/ci-policy: ci / node-10 (push) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (push) Skipped
QRun-IO/ci-policy: ci / source-config-13 (push) Skipped
QRun-IO/ci-policy: ci / original-business (push) Skipped
QRun-IO/ci-policy: native / fork-deny (push) Skipped
QRun-IO/ci-policy: native / native-result (push) Successful in 5s
QRun-IO/ci-policy: ci / repository-policy (push) Skipped
qrun-release / release (push) Successful in 4m50s
QRun-IO/ci-policy: ci / gradle-1 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (push) Skipped
QRun-IO/ci-policy: ci / android-0 (push) Skipped
QRun-IO/ci-policy: ci / original-mcp (push) Skipped
QRun-IO/ci-policy: ci / not-enrolled (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (push) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (push) Successful in 4m19s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (push) Successful in 8s
Shared Java Maven CI with Docker / gate (push) Successful in 9s
Shared QRun source version / version (push) Successful in 1m5s
2026-11-03 21:24:29 +00:00
ccc93ea803 docs: record Forge prerequisite fix for release
Shared Java Maven CI with Docker / verify (push) Successful in 4m33s
qrun-release / postpublish (push) Skipped
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-voyage (pull_request) Skipped
QRun-IO/ci-policy: ci / original-business (pull_request) Skipped
Release candidate / release-rc (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / ci-result (pull_request) Successful in 4s
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
Shared Java Maven CI with Docker / secrets (push) Successful in 13s
qrun-release / release (push) Successful in 4m45s
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / android-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-mcp (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Successful in 12s
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 7s
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
Shared Java Maven CI with Docker / gate (push) Successful in 11s
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 4m16s
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Successful in 17s
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Successful in 5m3s
Co-Authored-By: Claude <noreply@anthropic.com>

Co-Authored-By: Codex <noreply@openai.com>
2026-11-03 15:15:54 -06:00
james.maes e7926cbb20 Merge pull request 'fix: reject private analyses without a read owner' (#37) from james.maes/fix-private-analysis-read-owner into develop
QRun-IO/ci-policy: ci / ci-result (push) Successful in 5s
QRun-IO/ci-policy: ci / java-frontend-browser-5 (push) Skipped
Shared Java Maven CI with Docker / verify (push) Successful in 4m34s
qrun-release / postpublish (push) Successful in 3m14s
QRun-IO/ci-policy: ci / node-playwright-11 (push) Skipped
QRun-IO/ci-policy: ci / source-config-14 (push) Skipped
QRun-IO/ci-policy: ci / original-voyage (push) Skipped
QRun-IO/ci-policy: native / dotnet-0 (push) Skipped
Shared Java Maven CI with Docker / secrets (push) Successful in 19s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (push) Successful in 21s
QRun-IO/ci-policy: ci / java-core-2-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3 (push) Successful in 6m6s
QRun-IO/ci-policy: ci / fork-guard (push) Skipped
QRun-IO/ci-policy: ci / head-profile (push) Skipped
QRun-IO/ci-policy: ci / application-template-0 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (push) Skipped
qrun-release / release (push) Successful in 4m51s
QRun-IO/ci-policy: ci / node-8 (push) Skipped
QRun-IO/ci-policy: ci / node-10 (push) Skipped
QRun-IO/ci-policy: ci / node-9 (push) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (push) Skipped
QRun-IO/ci-policy: ci / source-config-13 (push) Skipped
QRun-IO/ci-policy: ci / original-business (push) Skipped
QRun-IO/ci-policy: native / fork-deny (push) Skipped
QRun-IO/ci-policy: native / native-result (push) Successful in 8s
QRun-IO/ci-policy: ci / repository-policy (push) Skipped
QRun-IO/ci-policy: ci / gradle-1 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (push) Skipped
Shared Java Maven CI with Docker / gate (push) Successful in 12s
Shared QRun source version / version (push) Successful in 3m14s
QRun-IO/ci-policy: ci / android-0 (push) Skipped
QRun-IO/ci-policy: ci / original-mcp (push) Skipped
QRun-IO/ci-policy: ci / not-enrolled (push) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (push) Successful in 5m26s
QRun-IO/ci-policy: ci / java-docker-3-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (push) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (push) Successful in 12s
2026-11-03 21:01:41 +00:00
James MaesandCodex 2dcc073f51 fix: reject private analyses without a read owner
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-business (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
QRun-IO/ci-policy: ci / ci-result (pull_request) Successful in 7s
Release candidate / release-rc (pull_request) Skipped
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / android-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-mcp (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 5s
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Successful in 16s
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Successful in 15s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 4m22s
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Successful in 39m52s
Use an explicit true sharing check so nullable flags cannot pass SQL CHECK as UNKNOWN. Add a generated-schema SQL regression and document the forward host migration.

Co-Authored-By: Codex (GPT-6) <noreply@openai.com>
2026-11-03 12:27:26 -06:00
forge-recovery 36f726417c ci: enroll shared Gitea lifecycle
QRun-IO/ci-policy: ci / ci-result (push) Successful in 4s
qrun-release / postpublish (push) Failing after 10m34s
QRun-IO/ci-policy: ci / java-docker-3 (push) Successful in 25m54s
QRun-IO/ci-policy: ci / java-frontend-browser-5 (push) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (push) Skipped
QRun-IO/ci-policy: ci / source-config-14 (push) Skipped
QRun-IO/ci-policy: native / dotnet-0 (push) Skipped
Shared Java Maven CI with Docker / secrets (push) Successful in 15s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (push) Successful in 14s
QRun-IO/ci-policy: ci / java-core-2-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (push) Skipped
Shared Java Maven CI with Docker / verify (push) Successful in 6m17s
qrun-release / release (push) Successful in 35m51s
QRun-IO/ci-policy: ci / fork-guard (push) Skipped
QRun-IO/ci-policy: ci / head-profile (push) Skipped
QRun-IO/ci-policy: ci / application-template-0 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (push) Skipped
QRun-IO/ci-policy: ci / node-8 (push) Skipped
QRun-IO/ci-policy: ci / node-9 (push) Skipped
QRun-IO/ci-policy: ci / node-10 (push) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (push) Skipped
QRun-IO/ci-policy: ci / source-config-13 (push) Skipped
QRun-IO/ci-policy: native / fork-deny (push) Skipped
QRun-IO/ci-policy: native / native-result (push) Successful in 5s
QRun-IO/ci-policy: ci / repository-policy (push) Skipped
Shared Java Maven CI with Docker / gate (push) Successful in 18s
Shared QRun source version / version (push) Failing after 10m34s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (push) Successful in 21s
QRun-IO/ci-policy: ci / gradle-1 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (push) Skipped
QRun-IO/ci-policy: ci / android-0 (push) Skipped
QRun-IO/ci-policy: ci / original-mcp (push) Skipped
QRun-IO/ci-policy: ci / not-enrolled (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (push) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (push) Successful in 5m28s
2026-11-02 22:15:31 +00:00
forge-recovery f35f8130b7 ci: enroll shared Gitea lifecycle
QRun-IO/ci-policy: ci / java-frontend-browser-5 (push) Skipped
QRun-IO/ci-policy: ci / source-config-14 (push) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (push) Skipped
QRun-IO/ci-policy: native / dotnet-0 (push) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (push) Successful in 26s
QRun-IO/ci-policy: ci / java-core-2-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3 (push) Successful in 13m58s
QRun-IO/ci-policy: ci / ci-result (push) Successful in 9s
QRun-IO/ci-policy: ci / fork-guard (push) Skipped
QRun-IO/ci-policy: ci / head-profile (push) Skipped
QRun-IO/ci-policy: ci / application-template-0 (push) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (push) Skipped
QRun-IO/ci-policy: ci / node-8 (push) Skipped
QRun-IO/ci-policy: ci / node-9 (push) Skipped
QRun-IO/ci-policy: ci / node-10 (push) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (push) Skipped
QRun-IO/ci-policy: ci / source-config-13 (push) Skipped
QRun-IO/ci-policy: native / fork-deny (push) Skipped
QRun-IO/ci-policy: ci / repository-policy (push) Skipped
QRun-IO/ci-policy: native / native-result (push) Successful in 10s
QRun-IO/ci-policy: ci / gradle-1 (push) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (push) Skipped
QRun-IO/ci-policy: ci / android-0 (push) Skipped
QRun-IO/ci-policy: ci / original-mcp (push) Skipped
QRun-IO/ci-policy: ci / not-enrolled (push) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (push) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (push) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (push) Successful in 5m50s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (push) Successful in 19s
2026-11-02 21:31:38 +00:00
forge-recoveryandCodex 665c14bd6d ci: enroll shared Gitea release-candidate lifecycle
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
QRun-IO/ci-policy: ci / ci-result (pull_request) Successful in 5s
Release candidate / release-rc (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / android-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 5s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Successful in 15s
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Successful in 15s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 4m50s
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Successful in 1h0m49s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-02 20:15:44 +00:00
d218ad0f4f ci: add the isolated postpublish job to the QRun release caller
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
Shared Java Maven CI with Docker / secrets (push) Successful in 12s
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
Shared Java Maven CI with Docker / verify (push) Canceled after 0s
qrun-release / postpublish (push) Canceled after 0s
QRun-IO/ci-policy: ci / ci-result (pull_request) Successful in 4s
Release candidate / release-rc (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 5s
qrun-release / release (push) Canceled after 2h38m43s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Successful in 9s
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Successful in 12s
Shared Java Maven CI with Docker / gate (push) Canceled after 0s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 3m48s
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Successful in 2h49m11s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Codex <noreply@openai.com>
2026-11-02 15:48:40 +00:00
a398dbf55a ci: move the QRun release caller to the thin v2 contract
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / ci-result (pull_request) Failing after 4s
Shared Java Maven CI with Docker / secrets (push) Successful in 12s
Shared Java Maven CI with Docker / verify (push) Canceled after 0s
QRun-IO/ci-policy: ci / java-frontend-browser-3 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 7s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Canceled after 0s
QRun-IO/ci-policy: ci / java-docker-2 (pull_request) Canceled after 1h8m43s
qrun-release / release (push) Canceled after 1h8m56s
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-7 (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Successful in 17s
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Canceled after 0s
Shared Java Maven CI with Docker / gate (push) Canceled after 0s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Codex <noreply@openai.com>
2026-11-02 06:17:39 +00:00
forge-recoveryandCodex 59322faaad ci: add the identical QRun release caller
QRun-IO/ci-policy: ci / ci-result (pull_request) Successful in 3s
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-7 (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / gate (pull_request) Successful in 12s
QRun-IO/ci-policy: ci / java-docker-2 (pull_request) Successful in 49m5s
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-3 (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / verify (pull_request) Successful in 4m30s
QRun-IO/ci-policy: ci / java-maven-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-8 (pull_request) Skipped
QRun-IO/ci-policy: Shared Java Maven CI with Docker / secrets (pull_request) Successful in 16s
Co-Authored-By: Codex <noreply@openai.com>
2026-11-02 04:10:12 +00:00
james.maesandCodex 368d2c0e3a ci: adopt managed orb 0.8 patch track (#31)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 16:04:08 -05:00
james.maesandCodex 68067df16b ci: adopt shared orb 0.7.18 (#30)
* ci: adopt shared orb 0.7.17

Co-Authored-By: Codex <noreply@openai.com>

* ci: adopt corrected orb bootstrap 0.7.18

Co-Authored-By: Codex <noreply@openai.com>

---------

Co-authored-by: Codex <noreply@openai.com>
2026-10-21 14:40:55 -05:00
james.maesandCodex 8cc13ff7e7 ci: centralize release branch verification and workflows (#29)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 12:39:01 -05:00
james.maesandCodex 6a520e5452 ci: use the shared branch-aware CodeQL worker (#28)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 10:46:49 -05:00
james.maesandCodex b1ede9f887 ci: adopt central orb 0.7.12 and stable gates (#26)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 08:56:56 -05:00
james.maesandCodex 81552784e9 ci: centralize rc release completion in qqq orb (#25)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 02:26:29 -05:00
james.maesandCodex a68d557fb2 ci: adopt shared orb 0.7.11 (#24)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 01:01:55 -05:00
james.maes 36527b06ff Merge pull request #23 from QRun-IO/feature/central-ci
ci: adopt shared QQQ orb standard
2026-10-20 18:57:32 -05:00
james.maesandCodex 7c78003765 ci: adopt verified central QQQ orb 0.7.3
Co-Authored-By: Codex <noreply@openai.com>
2026-10-20 18:52:18 -05:00
CircleCI 2b4b2c48e5 Bump version to 0.1.0-RC.6 [skip ci] 2026-10-16 18:46:07 +00:00
james.maesandClaude Opus 5.5 e82960ac52 Merge develop into release/0.1 for 0.1.0-RC.6 (#19 schedules and watches run as a service principal, QQQ RC.19)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:39:16 -05:00
james.maes ce127037e4 Merge pull request #19 from QRun-IO/feature/service-principal
fix(schedules): schedules and watches run as the data-analysis service principal
2026-10-16 13:33:34 -05:00
james.maesandClaude Opus 5.5 20545be7fc build: QQQ 4.1.0-RC.19
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:19:12 -05:00
CircleCI 16b639ce40 Bump version to 0.1.0-RC.5 [skip ci] 2026-10-16 16:01:42 +00:00
github-actions[bot] 2339aea28c Merge develop into release/0.1 for the next 0.1.0 RC 2026-10-16 15:58:10 +00:00
james.maes 96d2e48e47 Merge pull request #20 from QRun-IO/feature/data-analysis-business-home
feat(home): move Setup to admin and omit unpermitted home content
2026-10-16 10:19:27 -05:00
james.maesandClaude Sonnet 5.5 1d2c2b0029 feat(home): move Setup to admin and omit unpermitted home content
The Data Analysis home showed the engine Setup card (max rows, sampling,
cache, scheduler state) to every SAVED_READ user, and rendered
"Unavailable: READ permission required." shells for unreadable groups.

- dataAnalysisSetup is off the home widget list; it stays registered, gated
  to data_analysis.admin with DenyBehavior.HIDDEN. Hosts place
  DataAnalysisQBitProducer.SYSTEM_WIDGETS on their Admin area.
- Each home data widget requires READ on its table and is omitted from
  metadata otherwise.
- Overview groups the user cannot read are left out of the payload; no
  "Unavailable" text remains on the home.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-16 09:18:26 -05:00
james.maesandClaude Opus 5.5 21671b3df3 fix(schedules): run schedules and watches as the data-analysis service principal
The self-made data-analysis-scheduler session is rejected under OAuth2,
so every scheduled run failed. With the host's principal declared,
inventory runs as it and owner/recipient runs go on their behalf through
it (current access intersected). Undeclared: unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 08:27:23 -05:00
james.maes 9d1d712040 Merge pull request #18 from QRun-IO/ci/release-rc-secrets-inherit
ci(release-rc): pass secrets so the shared workflow can sign the RC tag
2026-10-16 08:03:37 -05:00
CircleCI 80e86fd207 Bump version to 0.1.0-RC.4 [skip ci] 2026-10-15 21:25:09 +00:00
james.maesandClaude Opus 5.5 2c1fa83cfd ci(release-rc): pass secrets to the shared workflow so it can sign the RC tag
QRun-IO/.github#2 adds a tag-and-release job that signs vX with the
QRUN_TAG_SIGNING_KEY secret after Maven Central confirms the artifact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:19:18 -05:00
james.maesandClaude Opus 5.5 666020b5b9 Merge develop into release/0.1 for 0.1.0-RC.4 (#17 UI API 1.6.0 extension, QQQ RC.15)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:18:44 -05:00
james.maes 25d03c1514 Merge pull request #17 from QRun-IO/feature/ui-api-1.6
feat(ui-api): extension for QQQ UI API 1.6.0 (operationIds, BasicErrorResponseV1, QQQ 4.1.0-RC.15)
2026-10-15 16:12:58 -05:00
james.maesandClaude Opus 5.5 442eb4398c chore: target QQQ 4.1.0-RC.15 (UI API 1.6.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:27:05 -05:00
james.maesandClaude Opus 5.5 3aa728d88a feat(ui-api): extension for QQQ UI API 1.6.0 (operationIds, BasicErrorResponseV1, QQQ 4.1.0-RC.14)
Regenerated against UI API 1.6.0: every operation has an operationId and
the standard error responses (BasicErrorResponseV1: error, code, message,
fieldErrors, traceId); the extension's own error schema is kept but
deprecated; hand-written error bodies go through QJavalinUtils so they carry
code/message/traceId. Extension MINOR bumped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 11:43:37 -05:00
james.maes 51ab908b11 Merge pull request #16 from QRun-IO/fix/producer-version-from-build
fix: qbit metadata version comes from the build
2026-10-15 01:42:56 -05:00
james.maesandClaude Opus 5.5 3474b0c188 fix: the qbit metadata version comes from the build, not a hardcoded constant
The producer read a literal version, so released artifacts reported a stale
or -SNAPSHOT version. qbit-data-analysis.properties (version=${project.version}) is
Maven-filtered and the producer loads it; tests assert producer == bundle ==
artifact version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 01:33:59 -05:00
james.maes b12cadfc75 Merge pull request #15 from QRun-IO/fix/help-bundle-version
fix(help): help bundle version comes from the build, not a hardcoded SNAPSHOT
2026-10-14 22:37:20 -05:00
james.maesandClaude Opus 5.5 6065d2d1c1 fix(help): the help bundle carries the artifact version (Maven-filtered) instead of a hardcoded SNAPSHOT
On release branches the bundle's version and the producer's differed, so the
bundle test that asserts they match failed, and released bundles recorded
SNAPSHOT as their provenance. help/*.yaml is now filtered:
version: ${project.version}.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 22:06:05 -05:00
CircleCI 0487f3ac40 Bump version to 0.1.0-RC.3 [skip ci] 2026-10-15 02:26:42 +00:00
james.maesandClaude Opus 5.5 546196af6d Merge develop into release/0.1 for 0.1.0-RC.3 (#13 help bundle)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 21:20:46 -05:00
james.maes 0e0cc0b83d Merge pull request #13 from QRun-IO/feature/help-bundle
feat(help): qbit-data-analysis help bundle via QQQ help bundles, with coverage gate
2026-10-14 20:45:30 -05:00
james.maesandClaude Opus 5.5 73de290a93 feat(help): ship the qbit-data-analysis help bundle through QQQ help bundles, with coverage gate
Host-neutral help (deployment-specific facts removed), registered with
HelpBundles, gated by HelpBundleAssertions. QQQ 4.1.0-RC.7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:27:13 -05:00
CircleCI eeec501834 Bump version to 0.1.0-RC.2 [skip ci] 2026-10-14 23:02:37 +00:00
james.maesandClaude Opus 5.5 a9b4f076f9 Merge develop into release/0.1 for 0.1.0-RC.2 (#12 tables work)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:57:17 -05:00
james.maes e11e1464cd Merge pull request #12 from QRun-IO/feature/tables-populated-defaults
feat: Create rows for analyzable tables, Setup card and table help
2026-10-14 17:47:00 -05:00
james.maesandClaude Opus 5.5 bab162e77c fix: accurate Result cache line, count-only summary, action visible only with settings insert
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:43:27 -05:00
james.maesandClaude Opus 5.5 cdce36d119 chore: well-formed STAND-IN marker for the help applier
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:30:33 -05:00
james.maesandClaude Opus 5.5 04d3c01cf3 feat: Create rows for analyzable tables, Setup card and table help so Analysis Settings is never a mystery
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:23:24 -05:00
james.maes 69800f755c Merge pull request #11 from QRun-IO/feature/orb-0.6.9
ci: qqq-orb 0.6.9 (refresh SNAPSHOT dependencies)
2026-10-14 10:45:55 -05:00
james.maesandClaude Opus 5.5 f8d1ed787c ci: qqq-orb 0.6.9 (refresh SNAPSHOT dependencies)
Moves qqq-orb@0.6.8 to qqq-orb@0.6.9, which passes --update-snapshots so cached SNAPSHOT dependencies are re-checked on every build (QRun-IO/qqq-orb#22).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:06:44 -05:00
CircleCI de205edfeb Bump version to 0.1.0-RC.1 [skip ci] 2026-10-14 12:20:07 +00:00
james.maes 8bda02bc4a Merge pull request #10 from QRun-IO/feature/saved
feat(saved): saved, shared, starred, scheduled and widget analyses, export, SQL handoff
2026-10-14 07:10:01 -05:00
james.maes 93ebd64fbe Merge pull request #9 from QRun-IO/feature/watches
feat(watches): anomaly watches through the alerts SPI, contingent pickers
2026-10-14 07:09:47 -05:00
james.maes a157f18edc Merge pull request #8 from QRun-IO/feature/compare
feat(compare): compare, distribution shift, correlation, scatter and crosstabs
2026-10-14 07:09:35 -05:00
james.maes 894cc98d9b Merge pull request #6 from QRun-IO/feature/pivot
feat(pivot): pivot / group-by explorer and the field-access resolver seam
2026-10-14 07:09:21 -05:00
james.maes 2c52814e33 Merge pull request #5 from QRun-IO/feature/profile-endpoints
feat(api): /qqq/v1 data-analysis extension, core pushdown backend, analyze permission
2026-10-14 07:09:09 -05:00
james.maesandClaude Opus 5.5 69154de566 fix(tables): a new saved analysis, star, watch or run belongs to the inserting user
Found driving the Next UI against the sample app: the UI cannot send the
user's id, and core checks required fields and record locks before the
customizers run. An insert-only field behavior fills empty owner/user
fields with the session user (never on update, so an administrator's
partial edit cannot take ownership); naming another owner is still
refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:49:18 -05:00
james.maes b3c8a0412a Merge remote-tracking branch 'origin/feature/watches' into feature/saved 2026-10-13 22:26:08 -05:00
james.maes 191e96b094 Merge remote-tracking branch 'origin/feature/compare' into feature/watches 2026-10-13 22:23:43 -05:00
james.maes 642401e633 Merge remote-tracking branch 'origin/feature/pivot' into feature/compare 2026-10-13 22:19:46 -05:00
james.maes 35901fe71a Merge remote-tracking branch 'origin/feature/profile-endpoints' into feature/pivot 2026-10-13 22:17:27 -05:00
james.maesandClaude Opus 5.5 1641b32296 fix(stats): pool sparse crosstab categories instead of refusing the test
Chi-square now pools the smallest category into Other one at a time until
every expected count is at least five (rows too, for independence), so a
crosstab with a single-record row still gets a valid test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:14:14 -05:00
james.maesandClaude Opus 5.5 d2c9871d98 feat(saved): saved, shared, starred, scheduled and widget analyses, export, SQL handoff
Extension 1.4.0: saved analyses of every kind re-run as the viewer
(fields they cannot analyze are dropped), owner-or-shared READ through
core record locks with owner-only writes (and a database CHECK so a
private row can never lose its read owner), personal stars, schedules
that run as the owner and mail only recipients who could run the analysis
themselves, CSV/XLSX export, the SQL Workbench handoff, an analysis
dashboard widget, and an Analyses home built from standard widgets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 21:23:23 -05:00
james.maesandClaude Opus 5.5 43c7571864 feat(watches): anomaly watches through the alerts SPI, contingent pickers
Watches evaluate a metric per time bucket as their owner (SPIKE, DROP,
OUT_OF_RANGE, NEW_CATEGORY, NULL_RATE_CREEP with robust baselines) on a
hidden scheduled process, raise and resolve data.analysis.anomaly alerts
through QAlerts, and offer Evaluate now / Enable / Disable record actions
and a preview endpoint (extension 1.3.0). Pivot and crosstab labels are
human (Yes/No, Average Annual Salary). Contingent fields: a watch's saved
analysis depends on its table, table names use the core tables PVS, and
analyzable/excluded fields pick from the chosen table's fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:34:19 -05:00
james.maesandClaude Opus 5.5 20b8223ce8 feat(compare): compare, distribution shift, correlation, scatter and crosstabs
Extension 1.2.0: compare two filters field by field with deltas and
significance (two-proportion z, Welch's t, chi-square with validity
rules and plain sentences), distribution shift over time with PSI, a
pushed-down Pearson correlation matrix with sampled scatter and trend,
and crosstabs with chi-square and Cramer's V. Pure-Java statistics
checked against scipy reference values; the privacy guard, field access
and drills apply as for profiles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:37:03 -05:00
james.maesandClaude Opus 5.5 d591d3d7e8 feat(pivot): pivot / group-by explorer and the field-access resolver seam
POST /tables/{table}/pivot (extension 1.1.0): up to 3 row and 2 column
dimensions with date buckets or nice numeric bins, fields from to-one
exposed joins, count/sum/avg/min/max/distinct/percentile measures,
totals, Other-merging by top-N, the privacy guard and a drill per cell.
FieldAnalysisAccessResolver maps fields to FULL / EXACT_MATCH_ONLY /
NONE (core secured-data tiers when present, FieldSecurityLock otherwise);
only FULL fields are analyzable, drills never name others, and exact-run
cache keys include the user's field-access fingerprint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 18:56:37 -05:00
130 changed files with 19623 additions and 403 deletions

No files matched your search

+11 -57
View File
@@ -1,60 +1,14 @@
version: 2.1
setup: true
orbs:
qqq-orb: kingsrook/qqq-orb@0.6.8
commands:
configure-package-install:
steps:
- run:
name: Keep package installation unattended
command: |
# These build machines are discarded after the job.
sudo install -d /etc/needrestart/conf.d
printf '%s\n' '$nrconf{restart} = "l";' | sudo tee /etc/needrestart/conf.d/99-qqq-ci.conf >/dev/null
qqq-orb: kingsrook/qqq-orb@0.8
workflows:
test_only:
jobs:
- qqq-orb/mvn_test_only:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
filters:
branches:
ignore: /(develop|release\/.*)/
publish_snapshot:
jobs:
- qqq-orb/mvn_publish:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
branch_type: snapshot
filters:
branches:
only: [develop]
publish_release_candidate:
jobs:
- qqq-orb/mvn_publish:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
branch_type: release_candidate
filters:
branches:
only: [/release\/.*/]
publish_release:
jobs:
- qqq-orb/mvn_publish:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
branch_type: release
filters:
branches:
ignore: /.*/
tags:
only: [/^v\d+\.\d+\.\d+$/]
setup:
jobs:
- qqq-orb/generate_pipeline:
orb_version: '0.8'
filters:
branches:
ignore: automation/qbit-rc-pending
tags:
only: /^v\d+\.\d+\.\d+$/
+7
View File
@@ -0,0 +1,7 @@
name: build
on:
push:
jobs:
maven:
uses: self:KofTwentyTwo/ci-workflows/.gitea/workflows/maven.yaml@v1
secrets: inherit
+23
View File
@@ -0,0 +1,23 @@
name: CodeQL
'on':
push:
branches:
- main
- develop
- release/**
- hotfix/**
pull_request: {}
schedule:
- cron: 41 16 * * 0
workflow_dispatch: {}
permissions:
contents: read
actions: read
security-events: write
packages: read
concurrency:
group: codeql-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
analyze:
uses: QRun-IO/qqq-orb/.github/workflows/qbit-codeql.yml@c288a8864fe9054f68410e1d78f5863aea4c4d22
+62 -13
View File
@@ -1,25 +1,74 @@
# 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:
'on':
workflow_dispatch:
inputs:
dry_run:
description: Print the plan without merging or creating branches
description: Plan a cut without changing release state
type: boolean
default: false
finalize:
description: Retry finalization of an existing cut; do not cut another RC
type: boolean
default: false
recover:
description: Recover the same published RC after a deployment timeout; never
reupload
type: boolean
default: false
circle_build:
description: Original Circle publisher build number (recovery only)
type: string
default: ''
merge_sha:
description: Existing cut merge_sha (finalize retry only)
type: string
default: ''
bump_sha:
description: Existing cut bump_sha (finalize retry only)
type: string
default: ''
branch:
description: Existing cut branch (finalize retry only)
type: string
default: ''
version:
description: Existing cut version (finalize retry only)
type: string
default: ''
pull_request:
types: [closed]
branches: [develop]
types:
- closed
branches:
- develop
repository_dispatch:
types:
- qbit-rc-published
permissions:
contents: write
actions: read
checks: read
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
if: github.event_name == 'workflow_dispatch' || github.event_name == 'repository_dispatch'
|| (github.event_name == 'pull_request' && github.event.pull_request.merged
== true && github.event.pull_request.base.ref == 'develop' && contains(github.event.pull_request.labels.*.name,
'release:rc'))
uses: QRun-IO/qqq-orb/.github/workflows/qbit-release-rc.yml@cc30f599e63c8e41629c99d23395bac1adb8bc44
with:
dry_run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
dry_run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false
}}
finalize: ${{ github.event_name == 'repository_dispatch' || (github.event_name
== 'workflow_dispatch' && inputs.finalize) }}
recover: ${{ github.event_name == 'workflow_dispatch' && inputs.recover || false
}}
circle_build: ${{ github.event_name == 'workflow_dispatch' && inputs.circle_build
|| '' }}
merge_sha: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.merge_sha
|| inputs.merge_sha || '' }}
bump_sha: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.bump_sha
|| inputs.bump_sha || '' }}
branch: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.branch
|| inputs.branch || '' }}
version: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.version
|| inputs.version || '' }}
secrets: inherit
+16
View File
@@ -0,0 +1,16 @@
profile: qbit
orb_version: '0.8'
default_branch: develop
java_version: '21'
browsers: true
api_checks: false
docs_only: false
release_on_main: false
release_tag_policy: stable
test_branch_policy: non-release
publish:
snapshot: true
release_candidate: true
release: true
asciidoc: false
release_completion: true
+50 -2
View File
@@ -4,17 +4,65 @@ Following [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and [Semantic
## [Unreleased]
### Changed
- Reconciled legacy release-branch history with the current Gitea CI while retaining the develop SNAPSHOT revision, so normal RC cuts can merge cleanly.
### Fixed
- Fixed HTTP 500 ("Unsupported class ...NowWithOffset for converting to Instant") from every analysis whose filter holds a relative date (a filter expression such as "now minus one day" or "this month") on a date or date-time field: the pivot, profiles, comparisons and the stand-in backend converted filter values to the field's type before querying and did not expect an expression. Expressions are now left for core to evaluate when the query runs, so "printed in the last day" works from the Analyses screens, over the UI API (`POST /qbit/data-analysis/tables/{table}/pivot`) and in a saved or scheduled analysis, where it means the last day on every run. Drill-through filters carry the expression.
- Reject saved analyses with a NULL or false shared flag and no read owner in the generated schema. Existing hosts must apply the documented constraint correction through a new migration.
- Scheduled analyses and watches work under OAuth2. When the host declares the `data-analysis` service principal (QQQ service identities, `DataAnalysisQBitConfig.withServicePrincipal`), schedule and watch inventory runs as that principal, and owner and recipient runs go on their behalf through it: their current access intersected with the principal's. The self-made `data-analysis-scheduler` session was rejected under OAuth2 (`Invalid session in request` on every `data_analysis_run_schedules` run). With no principal declared, behavior is unchanged. Needs the QQQ release with service identities (qqq#1255, #1256).
- QBit metadata now reports the Maven artifact version, including release versions, from a filtered build resource.
- The Data Analysis home no longer shows the engine Setup card or "Unavailable: READ permission required." shells. Setup is admin-only (hidden from everyone else) and off the home; hosts place `DataAnalysisQBitProducer.SYSTEM_WIDGETS` on their Admin area. Home widgets the user cannot read are omitted from metadata, and unreadable groups are left out of the overview.
### Added
- `data-analysis` UI API extension 1.0.0: seven session-bound profile, capability, distinct-value, duplicate and run endpoints, typed schemas and a checked OpenAPI fragment.
- Complete host-neutral in-app help bundle with live metadata references and a core help coverage gate.
- Analysis Settings table action **Create rows for analyzable tables**: writes the effective settings as editable `data_analysis_table_config` rows (insert-only, no change in behavior).
- Setup card on the Analyses home (settings, result cache, saved analyses, watches, schedules).
- Help bundle `help/qbit-data-analysis.yaml`: every table says what it is for and how its rows get created.
- `DataAnalysisTablesGuardrailTest` and `TableConfigDefaultsTest` (including a test that a settings row's `cache_ttl_minutes` changes result caching).
- Phase f saved execution for all seven kinds, core owner-or-shared READ with owner-only WRITE, typed definition validation and viewer-specific field reduction.
- Idempotent personal star endpoints and visible saved list; transient viewer runs, core CSV/XLSX downloads and QueryStat-backed SQL Workbench handoff.
- Five-minute owner-session schedule runner, per-recipient FULL access checks and record-scoped reruns, core messaging with attachments, explicit failure statuses/alerts, timezone/weekly/monthly/cron timing and streamed ETL Send now.
- Standard statistics/chart/table dashboard widgets, linked saved analysis widgets and real home rows with narrow tables and honest empty states.
- Extension 1.4.0, seven new assistant-discoverable endpoints, regenerated OpenAPI and memory/H2/HTTP/export/email/security regression coverage.
- Migration requirement: backfill saved `read_owner_user_id` before enabling shared reads and widen schedule `last_status` to TEXT. Stock core EMAIL attachment limitations fail visibly; supported messaging providers receive full attachments.
- Phase e anomaly watches: owner-locked configuration, validated metrics/detector parameters, complete calendar buckets, five pure detectors, and scheduled evaluation through owner sessions.
- Core alerts SPI type `data.analysis.anomaly` (core disallows the spec's underscore), stable watch keys, relative drill links, raise/recovery transitions, and persisted outcomes without an alerts implementation.
- Standard streamed ETL Evaluate now / Enable / Disable record actions and firing-first linked watches on the Analyses home.
- Read-only watch preview HTTP endpoint, semantic chart/baseline annotations, extension 1.3.0 and regenerated OpenAPI fragment.
- Detector edge cases, real-row owner/security/alert transition tests, calendar boundary and action tests, and HTTP preview coverage.
- Phase d compare, shift, correlation, scatter and crosstab service operations and HTTP specs; extension version 1.2.0 with typed `DataAnalysis*V1` schemas and regenerated OpenAPI.
- Pure-Java two-proportion, Welch, chi-square/Cramer V, PSI and Pearson statistics, including regularized incomplete beta/gamma and independent SciPy references.
- Core-pushed numeric moments and batched correlations, sample trend lines, calendar distribution shifts, category pooling, privacy suppression and exact count drills.
- Shared memory/H2/PostgreSQL relationship contracts, forced core streamed-fallback checks, batching checks and HTTP authorization/serialization/drill tests.
- Phase c pivot backend and `POST /qbit/data-analysis/tables/{table}/pivot`, extension version 1.1.0, typed schemas and regenerated OpenAPI fragment.
- Row/column dimensions, calendar/numeric buckets, seven measure operators, sparse cells, exact Other recomputation, totals, privacy suppression and count-equivalent drills.
- Exposed-join dimensions and measures with READ/FULL checks; filter-only drills for to-one paths and explicit null-drill warnings for to-many paths whose joined-row counts can exceed record counts.
- Configurable field-access resolver, cached reflective core tier bridge with legacy fallback, FULL-only capabilities/selections/labels, generated-drill protection and field-access cache fingerprints.
- Shared memory/H2/PostgreSQL pivot contracts, HTTP drills and errors, reflective resolver/fallback and tier-change cache tests.
- Session-bound profile, capability, distinct-value, duplicate and run endpoints, typed schemas and a checked OpenAPI fragment (introduced in extension 1.0.0).
- Core table-feature permission registration and capability-directed aggregate pushdown, with native sampling and portable streamed fallbacks.
- HTTP authorization, drill-to-core-count round trips, async polling, served OpenAPI and assistant discovery tests; H2 streamed and native-compatibility contract variants.
### Changed
- UI API extension data-analysis 1.5.0 (requires QQQ 4.1.0-RC.15, UI API 1.6.0): operationIds, standard error responses with BasicErrorResponseV1, extension tags, contract validation for operationIds and schema references, and HTTP error envelope regression assertions.
- Pin QQQ 4.1.0-RC.7 and replace the temporary help loader with core bundle registration and startup sync.
- Boolean pivot/crosstab headers now say Yes / No / (Blank). Pivot measures use human labels such as Count, Average Amount, Sum of Amount, Distinct Email, Median Amount and 90th percentile of Amount.
- Watch DDL includes owner/date fields and last value/message; existing databases need an owner/date backfill before enabling watches.
- Scalable estimates sample each native aggregate without primary-key IN lists, scale counts using observed sample sizes, retain exact population totals and unscaled ratios, and drill over the full population. Portable estimates use one primary-key boundary and report unscaled prefix counts.
- Target QQQ 4.1.0-RC.6; local verification uses `-Dqqq.snapshot.version=4.1.0-DATAANALYSIS-SNAPSHOT`.
- Empty-string and temporal drills round-trip through core HTTP filter interpretation.
### Previously added
+155 -12
View File
@@ -4,13 +4,13 @@ Statistical analysis and data dives on any QQQ table, filter or saved view: prof
## What works now
The host API provides column and table profiles, distinct-value pages, duplicate groups, drill-through filters, effective per-table configuration, privacy suppression, and asynchronous exact runs with a persistent per-user cache. Metadata, six visible tables, owner locks, PostgreSQL DDL generation and the Analyses home are also available.
The host API provides column and table profiles, pivots, comparisons, distribution shifts, correlations, scatter samples, crosstabs, distinct-value pages, duplicate groups, drill-through filters, privacy suppression, and asynchronous exact profile runs with a persistent per-user cache. Metadata, six visible tables, owner locks, PostgreSQL DDL generation and the Analyses home are also available.
Seven HTTP operations are available under `/qqq/v1/qbit/data-analysis`; the Analyze UI is a later phase. Pivots, comparisons, anomalies, saved-analysis execution, scheduling and exports remain later phases.
Twenty-one HTTP operations are available under `/qqq/v1/qbit/data-analysis` (extension **1.4.0**). Saved execution, shared reads, personal stars, scheduled email, CSV/XLSX exports, SQL Workbench handoff and standard dashboard widgets are implemented. The separate Analyze/pivot/relationship frontend remains outside this repository.
## Requirements
- Java 21; QQQ **4.1.0-RC.6+**.
- Java 21; QQQ **4.1.0-RC.7+**.
- A configured QQQ backend for the qbit tables and authenticated sessions with permissions and security keys.
- Core aggregate and table-feature permission APIs ([qqq#1139](https://github.com/QRun-IO/qqq/pull/1139)) and the UI API extension point ([qqq#1128](https://github.com/QRun-IO/qqq/pull/1128)). Middleware Javalin remains optional; the producer registers endpoints only when it is present.
@@ -32,6 +32,16 @@ new DataAnalysisQBitProducer()
The producer installs metadata into the instance. It scans only `com.kingsrook.qbits.dataanalysis.metadata`; helpers and renderers are not scanned as component producers. Set `withParentAppName("admin")` to nest the app under an existing parent.
## Starter defaults and setup
Data Analysis ships no SQL seed: `data_analysis_table_config` depends on which tables the host has and on the code configuration (`defaultMaxRows`, `tableDefaults`, `includeTables`, `excludeTables` and the other defaults), so its rows are computed at run time.
- With no rows, every analyzable table is on with the configured defaults. That is a complete, working setup.
- Open Analysis Settings and run the table action **Create rows for analyzable tables**. It adds one row per analyzable table that has none, holding the settings that already apply (table defaults over global defaults). Nothing changes until you edit a row. It is insert-only: it never touches an existing row, and running it again only adds rows for tables added since.
- Rows pin their values: after a row exists, later changes to the code defaults do not reach that table, edit the row instead. `cache_ttl_minutes` is what the exact-run result cache uses for that table (0 turns caching off); `TableConfigDefaultsTest` proves a row changes caching.
- The **Setup** card on the Analyses home lists settings, result cache, saved analyses, watches and schedules with their state and next step, using the same resolution the runtime uses.
- Every table has help (shown when it is empty) that says how its rows get created. Saved analyses, stars, schedules, watches and runs are user content or logs and start empty by design.
## Tables
QQQ names and physical SQL table names are identical. `backendName` in configuration identifies the backend connection; it is not a SQL table name. All tables have `id`, `createDate` and `modifyDate`; SQL columns use inferred snake_case names.
@@ -47,6 +57,8 @@ QQQ names and physical SQL table names are identical. `backendName` in configura
Only Saved Analyses, Watches, Analysis Settings and Analysis Runs appear in navigation. Schedules, stars and linked watches appear on saved records. Enum PVS cover analysis kind, chart kind, detector, watch state, run status, schedule frequency and format. JSON definitions and results are stored as text. Profile, distinct-value and duplicate requests have typed Java contracts and are validated by the facade.
The four `table_name` fields use core's `tables` possible-value source; an existing host source is preserved. A watch's `saved_id` options are filtered by its selected `table_name`. Analysis Settings' `analyzable_fields` and `excluded_fields` use a custom field picker scoped to the selected table. Core currently has no multi-select PVS field, so these settings use a single PVS with comma-separated TEXT storage (for example, `amount,status`); the configuration resolver continues to parse those lists. Explicit dependency metadata awaits core's `possibleValueSourceDependsOn` support.
## Permissions
| Permission | Grants |
@@ -64,7 +76,7 @@ Only Saved Analyses, Watches, Analysis Settings and Analysis Runs appear in navi
Every engine operation and home count runs under the current `QContext` session with `PermissionEnforcement.ENFORCE`. A denied section explains the missing permission instead of showing zero. Mine and starred counts explicitly filter the current user even for administrators. Shared counts include only readable shared rows. Stars pointing at unreadable or deleted saved analyses do not count. Run counts cover starts within the last seven days, excluding future rows.
Saved analyses have a READ_AND_WRITE lock on `owner_user_id`; stars and runs have locks on `user_id`. Schedules inherit the saved analysis owner's lock through their join. Null owners are denied. The host's authentication/session adapter must supply:
Saved analyses have a WRITE lock on `owner_user_id` and a separate READ lock on the hidden `read_owner_user_id` projection. Core pre-insert/update customizers set that projection to the owner for private rows and null for shared rows; the READ lock allows null. This expresses **owner OR shared READ**, while core retains owner-only writes and administrator all-access keys. Stars and runs have locks on `user_id`. Schedules inherit the saved analysis owner's lock through their join. Null owners are denied. The host's authentication/session adapter must supply:
```java
session.withSecurityKeyValue("data_analysis_user", session.getUser().getIdReference());
@@ -75,7 +87,26 @@ session.withPermission("data_analysis.admin")
QQQ permissions and security-key values are separate. An admin permission alone does not bypass record locks. User-id fields must use the same stable string identity as `QUser.idReference`.
**Shared READ is deliberately restricted in this scaffold.** The ordinary owner lock does not express owner OR shared while keeping writes owner-only, so setting `shared=true` currently does not expose a saved analysis to other users. Phase f will introduce separate read and write policies: reads permit owner OR shared only after checking `data_analysis.saved.read`; writes retain owner/admin checks. Query, get, count, joins, child lists and exports will receive cross-user regression tests before enabling shared READ. Collaboration sharing and favorites (§7.3, qqq#1136) will then replace the local sharing/star contracts. Shared analyses must always execute as their viewer.
**Shared READ is enabled through core record locks.** A viewer still needs `data_analysis.saved.read`. Query/get/count, standard CRUD, saved runs, lists and exports use core enforcement. Shared viewers cannot edit, delete, change ownership, or schedule another owner's analysis. No custom query filter grants access. Sharing exposes the saved definition and metadata, not the owner's data: every run computes under the viewer's source-table READ/Analyze permissions and field policy. There is no per-recipient/group sharing or access-request workflow yet; collaboration's sharing contract ([qqq#1136](https://github.com/QRun-IO/qqq/issues/1136)) will replace the local flag. Stars move to `collaboration_favorite` when collaboration ships.
**Existing databases must migrate before enabling the new metadata.** A missing/null read-owner projection would make an old private row readable. Apply this through the host's migration system while writes are stopped, before deploying this version:
```sql
ALTER TABLE data_analysis_saved ADD COLUMN IF NOT EXISTS read_owner_user_id VARCHAR(250);
UPDATE data_analysis_saved
SET read_owner_user_id = CASE WHEN shared IS TRUE THEN NULL ELSE owner_user_id END;
ALTER TABLE data_analysis_schedule ALTER COLUMN last_status TYPE TEXT;
```
The metadata-generated create script includes these fields for new installations; it does not migrate existing databases. Fix older placeholder definitions (such as `{}` for a column profile) to valid typed requests. Edit existing enabled schedules through core CRUD to validate recipients and initialize `next_run_at`.
Installations created with the earlier generated constraint also need a new host migration after ensuring the read-owner projection is populated. SQL CHECK constraints accept UNKNOWN, so `shared = TRUE` allowed a null shared flag and null read owner. Only explicit sharing may omit the read owner:
```sql
ALTER TABLE data_analysis_saved
DROP CONSTRAINT IF EXISTS ck_data_analysis_saved_read_owner,
ADD CONSTRAINT ck_data_analysis_saved_read_owner CHECK (shared IS TRUE OR read_owner_user_id IS NOT NULL);
```
Minimum group size defaults to 0 (off). Hosts should set it for personal-data tables. Groups, bins and distinct listings below N are merged into an Other row with no value or drill. Min/max, percentiles, mean and standard deviation are suppressed when the assessed population is below N. Outlier listings and their count's drill are removed whenever the guard is enabled. The guard runs before chart construction and before `result_json` is stored.
@@ -138,7 +169,7 @@ Count drills combine an untouched copy of the request filter with their producin
## HTTP endpoints
Extension `data-analysis` version **1.0.0**, prefix `/qbit/data-analysis` inside `/qqq/v1`:
Extension `data-analysis` version **1.3.0**, prefix `/qbit/data-analysis` inside `/qqq/v1`:
| Method | Path after `/qqq/v1` | Body or purpose |
| --- | --- | --- |
@@ -147,19 +178,40 @@ Extension `data-analysis` version **1.0.0**, prefix `/qbit/data-analysis` inside
| POST | `/qbit/data-analysis/tables/{table}/distinct-values` | `{fieldName, filter, page, pageSize, search}` |
| POST | `/qbit/data-analysis/tables/{table}/table-profile` | `{filter, fields}` |
| POST | `/qbit/data-analysis/tables/{table}/duplicates` | `{fields, filter, limit}`; default limit 50, maximum 500 |
| POST | `/qbit/data-analysis/tables/{table}/pivot` | `{rows, columns, values, filter, showTotals, limitGroups}`; 1–3 row dimensions, 0–2 column dimensions, 1–6 measures |
| POST | `/qbit/data-analysis/tables/{table}/compare` | `{filterA, filterB, labelA, labelB, fields}`; null filter selects the whole permitted table |
| POST | `/qbit/data-analysis/tables/{table}/shift` | `{field, dateField, bucket, filter}`; calendar buckets, top 8 categories or quartiles, first/last complete-bucket PSI |
| POST | `/qbit/data-analysis/tables/{table}/correlation` | `{fields, filter}`; 2–12 distinct numeric fields, pairwise r and n, scatter request per cell |
| POST | `/qbit/data-analysis/tables/{table}/scatter` | `{xField, yField, filter, limit}`; default/maximum 2000 points and a sample trend line |
| POST | `/qbit/data-analysis/tables/{table}/crosstab` | `{rowField, columnField, filter, limit}`; default/maximum 20 categories per axis plus Other |
| POST | `/qbit/data-analysis/runs` | `{operation: COLUMN_PROFILE or TABLE_PROFILE, tableName, request}` returns `{runId, status}` |
| GET | `/qbit/data-analysis/runs/{runId}` | Status, timestamps, error, typed `columnProfile` or `tableProfile` |
| POST | `/qbit/data-analysis/watches/{id}/preview` | No body; complete bucket series, `TIME_SERIES` chart with baseline annotations and detector verdict; no writes or alerts |
Every operation uses the request session through `DataAnalysisService`. Capabilities returns 200 with `canAnalyze: false` and no fields when denied. Other permission denials return 403, bad bodies or unavailable fields return 400, and unknown tables return 404. Core middleware supplies plain messages in its standard `{error: message}` JSON envelope. Run rows remain owner-locked.
Requests and drills reuse core's `QueryFilter` JSON shape and schema reference. Versioned `DataAnalysis...V1` schemas cover profiles, metrics, drills, charts, series, points, field summaries, distinct and duplicate results, capabilities and runs. The [OpenAPI fragment](src/main/resources/openapi/qqq-v1/data-analysis.yaml) is checked against regeneration. The deployed `/qqq/v1/openapi.json` and `UiApiInvoker.listOperations()` include all seven operations.
Requests and drills reuse core's `QueryFilter` JSON shape and schema reference. Versioned `DataAnalysis...V1` schemas cover profiles, metrics, drills, charts, series, points, field summaries, distinct and duplicate results, capabilities and runs. The [OpenAPI fragment](src/main/resources/openapi/qqq-v1/data-analysis.yaml) is checked against regeneration. The deployed `/qqq/v1/openapi.json` and `UiApiInvoker.listOperations()` include all fourteen operations.
Regenerate deliberately after an API change:
```bash
./mvnw -o -q test -Dtest=DataAnalysisApiTest#contract -Dopenapi.write=true -Dqqq.snapshot.version=4.1.0-DATAANALYSIS-SNAPSHOT
./mvnw -q test -Dtest=DataAnalysisApiTest#contract -Dopenapi.write=true
```
## Pivot backend and field access
`DataAnalysisService.pivot(PivotRequest)` returns sparse cells indexed into row/column header tuples, aligned totals, typed/formatted metrics, warnings and `asOf`. `COUNT` counts records (including null measure values); other operators require a field. `PERCENTILE` uses continuous interpolation with a fraction from 0 to 1. Calendar buckets use the session timezone. Numeric bins reuse profile nice-edge selection when explicit bounds are omitted; the last interior bin includes its maximum.
The planner first requests count-ordered top-N groups for every dimension (default 50, maximum 200), then dimension counts for privacy/cardinality, one grouped matrix and one aggregate per totals level. Additional aggregates recompute merged Other cells/totals: averages, distinct counts and percentiles cannot safely be combined from displayed cells. Ordinary Other predicates exclude kept values and handle null/empty strings separately. Boolean, temporal and bucketed Other groups use equivalent membership/range predicates for core HTTP compatibility. Cyclic date predicates enumerate observed values through core grouping; memory numeric boundaries reuse the profiles' decimal-scale compatibility helper. Native pivots are exact; bounded core streamed fallback marks partial results as estimates and disables their drills.
`joinTable.field` resolves only through an unambiguous exposed join path. Every table in that path requires READ and the selected field must be FULL; core enforces joins and record locks. The installed data-analysis snapshot does not contain the related-record picker path API, so this implementation uses `getExposedJoins()` and `QueryJoin`. Paths whose every hop is MANY_TO_ONE or ONE_TO_ONE in the analyzed direction support ordinary filter-only drills: core infers the joins from qualified criteria. To-many paths can multiply a base record, so their pivots retain null drills and warn that counts include one row per related table record.
`min_group_size` suppresses rare dimension groups and rare row/column tuples; every measure of a small cell or total is suppressed, including COUNT, with no drill. Totals include the full authorized population. As with existing profiles, separate aggregate calls are not a transactional snapshot.
Hosts can supply `withFieldAnalysisAccessResolver(() -> resolver)`. FULL fields alone appear in capabilities and may be selected. EXACT_MATCH_ONLY and NONE get the same 400 as an unknown field; user-authored filters are passed through for core enforcement. Generated drills using a restricted field (including representative primary keys) are disabled. Related PVS display labels also require FULL access. Exact-run cache identities hash the sorted FULL-field list, the optional core access fingerprint, and related label access.
The default resolver discovers the optional core `fieldaccess.FieldAccessHelper` class and its static methods once. FULL maps to FULL, REVEALABLE to EXACT_MATCH_ONLY, MASKED/HIDDEN to NONE. Without that class, legacy field locks supply FULL/NONE. Replace the reflective calls when the core package ships. Reflection tests use a local stand-in helper rather than shadowing a future real core class at its FQN; the pinned RC.7 exercises the actual core tier resolver selection. Exact-run persistence continues to support profiles only; pivot results are synchronous.
## Backend selection
`DataAnalysisService` selects `CoreAnalysisBackend` when the source backend advertises aggregate capabilities, including memory. Supported standard deviation, percentiles, null/blank counts, numeric/date buckets and length statistics execute through core aggregates as the current session. Unsupported primitives delegate to `StandInAnalysisBackend`. Patterns and derived length histograms remain streamed; representative distinct drills and cyclic-date membership use bounded scans.
@@ -172,23 +224,114 @@ Variance, interpolated percentiles, string lengths/shapes, date classification,
Data versions use filtered COUNT plus MAX of a readable modification-date-like field, otherwise MAX(primary key). This is the specified inexpensive invalidation heuristic, not snapshot isolation; updates on a table without a modification timestamp can remain cached until TTL expiry. Concurrent writes can also change drill counts after a profile is produced. Results always retain `asOf`.
## Compare and relationships
All five operations resolve FULL fields before reading source data and use core actions with `PermissionEnforcement.ENFORCE`. Core applies table permissions and record locks. Compare batches numeric COUNT, AVG, VAR_SAMP and quartiles per population; categorical comparisons use a common top-10-plus-Other distribution and pool categories with expected counts below five. Deltas are B minus A, and percent deltas divide by absolute A (null when A is zero). Significance uses a strict p < 0.05 threshold; invalid or privacy-suppressed tests return a plain reason.
Correlation batches all CORR pairs into one aggregate call. Pairwise non-null n values use enforced core count actions, since the current aggregate API has no per-measure filter. Unsupported aggregates use core's bounded streamed fallback; a truncated fallback returns 400 with a request to narrow the filter, rather than publishing a partial significance test. Scatter uses the first N paired records ordered by primary key because the current core QueryInput has no sampling API. Its least-squares line describes that displayed sample. Point drills contain only primary-key equality and are disabled whenever privacy is enabled or the primary key is not FULL.
Shift uses session-timezone calendar buckets. Only buckets whose end has passed enter PSI; categories share one top-8-plus-Other basis, and numeric PSI uses the first complete bucket's quartile boundaries for both populations. Zero shares are floored at 0.000001. PSI is descriptive, not a significance test. Category time series explicitly declare `stacked: true`.
The minimum-group-size guard removes small numeric summaries, suppresses crosstab cells and revealing marginal shares, disables drills on privacy-merged Other groups, and suppresses scatter points below the minimum. Statistical tests and PSI are unavailable when protected values would contribute. No runtime statistics dependency is added; beta/gamma, Welch, chi-square, proportions, PSI and Pearson are pure Java, checked against independently computed SciPy references.
## Anomaly watches
Watches are ordinary owner-locked `data_analysis_watch` rows. Create and edit them through core table CRUD with `data_analysis.watch.read`, `.insert`, `.edit`, and `.delete`. Standard table/record actions **Evaluate now**, **Enable**, and **Disable** use streamed ETL Review and Result summaries. They never appear in navigation. The home lists firing watches first and links to their records.
A watch has `owner_user_id`, `date_field`, `bucket` (`HOUR`, `DAY`, `WEEK`, `MONTH`), `detector`, `parameters_json`, `severity` (`INFO`, `WARNING`, `ERROR`, `CRITICAL`) and `enabled`. It targets either:
- `table_name`, optional core `filter_json`, and `metric_json`, such as `{"operator":"COUNT"}`, `{"operator":"SUM","field":"amount"}`, `{"operator":"AVG","field":"amount"}`, `{"operator":"NULL_SHARE","field":"email"}`, or `{"operator":"CATEGORY_SET","field":"status"}`.
- `saved_id`: the owner's saved table and filter, with an explicit watch `metric_json` or one saved definition `metric` / single pivot `values` measure. The date field and bucket remain explicit on the watch. Ambiguous saved measures are rejected; saved filters cannot be overridden by `filter_json` on the watch.
Detector parameters are validated by core pre-insert/update customizers, including partial updates. Unknown parameters and invalid metric/detector combinations return clear record errors.
| Detector | Parameters and behavior |
| --- | --- |
| SPIKE / DROP | `k=14`, `threshold=3.5`, `relativeChange=0.5`; robust z = `0.6745 * (latest - median) / MAD`, strict directional threshold. With zero MAD, compare relative change against the absolute median. A zero baseline fires only for a nonzero change in the requested direction. |
| OUT_OF_RANGE | Required `min` and `max`; fire outside the inclusive range. Needs only the latest bucket. |
| NEW_CATEGORY | `k=14`; requires `CATEGORY_SET`; compare latest categories with the union of previous buckets. Null is excluded from the category set. |
| NULL_RATE_CREEP | `k=14`, `delta=0.05`, `n=3`; requires `NULL_SHARE`; fire for a rise above the baseline median greater than delta, or `n` consecutive increases (`n+1` values). |
`k` and `n` are bounded to 1–1000. The trailing window contains at most `k+1` complete buckets, excludes the current bucket, and follows the owner's time zone (Monday-based weeks). Leading buckets with no observed rows do not invent history. After the first observed bucket, missing COUNT/SUM/category buckets are zero/empty; AVG and NULL_SHARE with no population are unavailable. Too little history, incomplete streamed results, unavailable fields, and privacy-suppressed buckets never cause a recovery. No suppressed series, categories, values or drills leave the computation. All source reads enforce READ, Analyze, record locks and FULL field access, including filter fields.
`data_analysis_evaluate_watches` is hidden and repeats every 900 seconds when `schedulerName` is configured. Give the scheduler session its standard process permission, `data_analysis_evaluate_watches.hasAccess`. Inventory and status writes use grants restricted to watch rows; source aggregation always switches to the owner. The default integration calls the host authentication module's `createAutomatedSessionForUser`. Hosts can instead configure `withOwnerSessionSupplier(userId -> session)`. The session must identify that owner and include the `data_analysis_user` owner key plus their current permissions. Missing/mismatched sessions record **Owner session unavailable**; there is no system-session fallback. Manual Evaluate now can also evaluate a disabled watch.
A transition from OK to FIRING raises through core `QAlerts`, with the watch record reference and a relative table-query `AlertLink`; recovery resolves the same `data_analysis_watch:<id>` key. The declared type is **`data.analysis.anomaly`**, labelled **Data anomaly**. This spelling is necessary because the supplied core SPI validator rejects the design's `data_analysis.anomaly` underscore. No qbit-alerts dependency is required. With no sink installed, core logs the signal and the watch row still records the outcome. Repeated FIRING/OK evaluations do not send duplicate transitions. Calls are serialized within each runtime; hosts should run this scheduler on one node (cross-node transactional coordination is not provided).
`state`, `alert_key`, `last_evaluated_at`, `last_value` and `last_message` describe the most recent attempt. Skips clear the last value and leave the existing OK/FIRING state intact. Preview uses the requesting viewer's permissions and never updates these fields.
`DataAnalysisSchema.postgresScript(config)` generates the new fields and owner requirement. Existing installations must add `date_field VARCHAR(250)`, `owner_user_id VARCHAR(250)`, `last_value NUMERIC`, and `last_message TEXT`, then backfill each watch's actual owner/date field before making the first two columns NOT NULL and enabling evaluation. The CREATE-IF-NOT-EXISTS generator does not migrate existing tables.
## Saved analyses, stars and exports
Create/edit saved analyses through ordinary core table CRUD. `kind` selects `COLUMN_PROFILE`, `TABLE_PROFILE`, `PIVOT`, `COMPARE`, `CORRELATION`, `CROSSTAB` or `SHIFT`; `definition_json` stores that kind's typed request. For example, a column profile has `{"fieldName":"amount","filter":{...}}`, and a pivot has `{"rows":[{"field":"status"}],"values":[{"operator":"COUNT"}]}`. `table_name` identifies the source table; a supplied `tableName` in the JSON must match. The customizers reject malformed JSON, missing selections, nonexistent tables/fields and invalid partial edits with plain record errors. A typed definition filter takes precedence over legacy `filter_json`.
`POST /saved/{id}/run` re-runs as the viewer and returns `{kind, warnings, columnProfile, tableProfile, pivot, compare, correlation, crosstab, shift}`, with the matching typed member populated. Selected fields without FULL analysis access are removed and `Some fields are not available to you` is returned. If a required axis, all required selections, or a filter predicate is unavailable, no computation is performed and the typed members are null; filters are never dropped to broaden the population. Saved profile runs are transient, so they do not require run-table write permission and cannot reuse an owner's cache.
`GET /saved` lists core-visible saved metadata with each viewer's `starred` flag. `PUT /saved/{id}/star` and `DELETE /saved/{id}/star` are idempotent and always target the signed-in user, using standard saved INSERT/DELETE grants. The local star table remains available through ordinary CRUD and has a unique `(saved_id,user_id)` key.
`GET /saved/{id}/export?format=csv|xlsx` re-runs as the viewer. `POST /export` accepts a discriminated request:
```json
{"kind":"PIVOT","tableName":"orders","request":{"rows":[{"field":"status"}],"values":[{"operator":"COUNT"}]},"format":"xlsx"}
```
Both routes return file bytes with attachment headers. Core `ReportFormat` CSV/XLSX streamers write computed result tables: profile metrics/top values, pivot grids, comparisons, correlation/crosstab tables and shift buckets. Values retain their formatting and privacy suppression. Warnings are included in downloads. All paths above are relative to `/qqq/v1/qbit/data-analysis` and appear in assistant operation discovery.
## Scheduled delivery
Configure `schedulerName`, `messagingProviderName`, `fromAddress`, `ownerSessionSupplier` and `recipientAddressSupplier` in `DataAnalysisQBitConfig`. The session supplier resolves both owners and recipients by their stable user id; without it, the authentication module's `createAutomatedSessionForUser` is used. The address supplier maps those ids to verified directory email addresses; schedule recipients are **user ids**, never arbitrary email addresses.
Schedules use `recipients` as a JSON array (1–100 ids), `format` as `HTML_SUMMARY`, `CSV` or `XLSX`, and either Quartz cron (including the seconds field) or `frequency` + `day` + `time` + `time_zone`. Weekly days are ISO Monday=1 through Sunday=7; monthly days are 1–31, clamped to the last day of shorter months. Times are local ISO times such as `09:00`; omitted time zone is UTC. Spring-forward gaps move forward, and the first occurrence is chosen in an autumn overlap. `next_run_at` is strictly after the evaluation time.
The hidden `data_analysis_run_schedules` process repeats every 300 seconds when a scheduler is configured. Its scheduler session needs `data_analysis_run_schedules.hasAccess`. Inventory/status operations use a narrow maintenance session; source computation always switches to the saved owner. Every recipient must resolve to the correct identity and pass source READ, Analyze and FULL access for all selected/filter fields. Different recipients receive a fresh computation under their own record locks. Skipped ids appear in `last_status`.
Email includes escaped HTML headline metrics and a result table (first 20 rows for pivots), with the requested CSV/XLSX attachment via core `SendMessageAction`. `HTML_SUMMARY` has no attachment. Missing messaging configuration and delivery errors persist an explicit failure and raise the declared **`data.analysis.schedule.failed`** alert. Core rejects underscores in alert names, so the spec's `data_analysis.schedule_failed` spelling cannot be registered. With no alert sink, core logs the signal and the status remains visible.
The installed core's stock `EMAIL` provider silently ignores `SendMessageInput.attachmentList`. CSV/XLSX schedules therefore reject that provider with an explicit status/alert; configure an attachment-capable core messaging provider. A test provider verifies the complete message and attachment contract. This qbit does not alter core's SMTP transport.
**Send now** uses the standard streamed ETL Review/Result record action. Reviews do not deliver; execution reauthorizes and reports actual outcomes. Disabled schedules can be sent manually. A runtime serializes scheduled and manual attempts, but there is no cross-node transaction or exactly-once email guarantee; run the scheduler on one node. New configurations compute their next occurrence; failed attempts advance to the next occurrence instead of retrying every five minutes.
## SQL Workbench and dashboard widgets
`POST /tables/{table}/sql` accepts `{kind,request}` and returns `{available,sql,note}`. It requires an installed SQL Workbench app/table and the configured app access permission (default `sql_workbench.hasAccess`), plus source permissions. Memory/non-RDBMS backends report unavailable. The engine executes the request as the viewer and reads the actual main aggregate's core `QueryStat`; grouped dimensions and the widest metric batch identify the main statement. Bound `?` placeholders remain, and the note states that QQQ applies record security at runtime and the SQL is for reading.
Core exposes `QueryStat` on the backend but not the backend reference on `AggregateAction`. A narrow read-only reflective bridge accesses that reference after normal core execution. Query-stat capability is enabled only on the request's cloned table metadata; no global logger or statistics-manager settings change. If core changes that private field or does not provide SQL, the endpoint reports unavailable rather than fabricating a statement.
The Analyses home uses standard `multiStatistics` and `table` widgets: mine/shared/starred counts, enabled/firing watches, my runs in the last seven days, starred analysis links, firing watches and recent run links. All counts and rows use the viewer's session. Tables have at most four columns and use Next's responsive table/card renderer, with explicit empty/permission states.
`SavedAnalysisWidget.widget()` supplies the **`DATA_ANALYSIS_SAVED`** metadata. Clone/rename it for another dashboard and set `.withDefaultValue("savedId", id)`. Its standard chart renderer re-runs as the viewer, shows formatted headline metrics, projects the semantic series/pivot/crosstab into a standard chart, and links back to the saved record. It never displays an owner's cached result. The standard chart is a dashboard summary; the full analysis UI remains responsible for specialized box/heatmap presentations.
## Adopting in another app
1. Add a backend, install the producer and run the usual `QInstanceValidator`.
2. For PostgreSQL, obtain `DataAnalysisSchema.postgresScript(config)` and apply it through your application's migration system. It derives fields and unique indexes from table metadata. It does not execute DDL or upgrade existing schemas.
3. Map user-id security keys and permissions in the authentication adapter. Configure core audit persistence if field audit history is needed.
4. Review per-table include/exclude sets, limits and minimum group sizes before enabling analysis. Integrate Saved Analyses and Watches with host ESB/Quick Search when those optional host features are installed; this scaffold does not add those dependencies.
5. Use the Analyses home as the owner of analysis data. Other dashboards should link there until saved-analysis widgets are implemented.
5. Use the Analyses home as the owner of analysis data. Other dashboards can place a configured DATA_ANALYSIS_SAVED widget linked to its saved record.
Phase **b** profiles, drill-through, runs/cache and HTTP endpoints are implemented. Remaining work: **b** analysis UI; **c** pivots; **d** comparisons and relationships; **e** watch evaluation and alerts; **f** saved-analysis execution, sharing, stars integration, schedules, chart widgets, full home and exports. The current home summarizes stored rows; the host facade executes profiles. The home does not send deliveries.
Backend phases **b–f** are implemented, including saved/shared/starred analyses, schedules, standard widgets, home, export and SQL handoff. The separate profile, pivot and relationship frontend remains outside this repository.
## In-app help
The qbit registers `src/main/resources/help/qbit-data-analysis.yaml` as a QBIT bundle.
Hosts with the core `helpContent` table receive it through QQQ's startup sync; registration
is harmless without that table. The app help follows `appName` when you configure a custom name.
To override text, register your own `layer: HOST` bundle with the same entry key and role
(using your configured app name for app help). HOST entries take precedence over QBIT entries;
QQQ preserves manually edited help during sync.
`DataAnalysisTablesGuardrailTest` uses `HelpBundleAssertions` to check owned metadata,
summary length and live references, and checks widget and possible-value-source coverage.
Update the bundle's literal version alongside the POM version when releasing.
## Build
```bash
./mvnw -o -q verify -Dqqq.snapshot.version=4.1.0-DATAANALYSIS-SNAPSHOT
./mvnw -q verify
```
The wrapper pins Maven 3.9.11. On Windows use `mvnw.cmd`. Verification runs Checkstyle, a shared JUnit 5/AssertJ contract suite on memory and H2, PostgreSQL via Testcontainers when Docker is available, and JaCoCo gates of 70% instructions and 90% classes. The suite checks numerical references, every exact count/drill pair, full-population estimate drills, security, guarded cache JSON, native sampling, asynchronous jobs and cache invalidation. The POM targets RC.6; until its release, always supply the locally installed snapshot override shown above. RDBMS, H2, Testcontainers PostgreSQL and the PostgreSQL driver are test-scoped; middleware Javalin is optional.
The wrapper pins Maven 3.9.11. On Windows use `mvnw.cmd`. Verification runs Checkstyle, a shared JUnit 5/AssertJ contract suite on memory and H2, PostgreSQL via Testcontainers when Docker is available, and JaCoCo gates of 70% instructions and 90% classes. The suite checks numerical references, every exact count/drill pair, full-population estimate drills, security, guarded cache JSON, native sampling, asynchronous jobs and cache invalidation. The POM pins QQQ 4.1.0-RC.7 from Maven Central. RDBMS, H2, Testcontainers PostgreSQL and the PostgreSQL driver are test-scoped; middleware Javalin is optional.
## License
+8
View File
@@ -0,0 +1,8 @@
# Upgrading
## Unreleased
No schema change and nothing required of hosts.
- New table action **Create rows for analyzable tables** on Analysis Settings. Run it once if you want the effective settings visible and editable as rows. It changes no behavior, is insert-only, and only adds rows for tables that have none. After a row exists it wins over later changes to the code defaults for that table.
- New **Setup** widget first on the Analyses home, and table help text. Hosts that override help on a table keep their own.
+1 -1
View File
@@ -2,7 +2,7 @@
Approved specification: [QQQ docs/DATA-ANALYSIS.md](https://github.com/QRun-IO/qqq/blob/develop/docs/DATA-ANALYSIS.md), introduced in [PR #1137](https://github.com/QRun-IO/qqq/pull/1137).
Data Analysis will provide profiles, pivots, comparisons, relationships and anomaly watches on existing QQQ data. It will push supported computation to the backend, use bounded streamed fallbacks, enforce the viewer’s permissions and privacy limits, and store configuration, saved definitions, schedules and run history in ordinary visible tables. This repository phase supplies those tables, permissions, configuration, PostgreSQL schema generation and an Analyses home with real session-scoped counts; analytical computation and delivery are planned.
Data Analysis will provide profiles, pivots, comparisons, relationships and anomaly watches on existing QQQ data. It will push supported computation to the backend, use bounded streamed fallbacks, enforce the viewer’s permissions and privacy limits, and store configuration, saved definitions, schedules and run history in ordinary visible tables. Backend phases b–f are implemented here: typed analysis engines, saved/shared/starred definitions, schedules, exports, SQL handoff and standard widgets with session-scoped data. Specialized analysis frontend work lives in Next. README documents the required shared-read migration and the installed core transport limitations.
## Phases (spec §11)
+32 -3
View File
@@ -18,7 +18,8 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<properties>
<revision>0.1.0-SNAPSHOT</revision>
<qqq.version>4.1.0-RC.26</qqq.version> <!-- feeds qbit-build-parent's qqq-bom-pom import -->
<revision>0.3.0-SNAPSHOT</revision>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<jacoco.version>0.8.15</jacoco.version>
@@ -27,7 +28,7 @@
<parent>
<groupId>com.kingsrook</groupId>
<artifactId>qbit-build-parent</artifactId>
<version>2.0.0</version>
<version>2.2.1</version>
</parent>
<groupId>com.kingsrook.qbits</groupId>
@@ -128,7 +129,35 @@
</dependencies>
<build>
<resources>
<!-- help bundles carry the artifact version (QQQ help bundle provenance) -->
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>help/*.yaml</include>
<include>qbit-data-analysis.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<excludes>
<exclude>help/*.yaml</exclude>
<exclude>qbit-data-analysis.properties</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables combine.children="append">
<qbit.artifactVersion>${project.version}</qbit.artifactVersion>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
@@ -215,7 +244,7 @@
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<qqq.snapshot.version>4.1.0-RC.6</qqq.snapshot.version>
<qqq.snapshot.version>4.1.0-RC.26</qqq.snapshot.version>
</properties>
<dependencyManagement>
<dependencies>
@@ -26,6 +26,9 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import com.kingsrook.qbits.dataanalysis.engine.CoreTierFieldAccessResolver;
import com.kingsrook.qbits.dataanalysis.engine.FieldAnalysisAccessResolver;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitConfig;
@@ -35,6 +38,8 @@ import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitConfig;
*******************************************************************************/
public class DataAnalysisQBitConfig implements QBitConfig
{
private Supplier<FieldAnalysisAccessResolver> fieldAnalysisAccessResolver = CoreTierFieldAccessResolver::defaultResolver;
private transient java.util.function.Function<String, com.kingsrook.qqq.backend.core.model.session.QSession> ownerSessionSupplier;
private String backendName;
private String schedulerName;
private String appName = "dataAnalysis";
@@ -387,4 +392,115 @@ public class DataAnalysisQBitConfig implements QBitConfig
this.tableDefaults = tableDefaults;
return (this);
}
/*******************************************************************************
** Host override for session-aware field analysis access.
*******************************************************************************/
public Supplier<FieldAnalysisAccessResolver> getFieldAnalysisAccessResolver()
{
return (fieldAnalysisAccessResolver);
}
/*******************************************************************************
** Configure an instance supplier; each service resolves one policy instance.
*******************************************************************************/
public DataAnalysisQBitConfig withFieldAnalysisAccessResolver(Supplier<FieldAnalysisAccessResolver> resolver)
{
this.fieldAnalysisAccessResolver = java.util.Objects.requireNonNull(resolver);
return (this);
}
/*******************************************************************************
** Optional host adapter for scheduled owner permissions and record-lock keys.
*******************************************************************************/
public java.util.function.Function<String, com.kingsrook.qqq.backend.core.model.session.QSession> getOwnerSessionSupplier()
{
return (ownerSessionSupplier);
}
/*******************************************************************************
** Without an adapter, use the host authentication module's automated session.
*******************************************************************************/
public DataAnalysisQBitConfig withOwnerSessionSupplier(java.util.function.Function<String, com.kingsrook.qqq.backend.core.model.session.QSession> supplier)
{
ownerSessionSupplier = supplier;
return (this);
}
private String servicePrincipal = "data-analysis";
/*******************************************************************************
** The service principal schedules and watches run as when the host declares
** it (QQQ service identities): inventory as the principal, owner and
** recipient runs on their behalf through it. Undeclared: the previous local
** sessions.
*******************************************************************************/
public String getServicePrincipal()
{
return (servicePrincipal);
}
/*******************************************************************************
** Fluent setter for servicePrincipal (default data-analysis).
*******************************************************************************/
public DataAnalysisQBitConfig withServicePrincipal(String servicePrincipal)
{
this.servicePrincipal = servicePrincipal;
return (this);
}
private String messagingProviderName;
private String fromAddress;
private transient java.util.function.Function<String, String> recipientAddressSupplier;
/*******************************************************************************
** Core messaging provider used for scheduled delivery.
*******************************************************************************/
public String getMessagingProviderName()
{
return (messagingProviderName);
}
/*******************************************************************************
** Select the host's configured SMTP or SES provider.
*******************************************************************************/
public DataAnalysisQBitConfig withMessagingProviderName(String value)
{
messagingProviderName = value;
return (this);
}
/*******************************************************************************
** Verified sender address supplied by the host.
*******************************************************************************/
public String getFromAddress()
{
return (fromAddress);
}
/*******************************************************************************
** Set the scheduled email sender.
*******************************************************************************/
public DataAnalysisQBitConfig withFromAddress(String value)
{
fromAddress = value;
return (this);
}
/*******************************************************************************
** Resolve a user id to its current email; never treat recipients as addresses.
*******************************************************************************/
public java.util.function.Function<String, String> getRecipientAddressSupplier()
{
return (recipientAddressSupplier);
}
/*******************************************************************************
** Bind the host directory's user-to-email lookup.
*******************************************************************************/
public DataAnalysisQBitConfig withRecipientAddressSupplier(java.util.function.Function<String, String> value)
{
recipientAddressSupplier = value;
return (this);
}
}
@@ -21,14 +21,21 @@
package com.kingsrook.qbits.dataanalysis;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import com.kingsrook.qbits.dataanalysis.api.DataAnalysisApi;
import com.kingsrook.qbits.dataanalysis.app.DataAnalysisHome;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.help.bundles.HelpBundles;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.TableFeaturePermission;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.TableFeaturePermissionsMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaDataProducer;
import com.kingsrook.qqq.backend.core.model.metadata.tables.TablesPossibleValueSourceMetaDataProvider;
/*******************************************************************************
@@ -38,13 +45,48 @@ public class DataAnalysisQBitProducer implements QBitMetaDataProducer<DataAnalys
{
public static final String GROUP_ID = "com.kingsrook.qbits";
public static final String ARTIFACT_ID = "qbit-data-analysis";
public static final String VERSION = "0.1.0";
public static final String VERSION = loadVersion();
/////////////////////////////////////////////////////////////////////////////////
// Widgets that show engine configuration. They are registered with the qbit //
// (admin-only, hidden from everyone else) but kept off the business home; the //
// host places them on its Admin area, e.g. withWidgets(SYSTEM_WIDGETS). //
/////////////////////////////////////////////////////////////////////////////////
public static final List<String> SYSTEM_WIDGETS = List.of(DataAnalysisHome.SETUP);
private DataAnalysisQBitConfig qBitConfig;
private String namespace;
/*******************************************************************************
** Read the artifact version from the Maven-filtered properties resource.
*******************************************************************************/
private static String loadVersion()
{
try(InputStream inputStream = DataAnalysisQBitProducer.class.getClassLoader().getResourceAsStream("qbit-data-analysis.properties"))
{
if(inputStream == null)
{
throw (new IllegalStateException("Missing qbit-data-analysis.properties; build with Maven to generate the artifact version"));
}
Properties properties = new Properties();
properties.load(inputStream);
String version = properties.getProperty("version");
if(version == null || version.isBlank() || version.contains("${"))
{
throw (new IllegalStateException("Missing or unfiltered version in qbit-data-analysis.properties; build with Maven resource filtering"));
}
return (version);
}
catch(IOException e)
{
throw (new IllegalStateException("Could not read artifact version from qbit-data-analysis.properties", e));
}
}
/*******************************************************************************
** Fluent configuration setter.
*******************************************************************************/
@@ -129,9 +171,27 @@ public class DataAnalysisQBitProducer implements QBitMetaDataProducer<DataAnalys
public MetaDataProducerMultiOutput produce(QInstance instance) throws QException
{
qBitConfig.validate(instance);
if(instance.getPossibleValueSource(TablesPossibleValueSourceMetaDataProvider.NAME) == null)
{
instance.addPossibleValueSource(TablesPossibleValueSourceMetaDataProvider.defineTablesPossibleValueSource(instance));
}
MetaDataProducerMultiOutput output = QBitMetaDataProducer.super.produce(instance);
output.addSelfToInstance(instance);
new DataAnalysisRuntime(qBitConfig).addSelfToInstance(instance);
com.kingsrook.qqq.backend.core.alerts.AlertsInstanceMetaData.ofOrWithNew(instance).withAlertType(
new com.kingsrook.qqq.backend.core.alerts.QAlertTypeMetaData().withName(com.kingsrook.qbits.dataanalysis.watch.WatchEvaluator.ALERT_TYPE)
.withLabel("Data anomaly").withSourceName(ARTIFACT_ID).withGroupName("data-analysis")
.withDefaultSeverity(com.kingsrook.qqq.backend.core.alerts.AlertSeverity.WARNING)
.withResolveMode(com.kingsrook.qqq.backend.core.alerts.ResolveMode.PRODUCER)
.withSubjectTableName(com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables.WATCH)
.withVisibilityPermission("data_analysis.watch.read"));
com.kingsrook.qqq.backend.core.alerts.AlertsInstanceMetaData.ofOrWithNew(instance).withAlertType(
new com.kingsrook.qqq.backend.core.alerts.QAlertTypeMetaData().withName(com.kingsrook.qbits.dataanalysis.schedule.ScheduleRunner.ALERT_TYPE)
.withLabel("Analysis schedule failed").withSourceName(ARTIFACT_ID).withGroupName("data-analysis")
.withDefaultSeverity(com.kingsrook.qqq.backend.core.alerts.AlertSeverity.ERROR)
.withResolveMode(com.kingsrook.qqq.backend.core.alerts.ResolveMode.PRODUCER)
.withSubjectTableName(com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables.SCHEDULE)
.withVisibilityPermission("data_analysis.saved.read"));
var included = java.util.Set.copyOf(qBitConfig.getIncludeTables());
var excluded = java.util.Set.copyOf(qBitConfig.getExcludeTables());
TableFeaturePermissionsMetaData.ofOrWithNew(instance).withPermission(new TableFeaturePermission()
@@ -152,6 +212,11 @@ public class DataAnalysisQBitProducer implements QBitMetaDataProducer<DataAnalys
{
instance.getApp(qBitConfig.getParentAppName()).withChild(instance.getApp(qBitConfig.getAppName()));
}
// Registration is metadata-only; core startup sync guards hosts without helpContent.
HelpBundles.register(instance, "help/qbit-data-analysis.yaml");
HelpBundles.of(instance).getBundles().getLast().getEntries().stream()
.filter(entry -> "app:dataAnalysis;slot:help".equals(entry.getKey()))
.forEach(entry -> entry.setKey("app:" + qBitConfig.getAppName() + ";slot:help"));
return (new MetaDataProducerMultiOutput());
}
}
@@ -30,6 +30,9 @@ import com.kingsrook.qqq.backend.core.model.metadata.QSupplementalInstanceMetaDa
public class DataAnalysisRuntime implements QSupplementalInstanceMetaData
{
private final transient DataAnalysisService service;
private final transient com.kingsrook.qbits.dataanalysis.schedule.ScheduleRunner schedules;
private final transient com.kingsrook.qbits.dataanalysis.saved.SavedAnalyses saved;
private final transient com.kingsrook.qbits.dataanalysis.watch.WatchEvaluator watches;
/*******************************************************************************
** Create a runtime for one configured instance.
@@ -37,6 +40,9 @@ public class DataAnalysisRuntime implements QSupplementalInstanceMetaData
public DataAnalysisRuntime(DataAnalysisQBitConfig config)
{
service = new DataAnalysisService(config);
schedules = new com.kingsrook.qbits.dataanalysis.schedule.ScheduleRunner(config, service);
saved = new com.kingsrook.qbits.dataanalysis.saved.SavedAnalyses(service);
watches = new com.kingsrook.qbits.dataanalysis.watch.WatchEvaluator(config, service);
}
@@ -70,4 +76,28 @@ public class DataAnalysisRuntime implements QSupplementalInstanceMetaData
{
return (((DataAnalysisRuntime) QContext.getQInstance().getSupplementalMetaData("dataAnalysisRuntime")).getService());
}
/*******************************************************************************
** Shared evaluator serializes manual and scheduled watch transitions.
*******************************************************************************/
public static com.kingsrook.qbits.dataanalysis.watch.WatchEvaluator watches()
{
return (((DataAnalysisRuntime) QContext.getQInstance().getSupplementalMetaData("dataAnalysisRuntime")).watches);
}
/*******************************************************************************
** Saved operations share the instance's engine and serialize star toggles.
*******************************************************************************/
public static com.kingsrook.qbits.dataanalysis.saved.SavedAnalyses saved()
{
return (((DataAnalysisRuntime) QContext.getQInstance().getSupplementalMetaData("dataAnalysisRuntime")).saved);
}
/*******************************************************************************
** Shared schedule runner for manual and automatic delivery.
*******************************************************************************/
public static com.kingsrook.qbits.dataanalysis.schedule.ScheduleRunner schedules()
{
return (((DataAnalysisRuntime) QContext.getQInstance().getSupplementalMetaData("dataAnalysisRuntime")).schedules);
}
}
@@ -57,6 +57,14 @@ public final class DataAnalysisSchema
columns.add(" " + field.getBackendName() + " " + ("id".equals(field.getName())
? "INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY" : sqlType(field) + (Boolean.TRUE.equals(field.getIsRequired()) ? " NOT NULL" : "")));
}
if(DataAnalysisTables.SAVED.equals(table.getName()))
{
///////////////////////////////////////////////////////////////////////////////
// a null read-owner projection means "shared": make the database refuse it //
// on a private row, so a row written outside QQQ fails closed, not open //
///////////////////////////////////////////////////////////////////////////////
columns.add(" CONSTRAINT ck_data_analysis_saved_read_owner CHECK (shared IS TRUE OR read_owner_user_id IS NOT NULL)");
}
statements.add("CREATE TABLE IF NOT EXISTS " + table.getName() + " (\n" + String.join(",\n", columns) + "\n)");
if(table.getUniqueKeys() != null)
{
@@ -83,6 +91,7 @@ public final class DataAnalysisSchema
{
case INTEGER -> "INTEGER";
case LONG -> "BIGINT";
case DECIMAL -> "NUMERIC";
case BOOLEAN -> "BOOLEAN";
case DATE_TIME -> "TIMESTAMP WITHOUT TIME ZONE";
case TEXT -> "TEXT";
@@ -21,25 +21,47 @@
package com.kingsrook.qbits.dataanalysis;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import com.kingsrook.qbits.dataanalysis.engine.AnalysisBackend;
import com.kingsrook.qbits.dataanalysis.engine.AnalysisDrillGuard;
import com.kingsrook.qbits.dataanalysis.engine.AnalysisLabels;
import com.kingsrook.qbits.dataanalysis.engine.AnalysisSecurity;
import com.kingsrook.qbits.dataanalysis.engine.ColumnProfiler;
import com.kingsrook.qbits.dataanalysis.engine.ComparisonExplorer;
import com.kingsrook.qbits.dataanalysis.engine.CoreAnalysisBackend;
import com.kingsrook.qbits.dataanalysis.engine.DistinctValues;
import com.kingsrook.qbits.dataanalysis.engine.DrillFilters;
import com.kingsrook.qbits.dataanalysis.engine.DuplicateFinder;
import com.kingsrook.qbits.dataanalysis.engine.EffectiveConfigResolver;
import com.kingsrook.qbits.dataanalysis.engine.FieldAnalysisAccessResolver;
import com.kingsrook.qbits.dataanalysis.engine.PivotExplorer;
import com.kingsrook.qbits.dataanalysis.engine.RelationshipExplorer;
import com.kingsrook.qbits.dataanalysis.engine.ShiftExplorer;
import com.kingsrook.qbits.dataanalysis.engine.StandInAnalysisBackend;
import com.kingsrook.qbits.dataanalysis.engine.TableProfiler;
import com.kingsrook.qbits.dataanalysis.result.AnalysisRequest;
import com.kingsrook.qbits.dataanalysis.result.Capabilities;
import com.kingsrook.qbits.dataanalysis.result.ColumnProfile;
import com.kingsrook.qbits.dataanalysis.result.ColumnProfileRequest;
import com.kingsrook.qbits.dataanalysis.result.CompareRequest;
import com.kingsrook.qbits.dataanalysis.result.CompareResult;
import com.kingsrook.qbits.dataanalysis.result.CorrelationRequest;
import com.kingsrook.qbits.dataanalysis.result.CorrelationResult;
import com.kingsrook.qbits.dataanalysis.result.CrosstabRequest;
import com.kingsrook.qbits.dataanalysis.result.CrosstabResult;
import com.kingsrook.qbits.dataanalysis.result.DistinctValuesPage;
import com.kingsrook.qbits.dataanalysis.result.DistinctValuesRequest;
import com.kingsrook.qbits.dataanalysis.result.DuplicatesRequest;
import com.kingsrook.qbits.dataanalysis.result.DuplicatesResult;
import com.kingsrook.qbits.dataanalysis.result.PivotRequest;
import com.kingsrook.qbits.dataanalysis.result.PivotResult;
import com.kingsrook.qbits.dataanalysis.result.RunStatus;
import com.kingsrook.qbits.dataanalysis.result.ScatterRequest;
import com.kingsrook.qbits.dataanalysis.result.ScatterResult;
import com.kingsrook.qbits.dataanalysis.result.ShiftRequest;
import com.kingsrook.qbits.dataanalysis.result.ShiftResult;
import com.kingsrook.qbits.dataanalysis.result.TableProfile;
import com.kingsrook.qbits.dataanalysis.result.TableProfileRequest;
import com.kingsrook.qbits.dataanalysis.run.AnalysisRunService;
@@ -53,6 +75,7 @@ public class DataAnalysisService
{
private final EffectiveConfigResolver configs;
private final AnalysisSecurity security;
private final FieldAnalysisAccessResolver fieldAccess;
private final AnalysisRunService runs;
/*******************************************************************************
@@ -71,7 +94,8 @@ public class DataAnalysisService
public DataAnalysisService(DataAnalysisQBitConfig config, Executor executor)
{
configs = new EffectiveConfigResolver(config);
security = new AnalysisSecurity(configs);
fieldAccess = config.getFieldAnalysisAccessResolver().get();
security = new AnalysisSecurity(configs, fieldAccess);
runs = new AnalysisRunService(this, executor);
}
@@ -116,7 +140,7 @@ public class DataAnalysisService
public DistinctValuesPage distinctValues(DistinctValuesRequest request) throws QException
{
validate(request);
return (new DistinctValues(backend(request.getTableName())).page(request, security.field(request.getTableName(), request.getFieldName()), configs.resolve(request.getTableName())));
return (protect(new DistinctValues(backend(request.getTableName()), fieldAccess).page(request, security.field(request.getTableName(), request.getFieldName()), configs.resolve(request.getTableName())), request));
}
@@ -127,7 +151,7 @@ public class DataAnalysisService
public DuplicatesResult duplicates(DuplicatesRequest request) throws QException
{
validate(request);
return (new DuplicateFinder(backend(request.getTableName())).find(request, configs.resolve(request.getTableName())));
return (protect(new DuplicateFinder(backend(request.getTableName())).find(request, configs.resolve(request.getTableName())), request));
}
@@ -219,7 +243,7 @@ public class DataAnalysisService
public ColumnProfile compute(ColumnProfileRequest request, AnalysisBackend backend, AnalysisBackend.Scope scope) throws QException
{
validate(request);
return (new ColumnProfiler(backend).profile(request, security.field(request.getTableName(), request.getFieldName()), scope, configs.resolve(request.getTableName())));
return (protect(new ColumnProfiler(backend, fieldAccess).profile(request, security.field(request.getTableName(), request.getFieldName()), scope, configs.resolve(request.getTableName())), request));
}
@@ -232,6 +256,124 @@ public class DataAnalysisService
validate(request);
List<QFieldMetaData> fields = security.analyzableFields(request.getTableName()).stream()
.filter(f -> request.getFields() == null || request.getFields().contains(f.getName())).toList();
return (new TableProfiler(backend).profile(request, fields, scope));
return (protect(new TableProfiler(backend).profile(request, fields, scope), request));
}
/*******************************************************************************
** Field policy identity is re-evaluated before cache reads and writes.
*******************************************************************************/
public String fieldAccessFingerprint(String table) throws QException
{
return (security.accessFingerprint(table));
}
/*******************************************************************************
** Execute a pivot as the current user through core aggregates.
*******************************************************************************/
public PivotResult pivot(PivotRequest request) throws QException
{
validate(request);
return (new PivotExplorer(security, configs.resolve(request.getTableName())).execute(request));
}
/*******************************************************************************
** Generated primary-key drills also obey the configured field-access seam.
*******************************************************************************/
private <T> T protect(T result, AnalysisRequest request) throws QException
{
new AnalysisDrillGuard(Set.copyOf(capabilities(request.getTableName()).getFields()),
DrillFilters.restoreTypes(request.getTableName(), request.getFilter())).apply(result);
return (result);
}
/*******************************************************************************
** Include resolved tiers of related label fields in cache identity.
*******************************************************************************/
public Map<String, Object> fieldAccessPolicy(String table) throws QException
{
return (AnalysisLabels.policy(table, fieldAccess));
}
/*******************************************************************************
** Execute compare under the current user's FULL-field and record policy.
*******************************************************************************/
public CompareResult compare(CompareRequest request) throws QException
{
validate(request);
return (new ComparisonExplorer(security, configs.resolve(request.getTableName()), request.getTableName()).compare(request));
}
/*******************************************************************************
** Execute correlation under the current user's FULL-field and record policy.
*******************************************************************************/
public CorrelationResult correlation(CorrelationRequest request) throws QException
{
validate(request);
return (new RelationshipExplorer(security, configs.resolve(request.getTableName()), request.getTableName()).correlation(request));
}
/*******************************************************************************
** Execute crosstab under the current user's FULL-field and record policy.
*******************************************************************************/
public CrosstabResult crosstab(CrosstabRequest request) throws QException
{
validate(request);
return (new RelationshipExplorer(security, configs.resolve(request.getTableName()), request.getTableName()).crosstab(request));
}
/*******************************************************************************
** Execute scatter under the current user's FULL-field and record policy.
*******************************************************************************/
public ScatterResult scatter(ScatterRequest request) throws QException
{
validate(request);
return (new RelationshipExplorer(security, configs.resolve(request.getTableName()), request.getTableName()).scatter(request));
}
/*******************************************************************************
** Execute shift under the current user's FULL-field and record policy.
*******************************************************************************/
public ShiftResult shift(ShiftRequest request) throws QException
{
validate(request);
return (new ShiftExplorer(security, configs.resolve(request.getTableName()), request.getTableName()).shift(request));
}
/*******************************************************************************
** Watch aggregates use the same current-user table and FULL-field policy.
*******************************************************************************/
public com.kingsrook.qbits.dataanalysis.watch.WatchPreview watchPreview(com.kingsrook.qqq.backend.core.model.data.QRecord row, java.time.Instant now) throws QException
{
var resolved = com.kingsrook.qbits.dataanalysis.watch.WatchRecords.resolve(row);
String table = resolved.getValueString("table_name");
security.table(table);
var definition = com.kingsrook.qbits.dataanalysis.watch.WatchDefinition.parse(resolved);
return (new com.kingsrook.qbits.dataanalysis.watch.WatchSeries(security, configs.resolve(table), table)
.preview(definition, com.kingsrook.qbits.dataanalysis.watch.WatchRecords.filter(resolved), now));
}
/*******************************************************************************
** Saved definitions drop selected fields using the same FULL access resolver.
*******************************************************************************/
public boolean isAvailableField(String table, String field)
{
try
{
if(field.contains("."))
{
String[] parts = field.split("\\.", 2);
security.joinedField(parts[0], parts[1]);
}
else
{
security.field(table, field);
}
return (true);
}
catch(QException e)
{
return (false);
}
}
}
@@ -0,0 +1,195 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.api;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.dataanalysis.DataAnalysisRuntime;
import com.kingsrook.qbits.dataanalysis.saved.AnalysisExport;
import com.kingsrook.qbits.dataanalysis.saved.SavedDefinition;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
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.Content;
import com.kingsrook.qqq.openapi.model.HttpMethod;
import com.kingsrook.qqq.openapi.model.In;
import com.kingsrook.qqq.openapi.model.Parameter;
import com.kingsrook.qqq.openapi.model.RequestBody;
import com.kingsrook.qqq.openapi.model.Response;
import com.kingsrook.qqq.openapi.model.Schema;
import com.kingsrook.qqq.openapi.model.Type;
import io.javalin.http.Context;
/*******************************************************************************
** Binary endpoints extend AbstractEndpointSpec directly, preserving core sessions.
*******************************************************************************/
public class AnalysisFileSpec extends AbstractEndpointSpec<AnalysisFileSpec.Input, AnalysisFileSpec.Output, AnalysisFileSpec.Executor>
{
/*******************************************************************************
** POST an arbitrary supported typed request plus CSV/XLSX format.
*******************************************************************************/
@Override
public BasicOperation defineBasicOperation()
{
return (new BasicOperation().withPath(DataAnalysisApi.PREFIX + "/export").withHttpMethod(HttpMethod.POST)
.withShortSummary("Export an analysis result").withLongDescription("Execute a typed analysis as the signed-in viewer and download its result table as CSV or XLSX. Requires source READ/Analyze and FULL fields; uses core report formats."));
}
/*******************************************************************************
** Saved export has only id/format parameters; ad hoc export uses a JSON body.
*******************************************************************************/
@Override
public List<Parameter> defineRequestParameters()
{
return (List.of());
}
/*******************************************************************************
** Typed discriminated request plus file format.
*******************************************************************************/
@Override
public RequestBody defineRequestBody()
{
return (new RequestBody().withRequired(true).withContent(Map.of("application/json", new Content()
.withSchema(new Schema().withRef("#/components/schemas/DataAnalysisSavedRequestV1")))));
}
/*******************************************************************************
** Both file representations are declared, without JSON response wrapping.
*******************************************************************************/
@Override
public Map<Integer, Response> defineResponses()
{
Schema file = new Schema().withRef("#/components/schemas/DataAnalysisFileV1");
return (Map.of(200, new Response().withDescription("Analysis result file").withContent(new java.util.TreeMap<>(Map.of("text/csv", new Content().withSchema(file),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", new Content().withSchema(file))))));
}
/*******************************************************************************
** Read transport data only; execution waits for middleware session setup.
*******************************************************************************/
@Override
public Input buildInput(Context context) throws Exception
{
Input input = new Input();
if(this instanceof Saved)
{
input.id = SavedApi.id(context.pathParam("id"));
input.format = context.queryParam("format");
}
else
{
if(context.contentType() == null || !context.contentType().toLowerCase(java.util.Locale.ROOT).startsWith("application/json"))
{
throw new QBadRequestException("The request body must be JSON.");
}
input.body = SavedDefinition.object(context.body());
input.format = input.body.get("format") instanceof String value ? value : null;
}
AnalysisExport.format(input.format);
return (input);
}
/*******************************************************************************
** Actual file bytes, a stable filename and the matching MIME type.
*******************************************************************************/
@Override
public void handleOutput(Context context, Output output)
{
context.contentType(output.file.mimeType()).header("Content-Disposition", "attachment; filename=\"" + output.file.filename() + "\"")
.header("Cache-Control", "no-store").result(output.file.bytes());
}
/*******************************************************************************
** Saved GET variant uses the same file executor.
*******************************************************************************/
public static class Saved extends AnalysisFileSpec
{
/*******************************************************************************
** Core-visible saved definition is re-run as viewer before export.
*******************************************************************************/
@Override
public BasicOperation defineBasicOperation()
{
return (new BasicOperation().withPath(DataAnalysisApi.PREFIX + "/saved/{id}/export").withHttpMethod(HttpMethod.GET)
.withShortSummary("Export a saved analysis").withLongDescription("Re-run a visible saved analysis as the viewer, applying current source permissions and dropping unavailable fields, then download its result table as CSV or XLSX."));
}
/*******************************************************************************
** Required id and CSV/XLSX query format.
*******************************************************************************/
@Override
public List<Parameter> defineRequestParameters()
{
return (List.of(new Parameter().withName("id").withIn(In.PATH).withRequired(true).withDescription("Visible saved analysis id.").withSchema(new Schema().withType(Type.INTEGER)),
new Parameter().withName("format").withIn(In.QUERY).withRequired(true).withDescription("Result file format.").withSchema(new Schema().withType(Type.STRING).withEnumValues(List.of("csv", "xlsx")))));
}
/*******************************************************************************
** GET has no request body.
*******************************************************************************/
@Override
public RequestBody defineRequestBody()
{
return (null);
}
}
/*******************************************************************************
** Input data only, inherited middleware fields carry the authenticated session.
*******************************************************************************/
public static class Input extends AbstractMiddlewareInput
{
private Integer id;
private String format;
private Map<String, Object> body;
}
/*******************************************************************************
** Binary output stays out of JSON serialization.
*******************************************************************************/
public static class Output implements AbstractMiddlewareOutputInterface
{
private AnalysisExport.File file;
}
/*******************************************************************************
** Invoked after the normal middleware session pipeline.
*******************************************************************************/
public static class Executor extends AbstractMiddlewareExecutor<Input, Output>
{
/*******************************************************************************
** No direct source access outside the existing authorized analysis engine.
*******************************************************************************/
@Override
public void execute(Input input, Output output) throws QException
{
var result = input.id == null ? SavedApi.definition(input.body, null).run(DataAnalysisRuntime.service(), true)
: DataAnalysisRuntime.saved().run(input.id);
output.file = AnalysisExport.file(result, input.format);
}
}
}
@@ -28,8 +28,14 @@ import com.kingsrook.qbits.dataanalysis.engine.CoreAnalysisBackend;
import com.kingsrook.qbits.dataanalysis.result.AnalysisRequest;
import com.kingsrook.qbits.dataanalysis.result.ChartKind;
import com.kingsrook.qbits.dataanalysis.result.ColumnProfileRequest;
import com.kingsrook.qbits.dataanalysis.result.CompareRequest;
import com.kingsrook.qbits.dataanalysis.result.CorrelationRequest;
import com.kingsrook.qbits.dataanalysis.result.CrosstabRequest;
import com.kingsrook.qbits.dataanalysis.result.DistinctValuesRequest;
import com.kingsrook.qbits.dataanalysis.result.DuplicatesRequest;
import com.kingsrook.qbits.dataanalysis.result.PivotRequest;
import com.kingsrook.qbits.dataanalysis.result.ScatterRequest;
import com.kingsrook.qbits.dataanalysis.result.ShiftRequest;
import com.kingsrook.qbits.dataanalysis.result.TableProfileRequest;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
@@ -51,7 +57,7 @@ import com.kingsrook.qqq.openapi.model.Schema;
import com.kingsrook.qqq.openapi.model.Type;
/*******************************************************************************
** Session-bound profile operations registered only with optional Javalin present.
** Session-bound analysis operations registered only with optional Javalin present.
*******************************************************************************/
public class DataAnalysisApi
{
@@ -70,14 +76,17 @@ public class DataAnalysisApi
*******************************************************************************/
public static MiddlewareSpecExtension extension()
{
return (new MiddlewareSpecExtension().withName("data-analysis").withSemanticVersion("1.0.0")
.withDescription("Profiles, distinct values, duplicate groups and exact analysis runs as the signed-in user.")
return (new MiddlewareSpecExtension().withName("data-analysis").withSemanticVersion("1.5.0")
.withDescription("Profiles, pivots, comparisons, distribution shifts, correlations, scatter samples, crosstabs and anomaly watch previews as the signed-in user.")
.withSpec(SavedApi.Run.class).withSpec(SavedApi.ListSaved.class).withSpec(SavedApi.Star.class).withSpec(SavedApi.Unstar.class)
.withSpec(SavedApi.Sql.class).withSpec(AnalysisFileSpec.class).withSpec(AnalysisFileSpec.Saved.class)
.withSpec(CapabilitiesSpec.class).withSpec(ColumnProfileSpec.class).withSpec(DistinctValuesSpec.class)
.withSpec(TableProfileSpec.class).withSpec(DuplicatesSpec.class).withSpec(StartRunSpec.class).withSpec(GetRunSpec.class));
.withSpec(CompareSpec.class).withSpec(ShiftSpec.class).withSpec(CorrelationSpec.class).withSpec(ScatterSpec.class).withSpec(CrosstabSpec.class)
.withSpec(WatchPreviewSpec.class).withSpec(PivotSpec.class).withSpec(TableProfileSpec.class).withSpec(DuplicatesSpec.class).withSpec(StartRunSpec.class).withSpec(GetRunSpec.class));
}
/*******************************************************************************
** Common schema catalog and path parameters for the seven JSON specs.
** Common schema catalog and path parameters for the analysis JSON specs.
*******************************************************************************/
public abstract static class ProfileSpec extends AbstractJsonEndpointSpec
{
@@ -116,9 +125,9 @@ public class DataAnalysisApi
@Override
public List<Parameter> defineRequestParameters()
{
String name = path.contains("{table}") ? "table" : path.contains("{runId}") ? "runId" : null;
String name = path.contains("{table}") ? "table" : path.contains("{runId}") ? "runId" : path.contains("{id}") ? "id" : null;
return (name == null ? List.of() : List.of(new Parameter().withName(name).withIn(In.PATH).withRequired(true)
.withDescription(name.equals("table") ? "QQQ table name to analyze." : "Owner-scoped analysis run id.").withSchema(new Schema().withType(Type.STRING))));
.withDescription(name.equals("table") ? "QQQ table name to analyze." : "Owner-scoped analysis run or watch id.").withSchema(new Schema().withType(Type.STRING))));
}
/*******************************************************************************
@@ -184,7 +193,7 @@ public class DataAnalysisApi
throw new IllegalArgumentException("exact must be a boolean.");
}
QQueryFilter filter = body.get("filter") == null ? null : JsonUtils.toObject(JsonUtils.toJson(body.get("filter")), QQueryFilter.class);
validateFilter(filter, readable);
validateFilter(filter);
List<String> fields = null;
if(body.get("fields") != null)
{
@@ -224,7 +233,7 @@ public class DataAnalysisApi
/*******************************************************************************
** Bad filter fields fail before any aggregate or cached result is consulted.
*******************************************************************************/
private static void validateFilter(QQueryFilter filter, List<String> readable)
private static void validateFilter(QQueryFilter filter)
{
if(filter == null)
{
@@ -232,13 +241,12 @@ public class DataAnalysisApi
}
for(var criterion : filter.getCriteria())
{
if(criterion.getOperator() == null || !readable.contains(criterion.getFieldName())
|| criterion.getOtherFieldName() != null && !readable.contains(criterion.getOtherFieldName()))
if(criterion.getOperator() == null || criterion.getFieldName() == null)
{
throw new IllegalArgumentException("Choose readable filter fields and a valid operator.");
}
}
filter.getSubFilters().forEach(sub -> validateFilter(sub, readable));
filter.getSubFilters().forEach(sub -> validateFilter(sub));
}
/*******************************************************************************
@@ -457,8 +465,7 @@ public class DataAnalysisApi
result.canAnalyze = false;
result.fields = List.of();
result.backendCapabilities = List.of();
result.sqlWorkbenchAvailable = QContext.getQInstance().getApp("sqlWorkbench") != null
|| QContext.getQInstance().getTables().keySet().stream().anyMatch(t -> t.startsWith("sql_workbench_"));
result.sqlWorkbenchAvailable = com.kingsrook.qbits.dataanalysis.saved.SqlHandoff.installedAndAllowed();
try
{
var capabilities = DataAnalysisRuntime.service().capabilities(name);
@@ -504,4 +511,284 @@ public class DataAnalysisApi
};
return (result);
}
/*******************************************************************************
** Group records by row and column dimensions.
*******************************************************************************/
public static class PivotSpec extends ProfileSpec
{
/*******************************************************************************
** Publish assistant-friendly grouping and measure capabilities.
*******************************************************************************/
public PivotSpec()
{
super("/tables/{table}/pivot", HttpMethod.POST, "Explore a pivot table",
"Group records by up to 3 row and 2 column fields (with date or numeric buckets) and compute counts, sums, averages, min/max, distinct counts or percentiles per cell; every cell has a drill-through filter.", "PivotRequest", "Pivot");
}
/*******************************************************************************
** Strict body validation precedes the session-bound engine.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
String tableName = input.getPathParam("table");
table(tableName);
DataAnalysisRuntime.service().capabilities(tableName);
PivotRequest pivot;
try
{
Map<String, Object> body = input.getBody();
integer(body, "limitGroups", 50, 1, 200);
if(body.containsKey("showTotals") && !(body.get("showTotals") instanceof Boolean))
{
throw new IllegalArgumentException("showTotals must be a boolean.");
}
for(String axis : List.of("rows", "columns"))
{
if(body.containsKey(axis))
{
if(!(body.get(axis) instanceof List<?> dimensions))
{
throw new IllegalArgumentException("Dimensions must be arrays.");
}
for(Object dimension : dimensions)
{
if(!(dimension instanceof Map<?, ?> map) || !(map.get("field") instanceof String))
{
throw new IllegalArgumentException("Each dimension requires a field name.");
}
if(map.get("numericBins") instanceof Map<?, ?> bins)
{
Object count = bins.get("count");
if(count != null && (!(count instanceof Number number) || number.doubleValue() != number.intValue()))
{
throw new IllegalArgumentException("Bin count must be an integer.");
}
}
}
}
}
if(!(body.get("values") instanceof List<?> values) || values.stream().anyMatch(v -> !(v instanceof Map<?, ?> m)
|| !(m.get("operator") instanceof String) || m.get("field") != null && !(m.get("field") instanceof String)))
{
throw new IllegalArgumentException("Measures require an operator and optional field name.");
}
pivot = JsonUtils.toObject(JsonUtils.toJson(body), PivotRequest.class).withTableName(tableName);
validateFilter(pivot.getFilter());
}
catch(Exception e)
{
throw new QBadRequestException("Invalid pivot request.");
}
return (transport(DataAnalysisRuntime.service().pivot(pivot), DataAnalysisSchemas.DataAnalysisPivotV1.class));
}
}
/*******************************************************************************
** Strict JSON types before Jackson conversion; engine validates FULL fields.
*******************************************************************************/
private static <T> T relationshipRequest(String tableName, Map<String, Object> body, Class<T> type) throws Exception
{
table(tableName);
DataAnalysisRuntime.service().capabilities(tableName);
try
{
for(String name : List.of("field", "dateField", "bucket", "xField", "yField", "rowField", "columnField", "labelA", "labelB"))
{
if(body.containsKey(name) && !(body.get(name) instanceof String))
{
throw new IllegalArgumentException("Expected a field name or label.");
}
}
if(body.containsKey("fields") && (!(body.get("fields") instanceof List<?> fields) || fields.stream().anyMatch(f -> !(f instanceof String))))
{
throw new IllegalArgumentException("Expected an array of field names.");
}
if(body.containsKey("limit"))
{
integer(body, "limit", 2000, 1, type == CrosstabRequest.class ? 20 : 2000);
}
for(String name : List.of("filter", "filterA", "filterB"))
{
Object filter = body.get(name);
if(filter != null)
{
if(!(filter instanceof Map<?, ?>))
{
throw new IllegalArgumentException("Expected a query filter object.");
}
validateFilter(JsonUtils.toObject(JsonUtils.toJson(filter), QQueryFilter.class));
}
}
return (JsonUtils.toObject(JsonUtils.toJson(body), type));
}
catch(Exception e)
{
throw new QBadRequestException("Invalid relationship request.");
}
}
/*******************************************************************************
** Compare filtered A with filtered B (null means the whole permitted table). Return means, medians or category shares, B-minus-A deltas, valid significance tests and count-equivalent drills. Only FULL fields are accepted.
*******************************************************************************/
public static class CompareSpec extends ProfileSpec
{
/*******************************************************************************
** Public constructor for endpoint and assistant discovery.
*******************************************************************************/
public CompareSpec()
{
super("/tables/{table}/compare", HttpMethod.POST, "Compare two populations",
"Compare filtered A with filtered B (null means the whole permitted table). Return means, medians or category shares, B-minus-A deltas, valid significance tests and count-equivalent drills. Only FULL fields are accepted.", "CompareRequest", "Compare");
}
/*******************************************************************************
** Execute with the calling session and versioned transport contract.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
String tableName = input.getPathParam("table");
CompareRequest request = relationshipRequest(tableName, input.getBody(), CompareRequest.class).withTableName(tableName);
return (transport(DataAnalysisRuntime.service().compare(request), RelationshipSchemas.DataAnalysisCompareV1.class));
}
}
/*******************************************************************************
** Compare category shares or numeric quartiles across session-timezone calendar buckets. Compute descriptive PSI between the first and last complete nonempty buckets using fixed categories or baseline quartile bins.
*******************************************************************************/
public static class ShiftSpec extends ProfileSpec
{
/*******************************************************************************
** Public constructor for endpoint and assistant discovery.
*******************************************************************************/
public ShiftSpec()
{
super("/tables/{table}/shift", HttpMethod.POST, "Measure distribution shift over time",
"Compare category shares or numeric quartiles across session-timezone calendar buckets. Compute descriptive PSI between the first and last complete nonempty buckets using fixed categories or baseline quartile bins.", "ShiftRequest", "Shift");
}
/*******************************************************************************
** Execute with the calling session and versioned transport contract.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
String tableName = input.getPathParam("table");
ShiftRequest request = relationshipRequest(tableName, input.getBody(), ShiftRequest.class).withTableName(tableName);
return (transport(DataAnalysisRuntime.service().shift(request), RelationshipSchemas.DataAnalysisShiftV1.class));
}
}
/*******************************************************************************
** Compute a Pearson correlation matrix for 2 to 12 distinct FULL numeric fields, using paired non-null records. Every cell includes n and parameters for the scatter endpoint; core pushes down CORR or uses bounded streaming.
*******************************************************************************/
public static class CorrelationSpec extends ProfileSpec
{
/*******************************************************************************
** Public constructor for endpoint and assistant discovery.
*******************************************************************************/
public CorrelationSpec()
{
super("/tables/{table}/correlation", HttpMethod.POST, "Find numeric relationships",
"Compute a Pearson correlation matrix for 2 to 12 distinct FULL numeric fields, using paired non-null records. Every cell includes n and parameters for the scatter endpoint; core pushes down CORR or uses bounded streaming.", "CorrelationRequest", "Correlation");
}
/*******************************************************************************
** Execute with the calling session and versioned transport contract.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
String tableName = input.getPathParam("table");
CorrelationRequest request = relationshipRequest(tableName, input.getBody(), CorrelationRequest.class).withTableName(tableName);
return (transport(DataAnalysisRuntime.service().correlation(request), RelationshipSchemas.DataAnalysisCorrelationV1.class));
}
}
/*******************************************************************************
** Return at most 2000 paired numeric points as the user, ordered by primary key when core query sampling is unavailable, plus a least-squares line fitted to the sample. Privacy disables individual drills and suppresses small populations.
*******************************************************************************/
public static class ScatterSpec extends ProfileSpec
{
/*******************************************************************************
** Public constructor for endpoint and assistant discovery.
*******************************************************************************/
public ScatterSpec()
{
super("/tables/{table}/scatter", HttpMethod.POST, "Inspect a numeric relationship",
"Return at most 2000 paired numeric points as the user, ordered by primary key when core query sampling is unavailable, plus a least-squares line fitted to the sample. Privacy disables individual drills and suppresses small populations.", "ScatterRequest", "Scatter");
}
/*******************************************************************************
** Execute with the calling session and versioned transport contract.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
String tableName = input.getPathParam("table");
ScatterRequest request = relationshipRequest(tableName, input.getBody(), ScatterRequest.class).withTableName(tableName);
return (transport(DataAnalysisRuntime.service().scatter(request), RelationshipSchemas.DataAnalysisScatterV1.class));
}
}
/*******************************************************************************
** Count combinations of two FULL fields with row and column shares, up to 20 categories per axis plus Other. Test independence using chi-square and Cramer V after pooling low expected counts; privacy suppresses small cells and their drills.
*******************************************************************************/
public static class CrosstabSpec extends ProfileSpec
{
/*******************************************************************************
** Public constructor for endpoint and assistant discovery.
*******************************************************************************/
public CrosstabSpec()
{
super("/tables/{table}/crosstab", HttpMethod.POST, "Cross-tabulate two fields",
"Count combinations of two FULL fields with row and column shares, up to 20 categories per axis plus Other. Test independence using chi-square and Cramer V after pooling low expected counts; privacy suppresses small cells and their drills.", "CrosstabRequest", "Crosstab");
}
/*******************************************************************************
** Execute with the calling session and versioned transport contract.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
String tableName = input.getPathParam("table");
CrosstabRequest request = relationshipRequest(tableName, input.getBody(), CrosstabRequest.class).withTableName(tableName);
return (transport(DataAnalysisRuntime.service().crosstab(request), RelationshipSchemas.DataAnalysisCrosstabV1.class));
}
}
/*******************************************************************************
** Read-only watch preview; standard table endpoints own watch CRUD.
*******************************************************************************/
public static class WatchPreviewSpec extends ProfileSpec
{
/*******************************************************************************
** Publish a side-effect-free detector preview for a saved watch.
*******************************************************************************/
public WatchPreviewSpec()
{
super("/watches/{id}/preview", HttpMethod.POST, "Preview an anomaly watch",
"Compute complete time buckets and a detector verdict under the signed-in user's READ, Analyze and FULL-field permissions. Includes a baseline band annotation. Does not update the watch or raise alerts.", null, "WatchPreview");
}
/*******************************************************************************
** Missing or inaccessible watch ids return the same not-found response.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
Integer id;
try
{
id = Integer.valueOf(input.getPathParam("id"));
}
catch(NumberFormatException e)
{
throw new QBadRequestException("Watch id must be an integer.");
}
return (transport(DataAnalysisRuntime.watches().preview(id, java.time.Instant.now()), WatchSchemas.DataAnalysisWatchPreviewV1.class));
}
}
}
@@ -106,6 +106,17 @@ public class DataAnalysisSchemas
result.put("DataAnalysisLimitsV1", new DataAnalysisLimitsV1().toSchema());
result.put("DataAnalysisStartRunRequestV1", new DataAnalysisStartRunRequestV1().toSchema());
result.put("DataAnalysisRunStartedV1", new DataAnalysisRunStartedV1().toSchema());
result.put("DataAnalysisPivotRequestV1", new DataAnalysisPivotRequestV1().toSchema());
result.put("DataAnalysisPivotDimensionV1", new DataAnalysisPivotDimensionV1().toSchema());
result.put("DataAnalysisPivotNumericBinsV1", new DataAnalysisPivotNumericBinsV1().toSchema());
result.put("DataAnalysisPivotMeasureV1", new DataAnalysisPivotMeasureV1().toSchema());
result.put("DataAnalysisPivotHeaderV1", new DataAnalysisPivotHeaderV1().toSchema());
result.put("DataAnalysisPivotMeasureInfoV1", new DataAnalysisPivotMeasureInfoV1().toSchema());
result.put("DataAnalysisPivotCellV1", new DataAnalysisPivotCellV1().toSchema());
result.put("DataAnalysisPivotV1", new DataAnalysisPivotV1().toSchema());
result.putAll(RelationshipSchemas.components());
result.putAll(WatchSchemas.components());
result.putAll(SavedSchemas.components());
return (result);
}
@@ -173,6 +184,9 @@ public class DataAnalysisSchemas
@OpenAPIDescription("Semantic field kind: NUMERIC, DATE, DATE_TIME, TEXT, BOOLEAN or CATEGORY.")
public ChartKind kind;
@OpenAPIDescription("Stack category series to a total share of one when true.")
public Boolean stacked;
@OpenAPIDescription("Alternatives.")
public List<ChartKind> alternatives;
@@ -195,6 +209,7 @@ public class DataAnalysisSchemas
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("stacked", new Schema().withType(Type.BOOLEAN).withNullable(true).withDescription("Stack category series to a total share of one when true."));
properties.put("kind", new Schema().withType(Type.STRING).withEnumValues(java.util.Arrays.stream(ChartKind.values()).map(Enum::name).toList()).withDescription("Semantic field kind: NUMERIC, DATE, DATE_TIME, TEXT, BOOLEAN or CATEGORY.").withNullable(true));
properties.put("alternatives", new Schema().withType(Type.ARRAY).withItems(new Schema().withType(Type.STRING).withEnumValues(java.util.Arrays.stream(ChartKind.values()).map(Enum::name).toList())).withDescription("Alternatives.").withNullable(true));
properties.put("x", ref("DataAnalysisAxisV1").withDescription("X.").withNullable(true));
@@ -1146,4 +1161,281 @@ public class DataAnalysisSchemas
return (new Schema().withType(Type.OBJECT).withNullable(true).withProperties(properties));
}
}
/*******************************************************************************
** Nested arrays share the same explicit schema construction.
*******************************************************************************/
private static Schema array(Schema items)
{
return (new Schema().withType(Type.ARRAY).withItems(items));
}
/*******************************************************************************
** PivotRequest version 1 transport contract.
*******************************************************************************/
public static class DataAnalysisPivotRequestV1 implements ToSchema
{
@OpenAPIDescription("User query filter, passed through for core enforcement.")
public QQueryFilter filter;
@OpenAPIDescription("One to three row dimensions.")
public List<DataAnalysisPivotDimensionV1> rows;
@OpenAPIDescription("Zero to two column dimensions; defaults to empty.")
public List<DataAnalysisPivotDimensionV1> columns;
@OpenAPIDescription("One to six measures.")
public List<DataAnalysisPivotMeasureV1> values;
@OpenAPIDescription("Include row, column and grand totals; defaults to true.")
public Boolean showTotals;
@OpenAPIDescription("Kept groups per dimension; default 50, maximum 200.")
public Integer limitGroups;
/*******************************************************************************
** Explicit references preserve the standalone extension contract.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("filter", ref("QueryFilter").withDescription("User query filter, passed through for core enforcement."));
properties.put("rows", array(ref("DataAnalysisPivotDimensionV1")).withDescription("One to three row dimensions."));
properties.put("columns", array(ref("DataAnalysisPivotDimensionV1")).withDescription("Zero to two column dimensions; defaults to empty."));
properties.put("values", array(ref("DataAnalysisPivotMeasureV1")).withDescription("One to six measures."));
properties.put("showTotals", new Schema().withType(Type.BOOLEAN).withDescription("Include row, column and grand totals; defaults to true."));
properties.put("limitGroups", new Schema().withType(Type.INTEGER).withDescription("Kept groups per dimension; default 50, maximum 200."));
return (new RequiredSchema(List.of("rows", "values")).withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** PivotDimension version 1 transport contract.
*******************************************************************************/
public static class DataAnalysisPivotDimensionV1 implements ToSchema
{
@OpenAPIDescription("FULL field name, optionally joinTable.field through an exposed join.")
public String field;
@OpenAPIDescription("Optional calendar or cyclic bucket in the session timezone.")
public String dateBucket;
@OpenAPIDescription("Optional equal-width numeric bins; mutually exclusive with dateBucket.")
public DataAnalysisPivotNumericBinsV1 numericBins;
/*******************************************************************************
** Explicit references preserve the standalone extension contract.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("field", new Schema().withType(Type.STRING).withDescription("FULL field name, optionally joinTable.field through an exposed join."));
properties.put("dateBucket", new Schema().withType(Type.STRING).withEnumValues(List.of("YEAR", "QUARTER", "MONTH", "WEEK", "DAY", "HOUR", "DAY_OF_WEEK", "HOUR_OF_DAY")).withDescription("Optional calendar or cyclic bucket in the session timezone."));
properties.put("numericBins", ref("DataAnalysisPivotNumericBinsV1").withDescription("Optional equal-width numeric bins; mutually exclusive with dateBucket."));
return (new RequiredSchema(List.of("field")).withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** PivotNumericBins version 1 transport contract.
*******************************************************************************/
public static class DataAnalysisPivotNumericBinsV1 implements ToSchema
{
@OpenAPIDescription("Number of bins, 1–200; defaults to 20.")
public Integer count;
@OpenAPIDescription("Optional explicit lower bound; otherwise a nice enclosing edge.")
public BigDecimal min;
@OpenAPIDescription("Optional explicit upper bound; final interior bin includes this value.")
public BigDecimal max;
/*******************************************************************************
** Explicit references preserve the standalone extension contract.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("count", new Schema().withType(Type.INTEGER).withDescription("Number of bins, 1–200; defaults to 20."));
properties.put("min", new Schema().withType(Type.NUMBER).withDescription("Optional explicit lower bound; otherwise a nice enclosing edge."));
properties.put("max", new Schema().withType(Type.NUMBER).withDescription("Optional explicit upper bound; final interior bin includes this value."));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** PivotMeasure version 1 transport contract.
*******************************************************************************/
public static class DataAnalysisPivotMeasureV1 implements ToSchema
{
@OpenAPIDescription("Aggregate operator. COUNT counts records, including null values.")
public String operator;
@OpenAPIDescription("FULL field to aggregate; optional for COUNT.")
public String field;
@OpenAPIDescription("PERCENTILE only: percentile_cont fraction from 0 to 1.")
public BigDecimal percentile;
/*******************************************************************************
** Explicit references preserve the standalone extension contract.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("operator", new Schema().withType(Type.STRING).withEnumValues(List.of("COUNT", "SUM", "AVG", "MIN", "MAX", "COUNT_DISTINCT", "PERCENTILE")).withDescription("Aggregate operator. COUNT counts records, including null values."));
properties.put("field", new Schema().withType(Type.STRING).withDescription("FULL field to aggregate; optional for COUNT."));
properties.put("percentile", new Schema().withType(Type.NUMBER).withDescription("PERCENTILE only: percentile_cont fraction from 0 to 1."));
return (new RequiredSchema(List.of("operator")).withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** PivotHeader version 1 transport contract.
*******************************************************************************/
public static class DataAnalysisPivotHeaderV1 implements ToSchema
{
@OpenAPIDescription("Typed group key; null for a blank group or Other.")
public Serializable value;
@OpenAPIDescription("Display label, including Other (k groups).")
public String label;
/*******************************************************************************
** Explicit references preserve the standalone extension contract.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("value", new Schema().withNullable(true).withDescription("Typed group key; null for a blank group or Other."));
properties.put("label", new Schema().withType(Type.STRING).withDescription("Display label, including Other (k groups)."));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** PivotMeasureInfo version 1 transport contract.
*******************************************************************************/
public static class DataAnalysisPivotMeasureInfoV1 implements ToSchema
{
@OpenAPIDescription("Stable measure key by request position.")
public String key;
@OpenAPIDescription("Display label.")
public String label;
@OpenAPIDescription("Semantic metric type.")
public ValueType valueType;
/*******************************************************************************
** Explicit references preserve the standalone extension contract.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("key", new Schema().withType(Type.STRING).withDescription("Stable measure key by request position."));
properties.put("label", new Schema().withType(Type.STRING).withDescription("Display label."));
properties.put("valueType", new Schema().withType(Type.STRING).withEnumValues(java.util.Arrays.stream(ValueType.values()).map(Enum::name).toList()).withDescription("Semantic metric type."));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** PivotCell version 1 transport contract.
*******************************************************************************/
public static class DataAnalysisPivotCellV1 implements ToSchema
{
@OpenAPIDescription("Zero-based index in rowHeaders.")
public Integer rowIndex;
@OpenAPIDescription("Zero-based index in columnHeaders.")
public Integer columnIndex;
@OpenAPIDescription("Metrics in requested measure order; suppressed metrics have no value or drill.")
public List<DataAnalysisMetricV1> values;
/*******************************************************************************
** Explicit references preserve the standalone extension contract.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("rowIndex", new Schema().withType(Type.INTEGER).withDescription("Zero-based index in rowHeaders."));
properties.put("columnIndex", new Schema().withType(Type.INTEGER).withDescription("Zero-based index in columnHeaders."));
properties.put("values", array(ref("DataAnalysisMetricV1")).withDescription("Metrics in requested measure order; suppressed metrics have no value or drill."));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** Pivot version 1 transport contract.
*******************************************************************************/
public static class DataAnalysisPivotV1 implements ToSchema
{
@OpenAPIDescription("Row header tuples in cell-index order.")
public List<List<DataAnalysisPivotHeaderV1>> rowHeaders;
@OpenAPIDescription("Column header tuples; an empty tuple represents no column dimensions.")
public List<List<DataAnalysisPivotHeaderV1>> columnHeaders;
@OpenAPIDescription("Measure metadata in request order.")
public List<DataAnalysisPivotMeasureInfoV1> measures;
@OpenAPIDescription("Sparse cells; absent combinations are not materialized.")
public List<DataAnalysisPivotCellV1> cells;
@OpenAPIDescription("Metric tuples aligned with rowHeaders; empty when totals disabled.")
public List<List<DataAnalysisMetricV1>> rowTotals;
@OpenAPIDescription("Metric tuples aligned with columnHeaders; empty when totals disabled.")
public List<List<DataAnalysisMetricV1>> columnTotals;
@OpenAPIDescription("Grand-total metrics; empty when totals disabled.")
public List<DataAnalysisMetricV1> grandTotals;
@OpenAPIDescription("Row groups were merged into Other.")
public Boolean truncatedRows;
@OpenAPIDescription("Column groups were merged into Other.")
public Boolean truncatedColumns;
@OpenAPIDescription("True when bounded streamed fallback produced a partial result.")
public Boolean estimate;
@OpenAPIDescription("Privacy, partial-result and joined-drill limitations.")
public List<String> warnings;
@OpenAPIDescription("UTC timestamp of computation.")
public String asOf;
/*******************************************************************************
** Explicit references preserve the standalone extension contract.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("rowHeaders", array(array(ref("DataAnalysisPivotHeaderV1"))).withDescription("Row header tuples in cell-index order."));
properties.put("columnHeaders", array(array(ref("DataAnalysisPivotHeaderV1"))).withDescription("Column header tuples; an empty tuple represents no column dimensions."));
properties.put("measures", array(ref("DataAnalysisPivotMeasureInfoV1")).withDescription("Measure metadata in request order."));
properties.put("cells", array(ref("DataAnalysisPivotCellV1")).withDescription("Sparse cells; absent combinations are not materialized."));
properties.put("rowTotals", array(array(ref("DataAnalysisMetricV1"))).withDescription("Metric tuples aligned with rowHeaders; empty when totals disabled."));
properties.put("columnTotals", array(array(ref("DataAnalysisMetricV1"))).withDescription("Metric tuples aligned with columnHeaders; empty when totals disabled."));
properties.put("grandTotals", array(ref("DataAnalysisMetricV1")).withDescription("Grand-total metrics; empty when totals disabled."));
properties.put("truncatedRows", new Schema().withType(Type.BOOLEAN).withDescription("Row groups were merged into Other."));
properties.put("truncatedColumns", new Schema().withType(Type.BOOLEAN).withDescription("Column groups were merged into Other."));
properties.put("estimate", new Schema().withType(Type.BOOLEAN).withDescription("True when bounded streamed fallback produced a partial result."));
properties.put("warnings", array(new Schema().withType(Type.STRING)).withDescription("Privacy, partial-result and joined-drill limitations."));
properties.put("asOf", new Schema().withType(Type.STRING).withDescription("UTC timestamp of computation."));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
}
@@ -0,0 +1,663 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.api;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.middleware.javalin.schemabuilder.ToSchema;
import com.kingsrook.qqq.middleware.javalin.schemabuilder.annotations.OpenAPIDescription;
import com.kingsrook.qqq.openapi.model.Schema;
import com.kingsrook.qqq.openapi.model.Type;
/*******************************************************************************
** Explicit version-one contracts for compare and relationships.
*******************************************************************************/
public class RelationshipSchemas
{
/*******************************************************************************
** Register every referenced response and request component.
*******************************************************************************/
public static Map<String, Schema> components()
{
Map<String, Schema> result = new LinkedHashMap<>();
result.put("DataAnalysisCompareRequestV1", new DataAnalysisCompareRequestV1().toSchema());
result.put("DataAnalysisShiftRequestV1", new DataAnalysisShiftRequestV1().toSchema());
result.put("DataAnalysisCorrelationRequestV1", new DataAnalysisCorrelationRequestV1().toSchema());
result.put("DataAnalysisScatterRequestV1", new DataAnalysisScatterRequestV1().toSchema());
result.put("DataAnalysisCrosstabRequestV1", new DataAnalysisCrosstabRequestV1().toSchema());
result.put("DataAnalysisSignificanceV1", new DataAnalysisSignificanceV1().toSchema());
result.put("DataAnalysisComparisonSideV1", new DataAnalysisComparisonSideV1().toSchema());
result.put("DataAnalysisComparisonValueV1", new DataAnalysisComparisonValueV1().toSchema());
result.put("DataAnalysisFieldComparisonV1", new DataAnalysisFieldComparisonV1().toSchema());
result.put("DataAnalysisCompareV1", new DataAnalysisCompareV1().toSchema());
result.put("DataAnalysisShiftBucketV1", new DataAnalysisShiftBucketV1().toSchema());
result.put("DataAnalysisShiftV1", new DataAnalysisShiftV1().toSchema());
result.put("DataAnalysisCorrelationCellV1", new DataAnalysisCorrelationCellV1().toSchema());
result.put("DataAnalysisCorrelationV1", new DataAnalysisCorrelationV1().toSchema());
result.put("DataAnalysisTrendLineV1", new DataAnalysisTrendLineV1().toSchema());
result.put("DataAnalysisScatterV1", new DataAnalysisScatterV1().toSchema());
result.put("DataAnalysisCrosstabCellV1", new DataAnalysisCrosstabCellV1().toSchema());
result.put("DataAnalysisCrosstabV1", new DataAnalysisCrosstabV1().toSchema());
return (result);
}
/*******************************************************************************
** Reuse the common metric, filter and chart contracts.
*******************************************************************************/
private static Schema ref(String name)
{
return (new Schema().withRef("#/components/schemas/" + name));
}
/*******************************************************************************
** CompareRequest version-one transport model.
*******************************************************************************/
public static class DataAnalysisCompareRequestV1 implements ToSchema
{
@OpenAPIDescription("Population A filter; null selects the whole permitted table.")
public QQueryFilter filterA;
@OpenAPIDescription("Population B filter; null selects the whole permitted table.")
public QQueryFilter filterB;
@OpenAPIDescription("Display name of population A; default A.")
public String labelA;
@OpenAPIDescription("Display name of population B; default B.")
public String labelB;
@OpenAPIDescription("Distinct FULL fields to analyze; correlation requires 2 to 12 numeric fields.")
public List<String> fields;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("filterA", ref("QueryFilter").withDescription("Population A filter; null selects the whole permitted table.").withNullable(true));
properties.put("filterB", ref("QueryFilter").withDescription("Population B filter; null selects the whole permitted table.").withNullable(true));
properties.put("labelA", new Schema().withType(Type.STRING).withDescription("Display name of population A; default A."));
properties.put("labelB", new Schema().withType(Type.STRING).withDescription("Display name of population B; default B."));
properties.put("fields", new Schema().withType(Type.ARRAY).withItems(new Schema().withType(Type.STRING)).withDescription("Distinct FULL fields to analyze; correlation requires 2 to 12 numeric fields."));
return (new DataAnalysisSchemas.RequiredSchema(List.of("fields")).withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** ShiftRequest version-one transport model.
*******************************************************************************/
public static class DataAnalysisShiftRequestV1 implements ToSchema
{
@OpenAPIDescription("Current-user query filter; record locks and core field rules apply.")
public QQueryFilter filter;
@OpenAPIDescription("FULL field whose distribution is compared over time.")
public String field;
@OpenAPIDescription("FULL DATE or DATE_TIME field for session-timezone calendar buckets.")
public String dateField;
@OpenAPIDescription("Calendar unit: HOUR, DAY, WEEK, MONTH, QUARTER or YEAR; default MONTH.")
public String bucket;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("filter", ref("QueryFilter").withDescription("Current-user query filter; record locks and core field rules apply.").withNullable(true));
properties.put("field", new Schema().withType(Type.STRING).withDescription("FULL field whose distribution is compared over time."));
properties.put("dateField", new Schema().withType(Type.STRING).withDescription("FULL DATE or DATE_TIME field for session-timezone calendar buckets."));
properties.put("bucket", new Schema().withType(Type.STRING).withDescription("Calendar unit: HOUR, DAY, WEEK, MONTH, QUARTER or YEAR; default MONTH."));
return (new DataAnalysisSchemas.RequiredSchema(List.of("field", "dateField")).withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** CorrelationRequest version-one transport model.
*******************************************************************************/
public static class DataAnalysisCorrelationRequestV1 implements ToSchema
{
@OpenAPIDescription("Current-user query filter; record locks and core field rules apply.")
public QQueryFilter filter;
@OpenAPIDescription("Distinct FULL fields to analyze; correlation requires 2 to 12 numeric fields.")
public List<String> fields;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("filter", ref("QueryFilter").withDescription("Current-user query filter; record locks and core field rules apply.").withNullable(true));
properties.put("fields", new Schema().withType(Type.ARRAY).withItems(new Schema().withType(Type.STRING)).withDescription("Distinct FULL fields to analyze; correlation requires 2 to 12 numeric fields."));
return (new DataAnalysisSchemas.RequiredSchema(List.of("fields")).withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** ScatterRequest version-one transport model.
*******************************************************************************/
public static class DataAnalysisScatterRequestV1 implements ToSchema
{
@OpenAPIDescription("Table for the scatter link; route parameter takes precedence.")
public String tableName;
@OpenAPIDescription("Compatibility flag; scatter always returns the bounded sample.")
public Boolean exact;
@OpenAPIDescription("Current-user query filter; record locks and core field rules apply.")
public QQueryFilter filter;
@OpenAPIDescription("FULL numeric field on the x axis.")
public String xField;
@OpenAPIDescription("FULL numeric field on the y axis.")
public String yField;
@OpenAPIDescription("Maximum sample points (1 to 2000, default 2000) or kept crosstab categories per axis (1 to 20, default 20).")
public Integer limit;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("tableName", new Schema().withType(Type.STRING).withDescription("Table for the scatter link; route parameter takes precedence.").withNullable(true));
properties.put("exact", new Schema().withType(Type.BOOLEAN).withDescription("Compatibility flag; scatter always returns the bounded sample.").withNullable(true));
properties.put("filter", ref("QueryFilter").withDescription("Current-user query filter; record locks and core field rules apply.").withNullable(true));
properties.put("xField", new Schema().withType(Type.STRING).withDescription("FULL numeric field on the x axis."));
properties.put("yField", new Schema().withType(Type.STRING).withDescription("FULL numeric field on the y axis."));
properties.put("limit", new Schema().withType(Type.INTEGER).withDescription("Maximum sample points (1 to 2000, default 2000) or kept crosstab categories per axis (1 to 20, default 20)."));
return (new DataAnalysisSchemas.RequiredSchema(List.of("xField", "yField")).withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** CrosstabRequest version-one transport model.
*******************************************************************************/
public static class DataAnalysisCrosstabRequestV1 implements ToSchema
{
@OpenAPIDescription("Current-user query filter; record locks and core field rules apply.")
public QQueryFilter filter;
@OpenAPIDescription("FULL field defining crosstab rows.")
public String rowField;
@OpenAPIDescription("FULL field defining crosstab columns.")
public String columnField;
@OpenAPIDescription("Maximum sample points (1 to 2000, default 2000) or kept crosstab categories per axis (1 to 20, default 20).")
public Integer limit;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("filter", ref("QueryFilter").withDescription("Current-user query filter; record locks and core field rules apply.").withNullable(true));
properties.put("rowField", new Schema().withType(Type.STRING).withDescription("FULL field defining crosstab rows."));
properties.put("columnField", new Schema().withType(Type.STRING).withDescription("FULL field defining crosstab columns."));
properties.put("limit", new Schema().withType(Type.INTEGER).withDescription("Maximum sample points (1 to 2000, default 2000) or kept crosstab categories per axis (1 to 20, default 20)."));
return (new DataAnalysisSchemas.RequiredSchema(List.of("rowField", "columnField")).withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** Significance version-one transport model.
*******************************************************************************/
public static class DataAnalysisSignificanceV1 implements ToSchema
{
@OpenAPIDescription("Test.")
public String test;
@OpenAPIDescription("Statistic.")
public Double statistic;
@OpenAPIDescription("Degrees of freedom; null when undefined.")
public Double df;
@OpenAPIDescription("Two-sided p-value; p >= 0.05 is never significant.")
public Double pValue;
@OpenAPIDescription("Whether all test validity and privacy requirements hold.")
public Boolean applicable;
@OpenAPIDescription("Plain-language result or reason the statistic is not applicable.")
public String sentence;
@OpenAPIDescription("Cramer association strength computed on the pooled contingency table; null when invalid.")
public Double cramersV;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("test", new Schema().withType(Type.STRING).withDescription("Test.").withNullable(true));
properties.put("statistic", new Schema().withType(Type.NUMBER).withDescription("Statistic.").withNullable(true));
properties.put("df", new Schema().withType(Type.NUMBER).withDescription("Degrees of freedom; null when undefined.").withNullable(true));
properties.put("pValue", new Schema().withType(Type.NUMBER).withDescription("Two-sided p-value; p >= 0.05 is never significant.").withNullable(true));
properties.put("applicable", new Schema().withType(Type.BOOLEAN).withDescription("Whether all test validity and privacy requirements hold.").withNullable(true));
properties.put("sentence", new Schema().withType(Type.STRING).withDescription("Plain-language result or reason the statistic is not applicable.").withNullable(true));
properties.put("cramersV", new Schema().withType(Type.NUMBER).withDescription("Cramer association strength computed on the pooled contingency table; null when invalid.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** ComparisonSide version-one transport model.
*******************************************************************************/
public static class DataAnalysisComparisonSideV1 implements ToSchema
{
@OpenAPIDescription("Label.")
public String label;
@OpenAPIDescription("Typed metrics with exact population drills unless privacy suppresses them.")
public List<DataAnalysisSchemas.DataAnalysisMetricV1> metrics;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("label", new Schema().withType(Type.STRING).withDescription("Label.").withNullable(true));
properties.put("metrics", new Schema().withType(Type.ARRAY).withItems(ref("DataAnalysisMetricV1")).withDescription("Typed metrics with exact population drills unless privacy suppresses them.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** ComparisonValue version-one transport model.
*******************************************************************************/
public static class DataAnalysisComparisonValueV1 implements ToSchema
{
@OpenAPIDescription("Value.")
public Serializable value;
@OpenAPIDescription("Label.")
public String label;
@OpenAPIDescription("Side a.")
public DataAnalysisComparisonSideV1 sideA;
@OpenAPIDescription("Side b.")
public DataAnalysisComparisonSideV1 sideB;
@OpenAPIDescription("B minus A, in original units (share differences are fractions).")
public DataAnalysisSchemas.DataAnalysisMetricV1 delta;
@OpenAPIDescription("(B minus A) divided by absolute A, a fraction; null at a zero baseline.")
public DataAnalysisSchemas.DataAnalysisMetricV1 percentDelta;
@OpenAPIDescription("Test assumptions, two-sided p-value, degrees of freedom and plain-language conclusion.")
public DataAnalysisSignificanceV1 significance;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("value", new Schema().withDescription("Value.").withNullable(true));
properties.put("label", new Schema().withType(Type.STRING).withDescription("Label.").withNullable(true));
properties.put("sideA", ref("DataAnalysisComparisonSideV1").withDescription("Side a.").withNullable(true));
properties.put("sideB", ref("DataAnalysisComparisonSideV1").withDescription("Side b.").withNullable(true));
properties.put("delta", ref("DataAnalysisMetricV1").withDescription("B minus A, in original units (share differences are fractions).").withNullable(true));
properties.put("percentDelta", ref("DataAnalysisMetricV1").withDescription("(B minus A) divided by absolute A, a fraction; null at a zero baseline.").withNullable(true));
properties.put("significance", ref("DataAnalysisSignificanceV1").withDescription("Test assumptions, two-sided p-value, degrees of freedom and plain-language conclusion.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** FieldComparison version-one transport model.
*******************************************************************************/
public static class DataAnalysisFieldComparisonV1 implements ToSchema
{
@OpenAPIDescription("FULL field whose distribution is compared over time.")
public String field;
@OpenAPIDescription("Values.")
public List<DataAnalysisComparisonValueV1> values;
@OpenAPIDescription("Test assumptions, two-sided p-value, degrees of freedom and plain-language conclusion.")
public DataAnalysisSignificanceV1 significance;
@OpenAPIDescription("Semantic series; category comparisons are grouped and category time series are stacked.")
public DataAnalysisSchemas.DataAnalysisChartV1 chart;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("field", new Schema().withType(Type.STRING).withDescription("FULL field whose distribution is compared over time.").withNullable(true));
properties.put("values", new Schema().withType(Type.ARRAY).withItems(ref("DataAnalysisComparisonValueV1")).withDescription("Values.").withNullable(true));
properties.put("significance", ref("DataAnalysisSignificanceV1").withDescription("Test assumptions, two-sided p-value, degrees of freedom and plain-language conclusion.").withNullable(true));
properties.put("chart", ref("DataAnalysisChartV1").withDescription("Semantic series; category comparisons are grouped and category time series are stacked.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** CompareResult version-one transport model.
*******************************************************************************/
public static class DataAnalysisCompareV1 implements ToSchema
{
@OpenAPIDescription("Distinct FULL fields to analyze; correlation requires 2 to 12 numeric fields.")
public List<DataAnalysisFieldComparisonV1> fields;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("fields", new Schema().withType(Type.ARRAY).withItems(ref("DataAnalysisFieldComparisonV1")).withDescription("Distinct FULL fields to analyze; correlation requires 2 to 12 numeric fields.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** ShiftBucket version-one transport model.
*******************************************************************************/
public static class DataAnalysisShiftBucketV1 implements ToSchema
{
@OpenAPIDescription("Value.")
public Serializable value;
@OpenAPIDescription("Label.")
public String label;
@OpenAPIDescription("True when the calendar bucket end has passed in the session timezone.")
public Boolean complete;
@OpenAPIDescription("Typed metrics with exact population drills unless privacy suppresses them.")
public List<DataAnalysisSchemas.DataAnalysisMetricV1> metrics;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("value", new Schema().withDescription("Value.").withNullable(true));
properties.put("label", new Schema().withType(Type.STRING).withDescription("Label.").withNullable(true));
properties.put("complete", new Schema().withType(Type.BOOLEAN).withDescription("True when the calendar bucket end has passed in the session timezone.").withNullable(true));
properties.put("metrics", new Schema().withType(Type.ARRAY).withItems(ref("DataAnalysisMetricV1")).withDescription("Typed metrics with exact population drills unless privacy suppresses them.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** ShiftResult version-one transport model.
*******************************************************************************/
public static class DataAnalysisShiftV1 implements ToSchema
{
@OpenAPIDescription("Buckets.")
public List<DataAnalysisShiftBucketV1> buckets;
@OpenAPIDescription("Population stability index, null when inapplicable; zero shares are floored at 0.000001.")
public DataAnalysisSchemas.DataAnalysisMetricV1 psi;
@OpenAPIDescription("Plain-language result or reason the statistic is not applicable.")
public String sentence;
@OpenAPIDescription("Semantic series; category comparisons are grouped and category time series are stacked.")
public DataAnalysisSchemas.DataAnalysisChartV1 chart;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("buckets", new Schema().withType(Type.ARRAY).withItems(ref("DataAnalysisShiftBucketV1")).withDescription("Buckets.").withNullable(true));
properties.put("psi", ref("DataAnalysisMetricV1").withDescription("Population stability index, null when inapplicable; zero shares are floored at 0.000001.").withNullable(true));
properties.put("sentence", new Schema().withType(Type.STRING).withDescription("Plain-language result or reason the statistic is not applicable.").withNullable(true));
properties.put("chart", ref("DataAnalysisChartV1").withDescription("Semantic series; category comparisons are grouped and category time series are stacked.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** CorrelationCell version-one transport model.
*******************************************************************************/
public static class DataAnalysisCorrelationCellV1 implements ToSchema
{
@OpenAPIDescription("FULL numeric field on the x axis.")
public String xField;
@OpenAPIDescription("FULL numeric field on the y axis.")
public String yField;
@OpenAPIDescription("Pairwise non-null population count; null when privacy suppresses it.")
public Long n;
@OpenAPIDescription("Pearson correlation; null for insufficient data, zero variance or privacy suppression.")
public Double r;
@OpenAPIDescription("POST the included parameters to the table scatter endpoint.")
public DataAnalysisScatterRequestV1 scatter;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("xField", new Schema().withType(Type.STRING).withDescription("FULL numeric field on the x axis.").withNullable(true));
properties.put("yField", new Schema().withType(Type.STRING).withDescription("FULL numeric field on the y axis.").withNullable(true));
properties.put("n", new Schema().withType(Type.INTEGER).withDescription("Pairwise non-null population count; null when privacy suppresses it.").withNullable(true));
properties.put("r", new Schema().withType(Type.NUMBER).withDescription("Pearson correlation; null for insufficient data, zero variance or privacy suppression.").withNullable(true));
properties.put("scatter", ref("DataAnalysisScatterRequestV1").withDescription("POST the included parameters to the table scatter endpoint.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** CorrelationResult version-one transport model.
*******************************************************************************/
public static class DataAnalysisCorrelationV1 implements ToSchema
{
@OpenAPIDescription("Distinct FULL fields to analyze; correlation requires 2 to 12 numeric fields.")
public List<String> fields;
@OpenAPIDescription("Cells.")
public List<DataAnalysisCorrelationCellV1> cells;
@OpenAPIDescription("Semantic series; category comparisons are grouped and category time series are stacked.")
public DataAnalysisSchemas.DataAnalysisChartV1 chart;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("fields", new Schema().withType(Type.ARRAY).withItems(new Schema().withType(Type.STRING)).withDescription("Distinct FULL fields to analyze; correlation requires 2 to 12 numeric fields.").withNullable(true));
properties.put("cells", new Schema().withType(Type.ARRAY).withItems(ref("DataAnalysisCorrelationCellV1")).withDescription("Cells.").withNullable(true));
properties.put("chart", ref("DataAnalysisChartV1").withDescription("Semantic series; category comparisons are grouped and category time series are stacked.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** TrendLine version-one transport model.
*******************************************************************************/
public static class DataAnalysisTrendLineV1 implements ToSchema
{
@OpenAPIDescription("Slope.")
public Double slope;
@OpenAPIDescription("Intercept.")
public Double intercept;
@OpenAPIDescription("Pearson correlation; null for insufficient data, zero variance or privacy suppression.")
public Double r;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("slope", new Schema().withType(Type.NUMBER).withDescription("Slope.").withNullable(true));
properties.put("intercept", new Schema().withType(Type.NUMBER).withDescription("Intercept.").withNullable(true));
properties.put("r", new Schema().withType(Type.NUMBER).withDescription("Pearson correlation; null for insufficient data, zero variance or privacy suppression.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** ScatterResult version-one transport model.
*******************************************************************************/
public static class DataAnalysisScatterV1 implements ToSchema
{
@OpenAPIDescription("Pairwise non-null population count; null when privacy suppresses it.")
public Long n;
@OpenAPIDescription("Number of displayed paired records.")
public Integer sampleSize;
@OpenAPIDescription("Sampling method; core query currently uses a deterministic primary-key prefix.")
public String sampling;
@OpenAPIDescription("Points.")
public List<DataAnalysisSchemas.DataAnalysisPointV1> points;
@OpenAPIDescription("Least-squares slope, intercept and r fitted to the displayed sample.")
public DataAnalysisTrendLineV1 trend;
@OpenAPIDescription("Semantic series; category comparisons are grouped and category time series are stacked.")
public DataAnalysisSchemas.DataAnalysisChartV1 chart;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("n", new Schema().withType(Type.INTEGER).withDescription("Pairwise non-null population count; null when privacy suppresses it.").withNullable(true));
properties.put("sampleSize", new Schema().withType(Type.INTEGER).withDescription("Number of displayed paired records.").withNullable(true));
properties.put("sampling", new Schema().withType(Type.STRING).withDescription("Sampling method; core query currently uses a deterministic primary-key prefix.").withNullable(true));
properties.put("points", new Schema().withType(Type.ARRAY).withItems(ref("DataAnalysisPointV1")).withDescription("Points.").withNullable(true));
properties.put("trend", ref("DataAnalysisTrendLineV1").withDescription("Least-squares slope, intercept and r fitted to the displayed sample.").withNullable(true));
properties.put("chart", ref("DataAnalysisChartV1").withDescription("Semantic series; category comparisons are grouped and category time series are stacked.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** CrosstabCell version-one transport model.
*******************************************************************************/
public static class DataAnalysisCrosstabCellV1 implements ToSchema
{
@OpenAPIDescription("Row index.")
public Integer rowIndex;
@OpenAPIDescription("Column index.")
public Integer columnIndex;
@OpenAPIDescription("Cell count with its exact drill, or a suppressed metric.")
public DataAnalysisSchemas.DataAnalysisMetricV1 count;
@OpenAPIDescription("Cell count divided by row total; suppressed if it could disclose a hidden cell.")
public DataAnalysisSchemas.DataAnalysisMetricV1 rowShare;
@OpenAPIDescription("Cell count divided by column total; suppressed if it could disclose a hidden cell.")
public DataAnalysisSchemas.DataAnalysisMetricV1 columnShare;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("rowIndex", new Schema().withType(Type.INTEGER).withDescription("Row index.").withNullable(true));
properties.put("columnIndex", new Schema().withType(Type.INTEGER).withDescription("Column index.").withNullable(true));
properties.put("count", ref("DataAnalysisMetricV1").withDescription("Cell count with its exact drill, or a suppressed metric.").withNullable(true));
properties.put("rowShare", ref("DataAnalysisMetricV1").withDescription("Cell count divided by row total; suppressed if it could disclose a hidden cell.").withNullable(true));
properties.put("columnShare", ref("DataAnalysisMetricV1").withDescription("Cell count divided by column total; suppressed if it could disclose a hidden cell.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** CrosstabResult version-one transport model.
*******************************************************************************/
public static class DataAnalysisCrosstabV1 implements ToSchema
{
@OpenAPIDescription("Rows.")
public List<DataAnalysisSchemas.DataAnalysisPivotHeaderV1> rows;
@OpenAPIDescription("Columns.")
public List<DataAnalysisSchemas.DataAnalysisPivotHeaderV1> columns;
@OpenAPIDescription("Cells.")
public List<DataAnalysisCrosstabCellV1> cells;
@OpenAPIDescription("Test assumptions, two-sided p-value, degrees of freedom and plain-language conclusion.")
public DataAnalysisSignificanceV1 significance;
/*******************************************************************************
** Explicit references preserve the standalone OpenAPI fragment.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("rows", new Schema().withType(Type.ARRAY).withItems(ref("DataAnalysisPivotHeaderV1")).withDescription("Rows.").withNullable(true));
properties.put("columns", new Schema().withType(Type.ARRAY).withItems(ref("DataAnalysisPivotHeaderV1")).withDescription("Columns.").withNullable(true));
properties.put("cells", new Schema().withType(Type.ARRAY).withItems(ref("DataAnalysisCrosstabCellV1")).withDescription("Cells.").withNullable(true));
properties.put("significance", ref("DataAnalysisSignificanceV1").withDescription("Test assumptions, two-sided p-value, degrees of freedom and plain-language conclusion.").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
}
@@ -0,0 +1,208 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.api;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.dataanalysis.DataAnalysisRuntime;
import com.kingsrook.qbits.dataanalysis.saved.SavedDefinition;
import com.kingsrook.qbits.dataanalysis.saved.SqlHandoff;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.openapi.model.HttpMethod;
/*******************************************************************************
** Saved execution, stars, visible lists and SQL discovery through the UI API.
*******************************************************************************/
public final class SavedApi
{
/*******************************************************************************
** Namespace only.
*******************************************************************************/
private SavedApi()
{
}
/*******************************************************************************
** Stable integer-id errors, without probing inaccessible records.
*******************************************************************************/
public static Integer id(String value) throws QBadRequestException
{
try
{
return (Integer.valueOf(value));
}
catch(Exception e)
{
throw new QBadRequestException("Saved analysis id must be an integer.");
}
}
/*******************************************************************************
** Accept a discriminated typed request; path table overrides only absent tableName.
*******************************************************************************/
@SuppressWarnings("unchecked")
public static SavedDefinition definition(Map<String, Object> body, String pathTable) throws QException
{
if(!(body.get("kind") instanceof String kind))
{
throw new QBadRequestException("An analysis kind is required.");
}
Map<String, Object> request = new LinkedHashMap<>(body);
request.remove("kind");
request.remove("format");
if(body.containsKey("request"))
{
if(!(body.get("request") instanceof Map<?, ?> map))
{
throw new QBadRequestException("request must be a typed analysis object.");
}
request = new LinkedHashMap<>((Map<String, Object>) map);
}
Object table = pathTable == null ? body.getOrDefault("tableName", request.get("tableName")) : pathTable;
if(!(table instanceof String name))
{
throw new QBadRequestException("tableName is required.");
}
return (SavedDefinition.parse(kind, name, request));
}
/*******************************************************************************
** Run the visible saved definition under the viewer's current source permissions.
*******************************************************************************/
public static class Run extends DataAnalysisApi.ProfileSpec
{
/*******************************************************************************
** Publish assistant-oriented semantics and field-reduction behavior.
*******************************************************************************/
public Run()
{
super("/saved/{id}/run", HttpMethod.POST, "Run a saved analysis",
"Re-run a visible saved analysis as the signed-in viewer. Requires saved READ and source READ/Analyze. Drops unavailable fields with a warning and returns the result typed by kind; inaccessible required axes or predicates produce no result.", null, "SavedResult");
}
/*******************************************************************************
** Core locks determine visibility, not an endpoint-specific owner check.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
return (DataAnalysisRuntime.saved().run(id(input.getPathParam("id"))));
}
}
/*******************************************************************************
** Visible saved metadata with this viewer's personal stars.
*******************************************************************************/
public static class ListSaved extends DataAnalysisApi.ProfileSpec
{
/*******************************************************************************
** A discoverable list rather than exposing the owner's cached result JSON.
*******************************************************************************/
public ListSaved()
{
super("/saved", HttpMethod.GET, "List visible saved analyses",
"List core-visible saved analyses with name, kind, source table label, owner, shared state, this viewer's starred flag and last update.", null, "SavedList");
}
/*******************************************************************************
** The list and star lookup both use enforced core queries.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
return (Map.of("analyses", DataAnalysisRuntime.saved().list()));
}
}
/*******************************************************************************
** Idempotent star PUT for the signed-in user.
*******************************************************************************/
public static class Star extends DataAnalysisApi.ProfileSpec
{
/*******************************************************************************
** No user-id body is accepted; stars always belong to the caller.
*******************************************************************************/
public Star()
{
super("/saved/{id}/star", HttpMethod.PUT, "Star a saved analysis",
"Star a visible saved analysis for the signed-in user. Idempotent; uses standard saved insert permission and the personal star record lock.", null, "Star");
}
/*******************************************************************************
** Persist through core table CRUD.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
return (Map.of("starred", DataAnalysisRuntime.saved().star(id(input.getPathParam("id")), true)));
}
}
/*******************************************************************************
** Idempotent star DELETE for the signed-in user.
*******************************************************************************/
public static class Unstar extends DataAnalysisApi.ProfileSpec
{
/*******************************************************************************
** Removal never targets another user's star.
*******************************************************************************/
public Unstar()
{
super("/saved/{id}/star", HttpMethod.DELETE, "Unstar a saved analysis",
"Remove the signed-in user's star on a visible saved analysis. Idempotent; uses standard saved delete permission and owner locks.", null, "Star");
}
/*******************************************************************************
** Persist through core table CRUD.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
return (Map.of("starred", DataAnalysisRuntime.saved().star(id(input.getPathParam("id")), false)));
}
}
/*******************************************************************************
** Actual backend aggregate SQL, captured only during this request.
*******************************************************************************/
public static class Sql extends DataAnalysisApi.ProfileSpec
{
/*******************************************************************************
** The assistant gets a reading aid, never an alternative execution endpoint.
*******************************************************************************/
public Sql()
{
super("/tables/{table}/sql", HttpMethod.POST, "Read an analysis aggregate SQL statement",
"Execute a typed analysis as the viewer and capture the main RDBMS aggregate SQL from core QueryStat. Requires installed SQL Workbench and its access permission. Non-RDBMS backends report unavailable; SQL is for reading and record security remains enforced at runtime.", "SavedRequest", "Sql");
}
/*******************************************************************************
** Requests pass through the same parser and analysis authorization.
*******************************************************************************/
@Override
protected Object handle(JsonInput input) throws Exception
{
return (SqlHandoff.execute(definition(input.getBody(), input.getPathParam("table")), DataAnalysisRuntime.service()));
}
}
}
@@ -0,0 +1,99 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.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 saved envelopes reuse all seven existing typed request/result schemas.
*******************************************************************************/
public final class SavedSchemas
{
/*******************************************************************************
** Utility class.
*******************************************************************************/
private SavedSchemas()
{
}
/*******************************************************************************
** JSON Schema union supported by the standard OpenAPI serializer.
*******************************************************************************/
public static class RequestUnion extends Schema
{
/*******************************************************************************
** All supported typed analysis requests, selected by the sibling kind.
*******************************************************************************/
public List<Schema> getAnyOf()
{
return (List.of("ColumnProfile", "TableProfile", "Pivot", "Compare", "Correlation", "Crosstab", "Shift").stream()
.map(name -> ref(name + "Request")).toList());
}
}
/*******************************************************************************
** Every new endpoint's request and response is discoverable by clients.
*******************************************************************************/
public static Map<String, Schema> components()
{
Map<String, Schema> result = new LinkedHashMap<>();
Map<String, Schema> fields = new LinkedHashMap<>();
fields.put("kind", new Schema().withType(Type.STRING).withEnumValues(List.of("COLUMN_PROFILE", "TABLE_PROFILE", "PIVOT", "COMPARE", "CORRELATION", "CROSSTAB", "SHIFT")));
fields.put("tableName", new Schema().withType(Type.STRING).withDescription("Source QQQ table name; required for ad hoc export, supplied by the path for SQL."));
fields.put("request", new RequestUnion().withDescription("Typed request matching kind. Field names, filters and dimensions use the existing analysis request contracts."));
fields.put("format", new Schema().withType(Type.STRING).withEnumValues(List.of("csv", "xlsx")).withDescription("Required for export; ignored for SQL."));
result.put("DataAnalysisSavedRequestV1", new DataAnalysisSchemas.RequiredSchema(List.of("kind", "request")).withType(Type.OBJECT).withProperties(fields));
Map<String, Schema> response = new LinkedHashMap<>();
response.put("kind", fields.get("kind"));
response.put("warnings", new Schema().withType(Type.ARRAY).withItems(new Schema().withType(Type.STRING)));
new java.util.TreeMap<>(Map.of("columnProfile", "ColumnProfile", "tableProfile", "TableProfile", "pivot", "Pivot", "compare", "Compare",
"correlation", "Correlation", "crosstab", "Crosstab", "shift", "Shift")).forEach((key, value) -> response.put(key, ref(value).withNullable(true)));
result.put("DataAnalysisSavedResultV1", new Schema().withType(Type.OBJECT).withProperties(response));
Map<String, Schema> entry = new LinkedHashMap<>();
entry.put("id", new Schema().withType(Type.INTEGER));
for(String name : List.of("name", "kind", "tableName", "tableLabel", "owner", "updated"))
{
entry.put(name, new Schema().withType(Type.STRING));
}
entry.put("updated", new Schema().withType(Type.STRING).withFormat("date-time").withNullable(true));
entry.put("shared", new Schema().withType(Type.BOOLEAN));
entry.put("starred", new Schema().withType(Type.BOOLEAN));
result.put("DataAnalysisSavedEntryV1", new Schema().withType(Type.OBJECT).withProperties(entry));
result.put("DataAnalysisSavedListV1", new Schema().withType(Type.OBJECT).withProperties(new java.util.TreeMap<>(Map.of("analyses", new Schema().withType(Type.ARRAY).withItems(ref("SavedEntry"))))));
result.put("DataAnalysisStarV1", new Schema().withType(Type.OBJECT).withProperties(new java.util.TreeMap<>(Map.of("starred", new Schema().withType(Type.BOOLEAN)))));
result.put("DataAnalysisSqlV1", new Schema().withType(Type.OBJECT).withProperties(new java.util.TreeMap<>(Map.of("available", new Schema().withType(Type.BOOLEAN),
"sql", new Schema().withType(Type.STRING).withNullable(true), "note", new Schema().withType(Type.STRING)))));
result.put("DataAnalysisFileV1", new Schema().withType(Type.STRING).withFormat("binary"));
return (result);
}
/*******************************************************************************
** Reuse the extension's stable schema prefix.
*******************************************************************************/
private static Schema ref(String name)
{
return (new Schema().withRef("#/components/schemas/DataAnalysis" + name + "V1"));
}
}
@@ -0,0 +1,126 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.api;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qqq.middleware.javalin.schemabuilder.ToSchema;
import com.kingsrook.qqq.openapi.model.Schema;
import com.kingsrook.qqq.openapi.model.Type;
/*******************************************************************************
** Standalone watch preview contracts referencing the existing chart and drill.
*******************************************************************************/
public class WatchSchemas
{
/*******************************************************************************
** Register every referenced version-one watch response component.
*******************************************************************************/
public static Map<String, Schema> components()
{
return (Map.of("DataAnalysisWatchPreviewV1", new DataAnalysisWatchPreviewV1().toSchema(),
"DataAnalysisWatchBucketV1", new DataAnalysisWatchBucketV1().toSchema(),
"DataAnalysisWatchVerdictV1", new DataAnalysisWatchVerdictV1().toSchema()));
}
/*******************************************************************************
** One complete bucket; suppressed series never expose categories or drills.
*******************************************************************************/
public static class DataAnalysisWatchBucketV1 implements ToSchema
{
public Serializable start;
public Double value;
public List<String> categories;
public DataAnalysisSchemas.DataAnalysisDrillV1 drill;
/*******************************************************************************
** Explicit nullable types and component references.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("start", new Schema().withType(Type.STRING).withDescription("Calendar date or hour-start instant in the user's time zone."));
properties.put("value", new Schema().withType(Type.NUMBER).withNullable(true));
properties.put("categories", new Schema().withType(Type.ARRAY).withItems(new Schema().withType(Type.STRING)));
properties.put("drill", new Schema().withRef("#/components/schemas/DataAnalysisDrillV1").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** Unevaluated means no state change; baseline bounds describe the annotation.
*******************************************************************************/
public static class DataAnalysisWatchVerdictV1 implements ToSchema
{
public Boolean evaluated;
public Boolean firing;
public Double value;
public Double baseline;
public Double baselineLow;
public Double baselineHigh;
public String message;
public DataAnalysisSchemas.DataAnalysisDrillV1 drill;
/*******************************************************************************
** Carry numeric baseline bounds as well as the plain-English explanation.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("evaluated", new Schema().withType(Type.BOOLEAN).withDescription("False for insufficient history or privacy suppression; must not resolve an alert."));
properties.put("firing", new Schema().withType(Type.BOOLEAN));
for(String field : List.of("value", "baseline", "baselineLow", "baselineHigh"))
{
properties.put(field, new Schema().withType(Type.NUMBER).withNullable(true));
}
properties.put("message", new Schema().withType(Type.STRING));
properties.put("drill", new Schema().withRef("#/components/schemas/DataAnalysisDrillV1").withNullable(true));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
/*******************************************************************************
** Complete preview, using the same semantic chart as other analysis endpoints.
*******************************************************************************/
public static class DataAnalysisWatchPreviewV1 implements ToSchema
{
public List<DataAnalysisWatchBucketV1> series;
public DataAnalysisSchemas.DataAnalysisChartV1 chart;
public DataAnalysisWatchVerdictV1 verdict;
/*******************************************************************************
** Stable references let clients vendor this fragment without middleware.
*******************************************************************************/
@Override
public Schema toSchema()
{
Map<String, Schema> properties = new LinkedHashMap<>();
properties.put("series", new Schema().withType(Type.ARRAY).withItems(new Schema().withRef("#/components/schemas/DataAnalysisWatchBucketV1")));
properties.put("chart", new Schema().withRef("#/components/schemas/DataAnalysisChartV1").withDescription("TIME_SERIES with baseline band annotations."));
properties.put("verdict", new Schema().withRef("#/components/schemas/DataAnalysisWatchVerdictV1"));
return (new Schema().withType(Type.OBJECT).withProperties(properties));
}
}
}
@@ -20,73 +20,124 @@
package com.kingsrook.qbits.dataanalysis.app;
import java.time.Instant;
import java.util.Arrays;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.Objects;
import com.kingsrook.qbits.dataanalysis.DataAnalysisQBitConfig;
import com.kingsrook.qbits.dataanalysis.engine.AnalysisFormatting;
import com.kingsrook.qbits.dataanalysis.DataAnalysisQBitProducer;
import com.kingsrook.qbits.dataanalysis.DataAnalysisRuntime;
import com.kingsrook.qbits.dataanalysis.engine.DrillFilters;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qbits.dataanalysis.permissions.DataAnalysisPermissions;
import com.kingsrook.qbits.dataanalysis.saved.SavedAnalyses;
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.AbstractWidgetRenderer;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionEnforcement;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
import com.kingsrook.qqq.backend.core.actions.permissions.UseOtherPermissionNameCustomPermissionChecker;
import com.kingsrook.qqq.backend.core.actions.tables.CountAction;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.count.CountInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryJoin;
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetInput;
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetOutput;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.RawHTML;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.MultiStatisticsData;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.QWidgetData;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.TableData;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.WidgetType;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppSection;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.DenyBehavior;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
/*******************************************************************************
** Analyses app home: real counts under the current user's permissions and locks.
** Standard QQQ statistics and narrow table widgets, all queried as the viewer.
*******************************************************************************/
public class DataAnalysisHome extends AbstractWidgetRenderer
{
public static final String SETUP = "dataAnalysisSetup";
public static final String HOME_WIDGET = "dataAnalysisHome";
public static final String STARRED = "dataAnalysisStarred";
public static final String FIRING = "dataAnalysisFiring";
public static final String RECENT = "dataAnalysisRecent";
/*******************************************************************************
** The home itself has no data privilege; each section checks its table READ.
** The existing home name now supplies standard multi-statistics data.
*******************************************************************************/
public static QWidgetMetaData widget()
{
return (new QWidgetMetaData().withName(HOME_WIDGET).withLabel("Overview").withType(WidgetType.HTML.getType())
.withCodeReference(new QCodeReference(DataAnalysisHome.class)).withGridColumns(12).withIsCard(false)
return (widget(HOME_WIDGET, "Analysis overview", WidgetType.MULTI_STATISTICS));
}
/*******************************************************************************
** Full-width tables have three or four columns and honest empty states.
*******************************************************************************/
public static List<QWidgetMetaData> widgets()
{
return (List.of(setupWidget(), widget().withPermissionRules(readRules(DataAnalysisTables.SAVED)),
widget(STARRED, "Starred analyses", WidgetType.TABLE).withPermissionRules(readRules(DataAnalysisTables.SAVED)),
widget(FIRING, "Firing watches", WidgetType.TABLE).withPermissionRules(readRules(DataAnalysisTables.WATCH)),
widget(RECENT, "My recent runs", WidgetType.TABLE).withPermissionRules(readRules(DataAnalysisTables.RUN))));
}
/*******************************************************************************
** Names of the widgets placed on the business home. Setup is system content and
** is deliberately absent; hosts place {@link DataAnalysisQBitProducer#SYSTEM_WIDGETS}
** on their Admin area instead.
*******************************************************************************/
public static List<String> homeWidgetNames()
{
return (widgets().stream().map(QWidgetMetaData::getName).filter(name -> !DataAnalysisQBitProducer.SYSTEM_WIDGETS.contains(name)).toList());
}
/*******************************************************************************
** The Setup card shows engine configuration, so only Data Analysis admins get it;
** everyone else has it omitted from metadata.
*******************************************************************************/
private static QWidgetMetaData setupWidget()
{
return (widget(SETUP, "Setup", WidgetType.TABLE).withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.HAS_ACCESS_PERMISSION)
.withDenyBehavior(DenyBehavior.HIDDEN).withCustomPermissionChecker(UseOtherPermissionNameCustomPermissionChecker.build(DataAnalysisPermissions.ADMIN))));
}
/*******************************************************************************
** A data widget is omitted from metadata for users who cannot read its table.
*******************************************************************************/
private static QPermissionRules readRules(String table)
{
return (new QPermissionRules().withLevel(PermissionLevel.HAS_ACCESS_PERMISSION).withDenyBehavior(DenyBehavior.HIDDEN)
.withCustomPermissionChecker(TableReadWidgetPermissionChecker.build(table)));
}
/*******************************************************************************
** The widget itself grants no privilege; each data section checks table READ.
*******************************************************************************/
private static QWidgetMetaData widget(String name, String label, WidgetType type)
{
return (new QWidgetMetaData().withName(name).withLabel(label).withType(type.getType()).withGridColumns(12).withIsCard(true)
.withShowReloadButton(true).withCodeReference(new QCodeReference(DataAnalysisHome.class))
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.NOT_PROTECTED)));
}
/*******************************************************************************
** Only main tables appear in navigation; schedules and stars are record children.
** Main tables remain navigation; schedules and stars remain child lists.
*******************************************************************************/
public static QAppMetaData app(DataAnalysisQBitConfig config, List<QTableMetaData> tables)
{
QAppMetaData app = new QAppMetaData().withName(config.getAppName()).withLabel(config.getAppLabel())
.withIcon(new QIcon("insights")).withWidgets(List.of(HOME_WIDGET))
.withIcon(new QIcon("insights")).withWidgets(homeWidgetNames())
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.NOT_PROTECTED))
.withSection(new QAppSection().withName("analyses").withLabel("Analyses").withIcon(new QIcon("insights")).withTables(DataAnalysisTables.NAV_TABLES));
app.setParentAppName(config.getParentAppName());
@@ -100,173 +151,205 @@ public class DataAnalysisHome extends AbstractWidgetRenderer
/*******************************************************************************
** RawHTML is carried as a JSON string by the HTML widget, not a text/html response.
** Entities keep static separators independent of any host charset handling.
** Dispatch data by registered metadata name, never by an arbitrary table input.
*******************************************************************************/
@Override
public RenderWidgetOutput render(RenderWidgetInput input) throws QException
{
return (new RenderWidgetOutput(new RawHTML(null, render(Instant.now()))));
return (new RenderWidgetOutput(render(input.getWidgetMetaData().getName(), Instant.now())));
}
/*******************************************************************************
** Counts and table rows share core-enforced permissions and record locks.
*******************************************************************************/
public static QWidgetData render(String name, Instant now) throws QException
{
if(SETUP.equals(name))
{
return (setup());
}
if(HOME_WIDGET.equals(name))
{
return (statistics(now));
}
if(STARRED.equals(name))
{
TableData data = table("Starred analyses", DataAnalysisTables.SAVED, "No starred analyses yet. Star a saved analysis to see it here.", "Name", "Table", "Kind");
if(canRead(DataAnalysisTables.SAVED))
{
for(var entry : DataAnalysisRuntime.saved().list().stream().filter(SavedAnalyses.Entry::starred).toList())
{
data.getRows().add(values(link(DataAnalysisTables.SAVED, entry.id(), entry.name()), entry.tableLabel(), entry.kind()));
}
}
return (data);
}
String source = FIRING.equals(name) ? DataAnalysisTables.WATCH : DataAnalysisTables.RUN;
TableData data = FIRING.equals(name)
? table("Firing watches", source, "No firing watches.", "Watch", "Table", "Last evaluated", "Message")
: table("My recent runs", source, "No analysis runs yet.", "Analysis", "Table", "Status", "Started");
if(!canRead(source))
{
return (data);
}
QQueryFilter filter = FIRING.equals(name) ? equal("state", "FIRING")
: equal("user_id", SavedAnalyses.user()).withCriteria("started_at", QCriteriaOperator.LESS_THAN_OR_EQUALS, now);
filter.withOrderBy(new QFilterOrderBy(FIRING.equals(name) ? "last_evaluated_at" : "started_at", false)).withLimit(10);
for(var row : SavedAnalyses.query(source, filter))
{
String tableName = row.getValueString("table_name");
var metadata = QContext.getQInstance().getTable(tableName);
String label = metadata == null ? Objects.toString(tableName, "Saved analysis") : metadata.getLabel();
data.getRows().add(FIRING.equals(name)
? values(link(source, row.getValue("id"), row.getValueString("detector")), label, row.getValue("last_evaluated_at"), row.getValue("last_message"))
: values(link(source, row.getValue("id"), row.getValueString("operation")), label, row.getValue("status"), row.getValue("started_at")));
}
return (data);
}
/*******************************************************************************
** Counts are evaluated at one instant; no system session or synthetic numbers.
** The Setup card: each settings or content table, its state and the next step.
*******************************************************************************/
public static String render(Instant now) throws QException
public static TableData setup() throws QException
{
StringBuilder html = new StringBuilder("<div class=\"data-analysis-home\" style=\"display:grid;gap:1rem;min-width:0;overflow-wrap:anywhere\">");
String userId = QContext.getQSession() == null || QContext.getQSession().getUser() == null ? null : QContext.getQSession().getUser().getIdReference();
html.append("<section><h3>Saved analyses</h3>");
if(userId == null)
TableData data = new TableData("Setup", List.of(new TableData.Column("html", "Part", "c0", null, "left"), new TableData.Column("text", "State", "c1", null, "left"),
new TableData.Column("text", "What it means", "c2", null, "left"), new TableData.Column("text", "Next step", "c3", null, "left")), new ArrayList<>())
.withNoRowsFoundHTML("Nothing to set up.").withRowsPerPage(10);
for(DataAnalysisSetupStatus.Item item : DataAnalysisSetupStatus.load())
{
html.append("<p>Sign in to see your saved analyses and stars.</p>");
}
else if(canRead(DataAnalysisTables.SAVED))
{
int mine = count(DataAnalysisTables.SAVED, equal("owner_user_id", userId));
int shared = count(DataAnalysisTables.SAVED, equal("shared", true));
html.append("<p>Mine: ").append(AnalysisFormatting.number(mine, 0)).append(" &middot; Shared (visible to you): ").append(AnalysisFormatting.number(shared, 0)).append("</p>");
if(canRead(DataAnalysisTables.SAVED_STAR))
String path = QContext.getQInstance().getTablePath(item.tableName());
String part = "<a href=\"" + escape(path) + "\">" + escape(item.label()) + "</a>";
String state = switch(item.state())
{
CountInput stars = new CountInput(DataAnalysisTables.SAVED).withIncludeDistinctCount(true)
.withQueryJoin(new QueryJoin(QContext.getQInstance().getJoin(DataAnalysisTables.joinName(DataAnalysisTables.SAVED_STAR))).withType(QueryJoin.Type.INNER))
.withFilter(equal(DataAnalysisTables.SAVED_STAR + ".user_id", userId));
stars.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
int starred = new CountAction().execute(stars).getDistinctCount();
html.append("<p>Starred by me: ").append(AnalysisFormatting.number(starred, 0)).append("</p>");
}
if(mine == 0 && shared == 0)
{
html.append("<p>No saved analyses yet. Open any table and choose Analyze on a column header to explore its data.</p>");
}
link(html, DataAnalysisTables.SAVED);
case OK -> "Set up";
case DEFAULT -> "Using defaults";
case OPTIONAL -> "Optional";
case UNAVAILABLE -> "Unavailable";
case UNKNOWN -> "Needs attention";
};
data.getRows().add(values(part, state, item.detail(), item.nextStep()));
}
else
return (data);
}
/*******************************************************************************
** One standard group per subject the viewer can read; unreadable subjects are left out.
*******************************************************************************/
public static MultiStatisticsData statistics(Instant now) throws QException
{
List<MultiStatisticsData.StatisticsGroupData> groups = new ArrayList<>();
if(canRead(DataAnalysisTables.SAVED))
{
html.append("<p>Saved analyses are unavailable: you need data_analysis.saved.read.</p>");
var saved = group("Saved analyses");
List<SavedAnalyses.Entry> entries = DataAnalysisRuntime.saved().list();
String user = SavedAnalyses.user();
saved.withStatisticList(List.of(stat("Mine", (int) entries.stream().filter(e -> e.owner().equals(user)).count(), DataAnalysisTables.SAVED),
stat("Shared", (int) entries.stream().filter(e -> Boolean.TRUE.equals(e.shared())).count(), DataAnalysisTables.SAVED),
stat("Starred", (int) entries.stream().filter(SavedAnalyses.Entry::starred).count(), DataAnalysisTables.SAVED)));
groups.add(saved);
}
html.append("</section><section><h3>Watches</h3>");
if(canRead(DataAnalysisTables.WATCH))
{
int total = count(DataAnalysisTables.WATCH, new QQueryFilter());
int enabled = count(DataAnalysisTables.WATCH, equal("enabled", true));
int firing = count(DataAnalysisTables.WATCH, equal("state", "FIRING"));
html.append("<p>Total: ").append(AnalysisFormatting.number(total, 0)).append(" &middot; Enabled: ").append(AnalysisFormatting.number(enabled, 0)).append(" &middot; Firing: ").append(AnalysisFormatting.number(firing, 0)).append("</p>");
if(total == 0)
{
html.append("<p>No watches yet.</p>");
}
link(html, DataAnalysisTables.WATCH);
var watches = group("Watches");
watches.withStatisticList(List.of(stat("Enabled", count(DataAnalysisTables.WATCH, equal("enabled", true)), DataAnalysisTables.WATCH),
stat("Firing", count(DataAnalysisTables.WATCH, equal("state", "FIRING")), DataAnalysisTables.WATCH)));
groups.add(watches);
}
else
if(canRead(DataAnalysisTables.RUN))
{
html.append("<p>Watches are unavailable: you need data_analysis.watch.read.</p>");
var runs = group("My runs");
runs.withStatisticList(List.of(stat("Last 7 days", count(DataAnalysisTables.RUN, equal("user_id", SavedAnalyses.user())
.withCriteria("started_at", QCriteriaOperator.GREATER_THAN_OR_EQUALS, now.minus(7, ChronoUnit.DAYS))
.withCriteria("started_at", QCriteriaOperator.LESS_THAN_OR_EQUALS, now)), DataAnalysisTables.RUN)));
groups.add(runs);
}
html.append("</section><section><h3>Recent analysis runs</h3>");
if(userId == null)
{
html.append("<p>Sign in to see your recent analysis runs.</p>");
}
else if(canRead(DataAnalysisTables.RUN))
{
QueryInput query = new QueryInput(DataAnalysisTables.RUN).withFilter(equal("user_id", userId)
.withCriteria(new QFilterCriteria("started_at", QCriteriaOperator.LESS_THAN_OR_EQUALS, now))
.withOrderBy(new QFilterOrderBy("started_at", false)).withOrderBy(new QFilterOrderBy("id", false)).withLimit(5));
query.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
List<QRecord> runs = new QueryAction().execute(query).getRecords();
if(runs.isEmpty())
{
html.append("<p>No analysis runs yet.</p>");
}
else
{
html.append("<ul class=\"data-analysis-runs\">");
for(QRecord run : runs)
{
QTableMetaData table = QContext.getQInstance().getTable(run.getValueString("table_name"));
String tableLabel = table == null ? run.getValueString("table_name") : table.getLabel();
String path = QContext.getQInstance().getTablePath(DataAnalysisTables.RUN) + "/" + run.getValueInteger("id");
html.append("<li><a href=\"").append(escape(path)).append("\">").append(escape(tableLabel)).append(" &middot; ")
.append(escape(words(run.getValueString("operation")))).append("</a><dl class=\"data-analysis-run-details\"><dt>Status</dt><dd>")
.append(escape(words(run.getValueString("status")))).append("</dd><dt>Finished</dt><dd>")
.append(run.getValue("finished_at") == null ? "Not finished" : escape(AnalysisFormatting.instant(run.getValueInstant("finished_at"))))
.append("</dd></dl></li>");
}
html.append("</ul>");
}
link(html, DataAnalysisTables.RUN);
}
else
{
html.append("<p>Run history is unavailable: you need data_analysis.run.read.</p>");
}
return (html.append("</section></div>").toString());
return (new MultiStatisticsData("Analyses", groups));
}
/*******************************************************************************
** Explicit permission checks avoid presenting denied sections as empty data.
** A group is only built for a readable subject, so its subheader is always true.
*******************************************************************************/
private static boolean canRead(String table)
private static MultiStatisticsData.StatisticsGroupData group(String label)
{
return (PermissionsHelper.hasTablePermission(new CountInput(table), table, TablePermissionSubType.READ));
return (new MultiStatisticsData.StatisticsGroupData().withHeader(label).withStatisticList(List.of()).withSubheader("Visible to you"));
}
/*******************************************************************************
** Equality filter for one count.
** Link every count to its actual table path.
*******************************************************************************/
private static QQueryFilter equal(String field, java.io.Serializable value)
private static MultiStatisticsData.StatisticsGroupData.Statistic stat(String label, int count, String table) throws QException
{
return (new QQueryFilter().withCriteria(new QFilterCriteria(field, QCriteriaOperator.EQUALS, value)));
return (new MultiStatisticsData.StatisticsGroupData.Statistic(label, count, QContext.getQInstance().getTablePath(table)));
}
/*******************************************************************************
** Stored operation and status keys are displayed as ordinary words.
** Standard table cells support escaped record links; other columns are plain text.
*******************************************************************************/
private static String words(String value)
private static TableData table(String label, String table, String empty, String... headers) throws QException
{
return (value == null ? "Unknown" : Arrays.stream(value.toLowerCase(Locale.ROOT).split("_"))
.filter(part -> !part.isEmpty()).map(part -> Character.toUpperCase(part.charAt(0)) + part.substring(1)).collect(Collectors.joining(" ")));
List<TableData.Column> columns = new ArrayList<>();
for(int i = 0; i < headers.length; i++)
{
columns.add(new TableData.Column(i == 0 ? "html" : "text", headers[i], "c" + i, null, "left"));
}
return (new TableData(label, columns, new ArrayList<>()).withNoRowsFoundHTML(empty)
.withLinkText("View all").withLinkURL(QContext.getQInstance().getTablePath(table)).withRowsPerPage(10));
}
/*******************************************************************************
** Preserve real values while avoiding null map entries and executable HTML.
*******************************************************************************/
private static Map<String, Object> values(Object... values)
{
Map<String, Object> row = new LinkedHashMap<>();
for(int i = 0; i < values.length; i++)
{
row.put("c" + i, Objects.toString(values[i], ""));
}
return (row);
}
/*******************************************************************************
** Metadata and persisted values must never become executable widget markup.
** Standard table HTML cell contains only an escaped link and escaped text.
*******************************************************************************/
private static String link(String table, Object id, String label) throws QException
{
return ("<a href=\"" + escape(QContext.getQInstance().getTablePath(table) + "/" + id) + "\">" + escape(label) + "</a>");
}
/*******************************************************************************
** Metadata labels and stored names are never trusted markup.
*******************************************************************************/
private static String escape(String value)
{
return (value == null ? "Unknown" : value.replace("&", "&amp;").replace("\"", "&quot;").replace("<", "&lt;").replace(">", "&gt;").replace("'", "&#39;"));
return (Objects.toString(value, "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("'", "&#39;"));
}
/*******************************************************************************
** Explicit checks distinguish denied sections from empty sections.
*******************************************************************************/
static boolean canRead(String table)
{
CountInput input = new CountInput(table);
input.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
return (PermissionsHelper.hasTablePermission(input, table, TablePermissionSubType.READ));
}
/*******************************************************************************
** CountAction enforces table permission and record locks using QContext's session.
** Simple filter; record security is applied exclusively by core.
*******************************************************************************/
private static int count(String table, QQueryFilter filter) throws QException
private static QQueryFilter equal(String field, java.io.Serializable value)
{
return (DrillFilters.condition(field, QCriteriaOperator.EQUALS, value));
}
/*******************************************************************************
** Counts use the viewer's session and explicitly enforce permissions.
*******************************************************************************/
static int count(String table, QQueryFilter filter) throws QException
{
CountInput input = new CountInput(table).withFilter(filter);
input.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
return (new CountAction().execute(input).getCount());
}
/*******************************************************************************
** Use the instance's actual app path, including custom names and parent apps.
*******************************************************************************/
private static void link(StringBuilder html, String table) throws QException
{
String path = QContext.getQInstance().getTablePath(table);
html.append("<a href=\"").append(escape(path))
.append("\">View all</a>");
}
}
@@ -0,0 +1,173 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.app;
import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qbits.dataanalysis.DataAnalysisQBitConfig;
import com.kingsrook.qbits.dataanalysis.DataAnalysisRuntime;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qbits.dataanalysis.processes.TableConfigDefaultsProcess;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
/*******************************************************************************
** The Setup card on the Analyses home: each configuration or content table,
** whether it is set up, and the next step. Reads settings through the same
** resolver the analysis runtime uses (code defaults, then rows), so the card
** never reports something the runtime would not do. Counts run as the viewer.
*******************************************************************************/
public final class DataAnalysisSetupStatus
{
/*******************************************************************************
** OK: set up. DEFAULT: working on built-in defaults (nothing required).
** OPTIONAL: a feature that stays off until someone uses it. UNAVAILABLE: the
** viewer cannot read the table.
*******************************************************************************/
public enum State
{
OK, DEFAULT, OPTIONAL, UNAVAILABLE, UNKNOWN
}
/*******************************************************************************
** One line of the card.
*******************************************************************************/
public record Item(String label, String tableName, State state, String detail, String nextStep)
{
}
/*******************************************************************************
** Utility class.
*******************************************************************************/
private DataAnalysisSetupStatus()
{
}
/*******************************************************************************
** The card's lines, in the order a person would set things up.
*******************************************************************************/
public static List<Item> load() throws QException
{
DataAnalysisQBitConfig config = DataAnalysisRuntime.service().getConfigResolver().getDefaults();
List<Item> items = new ArrayList<>();
///////////////////////
// analysis settings //
///////////////////////
List<String> analyzable = TableConfigDefaultsProcess.analyzableTables(QContext.getQInstance(), config);
if(!DataAnalysisHome.canRead(DataAnalysisTables.TABLE_CONFIG))
{
items.add(new Item("Analysis settings", DataAnalysisTables.TABLE_CONFIG, State.UNAVAILABLE, "Unavailable: READ permission required.", null));
}
else
{
int rows = DataAnalysisHome.count(DataAnalysisTables.TABLE_CONFIG, new QQueryFilter());
String defaults = "max rows " + config.getDefaultMaxRows() + ", sample " + config.getDefaultSampleRows() + " above " + config.getDefaultSampleThresholdRows()
+ ", smallest group " + config.getDefaultMinGroupSize() + ", results reused " + config.getDefaultCacheTtlMinutes() + " min";
if(rows == 0)
{
items.add(new Item("Analysis settings", DataAnalysisTables.TABLE_CONFIG, State.DEFAULT,
"All " + analyzable.size() + " analyzable tables are on, with the defaults (" + defaults + ").",
"Run Create rows for analyzable tables to see and edit them, or add a row to change one table."));
}
else
{
items.add(new Item("Analysis settings", DataAnalysisTables.TABLE_CONFIG, rows >= analyzable.size() ? State.OK : State.DEFAULT,
rows + " settings row" + (rows == 1 ? "" : "s") + " for " + analyzable.size() + " analyzable tables; tables without a row use the defaults (" + defaults + ").",
rows >= analyzable.size() ? null : "Run Create rows for analyzable tables to add rows for the rest."));
}
}
/////////////////////////////////////////////////////////////////////
// result cache: the resolved value, exactly what caching will use //
/////////////////////////////////////////////////////////////////////
items.add(cacheItem(analyzable, config));
///////////////////////////////////////////////////
// saved analyses, watches, schedules: optional //
///////////////////////////////////////////////////
items.add(optional("Saved analyses", DataAnalysisTables.SAVED, "No saved analyses yet.", "Save an analysis from the Analyze screen, then star or share it."));
String scheduler = config.getSchedulerName() == null ? " No scheduler is configured, so watches only run with Evaluate now." : "";
items.add(optional("Watches", DataAnalysisTables.WATCH, "No watches yet." + scheduler, "Add a watch on a saved analysis to be alerted to spikes, drops and new categories."));
String schedules = config.getSchedulerName() == null ? " No scheduler is configured, so schedules do not run." : "";
items.add(optional("Schedules", DataAnalysisTables.SCHEDULE, "No schedules yet." + schedules, "Add a schedule on a saved analysis to send it by email."));
return (items);
}
/*******************************************************************************
** One optional feature: set up once it has rows.
*******************************************************************************/
private static Item optional(String label, String table, String emptyDetail, String nextStep) throws QException
{
if(!DataAnalysisHome.canRead(table))
{
return (new Item(label, table, State.UNAVAILABLE, "Unavailable: READ permission required.", null));
}
int rows = DataAnalysisHome.count(table, new QQueryFilter());
return (rows == 0 ? new Item(label, table, State.OPTIONAL, emptyDetail, nextStep) : new Item(label, table, State.OK, rows + " in use.", null));
}
/*******************************************************************************
** The Result cache line, from the minutes every analyzable table actually
** resolves to (settings row, then table defaults, then the global default).
*******************************************************************************/
private static Item cacheItem(List<String> analyzable, DataAnalysisQBitConfig config)
{
java.util.TreeMap<Integer, Integer> tablesPerMinutes = new java.util.TreeMap<>();
for(String table : analyzable)
{
try
{
tablesPerMinutes.merge(DataAnalysisRuntime.service().getConfigResolver().resolve(table).getCacheTtlMinutes(), 1, Integer::sum);
}
catch(QException e)
{
return (new Item("Result cache", DataAnalysisTables.RUN, State.UNKNOWN, "The cache settings of " + table + " could not be read: " + e.getMessage(),
"Fix the settings row for that table (a negative limit is invalid)."));
}
}
if(tablesPerMinutes.isEmpty() || (tablesPerMinutes.size() == 1 && tablesPerMinutes.firstKey() == 0))
{
return (new Item("Result cache", DataAnalysisTables.RUN, State.DEFAULT, "Off: every exact run computes fresh.", "Set cache minutes on Analysis Settings to reuse results."));
}
if(tablesPerMinutes.size() == 1)
{
return (new Item("Result cache", DataAnalysisTables.RUN, State.OK, "Exact results are reused for " + tablesPerMinutes.firstKey() + " minutes.", null));
}
String parts = tablesPerMinutes.entrySet().stream().map(e -> e.getValue() + (e.getValue() == 1 ? " table" : " tables") + (e.getKey() == 0 ? ": off" : ": " + e.getKey() + " min"))
.collect(java.util.stream.Collectors.joining(", "));
return (new Item("Result cache", DataAnalysisTables.RUN, State.OK, "Exact results are reused per table (default " + config.getDefaultCacheTtlMinutes() + " min): " + parts + ".", null));
}
}
@@ -0,0 +1,157 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.app;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.kingsrook.qbits.dataanalysis.DataAnalysisRuntime;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qbits.dataanalysis.result.Chart;
import com.kingsrook.qbits.dataanalysis.result.Metric;
import com.kingsrook.qbits.dataanalysis.saved.AnalysisExport;
import com.kingsrook.qbits.dataanalysis.watch.WatchRecords;
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.AbstractWidgetRenderer;
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.actions.widgets.RenderWidgetInput;
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetOutput;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.ChartData;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.ChartSubheaderData;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.WidgetType;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
/*******************************************************************************
** Saved analysis rendered through Next's existing standard chart widget.
*******************************************************************************/
public class SavedAnalysisWidget extends AbstractWidgetRenderer
{
public static final String NAME = "DATA_ANALYSIS_SAVED";
/*******************************************************************************
** Hosts clone this metadata and set savedId to place an analysis on a dashboard.
*******************************************************************************/
public static QWidgetMetaData widget()
{
return (new QWidgetMetaData().withName(NAME).withLabel("Saved analysis").withType(WidgetType.BAR_CHART.getType())
.withGridColumns(12).withIsCard(true).withCodeReference(new QCodeReference(SavedAnalysisWidget.class))
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.NOT_PROTECTED)));
}
/*******************************************************************************
** Values come from a fresh viewer run; no stored owner result is ever reused.
*******************************************************************************/
@Override
public RenderWidgetOutput render(RenderWidgetInput input) throws QException
{
var defaults = ((QWidgetMetaData) input.getWidgetMetaData()).getDefaultValues();
Object value = defaults == null ? null : defaults.get("savedId");
if(value == null)
{
return (new RenderWidgetOutput(new ChartData("Saved analysis", "Choose a saved analysis for this widget.", "Analysis", List.of(), List.of())));
}
Integer id;
try
{
id = Integer.valueOf(value.toString());
}
catch(NumberFormatException e)
{
throw new QBadRequestException("savedId must be an integer.");
}
var saved = WatchRecords.get(DataAnalysisTables.SAVED, id);
var result = DataAnalysisRuntime.saved().run(id);
List<Metric> metrics = AnalysisExport.headlines(result);
Chart chart = null;
if(result.columnProfile() != null)
{
chart = result.columnProfile().getChart();
}
else if(result.tableProfile() != null)
{
chart = result.tableProfile().getHeatmap();
}
else if(result.correlation() != null)
{
chart = result.correlation().getChart();
}
else if(result.shift() != null)
{
chart = result.shift().getChart();
}
else if(result.compare() != null && !result.compare().getFields().isEmpty())
{
chart = result.compare().getFields().getFirst().getChart();
}
String description = metrics.stream().filter(Objects::nonNull).map(m -> m.getLabel() + ": " + AnalysisExport.value(m))
.collect(java.util.stream.Collectors.joining("; "));
if(!result.warnings().isEmpty())
{
description += " " + String.join("; ", result.warnings());
}
ChartData data = new ChartData().withTitle(saved.getValueString("name")).withDescription(description).withHeight(280);
String path = QContext.getQInstance().getTablePath(DataAnalysisTables.SAVED) + "/" + id;
Number mainNumber = metrics.stream().filter(m -> !Boolean.TRUE.equals(m.getSuppressed()) && m.getValue() instanceof Number)
.map(m -> (Number) m.getValue()).findFirst().orElse(null);
data.withChartSubheaderData(new ChartSubheaderData().withMainNumber(mainNumber).withMainNumberUrl(path));
List<String> labels = new ArrayList<>();
List<ChartData.Data.Dataset> datasets = new ArrayList<>();
if(chart != null && !chart.getSeries().isEmpty())
{
chart.getSeries().getFirst().getPoints().forEach(p -> labels.add(Objects.toString(p.getLabel(), Objects.toString(p.getX(), ""))));
for(var series : chart.getSeries())
{
datasets.add(new ChartData.Data.Dataset().withLabel(series.getName())
.withData(series.getPoints().stream().map(p -> (Number) p.getY()).toList()));
}
}
else if(result.pivot() != null)
{
List<Number> numbers = new ArrayList<>();
for(var cell : result.pivot().getCells())
{
labels.add(java.util.stream.Stream.concat(result.pivot().getRowHeaders().get(cell.getRowIndex()).stream(),
result.pivot().getColumnHeaders().get(cell.getColumnIndex()).stream()).map(p -> p.getLabel()).collect(java.util.stream.Collectors.joining(" / ")));
Metric metric = cell.getValues().getFirst();
numbers.add(!Boolean.TRUE.equals(metric.getSuppressed()) && metric.getValue() instanceof Number n ? n : null);
}
datasets.add(new ChartData.Data.Dataset().withLabel(result.pivot().getMeasures().getFirst().getLabel()).withData(numbers));
}
else if(result.crosstab() != null)
{
List<Number> numbers = new ArrayList<>();
for(var cell : result.crosstab().getCells())
{
labels.add(result.crosstab().getRows().get(cell.getRowIndex()).getLabel() + " / " + result.crosstab().getColumns().get(cell.getColumnIndex()).getLabel());
Metric metric = cell.getCount();
numbers.add(!Boolean.TRUE.equals(metric.getSuppressed()) && metric.getValue() instanceof Number n ? n : null);
}
datasets.add(new ChartData.Data.Dataset().withLabel("Count").withData(numbers));
}
data.withChartData(new ChartData.Data().withLabels(labels).withUrls(labels.stream().map(label -> path).toList()).withDatasets(datasets));
data.withFooterHTML("<a href=\"" + path.replace("&", "&amp;").replace("\"", "&quot;") + "\">View saved analysis</a>");
return (new RenderWidgetOutput(data));
}
}
@@ -0,0 +1,88 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.app;
import java.io.Serializable;
import java.util.Map;
import com.kingsrook.qqq.backend.core.actions.permissions.CustomPermissionChecker;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
import com.kingsrook.qqq.backend.core.model.actions.AbstractActionInput;
import com.kingsrook.qqq.backend.core.model.actions.AbstractTableActionInput;
import com.kingsrook.qqq.backend.core.model.metadata.code.InitializableViaCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReferenceWithProperties;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.MetaDataWithPermissionRules;
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
import com.kingsrook.qqq.backend.core.utils.collections.MapBuilder;
/*******************************************************************************
** A widget is available only to sessions that can READ the table it summarizes.
** Contributes no catalog entry of its own: the table's READ permission is the
** permission.
*******************************************************************************/
public class TableReadWidgetPermissionChecker implements CustomPermissionChecker, InitializableViaCodeReference
{
private static final String TABLE_NAME_PROPERTY = "tableName";
private String tableName;
/*******************************************************************************
** Code reference for the given table.
*******************************************************************************/
public static QCodeReferenceWithProperties build(String tableName)
{
return (new QCodeReferenceWithProperties(TableReadWidgetPermissionChecker.class, MapBuilder.of(TABLE_NAME_PROPERTY, tableName)));
}
/*******************************************************************************
** Read the table name from the code reference properties.
*******************************************************************************/
@Override
public void initialize(QCodeReference codeReference)
{
if(codeReference instanceof QCodeReferenceWithProperties withProperties)
{
Map<String, Serializable> properties = withProperties.getProperties();
tableName = ValueUtils.getValueAsString(properties.get(TABLE_NAME_PROPERTY));
}
}
/*******************************************************************************
** Deny unless the session may READ the table.
*******************************************************************************/
@Override
public void checkPermissionsThrowing(AbstractActionInput actionInput, MetaDataWithPermissionRules metaDataWithPermissionRules) throws QPermissionDeniedException
{
AbstractTableActionInput tableInput = new AbstractTableActionInput();
tableInput.setTableName(tableName);
PermissionsHelper.checkTablePermissionThrowing(tableInput, TablePermissionSubType.READ);
}
}
@@ -0,0 +1,168 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.engine;
import java.util.Set;
import com.kingsrook.qbits.dataanalysis.result.CandidateKey;
import com.kingsrook.qbits.dataanalysis.result.Chart;
import com.kingsrook.qbits.dataanalysis.result.ColumnProfile;
import com.kingsrook.qbits.dataanalysis.result.DateProfile;
import com.kingsrook.qbits.dataanalysis.result.DistinctValuesPage;
import com.kingsrook.qbits.dataanalysis.result.Drill;
import com.kingsrook.qbits.dataanalysis.result.DuplicatesResult;
import com.kingsrook.qbits.dataanalysis.result.FieldSummary;
import com.kingsrook.qbits.dataanalysis.result.Metric;
import com.kingsrook.qbits.dataanalysis.result.NumericProfile;
import com.kingsrook.qbits.dataanalysis.result.Point;
import com.kingsrook.qbits.dataanalysis.result.Series;
import com.kingsrook.qbits.dataanalysis.result.TableProfile;
import com.kingsrook.qbits.dataanalysis.result.TextProfile;
import com.kingsrook.qbits.dataanalysis.result.ValueCount;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
/*******************************************************************************
** Final defense for profile-generated drills, including representative primary
** keys and prefix bounds. User-authored predicates remain intact; unsafe generated
** drills are disabled rather than broadened by removing their conditions.
*******************************************************************************/
public class AnalysisDrillGuard
{
private final Set<String> fields;
private final String original;
/*******************************************************************************
** Resolve FULL fields once per completed result.
*******************************************************************************/
public AnalysisDrillGuard(Set<String> fields, QQueryFilter original)
{
this.fields = fields;
this.original = JsonUtils.toJson(DrillFilters.copy(original));
}
/*******************************************************************************
** Visit only typed result containers, never the caller's query.
*******************************************************************************/
public void apply(Object value)
{
if(value instanceof Iterable<?> list)
{
list.forEach(this::apply);
}
else if(value instanceof Metric metric)
{
metric.withDrill(permitted(metric.getDrill()));
}
else if(value instanceof ValueCount count)
{
count.withDrill(permitted(count.getDrill()));
}
else if(value instanceof Point point)
{
point.withDrill(permitted(point.getDrill()));
}
else if(value instanceof CandidateKey key)
{
key.withDrill(permitted(key.getDrill()));
}
else if(value instanceof ColumnProfile profile)
{
apply(profile.getCounts());
apply(profile.getTopValues());
apply(profile.getBooleans());
apply(profile.getNumeric());
apply(profile.getDates());
apply(profile.getText());
apply(profile.getChart());
}
else if(value instanceof NumericProfile profile)
{
apply(profile.getMetrics());
apply(profile.getHistogram());
apply(profile.getOutliers());
}
else if(value instanceof DateProfile profile)
{
apply(profile.getMetrics());
apply(profile.getBuckets());
apply(profile.getGaps());
apply(profile.getDayOfWeek());
apply(profile.getHourOfDay());
}
else if(value instanceof TextProfile profile)
{
apply(profile.getMetrics());
apply(profile.getHistogram());
apply(profile.getPatterns());
}
else if(value instanceof TableProfile profile)
{
apply(profile.getRowCount());
apply(profile.getFields());
apply(profile.getCandidateKeys());
apply(profile.getHeatmap());
}
else if(value instanceof FieldSummary field)
{
apply(field.getNulls());
apply(field.getBlanks());
}
else if(value instanceof Chart chart)
{
apply(chart.getSeries());
}
else if(value instanceof Series series)
{
apply(series.getPoints());
}
else if(value instanceof DistinctValuesPage page)
{
apply(page.getValues());
}
else if(value instanceof DuplicatesResult result)
{
apply(result.getGroups());
}
}
/*******************************************************************************
** Preserve count equivalence by removing the entire unsafe drill.
*******************************************************************************/
private Drill permitted(Drill drill)
{
return (drill == null || safe(drill.getFilter()) ? drill : null);
}
/*******************************************************************************
** An exact copy of a user subtree is exempt from analysis field restrictions.
*******************************************************************************/
private boolean safe(QQueryFilter filter)
{
if(original.equals(JsonUtils.toJson(DrillFilters.copy(filter))))
{
return (true);
}
return (filter.getCriteria().stream().allMatch(c -> fields.contains(c.getFieldName())
&& (c.getOtherFieldName() == null || fields.contains(c.getOtherFieldName()))
&& (c.getFieldFunction() == null || fields.contains(c.getFieldFunction().getFieldName())))
&& filter.getSubFilters().stream().allMatch(this::safe));
}
}
@@ -25,7 +25,6 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import com.kingsrook.qqq.backend.core.actions.metadata.personalization.TableMetaDataPersonalizerAction;
import com.kingsrook.qqq.backend.core.actions.permissions.FieldSecurityLockHelper;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionEnforcement;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.actions.values.QPossibleValueTranslator;
@@ -64,7 +63,7 @@ public final class AnalysisLabels
*******************************************************************************/
public static String translate(QFieldMetaData field, Serializable value) throws QException
{
return (translate(field, value, new LinkedHashSet<>()));
return (translate(field, value, CoreTierFieldAccessResolver.defaultResolver()));
}
@@ -72,12 +71,24 @@ public final class AnalysisLabels
/*******************************************************************************
** Resolve nested PVS label fields without invoking core's trusted lookup path.
*******************************************************************************/
private static String translate(QFieldMetaData field, Serializable value, Set<String> visited) throws QException
public static String translate(QFieldMetaData field, Serializable value, FieldAnalysisAccessResolver access) throws QException
{
return (translate(field, value, new LinkedHashSet<>(), access));
}
/*******************************************************************************
** Resolve nested labels only through FULL fields under the host policy.
*******************************************************************************/
private static String translate(QFieldMetaData field, Serializable value, Set<String> visited, FieldAnalysisAccessResolver access) throws QException
{
if(value == null)
{
return (null);
}
if(field.getType() == com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType.BOOLEAN)
{
return (com.kingsrook.qqq.backend.core.utils.ValueUtils.getValueAsBoolean(value) ? "Yes" : "No");
}
String fallback = value.toString();
QPossibleValueSource source = QContext.getQInstance().getPossibleValueSource(field.getPossibleValueSourceName());
if(source == null || visited.size() >= 8 || !visited.add(source.getName()))
@@ -98,7 +109,7 @@ public final class AnalysisLabels
List<String> labelFields = original.getRecordLabelFields() == null ? List.of() : original.getRecordLabelFields();
for(String labelField : labelFields)
{
if(!table.getFields().containsKey(labelField) || !FieldSecurityLockHelper.isFieldAccessible(table.getField(labelField)))
if(!table.getFields().containsKey(labelField) || access.resolve(table, table.getField(labelField)) != FieldAnalysisAccess.FULL)
{
return (fallback);
}
@@ -119,7 +130,7 @@ public final class AnalysisLabels
QFieldMetaData labelMetadata = table.getField(labelField);
if(labelMetadata.getPossibleValueSourceName() != null)
{
record.withDisplayValue(labelField, translate(labelMetadata, record.getValue(labelField), visited));
record.withDisplayValue(labelField, translate(labelMetadata, record.getValue(labelField), visited, access));
}
}
String label = QValueFormatter.formatRecordLabel(table, record);
@@ -144,6 +155,14 @@ public final class AnalysisLabels
** host changing field/record locks cannot release older translated labels.
*******************************************************************************/
public static java.util.Map<String, Object> policy(String tableName) throws QException
{
return (policy(tableName, CoreTierFieldAccessResolver.defaultResolver()));
}
/*******************************************************************************
** Include host-resolved tiers of related labels in the exact-run identity.
*******************************************************************************/
public static java.util.Map<String, Object> policy(String tableName, FieldAnalysisAccessResolver access) throws QException
{
java.util.Map<String, Object> result = new java.util.TreeMap<>();
java.util.ArrayDeque<String> pending = new java.util.ArrayDeque<>();
@@ -160,6 +179,7 @@ public final class AnalysisLabels
QTableMetaData table = TableMetaDataPersonalizerAction.execute(input, true);
java.util.Map<String, Object> entry = new java.util.TreeMap<>();
entry.put("fields", table.getFields());
entry.put("fullFields", table.getFields().values().stream().filter(f -> access.resolve(table, f) == FieldAnalysisAccess.FULL).map(QFieldMetaData::getName).sorted().toList());
entry.put("locks", table.getRecordSecurityLocks());
entry.put("labelFields", table.getRecordLabelFields());
entry.put("labelFormat", table.getRecordLabelFormat());
@@ -20,19 +20,21 @@
package com.kingsrook.qbits.dataanalysis.engine;
import java.io.Serializable;
import java.util.List;
import com.kingsrook.qbits.dataanalysis.permissions.DataAnalysisPermissions;
import com.kingsrook.qqq.backend.core.actions.metadata.personalization.TableMetaDataPersonalizerAction;
import com.kingsrook.qqq.backend.core.actions.permissions.FieldSecurityLockHelper;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionEnforcement;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
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.exceptions.QPermissionDeniedException;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
/*******************************************************************************
** Fail closed before any source-table computation, including cache retrieval.
@@ -40,17 +42,27 @@ import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
public class AnalysisSecurity
{
private final EffectiveConfigResolver configs;
private final FieldAnalysisAccessResolver fieldAccess;
/*******************************************************************************
** Use the runtime's configuration policy.
*******************************************************************************/
public AnalysisSecurity(EffectiveConfigResolver configs)
{
this.configs = configs;
this(configs, CoreTierFieldAccessResolver.defaultResolver());
}
/*******************************************************************************
** Bind the host field policy.
*******************************************************************************/
public AnalysisSecurity(EffectiveConfigResolver configs, FieldAnalysisAccessResolver fieldAccess)
{
this.configs = configs;
this.fieldAccess = fieldAccess;
}
/*******************************************************************************
** Explicit enforcement is independent of the instance's default switch.
*******************************************************************************/
@@ -76,7 +88,7 @@ public class AnalysisSecurity
{
QTableMetaData table = table(name);
EffectiveConfig c = configs.resolve(name);
return (table.getFields().values().stream().filter(FieldSecurityLockHelper::isFieldAccessible)
return (table.getFields().values().stream().filter(f -> fieldAccess.resolve(table, f) == FieldAnalysisAccess.FULL)
.filter(f -> c.getAnalyzableFields().isEmpty() || c.getAnalyzableFields().contains(f.getName()))
.filter(f -> !c.getExcludedFields().contains(f.getName())).toList());
}
@@ -89,6 +101,50 @@ public class AnalysisSecurity
public QFieldMetaData field(String table, String field) throws QException
{
return (analyzableFields(table).stream().filter(f -> f.getName().equals(field)).findFirst()
.orElseThrow(() -> new QPermissionDeniedException("Analysis is unavailable for this field.")));
.orElseThrow(() -> new QBadRequestException("Unknown analysis field.")));
}
/*******************************************************************************
** Core fingerprint plus the sorted FULL-field list, hashed by the run identity.
*******************************************************************************/
public String accessFingerprint(String table) throws QException
{
return (fieldAccess.getAccessFingerprint() + ":" + JsonUtils.toJson(analyzableFields(table).stream().map(QFieldMetaData::getName).sorted().toList()));
}
/*******************************************************************************
** Check a joined field without requiring the related table analyze permission.
*******************************************************************************/
public QFieldMetaData joinedField(String tableName, String fieldName) throws QException
{
QTableMetaData table = joinedTable(tableName);
QFieldMetaData field = table.getFields().get(fieldName);
if(field == null || fieldAccess.resolve(table, field) != FieldAnalysisAccess.FULL)
{
throw new QBadRequestException("Unknown analysis field.");
}
return (field);
}
/*******************************************************************************
** Display labels use the same policy as the selected pivot field.
*******************************************************************************/
public String label(QFieldMetaData field, Serializable value) throws QException
{
return (AnalysisLabels.translate(field, value, fieldAccess));
}
/*******************************************************************************
** Each intermediate exposed-join table requires READ, without analyze rights.
*******************************************************************************/
public QTableMetaData joinedTable(String tableName) throws QException
{
QueryInput input = new QueryInput(tableName);
input.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
if(QContext.getQInstance().getTable(tableName) == null || !PermissionsHelper.hasTablePermission(input, tableName, TablePermissionSubType.READ))
{
throw new QBadRequestException("Unknown analysis field.");
}
return (TableMetaDataPersonalizerAction.execute(input, true));
}
}
@@ -48,13 +48,23 @@ import com.kingsrook.qqq.backend.core.utils.ValueUtils;
public class ColumnProfiler
{
private final AnalysisBackend backend;
private final FieldAnalysisAccessResolver fieldAccess;
/*******************************************************************************
** The backend can be replaced when core's new operators ship.
*******************************************************************************/
public ColumnProfiler(AnalysisBackend backend)
{
this(backend, CoreTierFieldAccessResolver.defaultResolver());
}
/*******************************************************************************
** Bind the host field policy for possible-value labels.
*******************************************************************************/
public ColumnProfiler(AnalysisBackend backend, FieldAnalysisAccessResolver fieldAccess)
{
this.backend = backend;
this.fieldAccess = fieldAccess;
}
@@ -82,7 +92,7 @@ public class ColumnProfiler
}
result.getCounts().add(ProfileSupport.count("distinct", counts.distinct(), table, drillFilter, counts.distinctFilter()));
result.getCounts().add(ProfileSupport.metric("uniqueness", counts.uniqueness(), ValueType.PERCENT));
result.withTopValues(ProfileSupport.values(table, drillFilter, field, backend.topValues(table, filter, name, 20, 0, null), rows));
result.withTopValues(ProfileSupport.values(table, drillFilter, field, backend.topValues(table, filter, name, 20, 0, null), rows, fieldAccess));
QFieldType type = field.getType();
if(type == QFieldType.INTEGER || type == QFieldType.LONG || type == QFieldType.DECIMAL)
{
@@ -0,0 +1,254 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.engine;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.dataanalysis.result.ChartKind;
import com.kingsrook.qbits.dataanalysis.result.CompareRequest;
import com.kingsrook.qbits.dataanalysis.result.CompareResult;
import com.kingsrook.qbits.dataanalysis.result.ComparisonSide;
import com.kingsrook.qbits.dataanalysis.result.ComparisonValue;
import com.kingsrook.qbits.dataanalysis.result.FieldComparison;
import com.kingsrook.qbits.dataanalysis.result.Metric;
import com.kingsrook.qbits.dataanalysis.result.Point;
import com.kingsrook.qbits.dataanalysis.result.Series;
import com.kingsrook.qbits.dataanalysis.result.ValueType;
import com.kingsrook.qbits.dataanalysis.stats.Statistics;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.Aggregate;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
/*******************************************************************************
** Two populations share category boundaries and exact producing predicates.
*******************************************************************************/
public class ComparisonExplorer extends RelationshipSupport
{
/*******************************************************************************
** Bind request-local policy without modifying session metadata.
*******************************************************************************/
public ComparisonExplorer(AnalysisSecurity security, EffectiveConfig config, String table)
{
super(security, config, table);
}
/*******************************************************************************
** Resolve every field before issuing source queries.
*******************************************************************************/
public CompareResult compare(CompareRequest request) throws QException
{
if(request.getFields() == null || request.getFields().isEmpty() || request.getFields().size() > 100
|| request.getFields().stream().distinct().count() != request.getFields().size())
{
throw new QBadRequestException("Choose 1 to 100 distinct analysis fields.");
}
for(String field : request.getFields())
{
full(field);
}
CompareResult result = new CompareResult();
for(String field : request.getFields())
{
result.getFields().add(numeric(full(field)) ? numericComparison(request, field) : categoryComparison(request, field));
}
return (result);
}
/*******************************************************************************
** All moments and quartiles are computed together by core, including VAR_SAMP.
*******************************************************************************/
protected Map<String, BigDecimal> moments(String field, QQueryFilter filter) throws QException
{
Map<String, Aggregate> measures = new LinkedHashMap<>();
measures.put("count", measure(field, AggregateOperator.COUNT));
measures.put("mean", measure(field, AggregateOperator.AVG));
measures.put("variance", measure(field, AggregateOperator.VAR_SAMP));
measures.put("min", measure(field, AggregateOperator.MIN));
measures.put("max", measure(field, AggregateOperator.MAX));
for(int p : List.of(25, 50, 75))
{
measures.put("p" + p, measure(field, AggregateOperator.PERCENTILE_CONT).withPercentile(BigDecimal.valueOf(p, 2)));
}
var row = summarize(filter, new ArrayList<>(measures.values()));
Map<String, BigDecimal> result = new LinkedHashMap<>();
measures.forEach((name, aggregate) -> result.put(name, decimal(row.getAggregateValues().get(aggregate))));
result.putIfAbsent("count", BigDecimal.ZERO);
return (result);
}
/*******************************************************************************
** Two BOX series retain all five summary values; mean and median get drills.
*******************************************************************************/
private FieldComparison numericComparison(CompareRequest request, String field) throws QException
{
Map<String, BigDecimal> a = moments(field, request.getFilterA());
Map<String, BigDecimal> b = moments(field, request.getFilterB());
long nA = a.get("count").longValue();
long nB = b.get("count").longValue();
ComparisonSide sideA = numericSide(field, request.getLabelA(), request.getFilterA(), a);
ComparisonSide sideB = numericSide(field, request.getLabelB(), request.getFilterB(), b);
ComparisonValue value = new ComparisonValue().withSideA(sideA).withSideB(sideB).withLabel(field);
boolean hidden = nA < config.getMinGroupSize() || nB < config.getMinGroupSize();
if(!hidden)
{
deltas(value, a.get("mean"), b.get("mean"));
}
Statistics.Result test = hidden ? Statistics.unavailable("Welch's t-test", "privacy guard")
: Statistics.welch(nA, number(a, "mean"), number(a, "variance"), nB, number(b, "mean"), number(b, "variance"));
return (new FieldComparison().withField(field).withValues(List.of(value)).withSignificance(significance(test))
.withChart(chart(ChartKind.BOX, List.of(box(sideA), box(sideB)), "Two box summaries; delta is B minus A.")));
}
/*******************************************************************************
** Null moments remain invalid test inputs rather than becoming zero variance.
*******************************************************************************/
private static double number(Map<String, BigDecimal> values, String key)
{
return (values.get(key) == null ? Double.NaN : values.get(key).doubleValue());
}
/*******************************************************************************
** Count means non-null numeric records; every summary drills to that set.
*******************************************************************************/
protected ComparisonSide numericSide(String field, String label, QQueryFilter filter, Map<String, BigDecimal> values)
{
ComparisonSide result = new ComparisonSide().withLabel(label);
for(String key : List.of("count", "mean", "min", "p25", "p50", "p75", "max"))
{
String name = key.equals("p50") ? "median" : key;
result.getMetrics().add(metric(name, values.get(key), key.equals("count") ? ValueType.COUNT : ValueType.DECIMAL, filter, DrillFilters.nonNull(field, false)));
}
guard(result.getMetrics(), values.get("count").longValue());
return (result);
}
/*******************************************************************************
** Only guarded summary metrics enter charts.
*******************************************************************************/
private Series box(ComparisonSide side)
{
Series series = new Series().withName(side.getLabel());
side.getMetrics().stream().filter(m -> !List.of("count", "mean").contains(m.getKey()) && m.getValue() != null)
.forEach(m -> series.getPoints().add(new Point().withX(m.getKey()).withY(decimal(m.getValue())).withLabel(m.getLabel()).withDrill(m.getDrill())));
return (series);
}
/*******************************************************************************
** Top ten across the union gives both populations the same categories.
** Expected counts below five pool into Other before display and inference.
*******************************************************************************/
private FieldComparison categoryComparison(CompareRequest request, String field) throws QException
{
QQueryFilter union = request.getFilterA() == null || request.getFilterB() == null ? null
: new QQueryFilter().withBooleanOperator(QQueryFilter.BooleanOperator.OR).withSubFilter(DrillFilters.copy(request.getFilterA())).withSubFilter(DrillFilters.copy(request.getFilterB()));
long nA = size(request.getFilterA());
long nB = size(request.getFilterB());
List<Category> kept = new ArrayList<>();
List<Category> other = new ArrayList<>();
boolean privateOther = false;
for(Category category : categories(field, union, 10))
{
long a = size(DrillFilters.and(request.getFilterA(), category.condition()));
long b = size(DrillFilters.and(request.getFilterB(), category.condition()));
boolean hidden = category.privateGroup() || a < config.getMinGroupSize() || b < config.getMinGroupSize();
double pooled = nA + nB == 0 ? 0 : (double) (a + b) / (nA + nB);
if(hidden || Math.min(nA * pooled, nB * pooled) < 5 || category.label().equals("Other") && category.value() == null)
{
other.add(category);
privateOther |= hidden;
}
else
{
kept.add(category);
}
}
if(!other.isEmpty())
{
kept.add(merge(other, privateOther));
}
double[][] counts = new double[2][kept.size()];
FieldComparison result = new FieldComparison().withField(field);
Series seriesA = new Series().withName(request.getLabelA());
Series seriesB = new Series().withName(request.getLabelB());
for(int i = 0; i < kept.size(); i++)
{
Category category = kept.get(i);
long a = size(DrillFilters.and(request.getFilterA(), category.condition()));
long b = size(DrillFilters.and(request.getFilterB(), category.condition()));
counts[0][i] = a;
counts[1][i] = b;
ComparisonSide sideA = categorySide(request.getLabelA(), request.getFilterA(), category, a, nA);
ComparisonSide sideB = categorySide(request.getLabelB(), request.getFilterB(), category, b, nB);
ComparisonValue value = new ComparisonValue().withValue(category.value()).withLabel(category.label()).withSideA(sideA).withSideB(sideB);
boolean hidden = a < config.getMinGroupSize() || b < config.getMinGroupSize();
if(!hidden)
{
deltas(value, ProfileSupport.share(a, nA), ProfileSupport.share(b, nB));
}
value.withSignificance(significance(hidden || category.privateGroup() ? Statistics.unavailable("Two-proportion z-test", "privacy guard") : Statistics.proportions(a, nA, b, nB)));
result.getValues().add(value);
categoryPoint(seriesA, category, sideA);
categoryPoint(seriesB, category, sideB);
}
result.withSignificance(significance(privateOther ? Statistics.unavailable("Chi-square homogeneity", "privacy guard") : Statistics.chiSquare(counts, true)));
return (result.withChart(chart(ChartKind.BAR, List.of(seriesA, seriesB), "Grouped bars; delta is B minus A. Low expected counts are merged into Other.")));
}
/*******************************************************************************
** Sensitive merged categories reveal no predicate or original value.
*******************************************************************************/
private ComparisonSide categorySide(String label, QQueryFilter filter, Category category, long n, long total)
{
ComparisonSide side = new ComparisonSide().withLabel(label).withMetrics(List.of(metric("count", n, ValueType.COUNT, filter, category.condition()),
metric("share", ProfileSupport.share(n, total), ValueType.PERCENT, filter, category.condition())));
if(category.privateGroup())
{
side.getMetrics().forEach(m -> m.withDrill(null));
}
guard(side.getMetrics(), n);
return (side);
}
/*******************************************************************************
** Charts reflect only released count metrics.
*******************************************************************************/
private void categoryPoint(Series series, Category category, ComparisonSide side)
{
Metric count = side.getMetrics().getFirst();
series.getPoints().add(new Point().withX(category.label()).withLabel(category.label()).withY(decimal(count.getValue())).withDrill(count.getDrill()));
}
/*******************************************************************************
** Percent delta is a fraction relative to |A|; zero baseline is undefined.
*******************************************************************************/
private void deltas(ComparisonValue value, BigDecimal a, BigDecimal b)
{
BigDecimal delta = a == null || b == null ? null : b.subtract(a);
value.withDelta(ProfileSupport.metric("delta", delta, ValueType.DECIMAL));
value.withPercentDelta(ProfileSupport.metric("percentDelta", delta == null || a.signum() == 0 ? null : delta.divide(a.abs(), MathContext.DECIMAL128), ValueType.PERCENT));
}
}
@@ -0,0 +1,118 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.engine;
import java.lang.reflect.Method;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
/*******************************************************************************
** Optional core bridge: replace with direct calls once QQQ ships the fieldaccess package.
** Class and method discovery happen once; invocation failures fail closed.
*******************************************************************************/
public class CoreTierFieldAccessResolver implements FieldAnalysisAccessResolver
{
private static final CoreTierFieldAccessResolver DEFAULT = discover();
private final Method tier;
private final Method fingerprint;
/*******************************************************************************
** Bind discovered static methods once.
*******************************************************************************/
public CoreTierFieldAccessResolver(Class<?> helper) throws ReflectiveOperationException
{
tier = helper.getMethod("getTier", QTableMetaData.class, String.class);
Method optional;
try
{
optional = helper.getMethod("getAccessFingerprint");
}
catch(NoSuchMethodException e)
{
optional = null;
}
fingerprint = optional;
}
/*******************************************************************************
** Resolve the optional class once per class loader.
*******************************************************************************/
private static CoreTierFieldAccessResolver discover()
{
try
{
return (new CoreTierFieldAccessResolver(Class.forName("com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessHelper")));
}
catch(ClassNotFoundException e)
{
return (null);
}
catch(ReflectiveOperationException e)
{
throw new ExceptionInInitializerError(e);
}
}
/*******************************************************************************
** Use legacy locks only when the core helper class is absent.
*******************************************************************************/
public static FieldAnalysisAccessResolver defaultResolver()
{
return (DEFAULT == null ? new FieldSecurityLockFieldAccessResolver() : DEFAULT);
}
/*******************************************************************************
** Unknown tiers and invocation failures never grant analysis rights.
*******************************************************************************/
@Override
public FieldAnalysisAccess resolve(QTableMetaData table, QFieldMetaData field)
{
try
{
return (switch(String.valueOf(tier.invoke(null, table, field.getName())))
{
case "FULL" -> FieldAnalysisAccess.FULL;
case "REVEALABLE" -> FieldAnalysisAccess.EXACT_MATCH_ONLY;
default -> FieldAnalysisAccess.NONE;
});
}
catch(ReflectiveOperationException e)
{
return (FieldAnalysisAccess.NONE);
}
}
/*******************************************************************************
** A broken fingerprint prevents cache reuse rather than returning stale data.
*******************************************************************************/
@Override
public String getAccessFingerprint()
{
try
{
return (fingerprint == null ? "" : (String) fingerprint.invoke(null));
}
catch(ReflectiveOperationException e)
{
throw new IllegalStateException("Could not resolve field access fingerprint.", e);
}
}
}
@@ -34,13 +34,23 @@ import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
public class DistinctValues
{
private final AnalysisBackend backend;
private final FieldAnalysisAccessResolver fieldAccess;
/*******************************************************************************
** Bind primitive operations.
*******************************************************************************/
public DistinctValues(AnalysisBackend backend)
{
this(backend, CoreTierFieldAccessResolver.defaultResolver());
}
/*******************************************************************************
** Bind the host field policy for possible-value labels.
*******************************************************************************/
public DistinctValues(AnalysisBackend backend, FieldAnalysisAccessResolver fieldAccess)
{
this.backend = backend;
this.fieldAccess = fieldAccess;
}
@@ -60,7 +70,7 @@ public class DistinctValues
boolean wholeListing = config.getMinGroupSize() > 0 || request.getSearch() != null && !request.getSearch().isBlank();
int fetch = wholeListing ? Math.max(1, config.getMaxRows()) : request.getPageSize() + 1;
List<ValueCount> values = ProfileSupport.values(request.getTableName(), scope.filter(), field,
backend.topValues(request.getTableName(), scope.filter(), field.getName(), fetch, wholeListing ? 0 : offset, request.getSearch()), scope.rowsScanned());
backend.topValues(request.getTableName(), scope.filter(), field.getName(), fetch, wholeListing ? 0 : offset, request.getSearch()), scope.rowsScanned(), fieldAccess);
long totalDistinct = wholeListing ? values.stream().filter(v -> v.getValue() != null).count()
: backend.fieldCounts(request.getTableName(), scope.filter(), List.of(field.getName())).get(field.getName()).distinct();
values = new MinGroupSizeGuard(config.getMinGroupSize()).groups(values);
@@ -302,9 +302,19 @@ public final class DrillFilters
/*******************************************************************************
** String decimal operands preserve exact scale and precision across JSON round trips.
** Filter expressions (relative dates) are left for core to evaluate.
*******************************************************************************/
private static Serializable restoreValue(com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType type, Serializable value)
{
if(value instanceof com.kingsrook.qqq.backend.core.model.actions.tables.query.expressions.AbstractFilterExpression<?>)
{
///////////////////////////////////////////////////////////////////////////
// a relative date ("now minus one day", "this month") is not a value to //
// convert: core evaluates it when the query runs, so a saved or //
// scheduled analysis means "the last day" on every run //
///////////////////////////////////////////////////////////////////////////
return (value);
}
if(type == com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType.DECIMAL)
{
return (value == null ? null : value.toString());
@@ -65,6 +65,16 @@ public class EffectiveConfigResolver
/*******************************************************************************
** The code configuration this resolver starts from.
*******************************************************************************/
public DataAnalysisQBitConfig getDefaults()
{
return (defaults);
}
/*******************************************************************************
** Return a detached snapshot so callers cannot change memoized policy.
*******************************************************************************/
@@ -0,0 +1,29 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.engine;
/*******************************************************************************
** Analysis access is stricter than the ability to submit an exact query.
*******************************************************************************/
public enum FieldAnalysisAccess
{
FULL, EXACT_MATCH_ONLY, NONE
}
@@ -0,0 +1,43 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.engine;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
/*******************************************************************************
** Resolve the current user's analysis rights without exposing protected values.
*******************************************************************************/
public interface FieldAnalysisAccessResolver
{
/*******************************************************************************
** Only FULL fields may contribute generated analysis predicates.
*******************************************************************************/
FieldAnalysisAccess resolve(QTableMetaData table, QFieldMetaData field);
/*******************************************************************************
** Optional core policy fingerprint supplements the FULL-field list hash.
*******************************************************************************/
default String getAccessFingerprint()
{
return ("");
}
}
@@ -0,0 +1,42 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.engine;
import com.kingsrook.qqq.backend.core.actions.permissions.FieldSecurityLockHelper;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
/*******************************************************************************
** Legacy lock adapter. The core tier API (qbit-secured-data) will map REVEALABLE
** to EXACT_MATCH_ONLY, MASKED/HIDDEN without filter rights to NONE, and
** MASKED/HIDDEN with filter rights to FULL.
*******************************************************************************/
public class FieldSecurityLockFieldAccessResolver implements FieldAnalysisAccessResolver
{
/*******************************************************************************
** Keep the legacy lock enforcement when core tiers are not installed.
*******************************************************************************/
@Override
public FieldAnalysisAccess resolve(QTableMetaData table, QFieldMetaData field)
{
return (FieldSecurityLockHelper.isFieldAccessible(field) ? FieldAnalysisAccess.FULL : FieldAnalysisAccess.NONE);
}
}
@@ -30,6 +30,8 @@ import com.kingsrook.qbits.dataanalysis.result.ValueType;
public final class MetricLabels
{
private static final Map<String, String> LABELS = Map.ofEntries(
Map.entry("count", "Count"), Map.entry("delta", "Difference"), Map.entry("percentDelta", "Percent change"),
Map.entry("psi", "Population stability index"), Map.entry("rowShare", "Row share"), Map.entry("columnShare", "Column share"),
Map.entry("rows", "Rows"), Map.entry("nonNull", "Non-empty"), Map.entry("nulls", "Nulls"),
Map.entry("blanks", "Blanks"), Map.entry("distinct", "Distinct values"), Map.entry("uniqueness", "Uniqueness"),
Map.entry("completeness", "Completeness"), Map.entry("share", "Share"),
@@ -143,4 +143,16 @@ public class MinGroupSizeGuard
profile.getText().withHistogram(groups(profile.getText().getHistogram())).withPatterns(groups(profile.getText().getPatterns()));
}
}
/*******************************************************************************
** Small pivot cells suppress every measure, including count, with no drill.
*******************************************************************************/
public void pivotMetrics(List<Metric> metrics, long rows)
{
if(rows < minimum)
{
metrics.forEach(m -> m.withValue(null).withFormatted(null).withDrill(null).withSuppressed(true)
.withSuppressedReason("Hidden: fewer than " + minimum + " records"));
}
}
}
@@ -33,6 +33,14 @@ public record NiceBins(BigDecimal low, BigDecimal high, int count)
** Select the closest 10..25-bin enclosure from 1, 2, 2.5 and 5 times powers of ten.
*******************************************************************************/
public static NiceBins covering(BigDecimal low, BigDecimal high)
{
return (covering(low, high, 20));
}
/*******************************************************************************
** Choose readable enclosing edges for a requested pivot bin count.
*******************************************************************************/
public static NiceBins covering(BigDecimal low, BigDecimal high, int target)
{
BigDecimal span = high.subtract(low);
if(span.signum() == 0)
@@ -41,7 +49,7 @@ public record NiceBins(BigDecimal low, BigDecimal high, int count)
low = low.subtract(span.divide(BigDecimal.valueOf(2)));
high = high.add(span.divide(BigDecimal.valueOf(2)));
}
int exponent = span.precision() - span.scale() - 2;
int exponent = span.precision() - span.scale() - Integer.toString(target).length();
NiceBins best = null;
for(int power = exponent - 2; power <= exponent + 2; power++)
{
@@ -51,7 +59,7 @@ public record NiceBins(BigDecimal low, BigDecimal high, int count)
BigDecimal first = low.divide(step, 0, RoundingMode.FLOOR).multiply(step);
BigDecimal last = high.divide(step, 0, RoundingMode.CEILING).multiply(step);
int count = last.subtract(first).divide(step).intValueExact();
if(count >= 10 && count <= 25 && (best == null || Math.abs(count - 20) < Math.abs(best.count() - 20)))
if(count >= Math.max(1, target / 2) && count <= Math.max(2, target * 5 / 4) && (best == null || Math.abs(count - target) < Math.abs(best.count() - target)))
{
best = new NiceBins(first, last, count);
}
@@ -0,0 +1,641 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.engine;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.time.Instant;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.kingsrook.qbits.dataanalysis.result.Metric;
import com.kingsrook.qbits.dataanalysis.result.PivotCell;
import com.kingsrook.qbits.dataanalysis.result.PivotDimension;
import com.kingsrook.qbits.dataanalysis.result.PivotHeader;
import com.kingsrook.qbits.dataanalysis.result.PivotMeasure;
import com.kingsrook.qbits.dataanalysis.result.PivotMeasureInfo;
import com.kingsrook.qbits.dataanalysis.result.PivotRequest;
import com.kingsrook.qbits.dataanalysis.result.PivotResult;
import com.kingsrook.qbits.dataanalysis.result.ValueType;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionEnforcement;
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.actions.tables.aggregate.Aggregate;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateResult;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.DateBucket;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.DateBucketUnit;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.GroupBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.NumericBucket;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.QFilterOrderByAggregate;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryJoin;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.joins.JoinType;
import com.kingsrook.qqq.backend.core.model.metadata.tables.ExposedJoin;
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
import com.kingsrook.qqq.backend.core.utils.aggregates.AggregateAnalysis;
/*******************************************************************************
** Request-local pivot planner. Core executes every aggregate with ENFORCE.
** Merged cells are re-aggregated so non-additive measures remain exact.
*******************************************************************************/
public class PivotExplorer
{
private final AnalysisSecurity security;
private final EffectiveConfig config;
private final List<QueryJoin> joins = new ArrayList<>();
private final LinkedHashSet<String> toManyTables = new LinkedHashSet<>();
private final LinkedHashSet<String> multiHopTables = new LinkedHashSet<>();
private PivotRequest request;
private Aggregate count;
private final List<Aggregate> measures = new ArrayList<>();
private final List<PivotMeasureInfo> measureInfo = new ArrayList<>();
private boolean partial;
/*******************************************************************************
** Bind the current user's policy and bounded streamed fallback.
*******************************************************************************/
public PivotExplorer(AnalysisSecurity security, EffectiveConfig config)
{
this.security = security;
this.config = config;
}
/*******************************************************************************
** One slot is a visible group or the exact complement of the kept groups.
*******************************************************************************/
private record Slot(Serializable value, String label, QQueryFilter condition, boolean other)
{
}
/*******************************************************************************
** Dimension state owns predicates, so no generated filter names hidden fields.
*******************************************************************************/
private record Dimension(GroupBy group, QFieldMetaData field, Map<Serializable, Slot> kept, Map<Serializable, Long> counts, Slot other)
{
/*******************************************************************************
** Return the kept group, Other, or null for a privacy-suppressed group.
*******************************************************************************/
Slot slot(Serializable value, int minimum)
{
return (counts.getOrDefault(value, 0L) < minimum ? null : kept.getOrDefault(value, other));
}
}
/*******************************************************************************
** Validate the complete plan before any source computation.
*******************************************************************************/
public PivotResult execute(PivotRequest request) throws QException
{
this.request = request;
validate();
String primaryKey = QContext.getQInstance().getTable(request.getTableName()).getPrimaryKeyField();
count = new Aggregate(primaryKey, AggregateOperator.COUNT).withFieldType(QFieldType.INTEGER);
List<PivotDimension> requested = new ArrayList<>(request.getRows());
requested.addAll(request.getColumns());
List<QFieldMetaData> fields = new ArrayList<>();
for(PivotDimension dimension : requested)
{
fields.add(resolve(dimension.getField()));
}
for(int i = 0; i < request.getValues().size(); i++)
{
prepareMeasure(request.getValues().get(i), i);
}
List<Dimension> dimensions = new ArrayList<>();
for(int i = 0; i < requested.size(); i++)
{
dimensions.add(dimension(requested.get(i), fields.get(i)));
}
int rowCount = request.getRows().size();
List<Dimension> rows = dimensions.subList(0, rowCount);
List<Dimension> columns = dimensions.subList(rowCount, dimensions.size());
PivotResult result = new PivotResult().withAsOf(Instant.now()).withMeasures(measureInfo)
.withTruncatedRows(rows.stream().anyMatch(d -> d.other() != null))
.withTruncatedColumns(columns.stream().anyMatch(d -> d.other() != null));
Map<List<Slot>, List<Metric>> matrix = level(dimensions);
Map<List<Slot>, List<Metric>> rowTotals = request.getShowTotals() || config.getMinGroupSize() > 0 ? level(rows) : Map.of();
Map<List<Slot>, List<Metric>> columnTotals = request.getShowTotals() || config.getMinGroupSize() > 0 ? level(columns) : Map.of();
List<List<Slot>> rowKeys = new ArrayList<>();
List<List<Slot>> columnKeys = new ArrayList<>();
for(var entry : matrix.entrySet())
{
List<Slot> row = List.copyOf(entry.getKey().subList(0, rowCount));
List<Slot> column = List.copyOf(entry.getKey().subList(rowCount, dimensions.size()));
if(config.getMinGroupSize() > 0 && (rowTotals.getOrDefault(row, List.of()).stream().allMatch(m -> m.getSuppressed())
|| columnTotals.getOrDefault(column, List.of()).stream().allMatch(m -> m.getSuppressed())))
{
continue;
}
if(!rowKeys.contains(row))
{
rowKeys.add(row);
}
if(!columnKeys.contains(column))
{
columnKeys.add(column);
}
result.getCells().add(new PivotCell().withRowIndex(rowKeys.indexOf(row)).withColumnIndex(columnKeys.indexOf(column)).withValues(entry.getValue()));
}
result.withRowHeaders(headers(rowKeys)).withColumnHeaders(headers(columnKeys));
if(request.getShowTotals())
{
rowKeys.forEach(key -> result.getRowTotals().add(rowTotals.getOrDefault(key, List.of())));
columnKeys.forEach(key -> result.getColumnTotals().add(columnTotals.getOrDefault(key, List.of())));
result.withGrandTotals(level(List.of()).getOrDefault(List.of(), List.of()));
}
for(String tableName : toManyTables)
{
result.getWarnings().add("Counts include one row per related " + QContext.getQInstance().getTable(tableName).getLabel()
+ "; drill-through is not available for this dimension.");
}
for(String tableName : multiHopTables)
{
result.getWarnings().add("Drill-through is not available for fields reached through more than one join (" + QContext.getQInstance().getTable(tableName).getLabel() + ").");
}
if(config.getMinGroupSize() > 0)
{
result.getWarnings().add("Groups below " + config.getMinGroupSize() + " records are omitted; small cells and totals are suppressed.");
}
if(partial)
{
result.withEstimate(true);
result.getWarnings().add("Partial pivot: the streamed row limit was reached. Drills are disabled because aggregates may cover different prefixes.");
result.getCells().forEach(c -> disableDrills(c.getValues()));
result.getRowTotals().forEach(this::disableDrills);
result.getColumnTotals().forEach(this::disableDrills);
disableDrills(result.getGrandTotals());
}
return (result);
}
/*******************************************************************************
** Reject invalid shapes and types before aggregate execution.
*******************************************************************************/
private void validate() throws QException
{
if(request.getRows() == null || request.getRows().isEmpty() || request.getRows().size() > 3
|| request.getColumns() == null || request.getColumns().size() > 2 || request.getValues() == null
|| request.getValues().isEmpty() || request.getValues().size() > 6 || request.getShowTotals() == null
|| request.getLimitGroups() == null || request.getLimitGroups() < 1 || request.getLimitGroups() > 200)
{
throw new QBadRequestException("Choose 1�3 row dimensions, 0�2 column dimensions, 1�6 measures and a group limit from 1 to 200.");
}
List<PivotDimension> dimensions = new ArrayList<>(request.getRows());
dimensions.addAll(request.getColumns());
LinkedHashSet<String> names = new LinkedHashSet<>();
for(PivotDimension dimension : dimensions)
{
if(dimension == null || dimension.getField() == null || !names.add(dimension.getField()))
{
throw new QBadRequestException("Choose distinct dimension fields.");
}
QFieldMetaData field = resolve(dimension.getField());
var bins = dimension.getNumericBins();
if(dimension.getDateBucket() != null && (bins != null || field.getType() != QFieldType.DATE && field.getType() != QFieldType.DATE_TIME)
|| bins != null && (!numeric(field) || bins.getCount() == null || bins.getCount() < 1 || bins.getCount() > 200
|| bins.getMin() != null && bins.getMax() != null && bins.getMin().compareTo(bins.getMax()) >= 0))
{
throw new QBadRequestException("Buckets must match the field type; numeric bins require 1�200 bins and min < max.");
}
}
}
/*******************************************************************************
** Only exposed, unambiguous paths may introduce a joined field.
** The installed snapshot has no related-record picker join-path helper.
*******************************************************************************/
private QFieldMetaData resolve(String name) throws QException
{
if(name == null || !name.contains("."))
{
return (security.field(request.getTableName(), name));
}
String[] parts = name.split("\\.", -1);
var table = QContext.getQInstance().getTable(request.getTableName());
List<ExposedJoin> exposed = table.getExposedJoins() == null ? List.of() : table.getExposedJoins();
List<ExposedJoin> paths = exposed.stream().filter(j -> j.getJoinTable().equals(parts[0])).toList();
if(parts.length != 2 || paths.size() != 1 || paths.getFirst().getJoinPath() == null || paths.getFirst().getJoinPath().isEmpty())
{
throw new QBadRequestException("Unknown analysis field.");
}
String current = table.getName();
boolean toOne = true;
for(String joinName : paths.getFirst().getJoinPath())
{
var metadata = QContext.getQInstance().getJoin(joinName);
if(metadata == null || !current.equals(metadata.getLeftTable()) && !current.equals(metadata.getRightTable()))
{
throw new QBadRequestException("Unknown analysis field.");
}
String next = current.equals(metadata.getLeftTable()) ? metadata.getRightTable() : metadata.getLeftTable();
JoinType type = metadata.getType();
if(type != null && current.equals(metadata.getRightTable()))
{
type = type.flip();
}
toOne &= type == JoinType.MANY_TO_ONE || type == JoinType.ONE_TO_ONE;
security.joinedTable(next);
QueryJoin existing = joins.stream().filter(j -> next.equals(j.getJoinTable())).findFirst().orElse(null);
if(existing == null)
{
joins.add(new QueryJoin(current, next).withJoinMetaData(metadata));
}
else if(!existing.getJoinMetaData().getName().equals(joinName))
{
throw new QBadRequestException("Ambiguous analysis join path.");
}
current = next;
}
if(!current.equals(parts[0]))
{
throw new QBadRequestException("Unknown analysis field.");
}
if(!toOne)
{
toManyTables.add(current);
}
else if(paths.getFirst().getJoinPath().size() > 1)
{
///////////////////////////////////////////////////////////////////////////////
// counts are per record, but core's implicit joins for a multi-hop filter //
// do not reproduce them on every backend yet (memory counts differ), so no //
// drill until that is fixed in core //
///////////////////////////////////////////////////////////////////////////////
multiHopTables.add(current);
}
return (security.joinedField(parts[0], parts[1]));
}
/*******************************************************************************
** Count records even when a supplied COUNT field is nullable.
*******************************************************************************/
private void prepareMeasure(PivotMeasure measure, int index) throws QException
{
if(measure == null || measure.getOperator() == null)
{
throw new QBadRequestException("Choose a measure operator.");
}
QFieldMetaData field = measure.getField() == null && measure.getOperator() == PivotMeasure.Operator.COUNT ? null : resolve(measure.getField());
PivotMeasure.Operator operator = measure.getOperator();
if((operator == PivotMeasure.Operator.SUM || operator == PivotMeasure.Operator.AVG || operator == PivotMeasure.Operator.PERCENTILE) && !numeric(field)
|| operator == PivotMeasure.Operator.PERCENTILE && (measure.getPercentile() == null || measure.getPercentile().signum() < 0 || measure.getPercentile().compareTo(BigDecimal.ONE) > 0)
|| operator != PivotMeasure.Operator.PERCENTILE && measure.getPercentile() != null)
{
throw new QBadRequestException("Numeric measures require a numeric field; percentile must be between 0 and 1.");
}
Aggregate aggregate = operator == PivotMeasure.Operator.COUNT ? count : new Aggregate(measure.getField(),
operator == PivotMeasure.Operator.PERCENTILE ? AggregateOperator.PERCENTILE_CONT : AggregateOperator.valueOf(operator.name()));
if(operator == PivotMeasure.Operator.PERCENTILE)
{
aggregate.withPercentile(measure.getPercentile());
}
if(operator == PivotMeasure.Operator.COUNT_DISTINCT)
{
aggregate.withFieldType(QFieldType.INTEGER);
}
measures.add(aggregate);
ValueType type = operator == PivotMeasure.Operator.COUNT || operator == PivotMeasure.Operator.COUNT_DISTINCT ? ValueType.COUNT
: numeric(field) ? ValueType.DECIMAL : field.getType() == QFieldType.DATE ? ValueType.DATE : field.getType() == QFieldType.DATE_TIME ? ValueType.DATE_TIME : ValueType.TEXT;
measureInfo.add(new PivotMeasureInfo().withKey("value" + index).withLabel(measureLabel(measure, field)).withValueType(type));
}
/*******************************************************************************
** Human measure labels shared by headers, totals and cells.
*******************************************************************************/
private static String measureLabel(PivotMeasure measure, QFieldMetaData field)
{
String label = field == null ? "" : field.getLabel();
return (switch(measure.getOperator())
{
case COUNT -> "Count";
case AVG -> "Average " + label;
case SUM -> "Sum of " + label;
case COUNT_DISTINCT -> "Distinct " + label;
case MIN -> "Minimum " + label;
case MAX -> "Maximum " + label;
case PERCENTILE -> measure.getPercentile().compareTo(new BigDecimal("0.5")) == 0 ? "Median " + label
: ordinal(measure.getPercentile().multiply(BigDecimal.valueOf(100))) + " percentile of " + label;
});
}
/*******************************************************************************
** English ordinal suffixes, including the eleventh through thirteenth.
*******************************************************************************/
private static String ordinal(BigDecimal value)
{
int number = value.intValue();
String suffix = number % 100 >= 11 && number % 100 <= 13 ? "th" : switch(number % 10)
{
case 1 -> "st";
case 2 -> "nd";
case 3 -> "rd";
default -> "th";
};
return (value.stripTrailingZeros().toPlainString() + suffix);
}
/*******************************************************************************
** Numeric buckets and moments accept the same numeric QQQ field types.
*******************************************************************************/
private static boolean numeric(QFieldMetaData field)
{
return (field != null && (field.getType() == QFieldType.INTEGER || field.getType() == QFieldType.LONG || field.getType() == QFieldType.DECIMAL));
}
/*******************************************************************************
** Select top groups first, then collect cardinality and privacy counts.
*******************************************************************************/
private Dimension dimension(PivotDimension requested, QFieldMetaData field) throws QException
{
GroupBy group = new GroupBy(field.getType(), requested.getField());
if(requested.getDateBucket() != null)
{
group.withBucket(new DateBucket(requested.getDateBucket()));
}
if(requested.getNumericBins() != null)
{
var bins = requested.getNumericBins();
BigDecimal low = bins.getMin();
BigDecimal high = bins.getMax();
if(low == null || high == null)
{
Aggregate min = new Aggregate(requested.getField(), AggregateOperator.MIN);
Aggregate max = new Aggregate(requested.getField(), AggregateOperator.MAX);
var extrema = aggregate(List.of(), request.getFilter(), List.of(min, max), null);
Serializable first = extrema.isEmpty() ? null : extrema.getFirst().getAggregateValues().get(min);
Serializable last = extrema.isEmpty() ? null : extrema.getFirst().getAggregateValues().get(max);
NiceBins nice = NiceBins.covering(first == null ? BigDecimal.ZERO : new BigDecimal(first.toString()), last == null ? BigDecimal.ONE : new BigDecimal(last.toString()), bins.getCount());
low = low == null ? nice.low() : low;
high = high == null ? nice.high() : high;
}
if(low.compareTo(high) >= 0)
{
throw new QBadRequestException("Numeric bin min must be below max.");
}
group.withBucket(new NumericBucket(low, high, bins.getCount()));
}
List<AggregateResult> top = aggregate(List.of(group), request.getFilter(), List.of(count), request.getLimitGroups());
List<AggregateResult> all = aggregate(List.of(group), request.getFilter(), List.of(count), null);
Map<Serializable, Long> counts = new LinkedHashMap<>();
all.forEach(r -> counts.put(r.getGroupByValues().get(group), count(r)));
Map<Serializable, Slot> kept = new LinkedHashMap<>();
for(AggregateResult row : top)
{
Serializable value = row.getGroupByValues().get(group);
if(count(row) >= config.getMinGroupSize())
{
kept.put(value, new Slot(value, label(group, field, value), condition(group, field, value), false));
}
}
List<Serializable> remaining = counts.keySet().stream().filter(v -> !kept.containsKey(v) && counts.get(v) >= config.getMinGroupSize()).toList();
Slot other = null;
if(!remaining.isEmpty())
{
QQueryFilter predicate;
if(group.getBucket() == null && field.getType() != QFieldType.BOOLEAN && config.getMinGroupSize() == 0 && !kept.containsKey("") && kept.keySet().stream().noneMatch(v -> v instanceof Instant || v instanceof LocalDate))
{
List<Serializable> values = kept.keySet().stream().filter(Objects::nonNull).toList();
predicate = values.isEmpty() ? new QQueryFilter() : new QQueryFilter().withCriteria(group.getFieldName(), QCriteriaOperator.NOT_IN, values);
predicate = DrillFilters.and(predicate, DrillFilters.nonNull(group.getFieldName(), field.getType().isStringLike()));
if(!kept.containsKey(null))
{
predicate = new QQueryFilter().withBooleanOperator(QQueryFilter.BooleanOperator.OR).withSubFilter(predicate).withSubFilter(DrillFilters.nulls(group.getFieldName(), field.getType().isStringLike()));
}
if(field.getType().isStringLike())
{
predicate = new QQueryFilter().withBooleanOperator(QQueryFilter.BooleanOperator.OR).withSubFilter(predicate).withSubFilter(DrillFilters.value(group.getFieldName(), "", true));
}
}
else
{
predicate = new QQueryFilter().withBooleanOperator(QQueryFilter.BooleanOperator.OR);
for(Serializable value : remaining)
{
predicate.withSubFilter(condition(group, field, value));
}
}
other = new Slot(null, "Other (" + remaining.size() + " groups)", predicate, true);
}
return (new Dimension(group, field, kept, counts, other));
}
/*******************************************************************************
** Native group keys are displayed as labels without changing filter operands.
*******************************************************************************/
private String label(GroupBy group, QFieldMetaData field, Serializable value) throws QException
{
if(value == null)
{
return ("(Blank)");
}
if(group.getBucket() instanceof DateBucket date)
{
return (AnalysisFormatting.dateBucket(value, AnalysisBackend.DateUnit.valueOf(date.getUnit().name()), ValueUtils.getSessionOrInstanceZoneId()));
}
if(group.getBucket() instanceof NumericBucket bins)
{
BigDecimal[] edges = edges(bins, ((Number) value).intValue());
return (AnalysisFormatting.interval(field, edges[0], edges[1]));
}
return (security.label(field, value));
}
/*******************************************************************************
** Match core's final closed numeric bin and exterior bins.
*******************************************************************************/
private static BigDecimal[] edges(NumericBucket bins, int index)
{
BigDecimal width = bins.getMax().subtract(bins.getMin()).divide(BigDecimal.valueOf(bins.getCount()), MathContext.DECIMAL128);
return (new BigDecimal[] { index == 0 ? null : index > bins.getCount() ? bins.getMax() : bins.getMin().add(width.multiply(BigDecimal.valueOf(index - 1))),
index == 0 ? bins.getMin() : index > bins.getCount() ? null : index == bins.getCount() ? bins.getMax() : bins.getMin().add(width.multiply(BigDecimal.valueOf(index))) });
}
/*******************************************************************************
** Calendar and numeric predicates use core bucket boundaries in the session zone.
*******************************************************************************/
private QQueryFilter condition(GroupBy group, QFieldMetaData field, Serializable value) throws QException
{
String name = group.getFieldName();
if(value == null || group.getBucket() == null)
{
return (DrillFilters.value(name, value, field.getType().isStringLike()));
}
if(group.getBucket() instanceof NumericBucket bins)
{
int index = ((Number) value).intValue();
BigDecimal[] edges = edges(bins, index);
if(StandInAnalysisBackend.isMemory(request.getTableName()) && index <= bins.getCount())
{
GroupBy raw = new GroupBy(field.getType(), name);
List<BigDecimal> members = aggregate(List.of(raw), request.getFilter(), List.of(count), null).stream()
.map(r -> r.getGroupByValues().get(raw)).filter(Objects::nonNull).map(v -> new BigDecimal(v.toString())).toList();
return (new StandInAnalysisBackend(config).numericRange(request.getTableName(), name, members, edges[0], edges[1], index == bins.getCount()));
}
return (index > bins.getCount() ? DrillFilters.condition(name, QCriteriaOperator.GREATER_THAN, bins.getMax())
: DrillFilters.range(name, edges[0], edges[1], index == bins.getCount()));
}
DateBucketUnit unit = ((DateBucket) group.getBucket()).getUnit();
if(unit == DateBucketUnit.HOUR)
{
Instant start = ValueUtils.getValueAsInstant(value);
return (DrillFilters.range(name, start, start.plusSeconds(3600), false));
}
if(unit == DateBucketUnit.DAY_OF_WEEK || unit == DateBucketUnit.HOUR_OF_DAY)
{
GroupBy raw = new GroupBy(field.getType(), name);
List<Serializable> members = aggregate(List.of(raw), request.getFilter(), List.of(count), null).stream().map(r -> r.getGroupByValues().get(raw))
.filter(v -> Objects.equals(AggregateAnalysis.bucket(v, group.getBucket(), ValueUtils.getSessionOrInstanceZoneId()), value)).toList();
return (DrillFilters.in(name, members));
}
LocalDate start = ValueUtils.getValueAsLocalDate(value);
LocalDate end = switch(unit)
{
case YEAR -> start.plusYears(1);
case QUARTER -> start.plusMonths(3);
case MONTH -> start.plusMonths(1);
case WEEK -> start.plusWeeks(1);
default -> start.plusDays(1);
};
return (DrillFilters.dateRange(name, start, end, field.getType() == QFieldType.DATE_TIME, ValueUtils.getSessionOrInstanceZoneId()));
}
/*******************************************************************************
** A level is the full matrix, row totals, column totals or grand totals.
*******************************************************************************/
private Map<List<Slot>, List<Metric>> level(List<Dimension> dimensions) throws QException
{
List<Aggregate> requested = new ArrayList<>(measures);
if(!requested.contains(count))
{
requested.add(count);
}
Map<List<Slot>, List<AggregateResult>> grouped = new LinkedHashMap<>();
List<AggregateResult> aggregates = aggregate(dimensions.stream().map(Dimension::group).toList(), request.getFilter(), requested, null);
if(dimensions.isEmpty() && aggregates.isEmpty())
{
AggregateResult empty = new AggregateResult();
requested.forEach(a -> empty.withAggregateValue(a, a.getOperator() == AggregateOperator.COUNT || a.getOperator() == AggregateOperator.COUNT_DISTINCT ? 0L : null));
aggregates = List.of(empty);
}
for(AggregateResult row : aggregates)
{
List<Slot> key = new ArrayList<>();
for(Dimension dimension : dimensions)
{
key.add(dimension.slot(row.getGroupByValues().get(dimension.group()), config.getMinGroupSize()));
}
if(!key.contains(null))
{
grouped.computeIfAbsent(key, ignored -> new ArrayList<>()).add(row);
}
}
Map<List<Slot>, List<Metric>> result = new LinkedHashMap<>();
for(var entry : grouped.entrySet())
{
QQueryFilter predicate = new QQueryFilter();
entry.getKey().forEach(slot -> predicate.withSubFilter(slot.condition()));
AggregateResult row = entry.getValue().getFirst();
if(entry.getKey().stream().anyMatch(Slot::other))
{
var merged = aggregate(List.of(), DrillFilters.and(request.getFilter(), predicate), requested, null);
if(merged.isEmpty())
{
continue;
}
row = merged.getFirst();
}
List<Metric> values = new ArrayList<>();
for(int i = 0; i < measures.size(); i++)
{
PivotMeasureInfo info = measureInfo.get(i);
Serializable value = row.getAggregateValues().get(measures.get(i));
Metric metric = new Metric().withKey(info.getKey()).withLabel(info.getLabel()).withValueType(info.getValueType()).withValue(value)
.withFormatted(AnalysisFormatting.scalar(info.getKey(), value, info.getValueType()));
if(toManyTables.isEmpty() && multiHopTables.isEmpty())
{
metric.withDrill(DrillFilters.drill(request.getTableName(), request.getFilter(), predicate));
}
values.add(metric);
}
new MinGroupSizeGuard(config.getMinGroupSize()).pivotMetrics(values, count(row));
result.put(entry.getKey(), values);
}
return (result);
}
/*******************************************************************************
** Count is always present, even when the user selects only non-count measures.
*******************************************************************************/
private long count(AggregateResult row)
{
Object value = row.getAggregateValues().get(count);
return (value == null ? 0 : ((Number) value).longValue());
}
/*******************************************************************************
** Core owns SQL pushdown, joins, record locks, field locks and bounded fallback.
*******************************************************************************/
private List<AggregateResult> aggregate(List<GroupBy> groups, QQueryFilter filter, List<Aggregate> aggregates, Integer limit) throws QException
{
QQueryFilter query = DrillFilters.restoreTypes(request.getTableName(), filter);
if(limit != null)
{
query.withOrderBy(new QFilterOrderByAggregate(count, false));
}
AggregateInput input = new AggregateInput(request.getTableName()).withFilter(query).withQueryJoins(joins.stream().map(QueryJoin::clone).toList())
.withAllowStreamedFallback(true).withStreamedRowLimit(config.getMaxRows()).withLimit(limit);
groups.forEach(input::withGroupBy);
new LinkedHashSet<>(aggregates).forEach(input::withAggregate);
input.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
var output = com.kingsrook.qbits.dataanalysis.saved.SqlHandoff.aggregate(input);
partial |= output.getTruncated();
return (limit == null ? output.getResults() : output.getResults().stream().sorted(java.util.Comparator.comparingLong(this::count).reversed()
.thenComparing(r -> String.valueOf(r.getGroupByValues().values()))).limit(limit).toList());
}
/*******************************************************************************
** Header tuples retain typed values; Other is distinguished by its label.
*******************************************************************************/
private static List<List<PivotHeader>> headers(List<List<Slot>> keys)
{
return (keys.stream().map(key -> key.stream().map(slot -> new PivotHeader().withValue(slot.value()).withLabel(slot.label())).toList()).toList());
}
/*******************************************************************************
** Partial numbers must never claim an exact drill equivalence.
*******************************************************************************/
private void disableDrills(List<Metric> metrics)
{
metrics.forEach(m -> m.withDrill(null).withEstimate(true));
}
}
@@ -108,6 +108,15 @@ public final class ProfileSupport
** PVS translations run as the current user; drill values always remain ids.
*******************************************************************************/
public static List<ValueCount> values(String table, QQueryFilter filter, QFieldMetaData field, List<AnalysisBackend.GroupCount> groups, long total) throws QException
{
return (values(table, filter, field, groups, total, CoreTierFieldAccessResolver.defaultResolver()));
}
/*******************************************************************************
** Host field policy applies to related display labels as well as source values.
*******************************************************************************/
public static List<ValueCount> values(String table, QQueryFilter filter, QFieldMetaData field, List<AnalysisBackend.GroupCount> groups, long total,
FieldAnalysisAccessResolver access) throws QException
{
List<ValueCount> result = new ArrayList<>();
for(AnalysisBackend.GroupCount group : groups)
@@ -115,7 +124,7 @@ public final class ProfileSupport
String label = group.label();
if(field != null && field.getPossibleValueSourceName() != null && group.value() != null)
{
String translated = AnalysisLabels.translate(field, group.value());
String translated = AnalysisLabels.translate(field, group.value(), access);
if(translated != null)
{
label = translated;
@@ -0,0 +1,255 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.engine;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import com.kingsrook.qbits.dataanalysis.result.ChartKind;
import com.kingsrook.qbits.dataanalysis.result.CorrelationCell;
import com.kingsrook.qbits.dataanalysis.result.CorrelationRequest;
import com.kingsrook.qbits.dataanalysis.result.CorrelationResult;
import com.kingsrook.qbits.dataanalysis.result.CrosstabCell;
import com.kingsrook.qbits.dataanalysis.result.CrosstabRequest;
import com.kingsrook.qbits.dataanalysis.result.CrosstabResult;
import com.kingsrook.qbits.dataanalysis.result.Metric;
import com.kingsrook.qbits.dataanalysis.result.PivotHeader;
import com.kingsrook.qbits.dataanalysis.result.Point;
import com.kingsrook.qbits.dataanalysis.result.ScatterRequest;
import com.kingsrook.qbits.dataanalysis.result.ScatterResult;
import com.kingsrook.qbits.dataanalysis.result.Series;
import com.kingsrook.qbits.dataanalysis.result.TrendLine;
import com.kingsrook.qbits.dataanalysis.result.ValueType;
import com.kingsrook.qbits.dataanalysis.stats.Statistics;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.Aggregate;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
/*******************************************************************************
** Pairwise correlation, bounded scatter samples and guarded contingency tables.
*******************************************************************************/
public class RelationshipExplorer extends RelationshipSupport
{
/*******************************************************************************
** Each operation has its own execution state and policy snapshot.
*******************************************************************************/
public RelationshipExplorer(AnalysisSecurity security, EffectiveConfig config, String table)
{
super(security, config, table);
}
/*******************************************************************************
** All unique CORR pairs share one aggregate call, including streamed fallback.
** Pair counts use core CountAction because Aggregate has no per-measure filter.
*******************************************************************************/
public CorrelationResult correlation(CorrelationRequest request) throws QException
{
List<String> fields = request.getFields();
if(fields == null || fields.size() < 2 || fields.size() > 12 || new LinkedHashSet<>(fields).size() != fields.size())
{
throw new QBadRequestException("Choose 2 to 12 distinct numeric fields.");
}
for(String field : fields)
{
requireNumeric(field);
}
List<Aggregate> aggregates = new ArrayList<>();
for(int i = 0; i < fields.size(); i++)
{
for(int j = i; j < fields.size(); j++)
{
aggregates.add(measure(fields.get(i), AggregateOperator.CORR).withOtherFieldName(fields.get(j)));
}
}
var values = summarize(request.getFilter(), aggregates).getAggregateValues();
CorrelationResult result = new CorrelationResult().withFields(List.copyOf(fields));
List<Series> series = new ArrayList<>();
for(int i = 0; i < fields.size(); i++)
{
String x = fields.get(i);
Series row = new Series().withName(x);
for(int j = 0; j < fields.size(); j++)
{
String y = fields.get(j);
Aggregate key = measure(fields.get(Math.min(i, j)), AggregateOperator.CORR).withOtherFieldName(fields.get(Math.max(i, j)));
BigDecimal value = decimal(values.get(key));
long n = size(paired(request.getFilter(), x, y));
boolean hidden = n < config.getMinGroupSize();
Double r = hidden || n < 2 || value == null ? null : value.doubleValue();
result.getCells().add(new CorrelationCell().withXField(x).withYField(y).withN(hidden ? null : n).withR(r)
.withScatter(hidden ? null : new ScatterRequest().withTableName(table).withXField(x).withYField(y).withFilter(DrillFilters.copy(request.getFilter()))));
row.getPoints().add(new Point().withX(y).withY(r == null ? null : BigDecimal.valueOf(r)).withLabel(x + " / " + y));
}
series.add(row);
}
return (result.withChart(chart(ChartKind.HEATMAP, series, "Pearson r; each cell includes its paired non-null count and scatter request.")));
}
/*******************************************************************************
** QueryInput has no sampling API. Fetch the first N paired records by primary
** key as the user, with core-enforced record locks and a maximum of 2,000.
*******************************************************************************/
public ScatterResult scatter(ScatterRequest request) throws QException
{
requireNumeric(request.getXField());
requireNumeric(request.getYField());
if(request.getLimit() == null || request.getLimit() < 1 || request.getLimit() > 2000)
{
throw new QBadRequestException("Scatter limit must be from 1 to 2000.");
}
String x = request.getXField();
String y = request.getYField();
String pk = primaryKey(table);
QQueryFilter filter = paired(request.getFilter(), x, y);
long n = size(filter);
ScatterResult result = new ScatterResult().withN(n).withSampling("First N paired records by primary key").withSampleSize(0);
if(n < config.getMinGroupSize())
{
return (result.withN(null).withChart(chart(ChartKind.SCATTER, List.of(), "Hidden: fewer than " + config.getMinGroupSize() + " paired records.")));
}
Set<String> selected = new LinkedHashSet<>(List.of(x, y));
boolean drill = config.getMinGroupSize() == 0 && security.analyzableFields(table).stream().anyMatch(f -> f.getName().equals(pk));
if(drill)
{
selected.add(pk);
}
var records = rows(table, filter, selected, request.getLimit());
double[] xs = new double[records.size()];
double[] ys = new double[records.size()];
for(int i = 0; i < records.size(); i++)
{
var record = records.get(i);
BigDecimal xv = decimal(record.getValue(x));
BigDecimal yv = decimal(record.getValue(y));
xs[i] = xv.doubleValue();
ys[i] = yv.doubleValue();
result.getPoints().add(new Point().withX(xv).withY(yv).withDrill(drill ? DrillFilters.drill(table, null,
DrillFilters.condition(pk, QCriteriaOperator.EQUALS, record.getValue(pk))) : null));
}
result.withSampleSize(records.size()).withTrend(trend(xs, ys));
Series points = new Series().withName("Sample").withPoints(result.getPoints());
Series line = new Series().withName("Least-squares trend");
if(result.getTrend() != null)
{
double low = java.util.Arrays.stream(xs).min().orElseThrow();
double high = java.util.Arrays.stream(xs).max().orElseThrow();
for(double value : new double[] {low, high})
{
line.getPoints().add(new Point().withX(BigDecimal.valueOf(value)).withY(BigDecimal.valueOf(result.getTrend().getIntercept() + result.getTrend().getSlope() * value)));
}
}
return (result.withChart(chart(ChartKind.SCATTER, List.of(points, line), "Trend describes the displayed sample, not the full population.")));
}
/*******************************************************************************
** Centered least squares remains stable when coordinates have large offsets.
*******************************************************************************/
private TrendLine trend(double[] x, double[] y)
{
if(x.length < 2)
{
return (null);
}
double meanX = java.util.Arrays.stream(x).average().orElseThrow();
double meanY = java.util.Arrays.stream(y).average().orElseThrow();
double xx = 0;
double xy = 0;
for(int i = 0; i < x.length; i++)
{
xx += (x[i] - meanX) * (x[i] - meanX);
xy += (x[i] - meanX) * (y[i] - meanY);
}
return (xx == 0 ? null : new TrendLine().withSlope(xy / xx).withIntercept(meanY - xy / xx * meanX).withR(Statistics.pearson(x, y)));
}
/*******************************************************************************
** Cell counts include zero combinations. Suppression also removes shares
** that could reconstruct a hidden cell from a known marginal total.
*******************************************************************************/
public CrosstabResult crosstab(CrosstabRequest request) throws QException
{
full(request.getRowField());
full(request.getColumnField());
if(request.getRowField().equals(request.getColumnField()) || request.getLimit() == null || request.getLimit() < 1 || request.getLimit() > 20)
{
throw new QBadRequestException("Choose distinct crosstab fields and a limit from 1 to 20.");
}
List<Category> rows = categories(request.getRowField(), request.getFilter(), request.getLimit());
List<Category> columns = categories(request.getColumnField(), request.getFilter(), request.getLimit());
long[] rowTotals = new long[rows.size()];
long[] columnTotals = new long[columns.size()];
boolean[] hiddenRows = new boolean[rows.size()];
boolean[] hiddenColumns = new boolean[columns.size()];
double[][] counts = new double[rows.size()][columns.size()];
boolean hidden = false;
for(int i = 0; i < rows.size(); i++)
{
for(int j = 0; j < columns.size(); j++)
{
long n = size(DrillFilters.and(request.getFilter(), DrillFilters.and(rows.get(i).condition(), columns.get(j).condition())));
counts[i][j] = n;
rowTotals[i] += n;
columnTotals[j] += n;
if(n < config.getMinGroupSize())
{
hidden = true;
hiddenRows[i] = true;
hiddenColumns[j] = true;
}
}
}
CrosstabResult result = new CrosstabResult().withRows(rows.stream().map(c -> new PivotHeader().withValue(c.value()).withLabel(c.label())).toList())
.withColumns(columns.stream().map(c -> new PivotHeader().withValue(c.value()).withLabel(c.label())).toList());
for(int i = 0; i < rows.size(); i++)
{
for(int j = 0; j < columns.size(); j++)
{
long n = (long) counts[i][j];
QQueryFilter condition = DrillFilters.and(rows.get(i).condition(), columns.get(j).condition());
Metric count = metric("count", n, ValueType.COUNT, request.getFilter(), condition);
Metric rowShare = metric("rowShare", ProfileSupport.share(n, rowTotals[i]), ValueType.PERCENT, request.getFilter(), condition);
Metric columnShare = metric("columnShare", ProfileSupport.share(n, columnTotals[j]), ValueType.PERCENT, request.getFilter(), condition);
List<Metric> metrics = List.of(count, rowShare, columnShare);
if(rows.get(i).privateGroup() || columns.get(j).privateGroup())
{
metrics.forEach(m -> m.withDrill(null));
hidden = true;
}
guard(metrics, n);
if(hiddenRows[i])
{
guard(List.of(rowShare), 0);
}
if(hiddenColumns[j])
{
guard(List.of(columnShare), 0);
}
result.getCells().add(new CrosstabCell().withRowIndex(i).withColumnIndex(j).withCount(count).withRowShare(rowShare).withColumnShare(columnShare));
}
}
return (result.withSignificance(significance(hidden ? Statistics.unavailable("Chi-square independence", "privacy guard") : Statistics.chiSquare(counts, false))));
}
}
@@ -0,0 +1,240 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.engine;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import com.kingsrook.qbits.dataanalysis.result.Chart;
import com.kingsrook.qbits.dataanalysis.result.ChartKind;
import com.kingsrook.qbits.dataanalysis.result.Metric;
import com.kingsrook.qbits.dataanalysis.result.Series;
import com.kingsrook.qbits.dataanalysis.result.Significance;
import com.kingsrook.qbits.dataanalysis.result.ValueType;
import com.kingsrook.qbits.dataanalysis.stats.Statistics;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionEnforcement;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.Aggregate;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateResult;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.GroupBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
/*******************************************************************************
** Shared core execution and semantic output for request-local relationships.
*******************************************************************************/
public class RelationshipSupport extends StandInAnalysisBackend
{
protected final AnalysisSecurity security;
protected final String table;
/*******************************************************************************
** A bucket retains exact membership; privacy buckets intentionally lack drills.
*******************************************************************************/
protected record Category(Serializable value, String label, QQueryFilter condition, boolean privateGroup)
{
}
/*******************************************************************************
** Bind the caller's already-authorized table and current policy.
*******************************************************************************/
public RelationshipSupport(AnalysisSecurity security, EffectiveConfig config, String table)
{
super(config);
this.security = security;
this.table = table;
}
/*******************************************************************************
** Core owns pushdown and bounded fallback. Never label a partial test exact.
*******************************************************************************/
@Override
protected List<AggregateResult> aggregate(AggregateInput input) throws QException
{
input.withFilter(DrillFilters.restoreTypes(table, input.getFilter())).withAllowStreamedFallback(true).withStreamedRowLimit(config.getMaxRows());
input.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
var output = com.kingsrook.qbits.dataanalysis.saved.SqlHandoff.aggregate(input);
if(Boolean.TRUE.equals(output.getTruncated()))
{
throw new QBadRequestException("Analysis exceeds the streamed row limit; narrow the filter.");
}
return (output.getResults());
}
/*******************************************************************************
** All named fields, including PVS numerics, must pass the FULL resolver first.
*******************************************************************************/
protected QFieldMetaData full(String name) throws QException
{
return (security.field(table, name));
}
/*******************************************************************************
** PVS identifiers are categorical even when their storage type is numeric.
*******************************************************************************/
protected boolean numeric(QFieldMetaData field)
{
return (field.getPossibleValueSourceName() == null && List.of(QFieldType.INTEGER, QFieldType.LONG, QFieldType.DECIMAL).contains(field.getType()));
}
/*******************************************************************************
** Reject strings and categorical identifiers before computing relationships.
*******************************************************************************/
protected void requireNumeric(String name) throws QException
{
if(!numeric(full(name)))
{
throw new QBadRequestException("Choose numeric analysis fields.");
}
}
/*******************************************************************************
** Typed aggregate keys must match keys returned by all backend implementations.
*******************************************************************************/
protected Aggregate measure(String field, AggregateOperator operator)
{
Aggregate aggregate = new Aggregate(field, operator);
return (aggregate.withFieldType(com.kingsrook.qqq.backend.core.utils.aggregates.AggregateAnalysis.resultType(aggregate, field(table, field).getType())));
}
/*******************************************************************************
** Scalar summaries have one result; empty populations have null numeric values.
*******************************************************************************/
protected AggregateResult summarize(QQueryFilter filter, List<Aggregate> measures) throws QException
{
AggregateInput input = new AggregateInput(table).withFilter(DrillFilters.copy(filter));
measures.forEach(input::withAggregate);
List<AggregateResult> results = aggregate(input);
return (results.isEmpty() ? new AggregateResult() : results.getFirst());
}
/*******************************************************************************
** Exact row count uses the core count action with the caller's record locks.
*******************************************************************************/
protected long size(QQueryFilter filter) throws QException
{
return (count(table, filter));
}
/*******************************************************************************
** Count and scalar drills preserve the caller's original OR predicates.
*******************************************************************************/
protected Metric metric(String key, Serializable value, ValueType type, QQueryFilter filter, QQueryFilter condition)
{
return (ProfileSupport.metric(key.startsWith("category") ? type == ValueType.COUNT ? "count" : "share" : key, value, type).withKey(key).withDrill(DrillFilters.drill(table, filter, condition)));
}
/*******************************************************************************
** Apply the stricter cell guard to remove both values and membership drills.
*******************************************************************************/
protected void guard(List<Metric> metrics, long n)
{
new MinGroupSizeGuard(config.getMinGroupSize()).pivotMetrics(metrics, n);
}
/*******************************************************************************
** Group identities are typed; null and empty string remain distinct.
*******************************************************************************/
protected List<Category> categories(String field, QQueryFilter filter, int limit) throws QException
{
QFieldMetaData metadata = full(field);
GroupBy group = new GroupBy(metadata);
Aggregate count = measure(primaryKey(table), AggregateOperator.COUNT);
List<AggregateResult> groups = new ArrayList<>(aggregate(new AggregateInput(table).withFilter(DrillFilters.copy(filter)).withGroupBy(group).withAggregate(count)));
groups.sort(Comparator.<AggregateResult>comparingLong(r -> ((Number) r.getAggregateValues().get(count)).longValue()).reversed()
.thenComparing(r -> String.valueOf(r.getGroupByValues().get(group))));
List<Category> result = new ArrayList<>();
List<Category> other = new ArrayList<>();
boolean privacy = false;
for(AggregateResult row : groups)
{
Serializable value = row.getGroupByValues().get(group);
long n = ((Number) row.getAggregateValues().get(count)).longValue();
boolean hidden = n < config.getMinGroupSize();
Category category = new Category(value, hidden ? "Other" : value == null ? "(Blank)" : security.label(metadata, value),
DrillFilters.value(field, value, metadata.getType() == QFieldType.STRING), hidden);
if(hidden || result.size() >= limit)
{
other.add(category);
privacy |= hidden;
}
else
{
result.add(category);
}
}
if(!other.isEmpty())
{
result.add(merge(other, privacy));
}
return (result);
}
/*******************************************************************************
** An explicit union avoids null-sensitive NOT IN semantics for Other.
*******************************************************************************/
protected Category merge(List<Category> categories, boolean privacy)
{
QQueryFilter condition = new QQueryFilter().withBooleanOperator(QQueryFilter.BooleanOperator.OR);
categories.forEach(c -> condition.withSubFilter(c.condition()));
return (new Category(null, "Other", condition, privacy));
}
/*******************************************************************************
** Keep the math package free of QQQ and JSON dependencies.
*******************************************************************************/
protected Significance significance(Statistics.Result result)
{
return (new Significance().withTest(result.test()).withStatistic(result.statistic()).withDf(result.df()).withPValue(result.pValue())
.withApplicable(result.applicable()).withSentence(result.sentence()).withCramersV(result.cramersV()));
}
/*******************************************************************************
** Scalar conversion preserves null instead of leaking non-finite JSON numbers.
*******************************************************************************/
protected static BigDecimal decimal(Object value)
{
return (value == null ? null : new BigDecimal(value.toString()));
}
/*******************************************************************************
** Shared chart shape with a deliberate grouping/stacking annotation.
*******************************************************************************/
protected Chart chart(ChartKind kind, List<Series> series, String annotation)
{
return (new Chart().withKind(kind).withSeries(series).withAnnotations(List.of(annotation)));
}
/*******************************************************************************
** Correlation and regression exclude rows missing either numeric coordinate.
*******************************************************************************/
protected QQueryFilter paired(QQueryFilter filter, String x, String y)
{
return (DrillFilters.and(filter, DrillFilters.condition(x, QCriteriaOperator.IS_NOT_BLANK).withCriteria(y, QCriteriaOperator.IS_NOT_BLANK)));
}
}
@@ -0,0 +1,213 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.engine;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.dataanalysis.result.ChartKind;
import com.kingsrook.qbits.dataanalysis.result.Metric;
import com.kingsrook.qbits.dataanalysis.result.Point;
import com.kingsrook.qbits.dataanalysis.result.Series;
import com.kingsrook.qbits.dataanalysis.result.ShiftBucket;
import com.kingsrook.qbits.dataanalysis.result.ShiftRequest;
import com.kingsrook.qbits.dataanalysis.result.ShiftResult;
import com.kingsrook.qbits.dataanalysis.result.ValueType;
import com.kingsrook.qbits.dataanalysis.stats.Statistics;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.DateBucket;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.DateBucketUnit;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.GroupBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
/*******************************************************************************
** Distribution drift with stable categories or fixed baseline quartile bins.
*******************************************************************************/
public class ShiftExplorer extends ComparisonExplorer
{
/*******************************************************************************
** Bind the same core and privacy policy as compare.
*******************************************************************************/
public ShiftExplorer(AnalysisSecurity security, EffectiveConfig config, String table)
{
super(security, config, table);
}
/*******************************************************************************
** One calendar bucket with exact boundaries and whether its end has passed.
*******************************************************************************/
private record Bucket(Serializable start, QQueryFilter condition, boolean complete)
{
}
/*******************************************************************************
** First and last complete nonempty buckets define the descriptive PSI.
*******************************************************************************/
public ShiftResult shift(ShiftRequest request) throws QException
{
var field = full(request.getField());
var date = full(request.getDateField());
DateBucketUnit unit;
try
{
unit = DateBucketUnit.valueOf(request.getBucket());
}
catch(RuntimeException e)
{
throw new QBadRequestException("Choose a calendar bucket.");
}
if(!List.of(QFieldType.DATE, QFieldType.DATE_TIME).contains(date.getType()) || unit == DateBucketUnit.DAY_OF_WEEK
|| unit == DateBucketUnit.HOUR_OF_DAY || unit == DateBucketUnit.HOUR && date.getType() != QFieldType.DATE_TIME)
{
throw new QBadRequestException("Choose a date field and a calendar bucket from HOUR to YEAR.");
}
GroupBy group = new GroupBy(date).withBucket(new DateBucket(unit));
var aggregate = measure(primaryKey(table), AggregateOperator.COUNT);
var grouped = aggregate(new AggregateInput(table).withFilter(DrillFilters.copy(request.getFilter())).withGroupBy(group).withAggregate(aggregate));
List<Bucket> buckets = grouped.stream().map(r -> r.getGroupByValues().get(group)).filter(java.util.Objects::nonNull)
.sorted(Comparator.comparing(Object::toString)).map(start -> bucket(request.getDateField(), start, unit, date.getType())).toList();
if(buckets.size() > 2000)
{
throw new QBadRequestException("Choose a larger time bucket; at most 2000 buckets are supported.");
}
ShiftResult result = new ShiftResult();
List<Series> series = new ArrayList<>();
List<double[]> complete = new ArrayList<>();
boolean numeric = numeric(field);
List<Category> categories = numeric ? List.of() : categories(request.getField(), request.getFilter(), 8);
Map<String, BigDecimal> baseline = null;
boolean privateData = false;
if(numeric)
{
for(String name : List.of("p25", "median", "p75"))
{
series.add(new Series().withName(name));
}
}
else
{
for(Category category : categories)
{
series.add(new Series().withName(category.label()));
}
}
for(Bucket bucket : buckets)
{
QQueryFilter filter = DrillFilters.and(request.getFilter(), bucket.condition());
long n = size(filter);
ShiftBucket output = new ShiftBucket().withValue(bucket.start()).withLabel(bucket.start().toString()).withComplete(bucket.complete());
double[] counts;
if(numeric)
{
Map<String, BigDecimal> moments = moments(request.getField(), filter);
long nonNull = moments.get("count").longValue();
if(baseline == null && bucket.complete())
{
baseline = moments;
}
output.withMetrics(numericSide(request.getField(), output.getLabel(), filter, moments).getMetrics());
counts = baseline == null || baseline.get("count").signum() == 0 ? new double[0] : numericCounts(request.getField(), filter, baseline);
privateData |= nonNull < config.getMinGroupSize();
for(int i = 0; i < series.size(); i++)
{
String key = series.get(i).getName();
Metric metric = output.getMetrics().stream().filter(m -> m.getKey().equals(key)).findFirst().orElseThrow();
series.get(i).getPoints().add(new Point().withX(bucket.start()).withY(decimal(metric.getValue())).withDrill(metric.getDrill()));
}
}
else
{
counts = new double[categories.size()];
for(int i = 0; i < categories.size(); i++)
{
Category category = categories.get(i);
long count = size(DrillFilters.and(filter, category.condition()));
counts[i] = count;
Metric countMetric = metric("category" + i + "Count", count, ValueType.COUNT, filter, category.condition()).withLabel(category.label());
Metric share = metric("category" + i + "Share", ProfileSupport.share(count, n), ValueType.PERCENT, filter, category.condition()).withLabel(category.label());
List<Metric> metrics = List.of(countMetric, share);
guard(metrics, count);
if(category.privateGroup())
{
metrics.forEach(m -> m.withDrill(null));
}
privateData |= category.privateGroup() || count < config.getMinGroupSize();
output.getMetrics().addAll(metrics);
series.get(i).getPoints().add(new Point().withX(bucket.start()).withY(decimal(share.getValue())).withLabel(category.label()).withDrill(share.getDrill()));
}
}
result.getBuckets().add(output);
if(bucket.complete())
{
complete.add(counts);
}
}
Double psi = !privateData && complete.size() >= 2 && java.util.Arrays.stream(complete.getFirst()).sum() >= 2
&& java.util.Arrays.stream(complete.getLast()).sum() >= 2 ? Statistics.psi(complete.getFirst(), complete.getLast()) : null;
result.withPsi(ProfileSupport.metric("psi", psi, ValueType.DECIMAL));
result.withSentence(psi == null ? "Not applicable: " + (privateData ? "privacy guard" : "two complete buckets with at least two values are required")
: "The first and last complete buckets have a population stability index of " + BigDecimal.valueOf(psi).setScale(3, java.math.RoundingMode.HALF_UP) + ".");
return (result.withChart(chart(ChartKind.TIME_SERIES, series, numeric ? "Numeric quartiles; PSI uses fixed first-complete-bucket quartile boundaries."
: "Stacked category shares. PSI floors zero shares at 0.000001; it is not a significance test.").withStacked(!numeric)));
}
/*******************************************************************************
** Calendar boundaries use the session zone, including daylight-saving days.
*******************************************************************************/
private Bucket bucket(String field, Serializable value, DateBucketUnit unit, QFieldType type)
{
ZoneId zone = ValueUtils.getSessionOrInstanceZoneId();
if(unit == DateBucketUnit.HOUR)
{
Instant start = ValueUtils.getValueAsInstant(value);
Instant end = start.plusSeconds(3600);
return (new Bucket(start, DrillFilters.range(field, start, end, false), !end.isAfter(Instant.now())));
}
LocalDate start = ValueUtils.getValueAsLocalDate(value);
LocalDate end = next(start, DateUnit.valueOf(unit.name()));
return (new Bucket(start, DrillFilters.dateRange(field, start, end, type == QFieldType.DATE_TIME, zone), !end.atStartOfDay(zone).toInstant().isAfter(Instant.now())));
}
/*******************************************************************************
** Both populations use identical, half-open quartile ranges with infinite tails.
*******************************************************************************/
private double[] numericCounts(String field, QQueryFilter filter, Map<String, BigDecimal> baseline) throws QException
{
BigDecimal[] edges = {null, baseline.get("p25"), baseline.get("p50"), baseline.get("p75"), null};
double[] counts = new double[4];
for(int i = 0; i < 4; i++)
{
counts[i] = size(DrillFilters.and(filter, DrillFilters.range(field, edges[i], edges[i + 1], false)));
}
return (counts);
}
}
@@ -38,7 +38,6 @@ import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionEnforcement;
import com.kingsrook.qqq.backend.core.actions.tables.AggregateAction;
import com.kingsrook.qqq.backend.core.actions.tables.CountAction;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.context.QContext;
@@ -171,7 +170,7 @@ public class StandInAnalysisBackend implements AnalysisBackend
restored.setOrderBys(input.getFilter().getOrderBys());
input.setFilter(restored);
input.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
return (new AggregateAction().execute(input).getResults());
return (com.kingsrook.qbits.dataanalysis.saved.SqlHandoff.aggregate(input).getResults());
}
@@ -59,6 +59,7 @@ public class DataAnalysisMetaDataProducer extends QBitComponentMetaDataProducer<
DataAnalysisTables.joins().forEach(output::add);
DataAnalysisTables.childListWidgets().forEach(output::add);
output.add(DataAnalysisTables.userKeyType());
output.add(com.kingsrook.qbits.dataanalysis.processes.TableConfigDefaultsProcess.process());
List<QTableMetaData> tables = DataAnalysisTables.tables(getQBitConfig());
for(QTableMetaData table : tables)
{
@@ -66,7 +67,8 @@ public class DataAnalysisMetaDataProducer extends QBitComponentMetaDataProducer<
.filter(qbit -> DataAnalysisQBitProducer.ARTIFACT_ID.equals(qbit.getArtifactId())).findFirst().orElseThrow().getName());
output.add(table);
}
output.add(DataAnalysisHome.widget());
DataAnalysisHome.widgets().forEach(output::add);
output.add(com.kingsrook.qbits.dataanalysis.app.SavedAnalysisWidget.widget());
output.add(DataAnalysisHome.app(getQBitConfig(), tables));
return (output);
}
@@ -0,0 +1,93 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.metadata;
import java.util.List;
import com.kingsrook.qbits.dataanalysis.DataAnalysisQBitConfig;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qbits.dataanalysis.processes.ScheduleActions;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
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.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
import com.kingsrook.qqq.backend.core.model.metadata.scheduleing.QScheduleMetaData;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ExtractViaQueryStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcess;
/*******************************************************************************
** Watch record actions and one hidden scheduled process, never app children.
*******************************************************************************/
public class ScheduleProcesses extends QBitComponentMetaDataProducer<MetaDataProducerMultiOutput, DataAnalysisQBitConfig>
{
/*******************************************************************************
** Build after the watch table has been registered.
*******************************************************************************/
@Override
public int getSortOrder()
{
return (200);
}
/*******************************************************************************
** Component scanning also encounters unconfigured producers.
*******************************************************************************/
@Override
public boolean isEnabled()
{
return (getQBitConfig() != null);
}
/*******************************************************************************
** Ordinary core actions provide selected records, Review, and Result screens.
*******************************************************************************/
@Override
public MetaDataProducerMultiOutput produce(QInstance instance)
{
MetaDataProducerMultiOutput output = new MetaDataProducerMultiOutput();
for(String name : List.of(ScheduleActions.SEND))
{
String label = "Send now";
QProcessMetaData process = StreamedETLWithFrontendProcess.processMetaDataBuilder()
.withName(name).withLabel(label).withIcon(new QIcon("notifications_active"))
.withTableName(DataAnalysisTables.SCHEDULE).withSourceTable(DataAnalysisTables.SCHEDULE).withDestinationTable(DataAnalysisTables.SCHEDULE)
.withExtractStepClass(ExtractViaQueryStep.class).withTransformStepClass(ScheduleActions.Review.class).withLoadStepClass(ScheduleActions.Result.class)
.withSupportsFullValidation(true).withDoFullValidation(true).withMinInputRecords(1)
.withPreviewMessage("Review the selected schedules.").getProcessMetaData();
// Table READ/EDIT and owner locks are enforced by extraction and both steps.
process.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.NOT_PROTECTED));
output.add(process);
}
QProcessMetaData scheduled = new QProcessMetaData().withName(ScheduleActions.SCHEDULED).withLabel("Run analysis schedules").withIsHidden(true)
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.HAS_ACCESS_PERMISSION).withPermissionBaseName(ScheduleActions.SCHEDULED))
.withStep(new QBackendStepMetaData().withName("run").withCode(new QCodeReference(ScheduleActions.Scheduled.class)));
if(getQBitConfig().getSchedulerName() != null)
{
scheduled.withSchedule(new QScheduleMetaData().withSchedulerName(getQBitConfig().getSchedulerName()).withRepeatSeconds(300).withInitialDelaySeconds(300));
}
output.add(scheduled);
return (output);
}
}
@@ -0,0 +1,93 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.metadata;
import java.util.List;
import com.kingsrook.qbits.dataanalysis.DataAnalysisQBitConfig;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qbits.dataanalysis.processes.WatchActions;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
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.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitComponentMetaDataProducer;
import com.kingsrook.qqq.backend.core.model.metadata.scheduleing.QScheduleMetaData;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ExtractViaQueryStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcess;
/*******************************************************************************
** Watch record actions and one hidden scheduled process, never app children.
*******************************************************************************/
public class WatchProcesses extends QBitComponentMetaDataProducer<MetaDataProducerMultiOutput, DataAnalysisQBitConfig>
{
/*******************************************************************************
** Build after the watch table has been registered.
*******************************************************************************/
@Override
public int getSortOrder()
{
return (200);
}
/*******************************************************************************
** Component scanning also encounters unconfigured producers.
*******************************************************************************/
@Override
public boolean isEnabled()
{
return (getQBitConfig() != null);
}
/*******************************************************************************
** Ordinary core actions provide selected records, Review, and Result screens.
*******************************************************************************/
@Override
public MetaDataProducerMultiOutput produce(QInstance instance)
{
MetaDataProducerMultiOutput output = new MetaDataProducerMultiOutput();
for(String name : List.of(WatchActions.EVALUATE, WatchActions.ENABLE, WatchActions.DISABLE))
{
String label = WatchActions.EVALUATE.equals(name) ? "Evaluate now" : WatchActions.ENABLE.equals(name) ? "Enable" : "Disable";
QProcessMetaData process = StreamedETLWithFrontendProcess.processMetaDataBuilder()
.withName(name).withLabel(label).withIcon(new QIcon("notifications_active"))
.withTableName(DataAnalysisTables.WATCH).withSourceTable(DataAnalysisTables.WATCH).withDestinationTable(DataAnalysisTables.WATCH)
.withExtractStepClass(ExtractViaQueryStep.class).withTransformStepClass(WatchActions.Review.class).withLoadStepClass(WatchActions.Result.class)
.withSupportsFullValidation(true).withDoFullValidation(true).withMinInputRecords(1)
.withPreviewMessage("Review the selected watches.").getProcessMetaData();
// Table READ/EDIT and owner locks are enforced by extraction and both steps.
process.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.NOT_PROTECTED));
output.add(process);
}
QProcessMetaData scheduled = new QProcessMetaData().withName(WatchActions.SCHEDULED).withLabel("Evaluate watches").withIsHidden(true)
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.HAS_ACCESS_PERMISSION).withPermissionBaseName(WatchActions.SCHEDULED))
.withStep(new QBackendStepMetaData().withName("run").withCode(new QCodeReference(WatchActions.Scheduled.class)));
if(getQBitConfig().getSchedulerName() != null)
{
scheduled.withSchedule(new QScheduleMetaData().withSchedulerName(getQBitConfig().getSchedulerName()).withRepeatSeconds(900).withInitialDelaySeconds(900));
}
output.add(scheduled);
return (output);
}
}
@@ -0,0 +1,112 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.kingsrook.qqq.backend.core.actions.values.QCustomPossibleValueProvider;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.model.actions.values.SearchPossibleValueSourceInput;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValue;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
/*******************************************************************************
** Fields of the table selected in the settings form. Core has no multi-select
** PVS field yet; settings retain their comma-separated TEXT representation.
*******************************************************************************/
public class DataAnalysisFieldPossibleValueProvider implements QCustomPossibleValueProvider<String>
{
public static final String NAME = "data_analysis_fields";
/*******************************************************************************
** Without form values the table is unknown; preserve names, including CSV lists.
*******************************************************************************/
@Override
public QPossibleValue<String> getPossibleValue(Serializable idValue)
{
String name = ValueUtils.getValueAsString(idValue);
return (name == null ? null : new QPossibleValue<>(name, name));
}
/*******************************************************************************
** Offer only fields of the selected table, honoring search text and id lookups.
*******************************************************************************/
@Override
public List<QPossibleValue<String>> search(SearchPossibleValueSourceInput input)
{
List<QPossibleValue<String>> values = new ArrayList<>();
QTableMetaData table = resolveTable(input.getOtherValues());
if(table == null)
{
return (values);
}
for(QFieldMetaData field : table.getFields().values())
{
String label = field.getLabel() == null ? field.getName() : field.getLabel();
QPossibleValue<String> value = new QPossibleValue<>(field.getName(), label + " (" + field.getName() + ")");
if(CollectionUtils.nullSafeHasContents(input.getIdList()))
{
if(input.getIdList().stream().anyMatch(id -> value.getId().equals(ValueUtils.getValueAsString(id))))
{
values.add(value);
}
}
else
{
String term = input.getSearchTerm();
if(!StringUtils.hasContent(term) || value.getLabel().toLowerCase(Locale.ROOT).contains(term.toLowerCase(Locale.ROOT)))
{
values.add(value);
}
}
}
return (values);
}
/*******************************************************************************
** Resolve the table from the frontend form values, never from the config table.
*******************************************************************************/
private QTableMetaData resolveTable(Map<String, Serializable> otherValues)
{
if(otherValues == null || QContext.getQInstance() == null)
{
return (null);
}
String tableName = ValueUtils.getValueAsString(otherValues.get("table_name"));
return (StringUtils.hasContent(tableName) ? QContext.getQInstance().getTable(tableName) : null);
}
}
@@ -29,8 +29,12 @@ import com.kingsrook.qbits.dataanalysis.DataAnalysisQBitConfig;
import com.kingsrook.qbits.dataanalysis.permissions.DataAnalysisPermissions;
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.ChildRecordListRenderer;
import com.kingsrook.qqq.backend.core.instances.QInstanceEnricher;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.metadata.audits.AuditLevel;
import com.kingsrook.qqq.backend.core.model.metadata.audits.QAuditRules;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
@@ -49,6 +53,7 @@ import com.kingsrook.qqq.backend.core.model.metadata.tables.ExposedJoin;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QFieldSection;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.SectionFactory;
import com.kingsrook.qqq.backend.core.model.metadata.tables.TablesPossibleValueSourceMetaDataProvider;
import com.kingsrook.qqq.backend.core.model.metadata.tables.Tier;
import com.kingsrook.qqq.backend.core.model.metadata.tables.UniqueKey;
@@ -111,10 +116,15 @@ public final class DataAnalysisTables
public static List<QPossibleValueSource> possibleValueSources()
{
List<QPossibleValueSource> sources = new ArrayList<>();
sources.add(new QPossibleValueSource().withName(DataAnalysisFieldPossibleValueProvider.NAME)
.withType(QPossibleValueSourceType.CUSTOM).withIdType(QFieldType.STRING)
.withCustomCodeReference(new QCodeReference(DataAnalysisFieldPossibleValueProvider.class)));
sources.add(enumSource("kind", "COLUMN_PROFILE", "TABLE_PROFILE", "PIVOT", "COMPARE", "CORRELATION", "CROSSTAB", "SHIFT"));
sources.add(enumSource("chart_kind", "HISTOGRAM", "BOX", "BAR", "PARETO", "TIME_SERIES", "SCATTER", "HEATMAP"));
sources.add(enumSource("detector", "SPIKE", "DROP", "OUT_OF_RANGE", "NEW_CATEGORY", "NULL_RATE_CREEP"));
sources.add(enumSource("watch_state", "OK", "FIRING"));
sources.add(enumSource("watch_bucket", "HOUR", "DAY", "WEEK", "MONTH"));
sources.add(enumSource("watch_severity", "INFO", "WARNING", "ERROR", "CRITICAL"));
sources.add(enumSource("run_status", "RUNNING", "COMPLETE", "FAILED"));
sources.add(enumSource("schedule_frequency", "DAILY", "WEEKLY", "MONTHLY"));
sources.add(enumSource("schedule_format", "HTML_SUMMARY", "CSV", "XLSX"));
@@ -205,14 +215,16 @@ public final class DataAnalysisTables
List<QTableMetaData> tables = new ArrayList<>();
tables.add(base(config, TABLE_CONFIG, "Analysis Settings", "settings", "data_analysis.settings")
.withRecordLabelFormatAndFields("%s", "table_name")
.withField(field("table_name", QFieldType.STRING).withIsRequired(true))
.withField(field("table_name", QFieldType.STRING).withPossibleValueSourceName(TablesPossibleValueSourceMetaDataProvider.NAME).withIsRequired(true))
.withField(field("enabled", QFieldType.BOOLEAN).withDefaultValue(true))
.withField(field("max_rows", QFieldType.INTEGER))
.withField(field("sample_threshold_rows", QFieldType.INTEGER))
.withField(field("sample_rows", QFieldType.INTEGER))
.withField(field("min_group_size", QFieldType.INTEGER))
.withField(field("analyzable_fields", QFieldType.TEXT))
.withField(field("excluded_fields", QFieldType.TEXT))
// add possibleValueSourceDependsOn("table_name") once core has it
.withField(field("analyzable_fields", QFieldType.TEXT).withPossibleValueSourceName(DataAnalysisFieldPossibleValueProvider.NAME))
// add possibleValueSourceDependsOn("table_name") once core has it
.withField(field("excluded_fields", QFieldType.TEXT).withPossibleValueSourceName(DataAnalysisFieldPossibleValueProvider.NAME))
.withField(field("cache_ttl_minutes", QFieldType.INTEGER))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withUniqueKey(new UniqueKey("table_name")));
@@ -220,19 +232,26 @@ public final class DataAnalysisTables
.withRecordLabelFormatAndFields("%s", "name")
.withField(field("name", QFieldType.STRING).withIsRequired(true))
.withField(field("description", QFieldType.TEXT))
.withField(field("table_name", QFieldType.STRING).withIsRequired(true))
.withField(field("table_name", QFieldType.STRING).withPossibleValueSourceName(TablesPossibleValueSourceMetaDataProvider.NAME).withIsRequired(true))
.withField(field("filter_json", QFieldType.TEXT))
.withField(field("kind", QFieldType.STRING).withPossibleValueSourceName("data_analysis_kind").withIsRequired(true))
.withField(field("definition_json", QFieldType.TEXT).withIsRequired(true))
.withField(field("chart_kind", QFieldType.STRING).withPossibleValueSourceName("data_analysis_chart_kind"))
.withField(field("owner_user_id", QFieldType.STRING).withIsRequired(true))
.withField(field("owner_user_id", QFieldType.STRING).withIsRequired(true).withBehavior(InsertingUserBehavior.INSERTING_USER))
.withField(field("shared", QFieldType.BOOLEAN).withDefaultValue(false))
.withField(field("read_owner_user_id", QFieldType.STRING).withIsEditable(false).withIsHidden(true))
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.FIELD))
.withRecordSecurityLock(ownerLock("owner_user_id")));
.withRecordSecurityLock(ownerLock("owner_user_id").withLockScope(RecordSecurityLock.LockScope.WRITE))
.withRecordSecurityLock(ownerLock("read_owner_user_id").withLockScope(RecordSecurityLock.LockScope.READ)
.withNullValueBehavior(RecordSecurityLock.NullValueBehavior.ALLOW))
.withCustomizer(com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers.PRE_INSERT_RECORD,
new QCodeReference(com.kingsrook.qbits.dataanalysis.saved.SavedCustomizer.class))
.withCustomizer(com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers.PRE_UPDATE_RECORD,
new QCodeReference(com.kingsrook.qbits.dataanalysis.saved.SavedCustomizer.class)));
tables.add(base(config, SAVED_STAR, "Stars", "star", "data_analysis.saved")
.withRecordLabelFormatAndFields("%s", "user_id")
.withField(field("saved_id", QFieldType.INTEGER).withPossibleValueSourceName("data_analysis_saved").withIsRequired(true))
.withField(field("user_id", QFieldType.STRING).withIsRequired(true))
.withField(field("user_id", QFieldType.STRING).withIsRequired(true).withBehavior(InsertingUserBehavior.INSERTING_USER))
.withUniqueKey(new UniqueKey("saved_id", "user_id"))
.withRecordSecurityLock(ownerLock("user_id")));
tables.add(base(config, SCHEDULE, "Schedules", "schedule", "data_analysis.saved")
@@ -247,26 +266,40 @@ public final class DataAnalysisTables
.withField(field("recipients", QFieldType.TEXT))
.withField(field("enabled", QFieldType.BOOLEAN).withDefaultValue(false))
.withField(field("last_run_at", QFieldType.DATE_TIME))
.withField(field("last_status", QFieldType.STRING).withPossibleValueSourceName("data_analysis_run_status"))
.withField(field("last_status", QFieldType.TEXT).withIsEditable(false))
.withField(field("next_run_at", QFieldType.DATE_TIME))
.withRecordSecurityLock(ownerLock(SAVED + ".owner_user_id").withJoinNameChain(List.of(joinName(SCHEDULE)))));
.withRecordSecurityLock(ownerLock(SAVED + ".owner_user_id").withJoinNameChain(List.of(joinName(SCHEDULE))))
.withCustomizer(com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers.PRE_INSERT_RECORD,
new QCodeReference(com.kingsrook.qbits.dataanalysis.schedule.ScheduleCustomizer.class))
.withCustomizer(com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers.PRE_UPDATE_RECORD,
new QCodeReference(com.kingsrook.qbits.dataanalysis.schedule.ScheduleCustomizer.class)));
tables.add(base(config, WATCH, "Watches", "notifications_active", "data_analysis.watch")
.withRecordLabelFormatAndFields("%s", "detector")
.withField(field("saved_id", QFieldType.INTEGER).withPossibleValueSourceName("data_analysis_saved"))
.withField(field("table_name", QFieldType.STRING))
.withField(field("saved_id", QFieldType.INTEGER).withPossibleValueSourceName("data_analysis_saved")
.withPossibleValueSourceFilter(new QQueryFilter(new QFilterCriteria("table_name", QCriteriaOperator.EQUALS, "${input.table_name}"))))
.withField(field("table_name", QFieldType.STRING).withPossibleValueSourceName(TablesPossibleValueSourceMetaDataProvider.NAME))
.withField(field("filter_json", QFieldType.TEXT))
.withField(field("metric_json", QFieldType.TEXT))
.withField(field("detector", QFieldType.STRING).withPossibleValueSourceName("data_analysis_detector").withIsRequired(true))
.withField(field("parameters_json", QFieldType.TEXT))
.withField(field("bucket", QFieldType.STRING))
.withField(field("severity", QFieldType.STRING))
.withField(field("date_field", QFieldType.STRING).withIsRequired(true))
.withField(field("bucket", QFieldType.STRING).withDefaultValue("DAY").withIsRequired(true).withPossibleValueSourceName("data_analysis_watch_bucket"))
.withField(field("severity", QFieldType.STRING).withDefaultValue("WARNING").withIsRequired(true).withPossibleValueSourceName("data_analysis_watch_severity"))
.withField(field("owner_user_id", QFieldType.STRING).withIsRequired(true).withBehavior(InsertingUserBehavior.INSERTING_USER))
.withField(field("enabled", QFieldType.BOOLEAN).withDefaultValue(false))
.withField(field("last_evaluated_at", QFieldType.DATE_TIME))
.withField(field("state", QFieldType.STRING).withDefaultValue("OK").withPossibleValueSourceName("data_analysis_watch_state"))
.withField(field("alert_key", QFieldType.STRING)));
.withField(field("last_evaluated_at", QFieldType.DATE_TIME).withIsEditable(false))
.withField(field("last_value", QFieldType.DECIMAL).withIsEditable(false))
.withField(field("last_message", QFieldType.TEXT).withIsEditable(false))
.withField(field("state", QFieldType.STRING).withDefaultValue("OK").withIsEditable(false).withPossibleValueSourceName("data_analysis_watch_state"))
.withField(field("alert_key", QFieldType.STRING).withIsEditable(false))
.withRecordSecurityLock(ownerLock("owner_user_id"))
.withCustomizer(com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers.PRE_INSERT_RECORD,
new com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference(com.kingsrook.qbits.dataanalysis.watch.WatchCustomizer.class))
.withCustomizer(com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers.PRE_UPDATE_RECORD,
new com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference(com.kingsrook.qbits.dataanalysis.watch.WatchCustomizer.class)));
tables.add(base(config, RUN, "Analysis Runs", "history", "data_analysis.run")
.withRecordLabelFormatAndFields("%s", "operation")
.withField(field("table_name", QFieldType.STRING).withIsRequired(true))
.withField(field("table_name", QFieldType.STRING).withPossibleValueSourceName(TablesPossibleValueSourceMetaDataProvider.NAME).withIsRequired(true))
.withField(field("operation", QFieldType.STRING).withIsRequired(true))
.withField(field("request_hash", QFieldType.STRING))
.withField(field("filter_hash", QFieldType.STRING))
@@ -278,12 +311,12 @@ public final class DataAnalysisTables
.withField(field("sampled", QFieldType.BOOLEAN).withDefaultValue(false))
.withField(field("result_json", QFieldType.TEXT))
.withField(field("error", QFieldType.TEXT))
.withField(field("user_id", QFieldType.STRING).withIsRequired(true))
.withField(field("user_id", QFieldType.STRING).withIsRequired(true).withBehavior(InsertingUserBehavior.INSERTING_USER))
.withRecordSecurityLock(ownerLock("user_id")));
for(QTableMetaData table : tables)
{
List<String> fields = new ArrayList<>(table.getFields().keySet());
fields.removeAll(List.of("id", "createDate", "modifyDate"));
fields.removeAll(List.of("id", "createDate", "modifyDate", "read_owner_user_id"));
int headlineSize = Math.min(4, fields.size());
table.withSection(SectionFactory.defaultT1(fields.subList(0, headlineSize).toArray(String[]::new)));
if(fields.size() > headlineSize)
@@ -0,0 +1,84 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.model;
import java.util.List;
import com.kingsrook.qqq.backend.core.actions.values.ValueBehaviorApplier;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.fields.FieldBehavior;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
/*******************************************************************************
** On INSERT only, an owner/user field left empty gets the inserting user's id,
** so a UI (which does not know the user's id) can create a saved analysis,
** star or watch. Unlike core DynamicDefaultValueBehavior.USER_ID it never
** applies on UPDATE, so an administrator's partial edit cannot take ownership.
** Naming another owner is still refused by the table customizers and locks.
*******************************************************************************/
public enum InsertingUserBehavior implements FieldBehavior<InsertingUserBehavior>
{
INSERTING_USER,
NONE;
/*******************************************************************************
** No behavior unless asked for.
*******************************************************************************/
@Override
public InsertingUserBehavior getDefault()
{
return (NONE);
}
/*******************************************************************************
** Fill empty values with the session user's id on insert.
*******************************************************************************/
@Override
public void apply(ValueBehaviorApplier.Action action, List<QRecord> recordList, QInstance instance, QTableMetaData table, QFieldMetaData field)
{
if(this == NONE || action != ValueBehaviorApplier.Action.INSERT)
{
return;
}
String userId = QContext.getQSession() == null || QContext.getQSession().getUser() == null ? null : QContext.getQSession().getUser().getIdReference();
if(!StringUtils.hasContent(userId))
{
return;
}
for(QRecord record : CollectionUtils.nonNullList(recordList))
{
if(!StringUtils.hasContent(record.getValueString(field.getName())))
{
record.setValue(field.getName(), userId);
}
}
}
}
@@ -0,0 +1,144 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.processes;
import java.time.Instant;
import java.util.ArrayList;
import com.kingsrook.qbits.dataanalysis.DataAnalysisRuntime;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLine;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLineInterface;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.actions.processes.Status;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractLoadStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractTransformStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ProcessSummaryProviderInterface;
/*******************************************************************************
** Standard streamed ETL Review and Result actions for scheduled analyses.
*******************************************************************************/
public final class ScheduleActions
{
public static final String SEND = "data_analysis_schedule_send";
public static final String SCHEDULED = "data_analysis_run_schedules";
/*******************************************************************************
** Steps only.
*******************************************************************************/
private ScheduleActions()
{
}
/*******************************************************************************
** Review has no delivery side effects.
*******************************************************************************/
public static class Review extends AbstractTransformStep implements ProcessSummaryProviderInterface
{
private final ArrayList<ProcessSummaryLineInterface> lines = new ArrayList<>();
/*******************************************************************************
** Core extraction enforces record locks; verify the edit grant as well.
*******************************************************************************/
@Override
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
if(!PermissionsHelper.hasTablePermission(new UpdateInput(DataAnalysisTables.SCHEDULE), DataAnalysisTables.SCHEDULE, TablePermissionSubType.EDIT))
{
throw new QPermissionDeniedException("Schedule editing is unavailable.");
}
for(QRecord record : input.getRecords())
{
lines.add(new ProcessSummaryLine(Status.INFO, null, "Schedule " + record.getValueString("id") + " will be sent to authorized recipients."));
output.addRecord(record);
}
}
/*******************************************************************************
** Standard Review summary.
*******************************************************************************/
@Override
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean result)
{
return (result ? new ArrayList<>() : lines);
}
}
/*******************************************************************************
** Every selected record contributes its actual delivery status to Result.
*******************************************************************************/
public static class Result extends AbstractLoadStep implements ProcessSummaryProviderInterface
{
private final ArrayList<ProcessSummaryLineInterface> lines = new ArrayList<>();
/*******************************************************************************
** Reauthorize when executing after Review.
*******************************************************************************/
@Override
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
for(QRecord record : input.getRecords())
{
try
{
String status = DataAnalysisRuntime.schedules().sendNow(record.getValue("id"), Instant.now());
lines.add(new ProcessSummaryLine(status.startsWith("Failed") ? Status.ERROR : Status.OK, null, status));
output.addRecord(record);
}
catch(QException e)
{
lines.add(new ProcessSummaryLine(Status.ERROR, null, e.getMessage()));
}
}
}
/*******************************************************************************
** Actual results across streamed pages.
*******************************************************************************/
@Override
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean result)
{
return (lines);
}
}
/*******************************************************************************
** Hidden scheduler every five minutes.
*******************************************************************************/
public static class Scheduled implements BackendStep
{
/*******************************************************************************
** Count actual due schedule attempts.
*******************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
output.addValue("count", DataAnalysisRuntime.schedules().runDue(Instant.now()));
}
}
}
@@ -0,0 +1,301 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.processes;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.kingsrook.qbits.dataanalysis.DataAnalysisQBitConfig;
import com.kingsrook.qbits.dataanalysis.DataAnalysisRuntime;
import com.kingsrook.qbits.dataanalysis.engine.EffectiveConfig;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionEnforcement;
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
import com.kingsrook.qqq.backend.core.actions.permissions.UseTablePermissionCustomPermissionChecker;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLine;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLineInterface;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.actions.processes.Status;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
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.processes.implementations.etl.streamedwithfrontend.AbstractExtractStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractLoadStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractTransformStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ProcessSummaryProviderInterface;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcess;
/*******************************************************************************
** "Create rows for analyzable tables": a table action on Analysis Settings
** that writes one row per analyzable table that has none yet, holding the
** settings that already apply to it (code defaults for that table, then the
** global defaults). It changes no behavior on its own: it makes the defaults
** visible and editable. Existing rows are never touched. Standard streamed
** ETL: Review lists what will be added, Result what was added.
*******************************************************************************/
public final class TableConfigDefaultsProcess
{
public static final String NAME = "data_analysis_table_config_create_rows";
/*******************************************************************************
** Utility class.
*******************************************************************************/
private TableConfigDefaultsProcess()
{
}
/*******************************************************************************
** The process: a table-level action (no records need to be selected). Only
** people who may insert Analysis Settings see it; the steps enforce the table
** permissions again.
*******************************************************************************/
public static QProcessMetaData process()
{
Map<String, Serializable> values = new HashMap<>();
values.put(StreamedETLWithFrontendProcess.FIELD_SOURCE_TABLE, DataAnalysisTables.TABLE_CONFIG);
values.put(StreamedETLWithFrontendProcess.FIELD_DESTINATION_TABLE, DataAnalysisTables.TABLE_CONFIG);
values.put(StreamedETLWithFrontendProcess.FIELD_SUPPORTS_FULL_VALIDATION, false);
values.put(StreamedETLWithFrontendProcess.FIELD_PREVIEW_MESSAGE,
"These rows will be added: one per analyzable table that has none, holding the settings that already apply. Existing rows are not changed.");
QProcessMetaData process = StreamedETLWithFrontendProcess.defineProcessMetaData(Extract.class, Transform.class, Load.class, values);
process.setName(NAME);
process.setLabel("Create rows for analyzable tables");
process.setIcon(new QIcon("playlist_add"));
process.setTableName(DataAnalysisTables.TABLE_CONFIG);
process.setMinInputRecords(0);
process.setPermissionRules(new QPermissionRules().withLevel(PermissionLevel.NOT_PROTECTED)
.withCustomPermissionChecker(UseTablePermissionCustomPermissionChecker.build(DataAnalysisTables.TABLE_CONFIG, TablePermissionSubType.INSERT)));
return (process);
}
/*******************************************************************************
** The tables analysis may be used on: everything but the qbit's own tables,
** limited by the includeTables and excludeTables configuration. The same test
** the "analyze" table permission uses.
*******************************************************************************/
public static List<String> analyzableTables(QInstance instance, DataAnalysisQBitConfig config)
{
return (instance.getTables().values().stream().map(QTableMetaData::getName)
.filter(name -> !name.startsWith(DataAnalysisQBitConfig.TABLE_NAME_PREFIX))
.filter(name -> config.getIncludeTables().isEmpty() || config.getIncludeTables().contains(name))
.filter(name -> !config.getExcludeTables().contains(name)).sorted().toList());
}
/*******************************************************************************
** The rows that are missing: one per analyzable table without a row, with
** the effective settings (the same values EffectiveConfigResolver produces).
*******************************************************************************/
public static List<QRecord> missingRows(QInstance instance, DataAnalysisQBitConfig config) throws QException
{
Set<String> existing = existingTables();
DataAnalysisRuntime.service().getConfigResolver().invalidate();
List<QRecord> rows = new ArrayList<>();
for(String table : analyzableTables(instance, config))
{
if(!existing.contains(table))
{
EffectiveConfig c = DataAnalysisRuntime.service().getConfigResolver().resolve(table);
rows.add(new QRecord().withValue("table_name", table).withValue("enabled", c.getEnabled()).withValue("max_rows", c.getMaxRows())
.withValue("sample_threshold_rows", c.getSampleThresholdRows()).withValue("sample_rows", c.getSampleRows())
.withValue("min_group_size", c.getMinGroupSize()).withValue("cache_ttl_minutes", c.getCacheTtlMinutes())
.withValue("analyzable_fields", c.getAnalyzableFields().isEmpty() ? null : String.join(",", new TreeSet<>(c.getAnalyzableFields())))
.withValue("excluded_fields", c.getExcludedFields().isEmpty() ? null : String.join(",", new TreeSet<>(c.getExcludedFields()))));
}
}
return (rows);
}
/*******************************************************************************
** Table names that already have a settings row (read as the signed-in user).
*******************************************************************************/
private static Set<String> existingTables() throws QException
{
QueryInput input = new QueryInput(DataAnalysisTables.TABLE_CONFIG).withFilter(new QQueryFilter());
input.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
Set<String> existing = new HashSet<>();
new QueryAction().execute(input).getRecords().forEach(row -> existing.add(row.getValueString("table_name")));
return (existing);
}
/*******************************************************************************
** Extract: the missing rows, computed (no query of the selected records).
*******************************************************************************/
public static class Extract extends AbstractExtractStep
{
/*******************************************************************************
**
*******************************************************************************/
@Override
public Integer doCount(RunBackendStepInput input) throws QException
{
return (missingRows(QContext.getQInstance(), DataAnalysisRuntime.service().getConfigResolver().getDefaults()).size());
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
for(QRecord row : missingRows(QContext.getQInstance(), DataAnalysisRuntime.service().getConfigResolver().getDefaults()))
{
getRecordPipe().addRecord(row);
}
}
}
/*******************************************************************************
** Transform: lists what will be added for the review screen.
*******************************************************************************/
public static class Transform extends AbstractTransformStep implements ProcessSummaryProviderInterface
{
private final ProcessSummaryLine added = line(Status.OK, "table will get a settings row", "tables will get a settings row",
"table got a settings row", "tables got a settings row");
/*******************************************************************************
**
*******************************************************************************/
@Override
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
for(QRecord record : input.getRecords())
{
added.incrementCount();
output.getRecords().add(record);
}
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean isForResultScreen)
{
ArrayList<ProcessSummaryLineInterface> lines = new ArrayList<>();
added.addSelfToListIfAnyCount(lines);
if(lines.isEmpty())
{
lines.add(new ProcessSummaryLine(Status.INFO, null, "Every analyzable table already has a settings row."));
}
return (lines);
}
}
/*******************************************************************************
** Load: insert through the standard action with the user's own permissions.
*******************************************************************************/
public static class Load extends AbstractLoadStep implements ProcessSummaryProviderInterface
{
private final ProcessSummaryLine created = line(Status.OK, "row was added", "rows were added", "row was added", "rows were added");
/*******************************************************************************
**
*******************************************************************************/
@Override
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
InsertInput insert = new InsertInput(DataAnalysisTables.TABLE_CONFIG).withRecords(input.getRecords());
insert.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
for(QRecord record : new InsertAction().execute(insert).getRecords())
{
if(record.getErrors() != null && !record.getErrors().isEmpty())
{
throw (new QException("Could not add analysis settings: " + record.getErrors()));
}
created.incrementCount();
output.getRecords().add(record);
}
DataAnalysisRuntime.service().getConfigResolver().invalidate();
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean isForResultScreen)
{
ArrayList<ProcessSummaryLineInterface> lines = new ArrayList<>();
created.addSelfToListIfAnyCount(lines);
return (lines);
}
}
/*******************************************************************************
** A summary line with its four messages.
*******************************************************************************/
private static ProcessSummaryLine line(Status status, String singularFuture, String pluralFuture, String singularPast, String pluralPast)
{
ProcessSummaryLine line = new ProcessSummaryLine(status, 0, null);
line.setSingularFutureMessage(singularFuture);
line.setPluralFutureMessage(pluralFuture);
line.setSingularPastMessage(singularPast);
line.setPluralPastMessage(pluralPast);
return (line);
}
}
@@ -0,0 +1,186 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.processes;
import java.time.Instant;
import java.util.ArrayList;
import com.kingsrook.qbits.dataanalysis.DataAnalysisRuntime;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLine;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLineInterface;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.actions.processes.Status;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractLoadStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractTransformStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ProcessSummaryProviderInterface;
/*******************************************************************************
** Ordinary streamed ETL Review/Result steps; no custom forms or navigation.
*******************************************************************************/
public final class WatchActions
{
public static final String EVALUATE = "data_analysis_watch_evaluate";
public static final String ENABLE = "data_analysis_watch_enable";
public static final String DISABLE = "data_analysis_watch_disable";
public static final String SCHEDULED = "data_analysis_evaluate_watches";
/*******************************************************************************
** Steps only.
*******************************************************************************/
private WatchActions()
{
}
/*******************************************************************************
** Preview selected records without evaluating or mutating them.
*******************************************************************************/
public static class Review extends AbstractTransformStep implements ProcessSummaryProviderInterface
{
private final ArrayList<ProcessSummaryLineInterface> lines = new ArrayList<>();
/*******************************************************************************
** Extract runs as caller; enforce EDIT before promising any action.
*******************************************************************************/
@Override
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
if(!PermissionsHelper.hasTablePermission(new UpdateInput(DataAnalysisTables.WATCH), DataAnalysisTables.WATCH, TablePermissionSubType.EDIT))
{
throw new QPermissionDeniedException("Watch editing is unavailable.");
}
String verb = verb(input.getProcessName());
for(QRecord record : input.getRecords())
{
lines.add(new ProcessSummaryLine(Status.INFO, null, "Watch " + record.getValueString("id") + " (" + record.getValueString("detector") + ") will be " + verb + "."));
output.addRecord(record);
}
}
/*******************************************************************************
** Standard summary lines are rendered by the core Review screen.
*******************************************************************************/
@Override
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean result)
{
return (result ? new ArrayList<>() : lines);
}
}
/*******************************************************************************
** Apply selected records and report exact evaluated/firing/OK/skipped counts.
*******************************************************************************/
public static class Result extends AbstractLoadStep implements ProcessSummaryProviderInterface
{
private int done;
private int firing;
private int ok;
private String process;
private final ArrayList<ProcessSummaryLineInterface> failures = new ArrayList<>();
/*******************************************************************************
** Re-read and authorize each id when executing after Review.
*******************************************************************************/
@Override
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
process = input.getProcessName();
verb(process);
for(QRecord record : input.getRecords())
{
try
{
if(EVALUATE.equals(process))
{
var verdict = DataAnalysisRuntime.watches().evaluate(record.getValue("id"), Instant.now());
if(!verdict.evaluated())
{
failures.add(new ProcessSummaryLine(Status.WARNING, null, "Watch " + record.getValueString("id") + " skipped: " + verdict.message()));
continue;
}
firing += verdict.firing() ? 1 : 0;
ok += verdict.firing() ? 0 : 1;
}
else
{
DataAnalysisRuntime.watches().setEnabled(record.getValue("id"), ENABLE.equals(process));
}
done++;
output.addRecord(record);
}
catch(QException e)
{
failures.add(new ProcessSummaryLine(Status.ERROR, null, "Watch " + record.getValueString("id") + " failed: " + e.getMessage()));
}
}
}
/*******************************************************************************
** Counts span all streamed pages, so the Result screen is a true total.
*******************************************************************************/
@Override
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean result)
{
ArrayList<ProcessSummaryLineInterface> lines = new ArrayList<>();
String message = done + (done == 1 ? " watch " : " watches ") + (EVALUATE.equals(process) ? "evaluated: " + firing + " firing, " + ok + " OK"
: ENABLE.equals(process) ? "enabled" : "disabled");
lines.add(new ProcessSummaryLine(Status.OK, null, message));
lines.addAll(failures);
return (lines);
}
}
/*******************************************************************************
** Scheduler invokes a hidden backend-only process every fifteen minutes.
*******************************************************************************/
public static class Scheduled implements BackendStep
{
/*******************************************************************************
** Store the real count of successfully evaluated enabled watches.
*******************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
output.addValue("count", DataAnalysisRuntime.watches().evaluateEnabled(Instant.now()));
}
}
/*******************************************************************************
** Reject unknown processes instead of silently choosing a mutation.
*******************************************************************************/
private static String verb(String process) throws QException
{
return (switch(process)
{
case EVALUATE -> "evaluated";
case ENABLE -> "enabled";
case DISABLE -> "disabled";
default -> throw new QException("Unknown watch action.");
});
}
}
@@ -33,6 +33,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect;
public class Chart implements Serializable
{
private ChartKind kind;
private Boolean stacked;
private List<ChartKind> alternatives = List.of();
private Axis x;
private Axis y;
@@ -164,4 +165,21 @@ public class Chart implements Serializable
this.annotations = annotations;
return (this);
}
/*******************************************************************************
** Whether category series should stack to a total share of one.
*******************************************************************************/
public Boolean getStacked()
{
return (stacked);
}
/*******************************************************************************
** Declare stacked shares explicitly rather than relying on chart prose.
*******************************************************************************/
public Chart withStacked(Boolean stacked)
{
this.stacked = stacked;
return (this);
}
}
@@ -0,0 +1,213 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
/*******************************************************************************
** Typed CompareRequest contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class CompareRequest implements AnalysisRequest
{
private String tableName;
private QQueryFilter filter;
private Boolean exact = true;
private QQueryFilter filterA;
private QQueryFilter filterB;
private String labelA = "A";
private String labelB = "B";
private List<String> fields;
/*******************************************************************************
** Getter for tableName.
*******************************************************************************/
@Override
public String getTableName()
{
return (tableName);
}
/*******************************************************************************
** Fluent setter for tableName.
*******************************************************************************/
public CompareRequest withTableName(String tableName)
{
this.tableName = tableName;
return (this);
}
/*******************************************************************************
** Getter for filter.
*******************************************************************************/
@Override
public QQueryFilter getFilter()
{
return (filter);
}
/*******************************************************************************
** Fluent setter for filter.
*******************************************************************************/
public CompareRequest withFilter(QQueryFilter filter)
{
this.filter = filter;
return (this);
}
/*******************************************************************************
** Getter for exact.
*******************************************************************************/
@Override
public Boolean getExact()
{
return (exact);
}
/*******************************************************************************
** Fluent setter for exact.
*******************************************************************************/
public CompareRequest withExact(Boolean exact)
{
this.exact = exact;
return (this);
}
/*******************************************************************************
** Getter for filterA.
*******************************************************************************/
public QQueryFilter getFilterA()
{
return (filterA);
}
/*******************************************************************************
** Fluent setter for filterA.
*******************************************************************************/
public CompareRequest withFilterA(QQueryFilter filterA)
{
this.filterA = filterA;
return (this);
}
/*******************************************************************************
** Getter for filterB.
*******************************************************************************/
public QQueryFilter getFilterB()
{
return (filterB);
}
/*******************************************************************************
** Fluent setter for filterB.
*******************************************************************************/
public CompareRequest withFilterB(QQueryFilter filterB)
{
this.filterB = filterB;
return (this);
}
/*******************************************************************************
** Getter for labelA.
*******************************************************************************/
public String getLabelA()
{
return (labelA);
}
/*******************************************************************************
** Fluent setter for labelA.
*******************************************************************************/
public CompareRequest withLabelA(String labelA)
{
this.labelA = labelA;
return (this);
}
/*******************************************************************************
** Getter for labelB.
*******************************************************************************/
public String getLabelB()
{
return (labelB);
}
/*******************************************************************************
** Fluent setter for labelB.
*******************************************************************************/
public CompareRequest withLabelB(String labelB)
{
this.labelB = labelB;
return (this);
}
/*******************************************************************************
** Getter for fields.
*******************************************************************************/
public List<String> getFields()
{
return (fields);
}
/*******************************************************************************
** Fluent setter for fields.
*******************************************************************************/
public CompareRequest withFields(List<String> fields)
{
this.fields = fields;
return (this);
}
}
@@ -0,0 +1,55 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed CompareResult contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class CompareResult implements Serializable
{
private List<FieldComparison> fields = new java.util.ArrayList<>();
/*******************************************************************************
** Getter for fields.
*******************************************************************************/
public List<FieldComparison> getFields()
{
return (fields);
}
/*******************************************************************************
** Fluent setter for fields.
*******************************************************************************/
public CompareResult withFields(List<FieldComparison> fields)
{
this.fields = fields;
return (this);
}
}
@@ -0,0 +1,77 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed ComparisonSide contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class ComparisonSide implements Serializable
{
private String label;
private List<Metric> metrics = new java.util.ArrayList<>();
/*******************************************************************************
** Getter for label.
*******************************************************************************/
public String getLabel()
{
return (label);
}
/*******************************************************************************
** Fluent setter for label.
*******************************************************************************/
public ComparisonSide withLabel(String label)
{
this.label = label;
return (this);
}
/*******************************************************************************
** Getter for metrics.
*******************************************************************************/
public List<Metric> getMetrics()
{
return (metrics);
}
/*******************************************************************************
** Fluent setter for metrics.
*******************************************************************************/
public ComparisonSide withMetrics(List<Metric> metrics)
{
this.metrics = metrics;
return (this);
}
}
@@ -0,0 +1,186 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed ComparisonValue contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class ComparisonValue implements Serializable
{
private Serializable value;
private String label;
private ComparisonSide sideA;
private ComparisonSide sideB;
private Metric delta;
private Metric percentDelta;
private Significance significance;
/*******************************************************************************
** Getter for value.
*******************************************************************************/
public Serializable getValue()
{
return (value);
}
/*******************************************************************************
** Fluent setter for value.
*******************************************************************************/
public ComparisonValue withValue(Serializable value)
{
this.value = value;
return (this);
}
/*******************************************************************************
** Getter for label.
*******************************************************************************/
public String getLabel()
{
return (label);
}
/*******************************************************************************
** Fluent setter for label.
*******************************************************************************/
public ComparisonValue withLabel(String label)
{
this.label = label;
return (this);
}
/*******************************************************************************
** Getter for sideA.
*******************************************************************************/
public ComparisonSide getSideA()
{
return (sideA);
}
/*******************************************************************************
** Fluent setter for sideA.
*******************************************************************************/
public ComparisonValue withSideA(ComparisonSide sideA)
{
this.sideA = sideA;
return (this);
}
/*******************************************************************************
** Getter for sideB.
*******************************************************************************/
public ComparisonSide getSideB()
{
return (sideB);
}
/*******************************************************************************
** Fluent setter for sideB.
*******************************************************************************/
public ComparisonValue withSideB(ComparisonSide sideB)
{
this.sideB = sideB;
return (this);
}
/*******************************************************************************
** Getter for delta.
*******************************************************************************/
public Metric getDelta()
{
return (delta);
}
/*******************************************************************************
** Fluent setter for delta.
*******************************************************************************/
public ComparisonValue withDelta(Metric delta)
{
this.delta = delta;
return (this);
}
/*******************************************************************************
** Getter for percentDelta.
*******************************************************************************/
public Metric getPercentDelta()
{
return (percentDelta);
}
/*******************************************************************************
** Fluent setter for percentDelta.
*******************************************************************************/
public ComparisonValue withPercentDelta(Metric percentDelta)
{
this.percentDelta = percentDelta;
return (this);
}
/*******************************************************************************
** Getter for significance.
*******************************************************************************/
public Significance getSignificance()
{
return (significance);
}
/*******************************************************************************
** Fluent setter for significance.
*******************************************************************************/
public ComparisonValue withSignificance(Significance significance)
{
this.significance = significance;
return (this);
}
}
@@ -0,0 +1,142 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed CorrelationCell contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class CorrelationCell implements Serializable
{
private String xField;
private String yField;
private Long n;
private Double r;
private ScatterRequest scatter;
/*******************************************************************************
** Getter for xField.
*******************************************************************************/
public String getXField()
{
return (xField);
}
/*******************************************************************************
** Fluent setter for xField.
*******************************************************************************/
public CorrelationCell withXField(String xField)
{
this.xField = xField;
return (this);
}
/*******************************************************************************
** Getter for yField.
*******************************************************************************/
public String getYField()
{
return (yField);
}
/*******************************************************************************
** Fluent setter for yField.
*******************************************************************************/
public CorrelationCell withYField(String yField)
{
this.yField = yField;
return (this);
}
/*******************************************************************************
** Getter for n.
*******************************************************************************/
public Long getN()
{
return (n);
}
/*******************************************************************************
** Fluent setter for n.
*******************************************************************************/
public CorrelationCell withN(Long n)
{
this.n = n;
return (this);
}
/*******************************************************************************
** Getter for r.
*******************************************************************************/
public Double getR()
{
return (r);
}
/*******************************************************************************
** Fluent setter for r.
*******************************************************************************/
public CorrelationCell withR(Double r)
{
this.r = r;
return (this);
}
/*******************************************************************************
** Getter for scatter.
*******************************************************************************/
public ScatterRequest getScatter()
{
return (scatter);
}
/*******************************************************************************
** Fluent setter for scatter.
*******************************************************************************/
public CorrelationCell withScatter(ScatterRequest scatter)
{
this.scatter = scatter;
return (this);
}
}
@@ -0,0 +1,125 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
/*******************************************************************************
** Typed CorrelationRequest contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class CorrelationRequest implements AnalysisRequest
{
private String tableName;
private QQueryFilter filter;
private Boolean exact = true;
private List<String> fields;
/*******************************************************************************
** Getter for tableName.
*******************************************************************************/
@Override
public String getTableName()
{
return (tableName);
}
/*******************************************************************************
** Fluent setter for tableName.
*******************************************************************************/
public CorrelationRequest withTableName(String tableName)
{
this.tableName = tableName;
return (this);
}
/*******************************************************************************
** Getter for filter.
*******************************************************************************/
@Override
public QQueryFilter getFilter()
{
return (filter);
}
/*******************************************************************************
** Fluent setter for filter.
*******************************************************************************/
public CorrelationRequest withFilter(QQueryFilter filter)
{
this.filter = filter;
return (this);
}
/*******************************************************************************
** Getter for exact.
*******************************************************************************/
@Override
public Boolean getExact()
{
return (exact);
}
/*******************************************************************************
** Fluent setter for exact.
*******************************************************************************/
public CorrelationRequest withExact(Boolean exact)
{
this.exact = exact;
return (this);
}
/*******************************************************************************
** Getter for fields.
*******************************************************************************/
public List<String> getFields()
{
return (fields);
}
/*******************************************************************************
** Fluent setter for fields.
*******************************************************************************/
public CorrelationRequest withFields(List<String> fields)
{
this.fields = fields;
return (this);
}
}
@@ -0,0 +1,99 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed CorrelationResult contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class CorrelationResult implements Serializable
{
private List<String> fields;
private List<CorrelationCell> cells = new java.util.ArrayList<>();
private Chart chart;
/*******************************************************************************
** Getter for fields.
*******************************************************************************/
public List<String> getFields()
{
return (fields);
}
/*******************************************************************************
** Fluent setter for fields.
*******************************************************************************/
public CorrelationResult withFields(List<String> fields)
{
this.fields = fields;
return (this);
}
/*******************************************************************************
** Getter for cells.
*******************************************************************************/
public List<CorrelationCell> getCells()
{
return (cells);
}
/*******************************************************************************
** Fluent setter for cells.
*******************************************************************************/
public CorrelationResult withCells(List<CorrelationCell> cells)
{
this.cells = cells;
return (this);
}
/*******************************************************************************
** Getter for chart.
*******************************************************************************/
public Chart getChart()
{
return (chart);
}
/*******************************************************************************
** Fluent setter for chart.
*******************************************************************************/
public CorrelationResult withChart(Chart chart)
{
this.chart = chart;
return (this);
}
}
@@ -0,0 +1,142 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed CrosstabCell contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class CrosstabCell implements Serializable
{
private Integer rowIndex;
private Integer columnIndex;
private Metric count;
private Metric rowShare;
private Metric columnShare;
/*******************************************************************************
** Getter for rowIndex.
*******************************************************************************/
public Integer getRowIndex()
{
return (rowIndex);
}
/*******************************************************************************
** Fluent setter for rowIndex.
*******************************************************************************/
public CrosstabCell withRowIndex(Integer rowIndex)
{
this.rowIndex = rowIndex;
return (this);
}
/*******************************************************************************
** Getter for columnIndex.
*******************************************************************************/
public Integer getColumnIndex()
{
return (columnIndex);
}
/*******************************************************************************
** Fluent setter for columnIndex.
*******************************************************************************/
public CrosstabCell withColumnIndex(Integer columnIndex)
{
this.columnIndex = columnIndex;
return (this);
}
/*******************************************************************************
** Getter for count.
*******************************************************************************/
public Metric getCount()
{
return (count);
}
/*******************************************************************************
** Fluent setter for count.
*******************************************************************************/
public CrosstabCell withCount(Metric count)
{
this.count = count;
return (this);
}
/*******************************************************************************
** Getter for rowShare.
*******************************************************************************/
public Metric getRowShare()
{
return (rowShare);
}
/*******************************************************************************
** Fluent setter for rowShare.
*******************************************************************************/
public CrosstabCell withRowShare(Metric rowShare)
{
this.rowShare = rowShare;
return (this);
}
/*******************************************************************************
** Getter for columnShare.
*******************************************************************************/
public Metric getColumnShare()
{
return (columnShare);
}
/*******************************************************************************
** Fluent setter for columnShare.
*******************************************************************************/
public CrosstabCell withColumnShare(Metric columnShare)
{
this.columnShare = columnShare;
return (this);
}
}
@@ -0,0 +1,168 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
/*******************************************************************************
** Typed CrosstabRequest contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class CrosstabRequest implements AnalysisRequest
{
private String tableName;
private QQueryFilter filter;
private Boolean exact = true;
private String rowField;
private String columnField;
private Integer limit = 20;
/*******************************************************************************
** Getter for tableName.
*******************************************************************************/
@Override
public String getTableName()
{
return (tableName);
}
/*******************************************************************************
** Fluent setter for tableName.
*******************************************************************************/
public CrosstabRequest withTableName(String tableName)
{
this.tableName = tableName;
return (this);
}
/*******************************************************************************
** Getter for filter.
*******************************************************************************/
@Override
public QQueryFilter getFilter()
{
return (filter);
}
/*******************************************************************************
** Fluent setter for filter.
*******************************************************************************/
public CrosstabRequest withFilter(QQueryFilter filter)
{
this.filter = filter;
return (this);
}
/*******************************************************************************
** Getter for exact.
*******************************************************************************/
@Override
public Boolean getExact()
{
return (exact);
}
/*******************************************************************************
** Fluent setter for exact.
*******************************************************************************/
public CrosstabRequest withExact(Boolean exact)
{
this.exact = exact;
return (this);
}
/*******************************************************************************
** Getter for rowField.
*******************************************************************************/
public String getRowField()
{
return (rowField);
}
/*******************************************************************************
** Fluent setter for rowField.
*******************************************************************************/
public CrosstabRequest withRowField(String rowField)
{
this.rowField = rowField;
return (this);
}
/*******************************************************************************
** Getter for columnField.
*******************************************************************************/
public String getColumnField()
{
return (columnField);
}
/*******************************************************************************
** Fluent setter for columnField.
*******************************************************************************/
public CrosstabRequest withColumnField(String columnField)
{
this.columnField = columnField;
return (this);
}
/*******************************************************************************
** Getter for limit.
*******************************************************************************/
public Integer getLimit()
{
return (limit);
}
/*******************************************************************************
** Fluent setter for limit.
*******************************************************************************/
public CrosstabRequest withLimit(Integer limit)
{
this.limit = limit;
return (this);
}
}
@@ -0,0 +1,121 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed CrosstabResult contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class CrosstabResult implements Serializable
{
private List<PivotHeader> rows = new java.util.ArrayList<>();
private List<PivotHeader> columns = new java.util.ArrayList<>();
private List<CrosstabCell> cells = new java.util.ArrayList<>();
private Significance significance;
/*******************************************************************************
** Getter for rows.
*******************************************************************************/
public List<PivotHeader> getRows()
{
return (rows);
}
/*******************************************************************************
** Fluent setter for rows.
*******************************************************************************/
public CrosstabResult withRows(List<PivotHeader> rows)
{
this.rows = rows;
return (this);
}
/*******************************************************************************
** Getter for columns.
*******************************************************************************/
public List<PivotHeader> getColumns()
{
return (columns);
}
/*******************************************************************************
** Fluent setter for columns.
*******************************************************************************/
public CrosstabResult withColumns(List<PivotHeader> columns)
{
this.columns = columns;
return (this);
}
/*******************************************************************************
** Getter for cells.
*******************************************************************************/
public List<CrosstabCell> getCells()
{
return (cells);
}
/*******************************************************************************
** Fluent setter for cells.
*******************************************************************************/
public CrosstabResult withCells(List<CrosstabCell> cells)
{
this.cells = cells;
return (this);
}
/*******************************************************************************
** Getter for significance.
*******************************************************************************/
public Significance getSignificance()
{
return (significance);
}
/*******************************************************************************
** Fluent setter for significance.
*******************************************************************************/
public CrosstabResult withSignificance(Significance significance)
{
this.significance = significance;
return (this);
}
}
@@ -0,0 +1,121 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed FieldComparison contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class FieldComparison implements Serializable
{
private String field;
private List<ComparisonValue> values = new java.util.ArrayList<>();
private Significance significance;
private Chart chart;
/*******************************************************************************
** Getter for field.
*******************************************************************************/
public String getField()
{
return (field);
}
/*******************************************************************************
** Fluent setter for field.
*******************************************************************************/
public FieldComparison withField(String field)
{
this.field = field;
return (this);
}
/*******************************************************************************
** Getter for values.
*******************************************************************************/
public List<ComparisonValue> getValues()
{
return (values);
}
/*******************************************************************************
** Fluent setter for values.
*******************************************************************************/
public FieldComparison withValues(List<ComparisonValue> values)
{
this.values = values;
return (this);
}
/*******************************************************************************
** Getter for significance.
*******************************************************************************/
public Significance getSignificance()
{
return (significance);
}
/*******************************************************************************
** Fluent setter for significance.
*******************************************************************************/
public FieldComparison withSignificance(Significance significance)
{
this.significance = significance;
return (this);
}
/*******************************************************************************
** Getter for chart.
*******************************************************************************/
public Chart getChart()
{
return (chart);
}
/*******************************************************************************
** Fluent setter for chart.
*******************************************************************************/
public FieldComparison withChart(Chart chart)
{
this.chart = chart;
return (this);
}
}
@@ -0,0 +1,89 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed PivotCell contract.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class PivotCell implements Serializable
{
private Integer rowIndex;
private Integer columnIndex;
private List<Metric> values = new ArrayList<>();
/*******************************************************************************
** Getter for rowIndex.
*******************************************************************************/
public Integer getRowIndex()
{
return (rowIndex);
}
/*******************************************************************************
** Fluent setter for rowIndex.
*******************************************************************************/
public PivotCell withRowIndex(Integer rowIndex)
{
this.rowIndex = rowIndex;
return (this);
}
/*******************************************************************************
** Getter for columnIndex.
*******************************************************************************/
public Integer getColumnIndex()
{
return (columnIndex);
}
/*******************************************************************************
** Fluent setter for columnIndex.
*******************************************************************************/
public PivotCell withColumnIndex(Integer columnIndex)
{
this.columnIndex = columnIndex;
return (this);
}
/*******************************************************************************
** Getter for values.
*******************************************************************************/
public List<Metric> getValues()
{
return (values);
}
/*******************************************************************************
** Fluent setter for values.
*******************************************************************************/
public PivotCell withValues(List<Metric> values)
{
this.values = values;
return (this);
}
}
@@ -0,0 +1,88 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.DateBucketUnit;
/*******************************************************************************
** Typed PivotDimension contract.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class PivotDimension implements Serializable
{
private String field;
private DateBucketUnit dateBucket;
private PivotNumericBins numericBins;
/*******************************************************************************
** Getter for field.
*******************************************************************************/
public String getField()
{
return (field);
}
/*******************************************************************************
** Fluent setter for field.
*******************************************************************************/
public PivotDimension withField(String field)
{
this.field = field;
return (this);
}
/*******************************************************************************
** Getter for dateBucket.
*******************************************************************************/
public DateBucketUnit getDateBucket()
{
return (dateBucket);
}
/*******************************************************************************
** Fluent setter for dateBucket.
*******************************************************************************/
public PivotDimension withDateBucket(DateBucketUnit dateBucket)
{
this.dateBucket = dateBucket;
return (this);
}
/*******************************************************************************
** Getter for numericBins.
*******************************************************************************/
public PivotNumericBins getNumericBins()
{
return (numericBins);
}
/*******************************************************************************
** Fluent setter for numericBins.
*******************************************************************************/
public PivotDimension withNumericBins(PivotNumericBins numericBins)
{
this.numericBins = numericBins;
return (this);
}
}
@@ -0,0 +1,69 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed PivotHeader contract.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class PivotHeader implements Serializable
{
private Serializable value;
private String label;
/*******************************************************************************
** Getter for value.
*******************************************************************************/
public Serializable getValue()
{
return (value);
}
/*******************************************************************************
** Fluent setter for value.
*******************************************************************************/
public PivotHeader withValue(Serializable value)
{
this.value = value;
return (this);
}
/*******************************************************************************
** Getter for label.
*******************************************************************************/
public String getLabel()
{
return (label);
}
/*******************************************************************************
** Fluent setter for label.
*******************************************************************************/
public PivotHeader withLabel(String label)
{
this.label = label;
return (this);
}
}
@@ -0,0 +1,95 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.math.BigDecimal;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed PivotMeasure contract.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class PivotMeasure implements Serializable
{
private Operator operator;
private String field;
private BigDecimal percentile;
/*******************************************************************************
** Supported pivot measures. COUNT counts records, regardless of field nulls.
*******************************************************************************/
public enum Operator
{
COUNT, SUM, AVG, MIN, MAX, COUNT_DISTINCT, PERCENTILE
}
/*******************************************************************************
** Getter for operator.
*******************************************************************************/
public Operator getOperator()
{
return (operator);
}
/*******************************************************************************
** Fluent setter for operator.
*******************************************************************************/
public PivotMeasure withOperator(Operator operator)
{
this.operator = operator;
return (this);
}
/*******************************************************************************
** Getter for field.
*******************************************************************************/
public String getField()
{
return (field);
}
/*******************************************************************************
** Fluent setter for field.
*******************************************************************************/
public PivotMeasure withField(String field)
{
this.field = field;
return (this);
}
/*******************************************************************************
** Getter for percentile.
*******************************************************************************/
public BigDecimal getPercentile()
{
return (percentile);
}
/*******************************************************************************
** Fluent setter for percentile.
*******************************************************************************/
public PivotMeasure withPercentile(BigDecimal percentile)
{
this.percentile = percentile;
return (this);
}
}
@@ -0,0 +1,87 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed PivotMeasureInfo contract.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class PivotMeasureInfo implements Serializable
{
private String key;
private String label;
private ValueType valueType;
/*******************************************************************************
** Getter for key.
*******************************************************************************/
public String getKey()
{
return (key);
}
/*******************************************************************************
** Fluent setter for key.
*******************************************************************************/
public PivotMeasureInfo withKey(String key)
{
this.key = key;
return (this);
}
/*******************************************************************************
** Getter for label.
*******************************************************************************/
public String getLabel()
{
return (label);
}
/*******************************************************************************
** Fluent setter for label.
*******************************************************************************/
public PivotMeasureInfo withLabel(String label)
{
this.label = label;
return (this);
}
/*******************************************************************************
** Getter for valueType.
*******************************************************************************/
public ValueType getValueType()
{
return (valueType);
}
/*******************************************************************************
** Fluent setter for valueType.
*******************************************************************************/
public PivotMeasureInfo withValueType(ValueType valueType)
{
this.valueType = valueType;
return (this);
}
}
@@ -0,0 +1,88 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.math.BigDecimal;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed PivotNumericBins contract.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class PivotNumericBins implements Serializable
{
private Integer count = 20;
private BigDecimal min;
private BigDecimal max;
/*******************************************************************************
** Getter for count.
*******************************************************************************/
public Integer getCount()
{
return (count);
}
/*******************************************************************************
** Fluent setter for count.
*******************************************************************************/
public PivotNumericBins withCount(Integer count)
{
this.count = count;
return (this);
}
/*******************************************************************************
** Getter for min.
*******************************************************************************/
public BigDecimal getMin()
{
return (min);
}
/*******************************************************************************
** Fluent setter for min.
*******************************************************************************/
public PivotNumericBins withMin(BigDecimal min)
{
this.min = min;
return (this);
}
/*******************************************************************************
** Getter for max.
*******************************************************************************/
public BigDecimal getMax()
{
return (max);
}
/*******************************************************************************
** Fluent setter for max.
*******************************************************************************/
public PivotNumericBins withMax(BigDecimal max)
{
this.max = max;
return (this);
}
}
@@ -0,0 +1,182 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
/*******************************************************************************
** Typed PivotRequest contract.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class PivotRequest implements AnalysisRequest
{
private String tableName;
private QQueryFilter filter;
private Boolean exact = true;
private List<PivotDimension> rows = new ArrayList<>();
private List<PivotDimension> columns = new ArrayList<>();
private List<PivotMeasure> values = new ArrayList<>();
private Boolean showTotals = true;
private Integer limitGroups = 50;
/*******************************************************************************
** Getter for tableName.
*******************************************************************************/
@Override
public String getTableName()
{
return (tableName);
}
/*******************************************************************************
** Fluent setter for tableName.
*******************************************************************************/
public PivotRequest withTableName(String tableName)
{
this.tableName = tableName;
return (this);
}
/*******************************************************************************
** Getter for filter.
*******************************************************************************/
@Override
public QQueryFilter getFilter()
{
return (filter);
}
/*******************************************************************************
** Fluent setter for filter.
*******************************************************************************/
public PivotRequest withFilter(QQueryFilter filter)
{
this.filter = filter;
return (this);
}
/*******************************************************************************
** Getter for exact.
*******************************************************************************/
@Override
public Boolean getExact()
{
return (exact);
}
/*******************************************************************************
** Fluent setter for exact.
*******************************************************************************/
public PivotRequest withExact(Boolean exact)
{
this.exact = exact;
return (this);
}
/*******************************************************************************
** Getter for rows.
*******************************************************************************/
public List<PivotDimension> getRows()
{
return (rows);
}
/*******************************************************************************
** Fluent setter for rows.
*******************************************************************************/
public PivotRequest withRows(List<PivotDimension> rows)
{
this.rows = rows;
return (this);
}
/*******************************************************************************
** Getter for columns.
*******************************************************************************/
public List<PivotDimension> getColumns()
{
return (columns);
}
/*******************************************************************************
** Fluent setter for columns.
*******************************************************************************/
public PivotRequest withColumns(List<PivotDimension> columns)
{
this.columns = columns;
return (this);
}
/*******************************************************************************
** Getter for values.
*******************************************************************************/
public List<PivotMeasure> getValues()
{
return (values);
}
/*******************************************************************************
** Fluent setter for values.
*******************************************************************************/
public PivotRequest withValues(List<PivotMeasure> values)
{
this.values = values;
return (this);
}
/*******************************************************************************
** Getter for showTotals.
*******************************************************************************/
public Boolean getShowTotals()
{
return (showTotals);
}
/*******************************************************************************
** Fluent setter for showTotals.
*******************************************************************************/
public PivotRequest withShowTotals(Boolean showTotals)
{
this.showTotals = showTotals;
return (this);
}
/*******************************************************************************
** Getter for limitGroups.
*******************************************************************************/
public Integer getLimitGroups()
{
return (limitGroups);
}
/*******************************************************************************
** Fluent setter for limitGroups.
*******************************************************************************/
public PivotRequest withLimitGroups(Integer limitGroups)
{
this.limitGroups = limitGroups;
return (this);
}
}
@@ -0,0 +1,252 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed PivotResult contract.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class PivotResult implements Serializable
{
private List<List<PivotHeader>> rowHeaders = new ArrayList<>();
private List<List<PivotHeader>> columnHeaders = new ArrayList<>();
private List<PivotMeasureInfo> measures = new ArrayList<>();
private List<PivotCell> cells = new ArrayList<>();
private List<List<Metric>> rowTotals = new ArrayList<>();
private List<List<Metric>> columnTotals = new ArrayList<>();
private List<Metric> grandTotals = new ArrayList<>();
private Boolean truncatedRows = false;
private Boolean truncatedColumns = false;
private Boolean estimate = false;
private List<String> warnings = new ArrayList<>();
private Instant asOf;
/*******************************************************************************
** Getter for rowHeaders.
*******************************************************************************/
public List<List<PivotHeader>> getRowHeaders()
{
return (rowHeaders);
}
/*******************************************************************************
** Fluent setter for rowHeaders.
*******************************************************************************/
public PivotResult withRowHeaders(List<List<PivotHeader>> rowHeaders)
{
this.rowHeaders = rowHeaders;
return (this);
}
/*******************************************************************************
** Getter for columnHeaders.
*******************************************************************************/
public List<List<PivotHeader>> getColumnHeaders()
{
return (columnHeaders);
}
/*******************************************************************************
** Fluent setter for columnHeaders.
*******************************************************************************/
public PivotResult withColumnHeaders(List<List<PivotHeader>> columnHeaders)
{
this.columnHeaders = columnHeaders;
return (this);
}
/*******************************************************************************
** Getter for measures.
*******************************************************************************/
public List<PivotMeasureInfo> getMeasures()
{
return (measures);
}
/*******************************************************************************
** Fluent setter for measures.
*******************************************************************************/
public PivotResult withMeasures(List<PivotMeasureInfo> measures)
{
this.measures = measures;
return (this);
}
/*******************************************************************************
** Getter for cells.
*******************************************************************************/
public List<PivotCell> getCells()
{
return (cells);
}
/*******************************************************************************
** Fluent setter for cells.
*******************************************************************************/
public PivotResult withCells(List<PivotCell> cells)
{
this.cells = cells;
return (this);
}
/*******************************************************************************
** Getter for rowTotals.
*******************************************************************************/
public List<List<Metric>> getRowTotals()
{
return (rowTotals);
}
/*******************************************************************************
** Fluent setter for rowTotals.
*******************************************************************************/
public PivotResult withRowTotals(List<List<Metric>> rowTotals)
{
this.rowTotals = rowTotals;
return (this);
}
/*******************************************************************************
** Getter for columnTotals.
*******************************************************************************/
public List<List<Metric>> getColumnTotals()
{
return (columnTotals);
}
/*******************************************************************************
** Fluent setter for columnTotals.
*******************************************************************************/
public PivotResult withColumnTotals(List<List<Metric>> columnTotals)
{
this.columnTotals = columnTotals;
return (this);
}
/*******************************************************************************
** Getter for grandTotals.
*******************************************************************************/
public List<Metric> getGrandTotals()
{
return (grandTotals);
}
/*******************************************************************************
** Fluent setter for grandTotals.
*******************************************************************************/
public PivotResult withGrandTotals(List<Metric> grandTotals)
{
this.grandTotals = grandTotals;
return (this);
}
/*******************************************************************************
** Getter for truncatedRows.
*******************************************************************************/
public Boolean getTruncatedRows()
{
return (truncatedRows);
}
/*******************************************************************************
** Fluent setter for truncatedRows.
*******************************************************************************/
public PivotResult withTruncatedRows(Boolean truncatedRows)
{
this.truncatedRows = truncatedRows;
return (this);
}
/*******************************************************************************
** Getter for truncatedColumns.
*******************************************************************************/
public Boolean getTruncatedColumns()
{
return (truncatedColumns);
}
/*******************************************************************************
** Fluent setter for truncatedColumns.
*******************************************************************************/
public PivotResult withTruncatedColumns(Boolean truncatedColumns)
{
this.truncatedColumns = truncatedColumns;
return (this);
}
/*******************************************************************************
** Getter for estimate.
*******************************************************************************/
public Boolean getEstimate()
{
return (estimate);
}
/*******************************************************************************
** Fluent setter for estimate.
*******************************************************************************/
public PivotResult withEstimate(Boolean estimate)
{
this.estimate = estimate;
return (this);
}
/*******************************************************************************
** Getter for warnings.
*******************************************************************************/
public List<String> getWarnings()
{
return (warnings);
}
/*******************************************************************************
** Fluent setter for warnings.
*******************************************************************************/
public PivotResult withWarnings(List<String> warnings)
{
this.warnings = warnings;
return (this);
}
/*******************************************************************************
** Getter for asOf.
*******************************************************************************/
public Instant getAsOf()
{
return (asOf);
}
/*******************************************************************************
** Fluent setter for asOf.
*******************************************************************************/
public PivotResult withAsOf(Instant asOf)
{
this.asOf = asOf;
return (this);
}
}
@@ -0,0 +1,168 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
/*******************************************************************************
** Typed ScatterRequest contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class ScatterRequest implements AnalysisRequest
{
private String tableName;
private QQueryFilter filter;
private Boolean exact = true;
private String xField;
private String yField;
private Integer limit = 2000;
/*******************************************************************************
** Getter for tableName.
*******************************************************************************/
@Override
public String getTableName()
{
return (tableName);
}
/*******************************************************************************
** Fluent setter for tableName.
*******************************************************************************/
public ScatterRequest withTableName(String tableName)
{
this.tableName = tableName;
return (this);
}
/*******************************************************************************
** Getter for filter.
*******************************************************************************/
@Override
public QQueryFilter getFilter()
{
return (filter);
}
/*******************************************************************************
** Fluent setter for filter.
*******************************************************************************/
public ScatterRequest withFilter(QQueryFilter filter)
{
this.filter = filter;
return (this);
}
/*******************************************************************************
** Getter for exact.
*******************************************************************************/
@Override
public Boolean getExact()
{
return (exact);
}
/*******************************************************************************
** Fluent setter for exact.
*******************************************************************************/
public ScatterRequest withExact(Boolean exact)
{
this.exact = exact;
return (this);
}
/*******************************************************************************
** Getter for xField.
*******************************************************************************/
public String getXField()
{
return (xField);
}
/*******************************************************************************
** Fluent setter for xField.
*******************************************************************************/
public ScatterRequest withXField(String xField)
{
this.xField = xField;
return (this);
}
/*******************************************************************************
** Getter for yField.
*******************************************************************************/
public String getYField()
{
return (yField);
}
/*******************************************************************************
** Fluent setter for yField.
*******************************************************************************/
public ScatterRequest withYField(String yField)
{
this.yField = yField;
return (this);
}
/*******************************************************************************
** Getter for limit.
*******************************************************************************/
public Integer getLimit()
{
return (limit);
}
/*******************************************************************************
** Fluent setter for limit.
*******************************************************************************/
public ScatterRequest withLimit(Integer limit)
{
this.limit = limit;
return (this);
}
}
@@ -0,0 +1,165 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed ScatterResult contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class ScatterResult implements Serializable
{
private Long n;
private Integer sampleSize;
private String sampling;
private List<Point> points = new java.util.ArrayList<>();
private TrendLine trend;
private Chart chart;
/*******************************************************************************
** Getter for n.
*******************************************************************************/
public Long getN()
{
return (n);
}
/*******************************************************************************
** Fluent setter for n.
*******************************************************************************/
public ScatterResult withN(Long n)
{
this.n = n;
return (this);
}
/*******************************************************************************
** Getter for sampleSize.
*******************************************************************************/
public Integer getSampleSize()
{
return (sampleSize);
}
/*******************************************************************************
** Fluent setter for sampleSize.
*******************************************************************************/
public ScatterResult withSampleSize(Integer sampleSize)
{
this.sampleSize = sampleSize;
return (this);
}
/*******************************************************************************
** Getter for sampling.
*******************************************************************************/
public String getSampling()
{
return (sampling);
}
/*******************************************************************************
** Fluent setter for sampling.
*******************************************************************************/
public ScatterResult withSampling(String sampling)
{
this.sampling = sampling;
return (this);
}
/*******************************************************************************
** Getter for points.
*******************************************************************************/
public List<Point> getPoints()
{
return (points);
}
/*******************************************************************************
** Fluent setter for points.
*******************************************************************************/
public ScatterResult withPoints(List<Point> points)
{
this.points = points;
return (this);
}
/*******************************************************************************
** Getter for trend.
*******************************************************************************/
public TrendLine getTrend()
{
return (trend);
}
/*******************************************************************************
** Fluent setter for trend.
*******************************************************************************/
public ScatterResult withTrend(TrendLine trend)
{
this.trend = trend;
return (this);
}
/*******************************************************************************
** Getter for chart.
*******************************************************************************/
public Chart getChart()
{
return (chart);
}
/*******************************************************************************
** Fluent setter for chart.
*******************************************************************************/
public ScatterResult withChart(Chart chart)
{
this.chart = chart;
return (this);
}
}
@@ -0,0 +1,121 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed ShiftBucket contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class ShiftBucket implements Serializable
{
private Serializable value;
private String label;
private Boolean complete = false;
private List<Metric> metrics = new java.util.ArrayList<>();
/*******************************************************************************
** Getter for value.
*******************************************************************************/
public Serializable getValue()
{
return (value);
}
/*******************************************************************************
** Fluent setter for value.
*******************************************************************************/
public ShiftBucket withValue(Serializable value)
{
this.value = value;
return (this);
}
/*******************************************************************************
** Getter for label.
*******************************************************************************/
public String getLabel()
{
return (label);
}
/*******************************************************************************
** Fluent setter for label.
*******************************************************************************/
public ShiftBucket withLabel(String label)
{
this.label = label;
return (this);
}
/*******************************************************************************
** Getter for complete.
*******************************************************************************/
public Boolean getComplete()
{
return (complete);
}
/*******************************************************************************
** Fluent setter for complete.
*******************************************************************************/
public ShiftBucket withComplete(Boolean complete)
{
this.complete = complete;
return (this);
}
/*******************************************************************************
** Getter for metrics.
*******************************************************************************/
public List<Metric> getMetrics()
{
return (metrics);
}
/*******************************************************************************
** Fluent setter for metrics.
*******************************************************************************/
public ShiftBucket withMetrics(List<Metric> metrics)
{
this.metrics = metrics;
return (this);
}
}
@@ -0,0 +1,168 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
/*******************************************************************************
** Typed ShiftRequest contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class ShiftRequest implements AnalysisRequest
{
private String tableName;
private QQueryFilter filter;
private Boolean exact = true;
private String field;
private String dateField;
private String bucket = "MONTH";
/*******************************************************************************
** Getter for tableName.
*******************************************************************************/
@Override
public String getTableName()
{
return (tableName);
}
/*******************************************************************************
** Fluent setter for tableName.
*******************************************************************************/
public ShiftRequest withTableName(String tableName)
{
this.tableName = tableName;
return (this);
}
/*******************************************************************************
** Getter for filter.
*******************************************************************************/
@Override
public QQueryFilter getFilter()
{
return (filter);
}
/*******************************************************************************
** Fluent setter for filter.
*******************************************************************************/
public ShiftRequest withFilter(QQueryFilter filter)
{
this.filter = filter;
return (this);
}
/*******************************************************************************
** Getter for exact.
*******************************************************************************/
@Override
public Boolean getExact()
{
return (exact);
}
/*******************************************************************************
** Fluent setter for exact.
*******************************************************************************/
public ShiftRequest withExact(Boolean exact)
{
this.exact = exact;
return (this);
}
/*******************************************************************************
** Getter for field.
*******************************************************************************/
public String getField()
{
return (field);
}
/*******************************************************************************
** Fluent setter for field.
*******************************************************************************/
public ShiftRequest withField(String field)
{
this.field = field;
return (this);
}
/*******************************************************************************
** Getter for dateField.
*******************************************************************************/
public String getDateField()
{
return (dateField);
}
/*******************************************************************************
** Fluent setter for dateField.
*******************************************************************************/
public ShiftRequest withDateField(String dateField)
{
this.dateField = dateField;
return (this);
}
/*******************************************************************************
** Getter for bucket.
*******************************************************************************/
public String getBucket()
{
return (bucket);
}
/*******************************************************************************
** Fluent setter for bucket.
*******************************************************************************/
public ShiftRequest withBucket(String bucket)
{
this.bucket = bucket;
return (this);
}
}
@@ -0,0 +1,121 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed ShiftResult contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class ShiftResult implements Serializable
{
private List<ShiftBucket> buckets = new java.util.ArrayList<>();
private Metric psi;
private String sentence;
private Chart chart;
/*******************************************************************************
** Getter for buckets.
*******************************************************************************/
public List<ShiftBucket> getBuckets()
{
return (buckets);
}
/*******************************************************************************
** Fluent setter for buckets.
*******************************************************************************/
public ShiftResult withBuckets(List<ShiftBucket> buckets)
{
this.buckets = buckets;
return (this);
}
/*******************************************************************************
** Getter for psi.
*******************************************************************************/
public Metric getPsi()
{
return (psi);
}
/*******************************************************************************
** Fluent setter for psi.
*******************************************************************************/
public ShiftResult withPsi(Metric psi)
{
this.psi = psi;
return (this);
}
/*******************************************************************************
** Getter for sentence.
*******************************************************************************/
public String getSentence()
{
return (sentence);
}
/*******************************************************************************
** Fluent setter for sentence.
*******************************************************************************/
public ShiftResult withSentence(String sentence)
{
this.sentence = sentence;
return (this);
}
/*******************************************************************************
** Getter for chart.
*******************************************************************************/
public Chart getChart()
{
return (chart);
}
/*******************************************************************************
** Fluent setter for chart.
*******************************************************************************/
public ShiftResult withChart(Chart chart)
{
this.chart = chart;
return (this);
}
}
@@ -0,0 +1,186 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed Significance contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class Significance implements Serializable
{
private String test;
private Double statistic;
private Double df;
private Double pValue;
private Boolean applicable = false;
private String sentence;
private Double cramersV;
/*******************************************************************************
** Getter for test.
*******************************************************************************/
public String getTest()
{
return (test);
}
/*******************************************************************************
** Fluent setter for test.
*******************************************************************************/
public Significance withTest(String test)
{
this.test = test;
return (this);
}
/*******************************************************************************
** Getter for statistic.
*******************************************************************************/
public Double getStatistic()
{
return (statistic);
}
/*******************************************************************************
** Fluent setter for statistic.
*******************************************************************************/
public Significance withStatistic(Double statistic)
{
this.statistic = statistic;
return (this);
}
/*******************************************************************************
** Getter for df.
*******************************************************************************/
public Double getDf()
{
return (df);
}
/*******************************************************************************
** Fluent setter for df.
*******************************************************************************/
public Significance withDf(Double df)
{
this.df = df;
return (this);
}
/*******************************************************************************
** Getter for pValue.
*******************************************************************************/
public Double getPValue()
{
return (pValue);
}
/*******************************************************************************
** Fluent setter for pValue.
*******************************************************************************/
public Significance withPValue(Double pValue)
{
this.pValue = pValue;
return (this);
}
/*******************************************************************************
** Getter for applicable.
*******************************************************************************/
public Boolean getApplicable()
{
return (applicable);
}
/*******************************************************************************
** Fluent setter for applicable.
*******************************************************************************/
public Significance withApplicable(Boolean applicable)
{
this.applicable = applicable;
return (this);
}
/*******************************************************************************
** Getter for sentence.
*******************************************************************************/
public String getSentence()
{
return (sentence);
}
/*******************************************************************************
** Fluent setter for sentence.
*******************************************************************************/
public Significance withSentence(String sentence)
{
this.sentence = sentence;
return (this);
}
/*******************************************************************************
** Getter for cramersV.
*******************************************************************************/
public Double getCramersV()
{
return (cramersV);
}
/*******************************************************************************
** Fluent setter for cramersV.
*******************************************************************************/
public Significance withCramersV(Double cramersV)
{
this.cramersV = cramersV;
return (this);
}
}
@@ -0,0 +1,98 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.result;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/*******************************************************************************
** Typed TrendLine contract for comparison and relationship analysis.
*******************************************************************************/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
public class TrendLine implements Serializable
{
private Double slope;
private Double intercept;
private Double r;
/*******************************************************************************
** Getter for slope.
*******************************************************************************/
public Double getSlope()
{
return (slope);
}
/*******************************************************************************
** Fluent setter for slope.
*******************************************************************************/
public TrendLine withSlope(Double slope)
{
this.slope = slope;
return (this);
}
/*******************************************************************************
** Getter for intercept.
*******************************************************************************/
public Double getIntercept()
{
return (intercept);
}
/*******************************************************************************
** Fluent setter for intercept.
*******************************************************************************/
public TrendLine withIntercept(Double intercept)
{
this.intercept = intercept;
return (this);
}
/*******************************************************************************
** Getter for r.
*******************************************************************************/
public Double getR()
{
return (r);
}
/*******************************************************************************
** Fluent setter for r.
*******************************************************************************/
public TrendLine withR(Double r)
{
this.r = r;
return (this);
}
}
@@ -441,7 +441,8 @@ public class AnalysisRunService
identity.put("zone", ValueUtils.getSessionOrInstanceZoneId().getId());
identity.put("config", service.getConfigResolver().resolve(request.getTableName()));
identity.put("fields", service.capabilities(request.getTableName()).getFields().stream().sorted().toList());
identity.put("policy", com.kingsrook.qbits.dataanalysis.engine.AnalysisLabels.policy(request.getTableName()));
identity.put("fieldAccess", digest(service.fieldAccessFingerprint(request.getTableName())));
identity.put("policy", service.fieldAccessPolicy(request.getTableName()));
identity.put("backendVariants", QContext.getQSession().getBackendVariants());
try
{
@@ -0,0 +1,304 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.saved;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.kingsrook.qbits.dataanalysis.result.Metric;
import com.kingsrook.qbits.dataanalysis.result.PivotHeader;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.reporting.ExportInput;
import com.kingsrook.qqq.backend.core.model.actions.reporting.ReportDestination;
import com.kingsrook.qqq.backend.core.model.actions.reporting.ReportFormat;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.reporting.QReportField;
import com.kingsrook.qqq.backend.core.model.metadata.reporting.QReportView;
import com.kingsrook.qqq.backend.core.model.metadata.reporting.ReportType;
/*******************************************************************************
** Export already-authorized typed results using core CSV and XLSX streamers.
*******************************************************************************/
public final class AnalysisExport
{
/*******************************************************************************
** Utility class.
*******************************************************************************/
private AnalysisExport()
{
}
/*******************************************************************************
** A result table, also reused by scheduled HTML summaries.
*******************************************************************************/
public record ResultTable(List<String> columns, List<List<String>> rows)
{
}
/*******************************************************************************
** Download bytes and metadata; filenames are fixed rather than user supplied.
*******************************************************************************/
public record File(byte[] bytes, String mimeType, String filename)
{
}
/*******************************************************************************
** Accept only the two documented export formats.
*******************************************************************************/
public static ReportFormat format(String value) throws QBadRequestException
{
if("csv".equalsIgnoreCase(value))
{
return (ReportFormat.CSV);
}
if("xlsx".equalsIgnoreCase(value))
{
return (ReportFormat.XLSX);
}
throw new QBadRequestException("format must be csv or xlsx.");
}
/*******************************************************************************
** Core's report streamers accept computed records without a source-table query.
*******************************************************************************/
public static File file(SavedResult result, String format) throws QException
{
ReportFormat type = format(format);
ResultTable table = table(result);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
var destination = new ReportDestination().withReportFormat(type).withReportOutputStream(bytes);
var view = new QReportView().withName("analysis").withLabel("Analysis").withType(ReportType.TABLE);
List<QFieldMetaData> fields = new ArrayList<>();
for(int i = 0; i < table.columns().size(); i++)
{
fields.add(new QFieldMetaData("c" + i, QFieldType.STRING).withLabel(table.columns().get(i)));
view.withColumn(new QReportField("c" + i).withLabel(table.columns().get(i)).withType(QFieldType.STRING));
}
var streamer = type.newReportStreamer();
streamer.preRun(destination, List.of(view));
streamer.start(new ExportInput().withReportDestination(destination), fields, "Analysis", view);
List<QRecord> records = new ArrayList<>();
for(List<String> row : table.rows())
{
QRecord record = new QRecord();
for(int i = 0; i < row.size(); i++)
{
record.withValue("c" + i, row.get(i));
}
records.add(record);
}
for(String warning : result.warnings())
{
records.add(new QRecord().withValue("c0", "Warning: " + warning));
}
streamer.addRecords(records);
streamer.finish();
return (new File(bytes.toByteArray(), type.getMimeType(), "analysis." + type.getExtension()));
}
/*******************************************************************************
** Preserve formatted values and suppressed cells; never export underlying raw data.
*******************************************************************************/
public static ResultTable table(SavedResult result)
{
List<String> columns = new ArrayList<>(List.of("Section", "Metric", "Value"));
List<List<String>> rows = new ArrayList<>();
if(result.columnProfile() != null)
{
var p = result.columnProfile();
metrics(rows, "Counts", p.getCounts());
if(p.getNumeric() != null)
{
metrics(rows, "Numeric", p.getNumeric().getMetrics());
}
if(p.getText() != null)
{
metrics(rows, "Text", p.getText().getMetrics());
}
if(p.getDates() != null)
{
metrics(rows, "Dates", p.getDates().getMetrics());
}
if(p.getBooleans() != null)
{
metrics(rows, "Boolean", p.getBooleans());
}
p.getTopValues().forEach(v -> rows.add(row("Top values", v.getLabel(), v.getCount())));
}
else if(result.tableProfile() != null)
{
var p = result.tableProfile();
metrics(rows, "Table", List.of(p.getRowCount()));
for(var field : p.getFields())
{
rows.add(row(field.getLabel(), "Completeness", field.getCompleteness()));
rows.add(row(field.getLabel(), "Distinct", field.getDistinct()));
rows.add(row(field.getLabel(), "Uniqueness", field.getUniqueness()));
}
}
else if(result.pivot() != null)
{
var p = result.pivot();
columns = new ArrayList<>(List.of("Row"));
for(var headers : p.getColumnHeaders())
{
for(var measure : p.getMeasures())
{
columns.add(label(headers) + " / " + measure.getLabel());
}
}
for(int r = 0; r < p.getRowHeaders().size(); r++)
{
List<String> row = new ArrayList<>();
row.add(label(p.getRowHeaders().get(r)));
for(int c = 0; c < p.getColumnHeaders().size(); c++)
{
final int ri = r;
final int ci = c;
var cell = p.getCells().stream().filter(x -> x.getRowIndex() == ri && x.getColumnIndex() == ci).findFirst();
for(int m = 0; m < p.getMeasures().size(); m++)
{
row.add(cell.isPresent() ? value(cell.get().getValues().get(m)) : "");
}
}
rows.add(row);
}
}
else if(result.compare() != null)
{
columns = List.of("Field", "Value", "Metric", "A", "B", "Delta", "Percent delta");
for(var field : result.compare().getFields())
{
for(var comparison : field.getValues())
{
for(var metric : comparison.getSideA().getMetrics())
{
var b = comparison.getSideB().getMetrics().stream().filter(m -> Objects.equals(m.getKey(), metric.getKey())).findFirst().orElse(null);
rows.add(row(field.getField(), comparison.getLabel(), metric.getLabel(), value(metric), value(b), value(comparison.getDelta()), value(comparison.getPercentDelta())));
}
}
}
}
else if(result.correlation() != null)
{
columns = List.of("X", "Y", "Paired rows", "Correlation");
result.correlation().getCells().forEach(c -> rows.add(row(c.getXField(), c.getYField(), c.getN(), c.getR())));
}
else if(result.crosstab() != null)
{
columns = List.of("Row", "Column", "Count", "Row share", "Column share");
var p = result.crosstab();
p.getCells().forEach(c -> rows.add(row(p.getRows().get(c.getRowIndex()).getLabel(), p.getColumns().get(c.getColumnIndex()).getLabel(),
value(c.getCount()), value(c.getRowShare()), value(c.getColumnShare()))));
}
else if(result.shift() != null)
{
for(var bucket : result.shift().getBuckets())
{
metrics(rows, bucket.getLabel(), bucket.getMetrics());
}
if(result.shift().getPsi() != null)
{
metrics(rows, "Shift", List.of(result.shift().getPsi()));
}
}
return (new ResultTable(columns, rows));
}
/*******************************************************************************
** Headline metrics shared by standard chart widgets and email summaries.
*******************************************************************************/
public static List<Metric> headlines(SavedResult result)
{
List<Metric> metrics = new ArrayList<>();
if(result.columnProfile() != null)
{
metrics.addAll(result.columnProfile().getCounts());
if(result.columnProfile().getNumeric() != null)
{
metrics.addAll(result.columnProfile().getNumeric().getMetrics().stream()
.filter(m -> List.of("mean", "median", "min", "max").contains(m.getKey())).toList());
}
}
else if(result.tableProfile() != null)
{
metrics.add(result.tableProfile().getRowCount());
}
else if(result.pivot() != null)
{
metrics.addAll(result.pivot().getGrandTotals());
}
else if(result.compare() != null)
{
result.compare().getFields().stream().limit(4).forEach(f -> f.getValues().stream().limit(1).forEach(v -> metrics.add(v.getDelta())));
}
else if(result.shift() != null)
{
metrics.add(result.shift().getPsi());
}
else
{
int count = result.correlation() != null ? result.correlation().getFields().size() : result.crosstab() != null ? result.crosstab().getCells().size() : 0;
if(result.correlation() != null || result.crosstab() != null)
{
metrics.add(new Metric().withKey("visible").withLabel(result.correlation() != null ? "Numeric fields" : "Visible combinations")
.withValue(count).withValueType(com.kingsrook.qbits.dataanalysis.result.ValueType.COUNT).withFormatted(String.valueOf(count)));
}
}
return (metrics.stream().filter(Objects::nonNull).toList());
}
/*******************************************************************************
** No nulls in report cells; unknown and suppressed are distinct from zero.
*******************************************************************************/
private static List<String> row(Object... values)
{
return (java.util.Arrays.stream(values).map(v -> v == null ? "" : String.valueOf(v)).toList());
}
/*******************************************************************************
** Render a tuple using the engine's already-authorized display labels.
*******************************************************************************/
private static String label(List<PivotHeader> headers)
{
return (headers.stream().map(PivotHeader::getLabel).collect(java.util.stream.Collectors.joining(" / ")));
}
/*******************************************************************************
** Metrics always use their semantic formatted value.
*******************************************************************************/
public static String value(Metric metric)
{
return (metric == null ? "" : Boolean.TRUE.equals(metric.getSuppressed()) ? "Suppressed" : Objects.toString(metric.getFormatted(), ""));
}
/*******************************************************************************
** Profile metrics become one row per headline statistic.
*******************************************************************************/
private static void metrics(List<List<String>> rows, String section, List<Metric> metrics)
{
metrics.forEach(m -> rows.add(row(section, m.getLabel(), value(m))));
}
}
@@ -0,0 +1,151 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.saved;
import java.io.Serializable;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.kingsrook.qbits.dataanalysis.DataAnalysisService;
import com.kingsrook.qbits.dataanalysis.engine.DrillFilters;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qbits.dataanalysis.watch.WatchRecords;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionEnforcement;
import com.kingsrook.qqq.backend.core.actions.tables.DeleteAction;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
import com.kingsrook.qqq.backend.core.model.actions.tables.delete.DeleteInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
/*******************************************************************************
** Saved definitions always execute in the calling context, including shared reads.
*******************************************************************************/
public class SavedAnalyses
{
private final DataAnalysisService service;
/*******************************************************************************
** Use the instance's existing engine and cache policy.
*******************************************************************************/
public SavedAnalyses(DataAnalysisService service)
{
this.service = service;
}
/*******************************************************************************
** Standard core READ and record locks precede source-table authorization.
*******************************************************************************/
public SavedResult run(Serializable id) throws QException
{
return (SavedDefinition.parse(WatchRecords.get(DataAnalysisTables.SAVED, id)).run(service, false));
}
/*******************************************************************************
** Readable list rows contain presentation metadata, never cached owner results.
*******************************************************************************/
public record Entry(Serializable id, String name, String kind, String tableName, String tableLabel, String owner,
Boolean shared, Boolean starred, Instant updated)
{
}
/*******************************************************************************
** Only stars belonging to this viewer decorate their core-visible saved rows.
*******************************************************************************/
public List<Entry> list() throws QException
{
Set<Serializable> stars = new HashSet<>();
for(QRecord row : query(DataAnalysisTables.SAVED_STAR, DrillFilters.condition("user_id", QCriteriaOperator.EQUALS, user())))
{
stars.add(row.getValue("saved_id"));
}
List<Entry> result = new ArrayList<>();
for(QRecord row : query(DataAnalysisTables.SAVED, new QQueryFilter().withOrderBy(new QFilterOrderBy("modifyDate", false))))
{
String tableName = row.getValueString("table_name");
var table = QContext.getQInstance().getTable(tableName);
result.add(new Entry(row.getValue("id"), row.getValueString("name"), row.getValueString("kind"), tableName,
table == null ? tableName : table.getLabel(), row.getValueString("owner_user_id"), row.getValueBoolean("shared"),
stars.contains(row.getValue("id")), row.getValueInstant("modifyDate")));
}
return (result);
}
/*******************************************************************************
** Idempotent per-runtime PUT/DELETE, with standard insert/delete permissions.
*******************************************************************************/
public synchronized Boolean star(Serializable id, boolean starred) throws QException
{
WatchRecords.get(DataAnalysisTables.SAVED, id);
QQueryFilter filter = DrillFilters.and(DrillFilters.condition("saved_id", QCriteriaOperator.EQUALS, id),
DrillFilters.condition("user_id", QCriteriaOperator.EQUALS, user()));
List<QRecord> existing = query(DataAnalysisTables.SAVED_STAR, filter);
if(starred && existing.isEmpty())
{
InsertInput input = new InsertInput(DataAnalysisTables.SAVED_STAR).withRecords(List.of(new QRecord().withValue("saved_id", id).withValue("user_id", user())));
input.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
QRecord record = new InsertAction().execute(input).getRecords().getFirst();
if(record.getErrors() != null && !record.getErrors().isEmpty())
{
throw new QException("Could not save the star.");
}
}
else if(!starred && !existing.isEmpty())
{
DeleteInput input = new DeleteInput(DataAnalysisTables.SAVED_STAR).withPrimaryKeys(existing.stream().map(r -> r.getValue("id")).toList());
input.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
new DeleteAction().execute(input);
}
return (starred);
}
/*******************************************************************************
** Shared enforced query helper for visible records, not a security-filter layer.
*******************************************************************************/
public static List<QRecord> query(String table, QQueryFilter filter) throws QException
{
QueryInput input = new QueryInput(table).withShouldFetchHeavyFields(true).withFilter(filter);
input.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
return (new QueryAction().execute(input).getRecords());
}
/*******************************************************************************
** An authenticated identity is required even in an unprotected host app.
*******************************************************************************/
public static String user() throws QPermissionDeniedException
{
var session = QContext.getQSession();
if(session == null || session.getUser() == null || session.getUser().getIdReference() == null)
{
throw new QPermissionDeniedException("Sign in to use saved analyses.");
}
return (session.getUser().getIdReference());
}
}
@@ -0,0 +1,91 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.saved;
import java.util.List;
import java.util.Optional;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qbits.dataanalysis.permissions.DataAnalysisPermissions;
import com.kingsrook.qbits.dataanalysis.watch.WatchRecords;
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizerInterface;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.statusmessages.BadInputStatusMessage;
/*******************************************************************************
** Validate all core CRUD and maintain the read-lock projection atomically.
*******************************************************************************/
public class SavedCustomizer implements TableCustomizerInterface
{
/*******************************************************************************
** Inserts cannot forge an owner or the derived shared-read key.
*******************************************************************************/
@Override
public List<QRecord> preInsert(InsertInput input, List<QRecord> records, boolean preview) throws QException
{
for(QRecord row : records)
{
validate(row, row);
}
return (records);
}
/*******************************************************************************
** Merge partial edits so changing shared or owner also changes the read lock.
*******************************************************************************/
@Override
public List<QRecord> preUpdate(UpdateInput input, List<QRecord> records, boolean preview, Optional<List<QRecord>> oldRecords) throws QException
{
for(QRecord patch : records)
{
QRecord merged = new QRecord(WatchRecords.get(DataAnalysisTables.SAVED, patch.getValue("id")));
merged.getValues().putAll(patch.getValues());
validate(patch, merged);
}
return (records);
}
/*******************************************************************************
** Report a plain validation message on the standard record editor.
*******************************************************************************/
private void validate(QRecord output, QRecord merged)
{
try
{
String owner = merged.getValueString("owner_user_id");
var session = QContext.getQSession();
if(owner == null || owner.isBlank() || session == null || (!(session.getSecurityKeyValues() != null && session.getSecurityKeyValues().getOrDefault(DataAnalysisPermissions.ADMIN, List.of()).contains(true))
&& (session.getUser() == null || !owner.equals(session.getUser().getIdReference()))))
{
throw new QException("Only an administrator may assign another analysis owner.");
}
SavedDefinition.parse(merged);
output.withValue("read_owner_user_id", Boolean.TRUE.equals(merged.getValueBoolean("shared")) ? null : owner);
}
catch(QException e)
{
output.addError(new BadInputStatusMessage(e.getMessage()));
}
}
}
@@ -0,0 +1,313 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.saved;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.kingsrook.qbits.dataanalysis.DataAnalysisService;
import com.kingsrook.qbits.dataanalysis.result.AnalysisRequest;
import com.kingsrook.qbits.dataanalysis.result.ColumnProfileRequest;
import com.kingsrook.qbits.dataanalysis.result.CompareRequest;
import com.kingsrook.qbits.dataanalysis.result.CorrelationRequest;
import com.kingsrook.qbits.dataanalysis.result.CrosstabRequest;
import com.kingsrook.qbits.dataanalysis.result.PivotRequest;
import com.kingsrook.qbits.dataanalysis.result.ShiftRequest;
import com.kingsrook.qbits.dataanalysis.result.TableProfileRequest;
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.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
/*******************************************************************************
** One parser for persisted definitions, exports, schedules and SQL requests.
*******************************************************************************/
public record SavedDefinition(String kind, AnalysisRequest request)
{
private static final Map<String, Class<? extends AnalysisRequest>> TYPES = Map.of(
"COLUMN_PROFILE", ColumnProfileRequest.class, "TABLE_PROFILE", TableProfileRequest.class,
"PIVOT", PivotRequest.class, "COMPARE", CompareRequest.class, "CORRELATION", CorrelationRequest.class,
"CROSSTAB", CrosstabRequest.class, "SHIFT", ShiftRequest.class);
private static final Set<String> FIELD_KEYS = Set.of("fieldName", "field", "dateField", "rowField", "columnField");
public static final String FIELD_WARNING = "Some fields are not available to you";
/*******************************************************************************
** The definition owns the typed filter; legacy filter_json remains supported.
*******************************************************************************/
public static SavedDefinition parse(QRecord row) throws QException
{
Map<String, Object> body = object(row.getValueString("definition_json"));
if(body.get("filter") == null && row.getValueString("filter_json") != null)
{
body.put("filter", object(row.getValueString("filter_json")));
}
return (parse(row.getValueString("kind"), row.getValueString("table_name"), body));
}
/*******************************************************************************
** Reject malformed JSON with a plain, stable message.
*******************************************************************************/
@SuppressWarnings("unchecked")
public static Map<String, Object> object(String json) throws QBadRequestException
{
try
{
Object value = JsonUtils.toObject(json, Object.class);
if(value instanceof Map<?, ?> map)
{
return (new LinkedHashMap<>((Map<String, Object>) map));
}
}
catch(Exception expected)
{
// Normalize parser diagnostics; never return raw saved JSON in errors.
}
throw new QBadRequestException("definition_json must be a JSON object.");
}
/*******************************************************************************
** Validate metadata existence before saving, without querying source records.
*******************************************************************************/
public static SavedDefinition parse(String kind, String table, Map<String, Object> body) throws QException
{
if(!TYPES.containsKey(kind == null ? "" : kind))
{
throw new QBadRequestException("Choose a supported analysis kind.");
}
if(table == null || QContext.getQInstance().getTable(table) == null)
{
throw new QBadRequestException("Choose an existing analysis table.");
}
if(body.get("tableName") != null && !table.equals(body.get("tableName")))
{
throw new QBadRequestException("The definition table must match table_name.");
}
Map<String, Object> copy = new LinkedHashMap<>(body);
copy.put("tableName", table);
try
{
validateJson(copy);
AnalysisRequest request = JsonUtils.toObject(JsonUtils.toJson(copy), TYPES.get(kind));
requireShape(request);
for(String field : fields(copy))
{
String[] parts = field.split("\\.", 2);
var metadata = QContext.getQInstance().getTable(parts.length == 2 ? parts[0] : table);
if(metadata == null || metadata.getField(parts.length == 2 ? parts[1] : field) == null)
{
throw new IllegalArgumentException("A definition field does not exist.");
}
}
return (new SavedDefinition(kind, request));
}
catch(Exception e)
{
throw new QBadRequestException("Invalid analysis definition: " + (e instanceof IllegalArgumentException ? e.getMessage() : "check the request fields and types."));
}
}
/*******************************************************************************
** Reject coercible scalar types and malformed predicates before Jackson conversion.
*******************************************************************************/
private static void validateJson(Object value)
{
if(value instanceof Map<?, ?> map)
{
for(var entry : map.entrySet())
{
String name = String.valueOf(entry.getKey());
Object item = entry.getValue();
if(item == null)
{
continue;
}
if((FIELD_KEYS.contains(name) || Set.of("tableName", "bucket", "operator").contains(name)) && !(item instanceof String))
{
throw new IllegalArgumentException("Field names and operators must be strings.");
}
if(name.equals("fields") && (!(item instanceof List<?> list) || list.stream().anyMatch(v -> !(v instanceof String))))
{
throw new IllegalArgumentException("fields must be an array of field names.");
}
if(Set.of("filter", "filterA", "filterB").contains(name) && !(item instanceof Map<?, ?>))
{
throw new IllegalArgumentException("Filters must be query filter objects.");
}
if(name.equals("criteria") && (!(item instanceof List<?> list) || list.stream().anyMatch(v -> !(v instanceof Map<?, ?> c)
|| !(c.get("fieldName") instanceof String) || !(c.get("operator") instanceof String))))
{
throw new IllegalArgumentException("Filter criteria require a field and operator.");
}
if(Set.of("exact", "showTotals").contains(name) && !(item instanceof Boolean))
{
throw new IllegalArgumentException("Flags must be booleans.");
}
validateJson(item);
}
}
else if(value instanceof List<?> list)
{
list.forEach(SavedDefinition::validateJson);
}
}
/*******************************************************************************
** Required selections must not turn an invalid draft into a different query.
*******************************************************************************/
private static void requireShape(AnalysisRequest request)
{
boolean valid = switch(request)
{
case ColumnProfileRequest r -> r.getFieldName() != null;
case TableProfileRequest r -> r.getFields() == null || !r.getFields().isEmpty();
case CompareRequest r -> r.getFields() != null && !r.getFields().isEmpty();
case CorrelationRequest r -> r.getFields() != null && r.getFields().size() >= 2;
case CrosstabRequest r -> r.getRowField() != null && r.getColumnField() != null;
case ShiftRequest r -> r.getField() != null && r.getDateField() != null;
case PivotRequest r -> r.getValues() != null && !r.getValues().isEmpty()
&& r.getValues().stream().allMatch(v -> v.getOperator() != null && (v.getOperator().name().equals("COUNT") || v.getField() != null));
default -> false;
};
if(!valid)
{
throw new IllegalArgumentException("Choose the fields and measures required by this analysis kind.");
}
}
/*******************************************************************************
** Include selected and filter fields, including both compare populations.
*******************************************************************************/
public static Set<String> fields(Object value)
{
Set<String> names = new LinkedHashSet<>();
if(value instanceof Map<?, ?> map)
{
for(var entry : map.entrySet())
{
if(FIELD_KEYS.contains(entry.getKey()) && entry.getValue() instanceof String name)
{
names.add(name);
}
else if("fields".equals(entry.getKey()) && entry.getValue() instanceof List<?> list)
{
list.forEach(name -> names.add((String) name));
}
else
{
names.addAll(fields(entry.getValue()));
}
}
}
else if(value instanceof List<?> list)
{
list.forEach(item -> names.addAll(fields(item)));
}
return (names);
}
/*******************************************************************************
** A fresh tree makes field reduction request-local and cannot change storage.
*******************************************************************************/
public Map<String, Object> body() throws QException
{
return (object(JsonUtils.toJson(request)));
}
/*******************************************************************************
** Filter rights are not weakened: an unavailable predicate prevents execution.
** Required denied axes return an empty typed envelope rather than change meaning.
*******************************************************************************/
@SuppressWarnings("unchecked")
public SavedResult run(DataAnalysisService service, boolean strict) throws QException
{
service.capabilities(request.getTableName());
Map<String, Object> body = body();
Set<String> denied = new LinkedHashSet<>();
for(String field : fields(body))
{
if(!service.isAvailableField(request.getTableName(), field))
{
denied.add(field);
}
}
if(strict && !denied.isEmpty())
{
throw new QBadRequestException(FIELD_WARNING);
}
List<String> warnings = denied.isEmpty() ? List.of() : List.of(FIELD_WARNING);
for(String filter : List.of("filter", "filterA", "filterB"))
{
if(fields(body.get(filter)).stream().anyMatch(denied::contains))
{
return (SavedResult.of(kind, null, warnings));
}
}
if(body.get("fields") instanceof List<?> list)
{
body.put("fields", list.stream().filter(f -> !denied.contains(f)).toList());
}
for(String axis : List.of("rows", "columns", "values"))
{
if(body.get(axis) instanceof List<?> list)
{
body.put(axis, list.stream().filter(item -> fields(item).stream().noneMatch(denied::contains)).toList());
}
}
if(FIELD_KEYS.stream().anyMatch(key -> denied.contains(body.get(key))))
{
return (SavedResult.of(kind, null, warnings));
}
AnalysisRequest reduced;
try
{
reduced = JsonUtils.toObject(JsonUtils.toJson(body), TYPES.get(kind));
requireShape(reduced);
}
catch(Exception e)
{
return (SavedResult.of(kind, null, warnings));
}
Object result = switch(reduced)
{
case ColumnProfileRequest r ->
{
var backend = service.backend(r.getTableName());
yield service.compute(r, backend, backend.scope(r.getTableName(), r.getFilter(), Boolean.TRUE.equals(r.getExact())));
}
case TableProfileRequest r ->
{
var backend = service.backend(r.getTableName());
yield service.compute(r, backend, backend.scope(r.getTableName(), r.getFilter(), Boolean.TRUE.equals(r.getExact())));
}
case PivotRequest r -> service.pivot(r);
case CompareRequest r -> service.compare(r);
case CorrelationRequest r -> service.correlation(r);
case CrosstabRequest r -> service.crosstab(r);
case ShiftRequest r -> service.shift(r);
default -> throw new QBadRequestException("Unsupported analysis kind.");
};
return (SavedResult.of(kind, result, warnings));
}
}
@@ -0,0 +1,60 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.saved;
import java.util.List;
import com.kingsrook.qbits.dataanalysis.result.ColumnProfile;
import com.kingsrook.qbits.dataanalysis.result.CompareResult;
import com.kingsrook.qbits.dataanalysis.result.CorrelationResult;
import com.kingsrook.qbits.dataanalysis.result.CrosstabResult;
import com.kingsrook.qbits.dataanalysis.result.PivotResult;
import com.kingsrook.qbits.dataanalysis.result.ShiftResult;
import com.kingsrook.qbits.dataanalysis.result.TableProfile;
/*******************************************************************************
** Discriminated result: exactly the member named by kind is populated when runnable.
*******************************************************************************/
public record SavedResult(String kind, List<String> warnings, ColumnProfile columnProfile, TableProfile tableProfile,
PivotResult pivot, CompareResult compare, CorrelationResult correlation, CrosstabResult crosstab, ShiftResult shift)
{
/*******************************************************************************
** Preserve typed engine results without an untyped JSON payload.
*******************************************************************************/
public static SavedResult of(String kind, Object result, List<String> warnings)
{
java.util.ArrayList<String> notices = new java.util.ArrayList<>(warnings);
if(result instanceof ColumnProfile p)
{
notices.addAll(p.getWarnings());
}
else if(result instanceof TableProfile p)
{
notices.addAll(p.getWarnings());
}
else if(result instanceof PivotResult p)
{
notices.addAll(p.getWarnings());
}
return (new SavedResult(kind, notices.stream().distinct().toList(), result instanceof ColumnProfile p ? p : null, result instanceof TableProfile p ? p : null,
result instanceof PivotResult p ? p : null, result instanceof CompareResult p ? p : null,
result instanceof CorrelationResult p ? p : null, result instanceof CrosstabResult p ? p : null, result instanceof ShiftResult p ? p : null));
}
}
@@ -0,0 +1,147 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.saved;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qbits.dataanalysis.DataAnalysisService;
import com.kingsrook.qqq.backend.core.actions.interfaces.AggregateInterface;
import com.kingsrook.qqq.backend.core.actions.tables.AggregateAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.aggregate.AggregateOutput;
/*******************************************************************************
** Request-local capture of core's actual aggregate SQL, never a separate SQL planner.
*******************************************************************************/
public final class SqlHandoff
{
private static final ThreadLocal<List<Statement>> CAPTURE = new ThreadLocal<>();
private static final String NOTE = "Record security filters are applied by QQQ at run time. This SQL is for reading; ? placeholders remain bound by QQQ.";
/*******************************************************************************
** Utility class.
*******************************************************************************/
private SqlHandoff()
{
}
/*******************************************************************************
** Statement ranking prefers the main grouped matrix, then the widest metric batch.
*******************************************************************************/
private record Statement(String table, String sql, int dimensions, int measures)
{
}
/*******************************************************************************
** Transported capability, statement and security note.
*******************************************************************************/
public record Result(Boolean available, String sql, String note)
{
}
/*******************************************************************************
** Installation plus its configured access permission are both required.
*******************************************************************************/
public static boolean installedAndAllowed()
{
var instance = QContext.getQInstance();
var app = instance.getApp("sqlWorkbench");
boolean installed = app != null || instance.getTables().keySet().stream().anyMatch(t -> t.startsWith("sql_workbench_"));
String base = app != null && app.getPermissionRules() != null && app.getPermissionRules().getPermissionBaseName() != null
? app.getPermissionRules().getPermissionBaseName() : "sql_workbench";
return (installed && QContext.getQSession() != null && QContext.getQSession().hasPermission(base + ".hasAccess"));
}
/*******************************************************************************
** The backend metadata inheritance check avoids a production RDBMS dependency.
*******************************************************************************/
public static Result execute(SavedDefinition definition, DataAnalysisService service) throws QException
{
if(!installedAndAllowed())
{
return (new Result(false, null, "SQL Workbench is not installed or available to you."));
}
service.capabilities(definition.request().getTableName());
var table = QContext.getQInstance().getTable(definition.request().getTableName());
Class<?> type = QContext.getQInstance().getBackend(table.getBackendName()).getClass();
boolean rdbms = false;
while(type != null)
{
rdbms |= type.getSimpleName().equals("RDBMSBackendMetaData");
type = type.getSuperclass();
}
if(!rdbms)
{
return (new Result(false, null, "SQL is unavailable for a non-RDBMS backend."));
}
List<Statement> statements = new ArrayList<>();
CAPTURE.set(statements);
try
{
definition.run(service, true);
}
finally
{
CAPTURE.remove();
}
java.util.Comparator<Statement> ranking = List.of("PIVOT", "CROSSTAB", "SHIFT").contains(definition.kind())
? java.util.Comparator.comparingInt(Statement::dimensions).thenComparingInt(Statement::measures)
: java.util.Comparator.comparingInt(Statement::measures).thenComparingInt(s -> -s.dimensions());
Statement main = statements.stream().filter(s -> s.table().equals(table.getName())).max(ranking).orElse(null);
return (main == null ? new Result(false, null, "Core did not expose SQL for this aggregate. " + NOTE) : new Result(true, main.sql(), NOTE));
}
/*******************************************************************************
** Execute the ordinary authorized core action, then read its backend QueryStat.
** Core exposes QueryStat on the backend but not its action reference; this narrow
** bridge never changes action state, global logging, or QueryStatManager settings.
*******************************************************************************/
public static AggregateOutput aggregate(AggregateInput input) throws QException
{
if(CAPTURE.get() != null)
{
input.setTableMetaData(input.getTable().clone().withCapability(com.kingsrook.qqq.backend.core.model.metadata.tables.Capability.QUERY_STATS));
}
AggregateAction action = new AggregateAction();
AggregateOutput output = action.execute(input);
if(CAPTURE.get() != null)
{
try
{
Field field = AggregateAction.class.getDeclaredField("aggregateInterface");
field.setAccessible(true);
var stat = ((AggregateInterface) field.get(action)).getQueryStat();
if(stat != null && stat.getQueryText() != null)
{
CAPTURE.get().add(new Statement(input.getTableName(), stat.getQueryText(), input.getGroupBys().size(), input.getAggregates().size()));
}
}
catch(ReflectiveOperationException | RuntimeException expected)
{
// A future core change makes handoff unavailable rather than invent SQL.
}
}
return (output);
}
}
@@ -0,0 +1,90 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2026. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.schedule;
import java.util.function.Supplier;
import com.kingsrook.qbits.dataanalysis.DataAnalysisQBitConfig;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.modules.authentication.QAuthenticationModuleDispatcher;
import com.kingsrook.qqq.backend.core.serviceidentity.ServiceIdentities;
/*******************************************************************************
** Sessions for scheduled analysis work. With the host's data-analysis service
** principal declared (QQQ service identities): inventory runs as the
** principal, and owner or recipient runs go on their behalf through it (their
** current access intersected with the principal's). Without it: the previous
** local sessions (single-node default unchanged). Never a system session.
*******************************************************************************/
public final class AnalysisSessions
{
/*******************************************************************************
** Utility class.
*******************************************************************************/
private AnalysisSessions()
{
}
/*******************************************************************************
** The session for schedule/watch inventory and status updates.
*******************************************************************************/
public static QSession maintenance(DataAnalysisQBitConfig config, Supplier<QSession> legacy) throws QException
{
if(usesPrincipal(config))
{
return (ServiceIdentities.session(QContext.getQInstance(), config.getServicePrincipal()));
}
return (legacy.get());
}
/*******************************************************************************
** The session for running as a user (owner or recipient).
*******************************************************************************/
public static QSession forUser(DataAnalysisQBitConfig config, String userId) throws QException
{
if(config.getOwnerSessionSupplier() != null)
{
return (config.getOwnerSessionSupplier().apply(userId));
}
if(usesPrincipal(config))
{
return (ServiceIdentities.sessionOnBehalfOf(QContext.getQInstance(), config.getServicePrincipal(), userId));
}
return (new QAuthenticationModuleDispatcher().getQModule(QContext.getQInstance().getAuthentication()).createAutomatedSessionForUser(QContext.getQInstance(), userId));
}
/*******************************************************************************
** Whether the host declared the configured principal.
*******************************************************************************/
private static boolean usesPrincipal(DataAnalysisQBitConfig config)
{
return (config.getServicePrincipal() != null && ServiceIdentities.isDeclared(QContext.getQInstance(), config.getServicePrincipal()));
}
}
@@ -0,0 +1,116 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.schedule;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qbits.dataanalysis.saved.SavedDefinition;
import com.kingsrook.qbits.dataanalysis.watch.WatchRecords;
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizerInterface;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.statusmessages.BadInputStatusMessage;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
/*******************************************************************************
** Core CRUD validates recipients and computes the next occurrence on configuration edits.
*******************************************************************************/
public class ScheduleCustomizer implements TableCustomizerInterface
{
private static final Set<String> CONFIG = Set.of("saved_id", "cron", "frequency", "day", "time", "time_zone", "enabled", "recipients", "format");
/*******************************************************************************
** Disabled empty drafts may be completed later.
*******************************************************************************/
@Override
public List<QRecord> preInsert(InsertInput input, List<QRecord> records, boolean preview) throws QException
{
for(QRecord row : records)
{
validate(row, row);
}
return (records);
}
/*******************************************************************************
** Status-only scheduler writes do not move the next occurrence twice.
*******************************************************************************/
@Override
public List<QRecord> preUpdate(UpdateInput input, List<QRecord> records, boolean preview, Optional<List<QRecord>> oldRecords) throws QException
{
for(QRecord patch : records)
{
if(patch.getValues().keySet().stream().anyMatch(CONFIG::contains))
{
QRecord row = new QRecord(WatchRecords.get(DataAnalysisTables.SCHEDULE, patch.getValue("id")));
row.getValues().putAll(patch.getValues());
validate(patch, row);
}
}
return (records);
}
/*******************************************************************************
** User ids are stored as a JSON array, not an unchecked email recipient list.
*******************************************************************************/
public static List<String> recipients(QRecord row) throws QException
{
try
{
Object value = JsonUtils.toObject(row.getValueString("recipients"), Object.class);
if(value instanceof List<?> list && !list.isEmpty() && list.size() <= 100
&& list.stream().allMatch(v -> v instanceof String s && !s.isBlank()))
{
return (list.stream().map(String.class::cast).distinct().toList());
}
}
catch(Exception expected)
{
// Use the same plain error for JSON and shape errors.
}
throw new QException("Recipients must be a JSON array of 1 to 100 user ids.");
}
/*******************************************************************************
** Scheduling references a real, visible saved analysis.
*******************************************************************************/
private void validate(QRecord output, QRecord row)
{
try
{
SavedDefinition.parse(WatchRecords.get(DataAnalysisTables.SAVED, row.getValue("saved_id")));
if(Boolean.TRUE.equals(row.getValueBoolean("enabled")) || row.getValueString("frequency") != null || row.getValueString("cron") != null)
{
recipients(row);
output.withValue("next_run_at", ScheduleTiming.next(row, Instant.now()));
}
}
catch(QException e)
{
output.addError(new BadInputStatusMessage(e.getMessage()));
}
}
}
@@ -0,0 +1,306 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.schedule;
import java.io.Serializable;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.kingsrook.qbits.dataanalysis.DataAnalysisQBitConfig;
import com.kingsrook.qbits.dataanalysis.DataAnalysisService;
import com.kingsrook.qbits.dataanalysis.engine.DrillFilters;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qbits.dataanalysis.permissions.DataAnalysisPermissions;
import com.kingsrook.qbits.dataanalysis.saved.AnalysisExport;
import com.kingsrook.qbits.dataanalysis.saved.SavedAnalyses;
import com.kingsrook.qbits.dataanalysis.saved.SavedDefinition;
import com.kingsrook.qbits.dataanalysis.saved.SavedResult;
import com.kingsrook.qbits.dataanalysis.watch.WatchRecords;
import com.kingsrook.qqq.backend.core.actions.messaging.SendMessageAction;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionEnforcement;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
import com.kingsrook.qqq.backend.core.alerts.AlertRecordRef;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.alerts.AlertSignal;
import com.kingsrook.qqq.backend.core.alerts.QAlerts;
import com.kingsrook.qqq.backend.core.context.CapturedContext;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
import com.kingsrook.qqq.backend.core.model.actions.messaging.Attachment;
import com.kingsrook.qqq.backend.core.model.actions.messaging.Content;
import com.kingsrook.qqq.backend.core.model.actions.messaging.Party;
import com.kingsrook.qqq.backend.core.model.actions.messaging.SendMessageInput;
import com.kingsrook.qqq.backend.core.model.actions.messaging.email.EmailContentRole;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.model.session.QUser;
/*******************************************************************************
** Scheduled work uses owner and recipient sessions; maintenance only inventories rows.
*******************************************************************************/
public class ScheduleRunner
{
public static final String ALERT_TYPE = "data.analysis.schedule.failed";
private final DataAnalysisQBitConfig config;
private final DataAnalysisService service;
/*******************************************************************************
** One instance serializes manual and automatic delivery on this application node.
*******************************************************************************/
public ScheduleRunner(DataAnalysisQBitConfig config, DataAnalysisService service)
{
this.config = config;
this.service = service;
}
/*******************************************************************************
** Enumerate enabled due rows with a maintenance session restricted to metadata.
*******************************************************************************/
public synchronized Integer runDue(Instant now) throws QException
{
QSession maintenance = AnalysisSessions.maintenance(config, () ->
{
QSession legacy = new QSession().withUser(new QUser().withIdReference("data-analysis-scheduler"))
.withPermissions("data_analysis.saved.read", "data_analysis.saved.edit")
.withSecurityKeyValue(DataAnalysisPermissions.ADMIN, true);
if(QContext.getQSession().getBackendVariants() != null)
{
legacy.setBackendVariants(new java.util.HashMap<>(QContext.getQSession().getBackendVariants()));
}
return (legacy);
});
int[] count = {0};
QContext.withTemporaryContext(new CapturedContext(QContext.getQInstance(), maintenance), () ->
{
var filter = DrillFilters.and(DrillFilters.condition("enabled", QCriteriaOperator.EQUALS, true),
DrillFilters.condition("next_run_at", QCriteriaOperator.LESS_THAN_OR_EQUALS, now));
for(QRecord row : SavedAnalyses.query(DataAnalysisTables.SCHEDULE, filter))
{
sendNow(row.getValue("id"), now);
count[0]++;
}
});
return (count[0]);
}
/*******************************************************************************
** Manual delivery is authorized before source work; all attempts record their outcome.
*******************************************************************************/
public synchronized String sendNow(Serializable id, Instant now) throws QException
{
UpdateInput authorization = new UpdateInput(DataAnalysisTables.SCHEDULE);
authorization.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
if(!PermissionsHelper.hasTablePermission(authorization, DataAnalysisTables.SCHEDULE, TablePermissionSubType.EDIT))
{
throw new QPermissionDeniedException("Schedule editing is unavailable.");
}
QRecord schedule = WatchRecords.get(DataAnalysisTables.SCHEDULE, id);
String status;
boolean failed = false;
try
{
status = deliver(schedule);
}
catch(Exception e)
{
failed = true;
status = "Failed: " + (e instanceof QException ? e.getMessage() : "Delivery unavailable; check the host configuration.");
}
Instant next = null;
try
{
next = ScheduleTiming.next(schedule, now);
}
catch(QException e)
{
failed = true;
status += "; " + e.getMessage();
}
QRecord patch = new QRecord().withValue("id", id).withValue("last_run_at", now).withValue("last_status", status).withValue("next_run_at", next);
UpdateInput input = new UpdateInput(DataAnalysisTables.SCHEDULE).withRecords(List.of(patch));
input.setPermissionEnforcement(PermissionEnforcement.ENFORCE);
QRecord stored = new UpdateAction().execute(input).getRecords().getFirst();
if(stored.getErrors() != null && !stored.getErrors().isEmpty())
{
throw new QException("Schedule status could not be stored.");
}
if(failed)
{
QAlerts.raise(new AlertSignal(ALERT_TYPE).withDedupKey("data_analysis_schedule:" + id).withSeverity(AlertSeverity.ERROR)
.withTitle("Analysis schedule failed").withSummary(status).withRecordRef(AlertRecordRef.of(DataAnalysisTables.SCHEDULE, id)));
}
return (status);
}
/*******************************************************************************
** The host resolves identities; an unavailable identity never becomes a system user.
*******************************************************************************/
private QSession session(String id) throws QException
{
QSession session;
try
{
session = AnalysisSessions.forUser(config, id);
}
catch(Exception e)
{
throw new QException("User session unavailable.");
}
if(session == null || session.getUser() == null || !Objects.equals(id, session.getUser().getIdReference())
|| session.getSecurityKeyValues() == null || !session.getSecurityKeyValues().getOrDefault(DataAnalysisTables.USER_KEY, List.of()).contains(id))
{
throw new QException("User session unavailable.");
}
return (session);
}
/*******************************************************************************
** Re-run for each recipient to respect their record locks, not just table grants.
*******************************************************************************/
private String deliver(QRecord schedule) throws QException
{
if(config.getMessagingProviderName() == null || QContext.getQInstance().getMessagingProvider(config.getMessagingProviderName()) == null)
{
throw new QException("No messaging provider configured.");
}
if(config.getFromAddress() == null || config.getRecipientAddressSupplier() == null)
{
throw new QException("Configure fromAddress and recipientAddressSupplier for scheduled email.");
}
if(List.of("CSV", "XLSX").contains(Objects.toString(schedule.getValueString("format"), "")))
{
var provider = new com.kingsrook.qqq.backend.core.modules.messaging.QMessagingProviderDispatcher()
.getMessagingProviderInterface(QContext.getQInstance().getMessagingProvider(config.getMessagingProviderName()));
if(provider.getClass().equals(com.kingsrook.qqq.backend.core.model.metadata.messaging.email.EmailMessagingProvider.class))
{
throw new QException("Core EMAIL provider does not support attachments; configure an attachment-capable messaging provider.");
}
}
QRecord saved = WatchRecords.get(DataAnalysisTables.SAVED, schedule.getValue("saved_id"));
String owner = saved.getValueString("owner_user_id");
SavedDefinition[] definition = new SavedDefinition[1];
SavedResult[] ownerResult = new SavedResult[1];
QContext.withTemporaryContext(new CapturedContext(QContext.getQInstance(), session(owner)), () ->
{
definition[0] = SavedDefinition.parse(WatchRecords.get(DataAnalysisTables.SAVED, saved.getValue("id")));
if("TABLE_PROFILE".equals(definition[0].kind()) && definition[0].body().get("fields") == null)
{
var body = definition[0].body();
body.put("fields", service.capabilities(definition[0].request().getTableName()).getFields());
definition[0] = SavedDefinition.parse(definition[0].kind(), definition[0].request().getTableName(), body);
}
ownerResult[0] = definition[0].run(service, true);
});
List<String> skipped = new ArrayList<>();
List<String> failures = new ArrayList<>();
int sent = 0;
for(String recipient : ScheduleCustomizer.recipients(schedule))
{
SavedResult[] result = new SavedResult[1];
String address;
try
{
QSession viewer = session(recipient);
QContext.withTemporaryContext(new CapturedContext(QContext.getQInstance(), viewer), () ->
{
result[0] = recipient.equals(owner) ? ownerResult[0] : definition[0].run(service, true);
});
address = config.getRecipientAddressSupplier().apply(recipient);
if(address == null || address.isBlank())
{
throw new QException("No email address.");
}
}
catch(Exception e)
{
skipped.add(recipient);
continue;
}
try
{
SendMessageInput message = new SendMessageInput().withMessagingProviderName(config.getMessagingProviderName())
.withFrom(new Party().withAddress(config.getFromAddress())).withTo(new Party().withAddress(address))
.withSubject("Analysis: " + saved.getValueString("name"))
.withContent(new Content().withContentRole(EmailContentRole.HTML).withBody(html(saved.getValueString("name"), result[0])));
String format = schedule.getValueString("format");
if("CSV".equals(format) || "XLSX".equals(format))
{
var file = AnalysisExport.file(result[0], format);
message.withAttachment(new Attachment().withName(file.filename()).withContents(file.bytes()));
}
new SendMessageAction().execute(message);
sent++;
}
catch(Exception e)
{
failures.add(recipient);
}
}
String status = "Sent " + sent + "; skipped: " + (skipped.isEmpty() ? "none" : String.join(", ", skipped));
if(!failures.isEmpty())
{
throw new QException(status + "; delivery failed for: " + String.join(", ", failures));
}
return (status);
}
/*******************************************************************************
** Formatted result rows are escaped; pivots include only the first twenty rows.
*******************************************************************************/
public static String html(String name, SavedResult result)
{
var table = AnalysisExport.table(result);
StringBuilder html = new StringBuilder("<h2>").append(escape(name)).append("</h2>");
for(String warning : result.warnings())
{
html.append("<p>").append(escape(warning)).append("</p>");
}
html.append("<dl>");
for(var metric : AnalysisExport.headlines(result))
{
html.append("<dt>").append(escape(metric.getLabel())).append("</dt><dd>").append(escape(AnalysisExport.value(metric))).append("</dd>");
}
html.append("</dl><table><thead><tr>");
table.columns().forEach(c -> html.append("<th>").append(escape(c)).append("</th>"));
html.append("</tr></thead><tbody>");
for(var row : table.rows().stream().limit(20).toList())
{
html.append("<tr>");
row.forEach(value -> html.append("<td>").append(escape(value)).append("</td>"));
html.append("</tr>");
}
return (html.append("</tbody></table>").toString());
}
/*******************************************************************************
** Source labels and values are text, never trusted email markup.
*******************************************************************************/
private static String escape(String value)
{
return (Objects.toString(value, "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("'", "&#39;"));
}
}
@@ -0,0 +1,111 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.schedule;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.TimeZone;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import org.quartz.CronExpression;
/*******************************************************************************
** Calendar schedules use local wall time; cron uses Quartz's existing parser.
*******************************************************************************/
public final class ScheduleTiming
{
/*******************************************************************************
** Utility class.
*******************************************************************************/
private ScheduleTiming()
{
}
/*******************************************************************************
** Strictly after now; missing monthly dates clamp to that month's last day.
** Java resolves spring gaps forward and chooses the first autumn occurrence.
*******************************************************************************/
public static Instant next(QRecord row, Instant now) throws QBadRequestException
{
try
{
ZoneId zone = ZoneId.of(row.getValueString("time_zone") == null ? "UTC" : row.getValueString("time_zone"));
String cron = row.getValueString("cron");
if(cron != null && !cron.isBlank())
{
CronExpression expression = new CronExpression(cron);
expression.setTimeZone(TimeZone.getTimeZone(zone));
Date next = expression.getNextValidTimeAfter(Date.from(now));
if(next == null)
{
throw new IllegalArgumentException("Cron has no future occurrence.");
}
return (next.toInstant());
}
LocalTime time = LocalTime.parse(row.getValueString("time"));
String frequency = row.getValueString("frequency");
Integer day = row.getValueInteger("day");
LocalDate date = now.atZone(zone).toLocalDate();
for(int attempt = 0; attempt < 3; attempt++)
{
LocalDate candidate = switch(frequency)
{
case "DAILY" -> date;
case "WEEKLY" -> date.with(TemporalAdjusters.nextOrSame(java.time.DayOfWeek.of(day)));
case "MONTHLY" -> date.withDayOfMonth(Math.min(requireDay(day), date.lengthOfMonth()));
default -> throw new IllegalArgumentException("Choose DAILY, WEEKLY or MONTHLY.");
};
Instant instant = candidate.atTime(time).atZone(zone).toInstant();
if(instant.isAfter(now))
{
return (instant);
}
date = switch(frequency)
{
case "WEEKLY" -> candidate.plusWeeks(1);
case "MONTHLY" -> candidate.plusMonths(1).withDayOfMonth(1);
default -> candidate.plusDays(1);
};
}
throw new IllegalArgumentException("No future occurrence.");
}
catch(Exception e)
{
throw new QBadRequestException("Invalid schedule: choose a valid frequency/day, local time, time zone or Quartz cron.");
}
}
/*******************************************************************************
** Month days are one-based and never silently wrap into another month.
*******************************************************************************/
private static int requireDay(Integer day)
{
if(day == null || day < 1 || day > 31)
{
throw new IllegalArgumentException("Monthly day must be 1 to 31.");
}
return (day);
}
}
@@ -0,0 +1,179 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.stats;
/*******************************************************************************
** Regularized beta and gamma using convergent series and continued fractions.
** Lanczos log-gamma keeps products in log space; tails are evaluated directly.
*******************************************************************************/
public final class SpecialFunctions
{
private static final double EPSILON = 1e-14;
private static final double TINY = 1e-300;
private static final int ITERATIONS = 10000;
/*******************************************************************************
** Utility class.
*******************************************************************************/
private SpecialFunctions()
{
}
/*******************************************************************************
** Student t cumulative distribution, with symmetry around zero.
*******************************************************************************/
public static double studentTCdf(double t, double df)
{
double tail = beta(df / (df + t * t), df / 2, 0.5) / 2;
return (t < 0 ? tail : 1 - tail);
}
/*******************************************************************************
** Chi-square CDF; significance tests use gammaQ directly to retain tiny tails.
*******************************************************************************/
public static double chiSquareCdf(double x, double df)
{
return (1 - gammaQ(df / 2, x / 2));
}
/*******************************************************************************
** Lanczos approximation, reflected below one half.
*******************************************************************************/
public static double logGamma(double z)
{
double[] coefficients = {676.5203681218851, -1259.1392167224028, 771.3234287776531, -176.6150291621406,
12.507343278686905, -0.13857109526572012, 9.984369578019572e-6, 1.5056327351493116e-7};
if(z < 0.5)
{
return (Math.log(Math.PI) - Math.log(Math.sin(Math.PI * z)) - logGamma(1 - z));
}
double x = 0.99999999999980993;
for(int i = 0; i < coefficients.length; i++)
{
x += coefficients[i] / (z + i);
}
double t = z + 6.5;
return (0.5 * Math.log(2 * Math.PI) + (z - 0.5) * Math.log(t) - t + Math.log(x));
}
/*******************************************************************************
** Regularized incomplete beta I_x(a,b), with symmetry for stable tails.
*******************************************************************************/
public static double beta(double x, double a, double b)
{
if(x <= 0 || x >= 1)
{
return (x <= 0 ? 0 : 1);
}
double factor = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log1p(-x));
return (clamp(x < (a + 1) / (a + b + 2) ? factor * betaFraction(x, a, b) / a : 1 - factor * betaFraction(1 - x, b, a) / b));
}
/*******************************************************************************
** Modified Lentz evaluation of the incomplete beta continued fraction.
*******************************************************************************/
private static double betaFraction(double x, double a, double b)
{
double c = 1;
double d = 1 / nonzero(1 - (a + b) * x / (a + 1));
double h = d;
for(int m = 1; m <= ITERATIONS; m++)
{
double aa = m * (b - m) * x / ((a + 2 * m - 1) * (a + 2 * m));
d = 1 / nonzero(1 + aa * d);
c = nonzero(1 + aa / c);
h *= d * c;
aa = -(a + m) * (a + b + m) * x / ((a + 2 * m) * (a + 2 * m + 1));
d = 1 / nonzero(1 + aa * d);
c = nonzero(1 + aa / c);
double delta = d * c;
h *= delta;
if(Math.abs(delta - 1) < EPSILON)
{
return (h);
}
}
throw new ArithmeticException("Incomplete beta did not converge");
}
/*******************************************************************************
** Upper regularized gamma Q(a,x), the chi-square survival probability.
*******************************************************************************/
public static double gammaQ(double a, double x)
{
if(x <= 0)
{
return (1);
}
double factor = Math.exp(-x + a * Math.log(x) - logGamma(a));
if(x < a + 1)
{
double term = 1 / a;
double sum = term;
for(int n = 1; n <= ITERATIONS; n++)
{
term *= x / (a + n);
sum += term;
if(Math.abs(term) < Math.abs(sum) * EPSILON)
{
return (clamp(1 - sum * factor));
}
}
}
else
{
double b = x + 1 - a;
double c = 1 / TINY;
double d = 1 / nonzero(b);
double h = d;
for(int n = 1; n <= ITERATIONS; n++)
{
double an = -n * (n - a);
b += 2;
d = 1 / nonzero(an * d + b);
c = nonzero(b + an / c);
double delta = d * c;
h *= delta;
if(Math.abs(delta - 1) < EPSILON)
{
return (clamp(factor * h));
}
}
}
throw new ArithmeticException("Incomplete gamma did not converge");
}
/*******************************************************************************
** Avoid divisions by zero without changing the sign of a fraction term.
*******************************************************************************/
private static double nonzero(double value)
{
return (Math.abs(value) < TINY ? Math.copySign(TINY, value) : value);
}
/*******************************************************************************
** Roundoff cannot create a probability outside its domain.
*******************************************************************************/
private static double clamp(double value)
{
return (Math.max(0, Math.min(1, value)));
}
}
@@ -0,0 +1,331 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.stats;
import java.util.Arrays;
import java.util.Locale;
/*******************************************************************************
** Dependency-free statistical tests. All tests use two-sided 5% significance.
*******************************************************************************/
public final class Statistics
{
/*******************************************************************************
** Non-applicable results never contain NaN, infinity or an invented p-value.
*******************************************************************************/
public record Result(String test, Double statistic, Double df, Double pValue, boolean applicable, String sentence, Double cramersV)
{
}
/*******************************************************************************
** Utility class.
*******************************************************************************/
private Statistics()
{
}
/*******************************************************************************
** Explain failed assumptions without claiming a negative test result.
*******************************************************************************/
public static Result unavailable(String test, String reason)
{
return (new Result(test, null, null, null, false, "Not applicable: " + reason, null));
}
/*******************************************************************************
** The strict comparison deliberately excludes p equal to 0.05.
*******************************************************************************/
public static String sentence(double p)
{
String formatted = p < 0.001 ? String.format(Locale.ROOT, "%.3g", p)
: java.math.BigDecimal.valueOf(p).setScale(p < 0.01 ? 3 : 2, java.math.RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
return ((p < 0.05 ? "A and B differ" : "No significant difference") + " (p = " + formatted + ")");
}
/*******************************************************************************
** Pooled standard error under equal proportions; require expected counts >= 5.
*******************************************************************************/
public static Result proportions(long successesA, long nA, long successesB, long nB)
{
String test = "Two-proportion z-test";
if(nA < 2 || nB < 2)
{
return (unavailable(test, "too few records"));
}
if(successesA < 0 || successesB < 0 || successesA > nA || successesB > nB)
{
return (unavailable(test, "invalid counts"));
}
double pooled = ((double) successesA + successesB) / ((double) nA + nB);
if(Math.min(Math.min(nA * pooled, nA * (1 - pooled)), Math.min(nB * pooled, nB * (1 - pooled))) < 5)
{
return (unavailable(test, "expected counts below 5"));
}
double z = ((double) successesA / nA - (double) successesB / nB) / Math.sqrt(pooled * (1 - pooled) * (1.0 / nA + 1.0 / nB));
double p = SpecialFunctions.gammaQ(0.5, z * z / 2);
return (new Result(test, z, null, p, true, sentence(p), null));
}
/*******************************************************************************
** Welch-Satterthwaite degrees of freedom from sample (ddof=1) variances.
*******************************************************************************/
public static Result welch(long nA, double meanA, double varianceA, long nB, double meanB, double varianceB)
{
String test = "Welch's t-test";
if(nA < 2 || nB < 2)
{
return (unavailable(test, "too few records"));
}
if(!Double.isFinite(meanA) || !Double.isFinite(meanB) || !Double.isFinite(varianceA) || !Double.isFinite(varianceB) || varianceA < 0 || varianceB < 0)
{
return (unavailable(test, "invalid numeric summary"));
}
double a = varianceA / nA;
double b = varianceB / nB;
if(a + b == 0)
{
return (unavailable(test, "both groups have zero variance"));
}
double t = (meanA - meanB) / Math.sqrt(a + b);
double df = (a + b) * (a + b) / (a * a / (nA - 1) + b * b / (nB - 1));
double p = SpecialFunctions.beta(df / (df + t * t), df / 2, 0.5);
return (new Result(test, t, df, p, true, sentence(p), null));
}
/*******************************************************************************
** Pearson chi-square without Yates correction; low expected categories pool
** into Other. Homogeneity preserves sample rows; independence pools both axes.
*******************************************************************************/
public static Result chiSquare(double[][] observed, boolean homogeneity)
{
String test = homogeneity ? "Chi-square homogeneity" : "Chi-square independence";
if(observed == null || observed.length < 2 || observed[0] == null || observed[0].length < 2)
{
return (unavailable(test, "a table of at least 2 by 2 is required"));
}
int columns = observed[0].length;
for(double[] row : observed)
{
if(row == null || row.length != columns || Arrays.stream(row).anyMatch(v -> !Double.isFinite(v) || v < 0))
{
return (unavailable(test, "invalid counts"));
}
if(homogeneity && Arrays.stream(row).sum() < 2)
{
return (unavailable(test, "too few records"));
}
}
////////////////////////////////////////////////////////////////////////////////
// pool the smallest category into Other until every expected count is >= 5. //
// homogeneity compares fixed samples (rows), so only columns are pooled. //
////////////////////////////////////////////////////////////////////////////////
double[][] table = Arrays.stream(observed).map(double[]::clone).toArray(double[][]::new);
boolean rowOther = false;
boolean columnOther = false;
while(!validExpected(table))
{
double[] rows = Arrays.stream(table).mapToDouble(r -> Arrays.stream(r).sum()).toArray();
double[] cols = Arrays.stream(transpose(table)).mapToDouble(r -> Arrays.stream(r).sum()).toArray();
int smallestRow = homogeneity ? -1 : smallestIndex(rows, rowOther);
int smallestCol = smallestIndex(cols, columnOther);
boolean poolRow = smallestRow >= 0 && (smallestCol < 0 || rows[smallestRow] <= cols[smallestCol]);
if(poolRow)
{
table = transpose(poolInto(transpose(table), smallestRow, rowOther));
rowOther = true;
}
else if(smallestCol >= 0)
{
table = poolInto(table, smallestCol, columnOther);
columnOther = true;
}
else
{
break;
}
if(table.length < 2 || table[0].length < 2)
{
break;
}
}
if(table.length < 2 || table[0].length < 2)
{
return (unavailable(test, "too few categories after merging expected counts below 5 into Other"));
}
if(!validExpected(table))
{
return (unavailable(test, homogeneity ? "too few records" : "expected counts below 5 after merging into Other"));
}
double[] rows = Arrays.stream(table).mapToDouble(r -> Arrays.stream(r).sum()).toArray();
double[] cols = Arrays.stream(transpose(table)).mapToDouble(r -> Arrays.stream(r).sum()).toArray();
double total = Arrays.stream(rows).sum();
double statistic = 0;
for(int i = 0; i < rows.length; i++)
{
for(int j = 0; j < cols.length; j++)
{
double expected = rows[i] * cols[j] / total;
statistic += Math.pow(table[i][j] - expected, 2) / expected;
}
}
double df = (rows.length - 1.0) * (cols.length - 1.0);
double p = SpecialFunctions.gammaQ(df / 2, statistic / 2);
double v = Math.sqrt(statistic / (total * Math.min(rows.length - 1, cols.length - 1)));
return (new Result(test, statistic, df, p, true, sentence(p), v));
}
/*******************************************************************************
** Every expected count is at least five (and the table is at least 2 by 2).
*******************************************************************************/
private static boolean validExpected(double[][] table)
{
if(table.length < 2 || table[0].length < 2)
{
return (false);
}
double[] rows = Arrays.stream(table).mapToDouble(r -> Arrays.stream(r).sum()).toArray();
double[] columns = Arrays.stream(transpose(table)).mapToDouble(r -> Arrays.stream(r).sum()).toArray();
double total = Arrays.stream(rows).sum();
return (total > 0 && Arrays.stream(rows).min().orElse(0) * Arrays.stream(columns).min().orElse(0) / total >= 5);
}
/*******************************************************************************
** The index of the smallest category, not counting a trailing Other (which
** only grows), or -1 when there is nothing left to pool.
*******************************************************************************/
private static int smallestIndex(double[] totals, boolean lastIsOther)
{
int limit = lastIsOther ? totals.length - 1 : totals.length;
if(limit <= (lastIsOther ? 0 : 1))
{
return (-1);
}
int smallest = 0;
for(int i = 1; i < limit; i++)
{
if(totals[i] < totals[smallest])
{
smallest = i;
}
}
return (smallest);
}
/*******************************************************************************
** Move one column into a trailing Other column (creating it if needed).
*******************************************************************************/
private static double[][] poolInto(double[][] table, int column, boolean hasOther)
{
int columns = table[0].length;
int width = hasOther ? columns - 1 : columns;
double[][] result = new double[table.length][width];
for(int i = 0; i < table.length; i++)
{
int target = 0;
for(int j = 0; j < columns; j++)
{
if(j == column || (hasOther && j == columns - 1))
{
continue;
}
result[i][target++] = table[i][j];
}
result[i][width - 1] = table[i][column] + (hasOther ? table[i][columns - 1] : 0);
}
return (result);
}
/*******************************************************************************
** Transposition lets independence apply the same pooling rule to both axes.
*******************************************************************************/
private static double[][] transpose(double[][] input)
{
double[][] result = new double[input[0].length][input.length];
for(int i = 0; i < input.length; i++)
{
for(int j = 0; j < input[i].length; j++)
{
result[j][i] = input[i][j];
}
}
return (result);
}
/*******************************************************************************
** Normalize counts to shares; floor zero shares at 1e-6 for finite PSI.
** This descriptive index is not a p-value or a significance test.
*******************************************************************************/
public static Double psi(double[] first, double[] last)
{
if(first == null || last == null || first.length == 0 || first.length != last.length
|| Arrays.stream(first).anyMatch(v -> !Double.isFinite(v) || v < 0) || Arrays.stream(last).anyMatch(v -> !Double.isFinite(v) || v < 0))
{
return (null);
}
double a = Arrays.stream(first).sum();
double b = Arrays.stream(last).sum();
if(a <= 0 || b <= 0)
{
return (null);
}
double result = 0;
for(int i = 0; i < first.length; i++)
{
double x = Math.max(1e-6, first[i] / a);
double y = Math.max(1e-6, last[i] / b);
result += (y - x) * Math.log(y / x);
}
return (result);
}
/*******************************************************************************
** Centered covariance avoids cancellation for large offsets; null on constants.
*******************************************************************************/
public static Double pearson(double[] x, double[] y)
{
if(x == null || y == null || x.length < 2 || x.length != y.length
|| Arrays.stream(x).anyMatch(v -> !Double.isFinite(v)) || Arrays.stream(y).anyMatch(v -> !Double.isFinite(v)))
{
return (null);
}
double meanX = Arrays.stream(x).average().orElseThrow();
double meanY = Arrays.stream(y).average().orElseThrow();
double xx = 0;
double yy = 0;
double xy = 0;
for(int i = 0; i < x.length; i++)
{
xx += (x[i] - meanX) * (x[i] - meanX);
yy += (y[i] - meanY) * (y[i] - meanY);
xy += (x[i] - meanX) * (y[i] - meanY);
}
return (xx == 0 || yy == 0 ? null : Math.max(-1, Math.min(1, xy / Math.sqrt(xx * yy))));
}
}
@@ -0,0 +1,32 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.watch;
import java.io.Serializable;
import java.util.Set;
import com.kingsrook.qbits.dataanalysis.result.Drill;
/*******************************************************************************
** One complete calendar bucket, ordered oldest first for detector input.
*******************************************************************************/
public record WatchBucket(Serializable start, Double value, Set<String> categories, Drill drill)
{
}
@@ -0,0 +1,97 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.watch;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import com.kingsrook.qbits.dataanalysis.model.DataAnalysisTables;
import com.kingsrook.qbits.dataanalysis.permissions.DataAnalysisPermissions;
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizerInterface;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.statusmessages.BadInputStatusMessage;
/*******************************************************************************
** Validate standard table CRUD, including partial updates and owner changes.
*******************************************************************************/
public class WatchCustomizer implements TableCustomizerInterface
{
private static final Set<String> CONFIGURATION = Set.of("saved_id", "table_name", "filter_json", "metric_json", "date_field", "bucket",
"detector", "parameters_json", "severity", "owner_user_id", "enabled");
/*******************************************************************************
** Validate every inserted watch, including disabled drafts.
*******************************************************************************/
@Override
public List<QRecord> preInsert(InsertInput input, List<QRecord> records, boolean preview) throws QException
{
for(QRecord record : records)
{
validate(record, record);
}
return (records);
}
/*******************************************************************************
** Merge partial patches with the stored row before checking detector parameters.
*******************************************************************************/
@Override
public List<QRecord> preUpdate(UpdateInput input, List<QRecord> records, boolean preview, Optional<List<QRecord>> oldRecords) throws QException
{
for(QRecord record : records)
{
if(record.getValues().keySet().stream().noneMatch(CONFIGURATION::contains))
{
continue;
}
QRecord old = WatchRecords.get(DataAnalysisTables.WATCH, record.getValue("id"));
QRecord merged = new QRecord(old);
merged.getValues().putAll(record.getValues());
validate(record, merged);
}
return (records);
}
/*******************************************************************************
** Record-level messages are shown by normal core insert/update screens.
*******************************************************************************/
private void validate(QRecord output, QRecord merged)
{
try
{
String owner = merged.getValueString("owner_user_id");
var session = QContext.getQSession();
WatchDefinition.require(owner != null && !owner.isBlank(), "owner_user_id is required.");
WatchDefinition.require(session != null && (session.hasPermission(DataAnalysisPermissions.ADMIN)
|| session.getUser() != null && owner.equals(session.getUser().getIdReference())), "Only an administrator may assign another watch owner.");
WatchDefinition.parse(WatchRecords.resolve(merged));
}
catch(QException e)
{
output.addError(new BadInputStatusMessage(e.getMessage()));
}
}
}
@@ -0,0 +1,152 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.watch;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
/*******************************************************************************
** Validated watch configuration; JSON accepts only documented, typed parameters.
*******************************************************************************/
public record WatchDefinition(String detector, String metric, String field, String dateField, String bucket,
Integer k, Double threshold, Double relativeChange, Double min, Double max, Double delta, Integer n)
{
/*******************************************************************************
** Parse a definition after resolving an optional saved analysis.
*******************************************************************************/
public static WatchDefinition parse(QRecord row) throws QBadRequestException
{
String detector = row.getValueString("detector");
require(List.of("SPIKE", "DROP", "OUT_OF_RANGE", "NEW_CATEGORY", "NULL_RATE_CREEP").contains(detector == null ? "" : detector), "Choose a supported detector.");
Map<String, Object> metric = object(row.getValueString("metric_json"), "metric_json");
require(metric.keySet().stream().allMatch(Set.of("operator", "field")::contains), "metric_json accepts operator and field only.");
String operator = string(metric.get("operator"));
String field = string(metric.get("field"));
require(List.of("COUNT", "SUM", "AVG", "NULL_SHARE", "CATEGORY_SET").contains(operator == null ? "" : operator), "Metric operator must be COUNT, SUM, AVG, NULL_SHARE or CATEGORY_SET.");
require("COUNT".equals(operator) || field != null && !field.isBlank(), "This metric requires a field.");
require("NEW_CATEGORY".equals(detector) == "CATEGORY_SET".equals(operator), "NEW_CATEGORY requires CATEGORY_SET; other detectors require a numeric metric.");
require(!"NULL_RATE_CREEP".equals(detector) || "NULL_SHARE".equals(operator), "NULL_RATE_CREEP requires NULL_SHARE.");
String date = row.getValueString("date_field");
String bucket = row.getValueString("bucket");
require(date != null && !date.isBlank(), "Choose a date field.");
require(List.of("HOUR", "DAY", "WEEK", "MONTH").contains(bucket == null ? "" : bucket), "Bucket must be HOUR, DAY, WEEK or MONTH.");
try
{
AlertSeverity.valueOf(row.getValueString("severity"));
}
catch(RuntimeException e)
{
throw new QBadRequestException("Choose a valid alert severity.");
}
Map<String, Object> parameters = object(row.getValueString("parameters_json"), "parameters_json");
Set<String> allowed = switch(detector)
{
case "SPIKE", "DROP" -> Set.of("k", "threshold", "relativeChange");
case "OUT_OF_RANGE" -> Set.of("k", "min", "max");
case "NULL_RATE_CREEP" -> Set.of("k", "delta", "n");
default -> Set.of("k");
};
require(allowed.containsAll(parameters.keySet()), "Unsupported parameter for " + detector + ". Allowed: " + String.join(", ", allowed.stream().sorted().toList()) + ".");
int k = integer(parameters, "k", 14, 1, 1000);
int n = integer(parameters, "n", 3, 1, 1000);
double threshold = number(parameters, "threshold", 3.5);
double relative = number(parameters, "relativeChange", 0.5);
double delta = number(parameters, "delta", 0.05);
require(threshold > 0, "threshold must be positive.");
require(relative >= 0, "relativeChange must be non-negative (0.5 means 50%).");
require(delta >= 0 && delta <= 1, "delta must be between 0 and 1.");
Double min = parameters.containsKey("min") ? number(parameters, "min", 0) : null;
Double max = parameters.containsKey("max") ? number(parameters, "max", 0) : null;
require(!"OUT_OF_RANGE".equals(detector) || min != null && max != null && min <= max, "OUT_OF_RANGE requires min and max with min <= max.");
return (new WatchDefinition(detector, operator, field, date, bucket, k, threshold, relative, min, max, delta, n));
}
/*******************************************************************************
** Strict JSON objects keep malformed definitions out of standard CRUD.
*******************************************************************************/
@SuppressWarnings("unchecked")
public static Map<String, Object> object(String json, String name) throws QBadRequestException
{
try
{
Object value = JsonUtils.toObject(json == null || json.isBlank() ? "{}" : json, Object.class);
if(value instanceof Map<?, ?> map)
{
return ((Map<String, Object>) map);
}
}
catch(Exception expected)
{
// Report a stable validation error, without echoing stored JSON.
}
throw new QBadRequestException(name + " must be a JSON object.");
}
/*******************************************************************************
** Numeric values must be finite JSON numbers, never coerced strings.
*******************************************************************************/
private static double number(Map<String, Object> values, String key, double fallback) throws QBadRequestException
{
if(!values.containsKey(key))
{
return (fallback);
}
require(values.get(key) instanceof Number, key + " must be a number.");
double value = ((Number) values.get(key)).doubleValue();
require(Double.isFinite(value), key + " must be finite.");
return (value);
}
/*******************************************************************************
** Bound work and reject fractional window sizes.
*******************************************************************************/
private static int integer(Map<String, Object> values, String key, int fallback, int min, int max) throws QBadRequestException
{
double value = number(values, key, fallback);
require(value == Math.rint(value) && value >= min && value <= max, key + " must be an integer from " + min + " to " + max + ".");
return ((int) value);
}
/*******************************************************************************
** Optional strings still reject incompatible scalar types.
*******************************************************************************/
private static String string(Object value) throws QBadRequestException
{
require(value == null || value instanceof String, "Metric operator and field must be strings.");
return ((String) value);
}
/*******************************************************************************
** Clear errors shared by table validation and preview.
*******************************************************************************/
public static void require(boolean valid, String message) throws QBadRequestException
{
if(!valid)
{
throw new QBadRequestException(message);
}
}
}
@@ -0,0 +1,131 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* 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
*
* https://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.dataanalysis.watch;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.kingsrook.qbits.dataanalysis.engine.AnalysisFormatting;
/*******************************************************************************
** Pure detectors over complete buckets, with no context, queries or side effects.
*******************************************************************************/
public final class WatchDetectors
{
/*******************************************************************************
** Utility class.
*******************************************************************************/
private WatchDetectors()
{
}
/*******************************************************************************
** Compare the latest value to the preceding k complete buckets.
*******************************************************************************/
public static WatchVerdict evaluate(WatchDefinition definition, List<WatchBucket> series, String label)
{
int k = definition.k();
if(series.isEmpty() || !"OUT_OF_RANGE".equals(definition.detector()) && series.size() < k + 1)
{
return (WatchVerdict.skipped("Not enough history."));
}
WatchBucket latest = series.getLast();
List<WatchBucket> history = series.subList(Math.max(0, series.size() - k - 1), series.size() - 1);
if("NEW_CATEGORY".equals(definition.detector()))
{
Set<String> previous = new HashSet<>();
history.forEach(bucket -> previous.addAll(bucket.categories()));
long added = latest.categories().stream().filter(value -> !previous.contains(value)).count();
return (new WatchVerdict(true, added > 0, (double) latest.categories().size(), (double) previous.size(), null, null,
label + (added > 0 ? " has " + added + " new " + (added == 1 ? "category." : "categories.") : " has no new categories."), latest.drill()));
}
if(latest.value() == null || !Double.isFinite(latest.value()) || !"OUT_OF_RANGE".equals(definition.detector()) && history.stream().anyMatch(bucket -> bucket.value() == null || !Double.isFinite(bucket.value())))
{
return (WatchVerdict.skipped("Not enough history: a bucket has no numeric value."));
}
double x = latest.value();
double[] values = history.stream().filter(bucket -> bucket.value() != null && Double.isFinite(bucket.value())).mapToDouble(WatchBucket::value).sorted().toArray();
Double baseline = values.length == 0 ? null : median(values);
Double low = values.length == 0 ? null : values[0];
Double high = values.length == 0 ? null : values[values.length - 1];
boolean firing;
switch(definition.detector())
{
case "SPIKE", "DROP" ->
{
double mad = median(java.util.Arrays.stream(values).map(value -> Math.abs(value - baseline)).sorted().toArray());
double change = x - baseline;
double score = mad == 0 ? baseline == 0 ? Math.signum(change) * (change == 0 ? 0 : Double.POSITIVE_INFINITY)
: change / Math.abs(baseline) : 0.6745 * change / mad;
double threshold = mad == 0 ? definition.relativeChange() : definition.threshold();
firing = "SPIKE".equals(definition.detector()) ? score > threshold : score < -threshold;
}
case "OUT_OF_RANGE" ->
{
low = definition.min();
high = definition.max();
firing = x < low || x > high;
}
case "NULL_RATE_CREEP" -> firing = x - baseline > definition.delta() || rising(series, definition.n());
default -> throw new IllegalArgumentException("Unsupported numeric detector.");
}
String verb = firing ? "DROP".equals(definition.detector()) ? " dropped to " : "SPIKE".equals(definition.detector())
|| "NULL_RATE_CREEP".equals(definition.detector()) ? " rose to " : " is out of range at " : " is ";
String band = low == null ? "" : " (" + ("OUT_OF_RANGE".equals(definition.detector()) ? "expected " : "usual ") + format(low) + "–" + format(high) + ")";
return (new WatchVerdict(true, firing, x, baseline, low, high, label + verb + format(x) + band + ".", latest.drill()));
}
/*******************************************************************************
** n consecutive rises require n+1 values, including the latest bucket.
*******************************************************************************/
private static boolean rising(List<WatchBucket> series, int n)
{
if(series.size() <= n)
{
return (false);
}
for(int i = series.size() - n; i < series.size(); i++)
{
if(series.get(i).value() <= series.get(i - 1).value())
{
return (false);
}
}
return (true);
}
/*******************************************************************************
** Median of a sorted non-empty array, including even-sized baselines.
*******************************************************************************/
private static double median(double[] values)
{
int middle = values.length / 2;
return (values.length % 2 == 0 ? values[middle - 1] / 2 + values[middle] / 2 : values[middle]);
}
/*******************************************************************************
** Compact English numeric labels with no scientific notation.
*******************************************************************************/
private static String format(double value)
{
return (AnalysisFormatting.number(value, 3));
}
}
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more