Skip to content

Commit

Permalink
fix: simplify queryBuilder zod schema
Browse files Browse the repository at this point in the history
Dimensions and metrics are now validated with refine, instead of being exposed as enum
  • Loading branch information
retro committed Apr 15, 2024
1 parent 05ad23d commit c5d9fa1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 26 deletions.
14 changes: 2 additions & 12 deletions src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -918,22 +918,12 @@ await describe("semantic layer", async () => {
assert.deepEqual(jsonSchema, {
type: "object",
properties: {
dimensions: {
type: "array",
items: {
type: "string",
enum: [
"customers.customer_id",
"invoices.invoice_id",
"invoices.customer_id",
],
},
},
dimensions: { type: "array", items: { type: "string" } },
metrics: {
type: "array",
items: {
anyOf: [
{ type: "string", enum: ["invoices.total"] },
{ type: "string" },
{
type: "object",
properties: {
Expand Down
25 changes: 11 additions & 14 deletions src/lib/query-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,10 @@ import { findOptimalJoinGraph } from "./query-builder/optimal-join-graph.js";
import { processQueryAndExpandToSegments } from "./query-builder/process-query-and-expand-to-segments.js";
import type { AnyRepository } from "./repository.js";

function isNonEmptyArray<T>(arr: T[]): arr is [T, ...T[]] {
return arr.length > 0;
}

function getDimensionNamesSchema(dimensionPaths: string[]) {
if (isNonEmptyArray(dimensionPaths)) {
const [first, ...rest] = dimensionPaths;
return z.array(z.enum([first, ...rest])).optional();
}
return z.array(z.string()).max(0).optional();
return z
.array(z.string().refine((arg) => dimensionPaths.includes(arg)))
.optional();
}

function getMetricNamesSchema(metricPaths: string[]) {
Expand All @@ -41,11 +35,14 @@ function getMetricNamesSchema(metricPaths: string[]) {
dimension: z.string(),
});

if (isNonEmptyArray(metricPaths)) {
const [first, ...rest] = metricPaths;
return z.array(z.enum([first, ...rest]).or(adHocMetricSchema)).optional();
}
return z.array(adHocMetricSchema).optional();
return z
.array(
z
.string()
.refine((arg) => metricPaths.includes(arg))
.or(adHocMetricSchema),
)
.optional();
}

export function buildQuerySchema(repository: AnyRepository) {
Expand Down

0 comments on commit c5d9fa1

Please sign in to comment.