Skip to content

Commit c733aa4

Browse files
ampagenttmm
andcommitted
feat(zero-swift): aggregates, groupBy and JSON paths in the AST; JSON path filters
The AST gets the query features of sync protocols 54-57: aggregate on a query and on a relationship, groupBy, and JSON path references in conditions, with JS's wire checks, normalization, hashes and name mapping, and Format.aggregate. where() can compare a value inside a json column, in the untyped builder (eb.json) and the typed one ($0.json(\.metadata, ...)), type-strict as in JS. Building a pipeline for an aggregate or a groupBy throws until the IVM operators land. New vectors from JS: ast-features (strictASTSchema's verdict, normalizeAST, hashOfAST and mapAST), query-internals-hash (Format.aggregate), and ivm-features (JSON path filters over datasets with varied metadata, including the builder's errors). Amp-Thread-ID: https://ampcode.com/threads/T-01a19a37-5aa9-7256-bff5-cdc47c01a1fe Co-authored-by: tmm <tmm@tmm.dev>
1 parent 8c4116d commit c733aa4

22 files changed

Lines changed: 4048 additions & 18 deletions

‎.changeset/swift-ast-json-paths.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'zero-swift': minor
3+
---
4+
5+
The AST has the query features of sync protocols 54–57: `aggregate` on a query and on a relationship, `groupBy`, and JSON path references (`AST.ValuePosition.json`), with JS's wire checks, normalization, hashes and name mapping. `where` can compare a value inside a `json` column: `$0.json(\.metadata, "tags", 0) == "bug"` in the typed builder, `eb.cmp(eb.json("metadata", "tags", 0), "bug")` in the untyped one. As in JS, a value of another JSON type than the one compared with never equals it.
6+
7+
Breaking: `AST.ValuePosition` has a new case, `.json`; an exhaustive `switch` over it needs one too. Building a pipeline for an AST with an aggregate or a `groupBy` throws until the Swift client supports them.

‎packages/zero-conformance/src/ivm/harness.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,15 @@ export type Op =
4848

4949
export type Expr =
5050
| {cmp: [field: string, op: SimpleOperator, value: JSONValue]}
51+
/** `cmp(json(field, ...path), op, value)`. */
52+
| {
53+
cmpJson: [
54+
field: string,
55+
path: (string | number)[],
56+
op: SimpleOperator,
57+
value: JSONValue,
58+
];
59+
}
5160
| {and: Expr[]}
5261
| {or: Expr[]}
5362
| {not: Expr}
@@ -126,6 +135,10 @@ function buildExpr(eb: AnyEB, expr: Expr): unknown {
126135
if ('cmp' in expr) {
127136
return eb.cmp(expr.cmp[0], expr.cmp[1], expr.cmp[2]);
128137
}
138+
if ('cmpJson' in expr) {
139+
const [field, path, op, value] = expr.cmpJson;
140+
return eb.cmp(eb.json(field, ...path), op, value);
141+
}
129142
if ('and' in expr) {
130143
return eb.and(...expr.and.map(e => buildExpr(eb, e)));
131144
}
Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
/**
2+
* IVM vectors for the query features of sync protocols 54–57 (JSON path
3+
* filters, aggregates, distinct and groupBy), over the zql test schema with
4+
* datasets whose `user.metadata` holds varied JSON. A program the JS builder
5+
* rejects records its error, which the Swift builder must report too.
6+
*/
7+
import {test} from 'vitest';
8+
import type {JSONValue} from '../../../shared/src/json.ts';
9+
import type {Row} from '../../../zero-protocol/src/data.ts';
10+
import {schema} from '../../../zql/src/query/test/test-schemas.ts';
11+
import {Random} from '../random.ts';
12+
import {emitVectors} from '../vectors.ts';
13+
import {makeData, makePushes} from './generate.ts';
14+
import {
15+
buildProgram,
16+
runQuery,
17+
schemaJSON,
18+
type Expr,
19+
type Program,
20+
type Push,
21+
type QueryResult,
22+
} from './harness.ts';
23+
24+
/** The JSON a `user.metadata` holds. */
25+
const metadataValues: JSONValue[] = [
26+
null,
27+
{
28+
registrar: 'github',
29+
email: 'a',
30+
points: 3,
31+
tags: ['x', 'y'],
32+
nested: {a: [1, 'b']},
33+
},
34+
{registrar: 'google', points: '3', tags: []},
35+
{points: 2.5, tags: ['y'], nested: {a: [2]}},
36+
{points: null, nested: {a: 'x'}},
37+
{registrar: 'github', points: -1, login: 'u'},
38+
{registrar: true, points: 0},
39+
[1, 2, 3],
40+
'github',
41+
7,
42+
{'0': 'key', 'points': 1e21, 'registrar': 'Google'},
43+
{registrar: 'gitlab', points: 3, tags: ['x']},
44+
];
45+
46+
/**
47+
* The metadata of `row`, a function of its id and generated metadata only,
48+
* so an edit that leaves the metadata alone leaves it alone here too.
49+
*/
50+
function richMetadata(row: Row): JSONValue {
51+
const key = String(row['id']) + JSON.stringify(row['metadata'] ?? null);
52+
let h = 7;
53+
for (let i = 0; i < key.length; i++) {
54+
h = (h * 31 + key.charCodeAt(i)) >>> 0;
55+
}
56+
return metadataValues[h % metadataValues.length];
57+
}
58+
59+
function enrich(table: string, row: Row): Row {
60+
return table === 'user' ? {...row, metadata: richMetadata(row)} : row;
61+
}
62+
63+
type Dataset = {data: Record<string, Row[]>; pushes: Push[]};
64+
65+
function datasets(seed: number, count: number, pushes: number): Dataset[] {
66+
const r = new Random(seed);
67+
return Array.from({length: count}, () => {
68+
const data = makeData(r, schema);
69+
const ps = makePushes(r, schema, data, pushes);
70+
return {
71+
data: Object.fromEntries(
72+
Object.entries(data).map(([t, rows]) => [
73+
t,
74+
rows.map(row => enrich(t, row)),
75+
]),
76+
),
77+
pushes: ps.map(p => ({
78+
...p,
79+
row: enrich(p.table, p.row),
80+
...(p.oldRow ? {oldRow: enrich(p.table, p.oldRow)} : {}),
81+
})),
82+
};
83+
});
84+
}
85+
86+
const p = (table: string, ...ops: Program['ops']): Program => ({table, ops});
87+
const json = (
88+
path: (string | number)[],
89+
op: string,
90+
value: JSONValue,
91+
field = 'metadata',
92+
): Expr => ({cmpJson: [field, path, op, value]}) as Expr;
93+
const whereJson = (
94+
path: (string | number)[],
95+
op: string,
96+
value: JSONValue,
97+
): Program['ops'][number] => ({
98+
op: 'whereExpr',
99+
expr: json(path, op, value),
100+
});
101+
102+
const curated: [string, Program][] = [
103+
['json =', p('user', whereJson(['registrar'], '=', 'github'))],
104+
['json !=', p('user', whereJson(['registrar'], '!=', 'github'))],
105+
['json = bool', p('user', whereJson(['registrar'], '=', true))],
106+
['json >', p('user', whereJson(['points'], '>', 2))],
107+
['json <=', p('user', whereJson(['points'], '<=', 2.5))],
108+
['json < string', p('user', whereJson(['points'], '<', '4'))],
109+
['json IN', p('user', whereJson(['points'], 'IN', [3, -1]))],
110+
['json NOT IN', p('user', whereJson(['points'], 'NOT IN', [3]))],
111+
['json IN empty', p('user', whereJson(['points'], 'IN', []))],
112+
['json NOT IN empty', p('user', whereJson(['points'], 'NOT IN', []))],
113+
['json IN strings', p('user', whereJson(['registrar'], 'IN', ['google']))],
114+
['json IS null', p('user', whereJson(['points'], 'IS', null))],
115+
['json IS NOT null', p('user', whereJson(['points'], 'IS NOT', null))],
116+
['json IS value', p('user', whereJson(['registrar'], 'IS', 'github'))],
117+
['json = null', p('user', whereJson(['points'], '=', null))],
118+
['json LIKE', p('user', whereJson(['registrar'], 'LIKE', 'g%'))],
119+
['json NOT ILIKE', p('user', whereJson(['registrar'], 'NOT ILIKE', 'G%'))],
120+
['json LIKE number', p('user', whereJson(['points'], 'LIKE', '3'))],
121+
['json array index', p('user', whereJson(['tags', 0], '=', 'x'))],
122+
['json nested path', p('user', whereJson(['nested', 'a', 1], '=', 'b'))],
123+
['json object key "0"', p('user', whereJson(['0'], '=', 'key'))],
124+
['json index into array', p('user', whereJson([0], '=', 1))],
125+
['json key into array', p('user', whereJson(['0'], '=', 1))],
126+
['json index into object', p('user', whereJson([0], '=', 'key'))],
127+
['json whole object', p('user', whereJson(['nested'], '!=', 'x'))],
128+
['json non-json column', p('user', whereJson(['a'], '=', 'x'))],
129+
[
130+
'json or column',
131+
p('user', {
132+
op: 'whereExpr',
133+
expr: {
134+
or: [json(['points'], '>=', 3), {cmp: ['name', '=', 'a']}],
135+
},
136+
}),
137+
],
138+
[
139+
'json in exists',
140+
p('comment', {
141+
op: 'whereExists',
142+
rel: 'author',
143+
sub: [whereJson(['registrar'], '=', 'github')],
144+
}),
145+
],
146+
[
147+
'json in related',
148+
p('issue', {
149+
op: 'related',
150+
rel: 'owner',
151+
sub: [whereJson(['points'], '>', 0)],
152+
}),
153+
],
154+
[
155+
'json ordered and limited',
156+
p(
157+
'user',
158+
whereJson(['registrar'], 'IS NOT', null),
159+
{op: 'orderBy', field: 'name', dir: 'desc'},
160+
{op: 'limit', n: 2},
161+
),
162+
],
163+
// The builder rejects these.
164+
['json negative index', p('user', whereJson([-1], '=', 1))],
165+
['json fractional index', p('user', whereJson([1.5], '=', 1))],
166+
['json index too large', p('user', whereJson([2 ** 31], '=', 1))],
167+
['json empty path', p('user', whereJson([], '=', 1))],
168+
['json mixed IN', p('user', whereJson(['points'], 'IN', [3, '3']))],
169+
['json mixed NOT IN', p('user', whereJson(['points'], 'NOT IN', [true, 1]))],
170+
];
171+
172+
type Case = {
173+
name: string;
174+
dataset: number;
175+
program: Program;
176+
ast?: unknown;
177+
format?: unknown;
178+
result?: QueryResult;
179+
builderError?: string;
180+
};
181+
182+
function makeCase(
183+
name: string,
184+
dataset: number,
185+
data: Dataset,
186+
program: Program,
187+
): Case {
188+
let built;
189+
try {
190+
built = buildProgram(schema, program);
191+
} catch (e) {
192+
return {name, dataset, program, builderError: (e as Error).message};
193+
}
194+
return {
195+
name,
196+
dataset,
197+
program,
198+
ast: built.ast,
199+
format: built.format,
200+
result: runQuery(schema, data.data, built.ast, built.format, data.pushes),
201+
};
202+
}
203+
204+
test('ivm features', () => {
205+
const sets = datasets(57, 4, 30);
206+
const cases: Case[] = [];
207+
for (const [name, program] of curated) {
208+
sets.forEach((set, i) => {
209+
const c = makeCase(name, i, set, program);
210+
// A builder error is the same for every dataset.
211+
if (c.builderError === undefined || i === 0) {
212+
cases.push(c);
213+
}
214+
});
215+
}
216+
emitVectors(
217+
'ivm-features',
218+
'ivm',
219+
'Queries with JSON path filters, aggregates, distinct and groupBy over the zql test schema: the view after hydration and after each source push, and the changes the view received; or the error the builder throws.',
220+
cases,
221+
{schema: schemaJSON(schema), datasets: sets},
222+
{compact: true},
223+
);
224+
});

0 commit comments

Comments
 (0)