-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquery.zod.ts
More file actions
563 lines (534 loc) · 17.3 KB
/
query.zod.ts
File metadata and controls
563 lines (534 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
import { FilterConditionSchema } from './filter.zod';
/**
* Sort Node
* Represents "Order By".
*/
export const SortNodeSchema = z.object({
field: z.string(),
order: z.enum(['asc', 'desc']).default('asc')
});
/**
* Aggregation Function Enum
* Standard aggregation functions for data analysis.
*
* Supported Functions:
* - **count**: Count rows (SQL: COUNT(*) or COUNT(field))
* - **sum**: Sum numeric values (SQL: SUM(field))
* - **avg**: Average numeric values (SQL: AVG(field))
* - **min**: Minimum value (SQL: MIN(field))
* - **max**: Maximum value (SQL: MAX(field))
* - **count_distinct**: Count unique values (SQL: COUNT(DISTINCT field))
* - **array_agg**: Aggregate values into array (SQL: ARRAY_AGG(field))
* - **string_agg**: Concatenate values (SQL: STRING_AGG(field, delimiter))
*
* Performance Considerations:
* - COUNT(*) is typically faster than COUNT(field) as it doesn't check for nulls
* - COUNT DISTINCT may require additional memory for tracking unique values
* - Window aggregates (with OVER clause) can be more efficient than subqueries
* - Large GROUP BY operations benefit from proper indexing on grouped fields
*
* @example
* // SQL: SELECT region, SUM(amount) FROM sales GROUP BY region
* {
* object: 'sales',
* fields: ['region'],
* aggregations: [
* { function: 'sum', field: 'amount', alias: 'total_sales' }
* ],
* groupBy: ['region']
* }
*
* @example
* // Salesforce SOQL: SELECT COUNT(Id) FROM Account
* {
* object: 'account',
* aggregations: [
* { function: 'count', alias: 'total_accounts' }
* ]
* }
*/
export const AggregationFunction = z.enum([
'count', 'sum', 'avg', 'min', 'max',
'count_distinct', 'array_agg', 'string_agg'
]);
/**
* Aggregation Node
* Represents an aggregated field with function.
*
* Aggregations summarize data across groups of rows (GROUP BY).
* Used with `groupBy` to create analytical queries.
*
* @example
* // SQL: SELECT customer_id, COUNT(*), SUM(amount) FROM orders GROUP BY customer_id
* {
* object: 'order',
* fields: ['customer_id'],
* aggregations: [
* { function: 'count', alias: 'order_count' },
* { function: 'sum', field: 'amount', alias: 'total_amount' }
* ],
* groupBy: ['customer_id']
* }
*
* @example
* // Salesforce SOQL: SELECT LeadSource, COUNT(Id) FROM Lead GROUP BY LeadSource
* {
* object: 'lead',
* fields: ['lead_source'],
* aggregations: [
* { function: 'count', alias: 'lead_count' }
* ],
* groupBy: ['lead_source']
* }
*/
export const AggregationNodeSchema = z.object({
function: AggregationFunction.describe('Aggregation function'),
field: z.string().optional().describe('Field to aggregate (optional for COUNT(*))'),
alias: z.string().describe('Result column alias'),
distinct: z.boolean().optional().describe('Apply DISTINCT before aggregation'),
filter: FilterConditionSchema.optional().describe('Filter/Condition to apply to the aggregation (FILTER WHERE clause)'),
});
/**
* Join Type Enum
* Standard SQL join types for combining tables.
*
* Join Types:
* - **inner**: Returns only matching rows from both tables (SQL: INNER JOIN)
* - **left**: Returns all rows from left table, matching rows from right (SQL: LEFT JOIN)
* - **right**: Returns all rows from right table, matching rows from left (SQL: RIGHT JOIN)
* - **full**: Returns all rows from both tables (SQL: FULL OUTER JOIN)
*
* @example
* // SQL: SELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.id
* {
* object: 'order',
* joins: [
* {
* type: 'inner',
* object: 'customer',
* on: ['order.customer_id', '=', 'customer.id']
* }
* ]
* }
*
* @example
* // Salesforce SOQL-style: Find all customers and their orders (if any)
* {
* object: 'customer',
* joins: [
* {
* type: 'left',
* object: 'order',
* on: ['customer.id', '=', 'order.customer_id']
* }
* ]
* }
*/
export const JoinType = z.enum(['inner', 'left', 'right', 'full']);
/**
* Join Execution Strategy
* Hints to the query engine on how to execute the join.
*
* Strategies:
* - **auto**: Engine decides best strategy (Default).
* - **database**: Push down join to the database (Requires same datasource).
* - **hash**: Load both sets into memory and hash join (Cross-datasource, memory intensive).
* - **loop**: Nested loop lookup (N+1 safe version). (Good for small right-side lookups).
*/
export const JoinStrategy = z.enum(['auto', 'database', 'hash', 'loop']);
/**
* Join Node
* Represents table joins for combining data from multiple objects.
*
* Joins connect related data across multiple tables using ON conditions.
* Supports both direct object joins and subquery joins.
*
* @example
* // SQL: SELECT o.*, c.name FROM orders o INNER JOIN customers c ON o.customer_id = c.id
* {
* object: 'order',
* fields: ['id', 'amount'],
* joins: [
* {
* type: 'inner',
* object: 'customer',
* alias: 'c',
* on: ['order.customer_id', '=', 'c.id']
* }
* ]
* }
*
* @example
* // SQL: Multi-table join
* // SELECT * FROM orders o
* // INNER JOIN customers c ON o.customer_id = c.id
* // LEFT JOIN shipments s ON o.id = s.order_id
* {
* object: 'order',
* joins: [
* {
* type: 'inner',
* object: 'customer',
* alias: 'c',
* on: ['order.customer_id', '=', 'c.id']
* },
* {
* type: 'left',
* object: 'shipment',
* alias: 's',
* on: ['order.id', '=', 's.order_id']
* }
* ]
* }
*
* @example
* // Salesforce SOQL: SELECT Name, (SELECT LastName FROM Contacts) FROM Account
* {
* object: 'account',
* fields: ['name'],
* joins: [
* {
* type: 'left',
* object: 'contact',
* on: ['account.id', '=', 'contact.account_id']
* }
* ]
* }
*
* @example
* // Subquery Join: Join with a filtered/aggregated dataset
* {
* object: 'customer',
* joins: [
* {
* type: 'left',
* object: 'order',
* alias: 'high_value_orders',
* on: ['customer.id', '=', 'high_value_orders.customer_id'],
* subquery: {
* object: 'order',
* fields: ['customer_id', 'total'],
* filters: ['total', '>', 1000]
* }
* }
* ]
* }
*/
export const JoinNodeSchema: z.ZodType<any> = z.lazy(() =>
z.object({
type: JoinType.describe('Join type'),
strategy: JoinStrategy.optional().describe('Execution strategy hint'),
object: z.string().describe('Object/table to join'),
alias: z.string().optional().describe('Table alias'),
on: FilterConditionSchema.describe('Join condition'),
subquery: z.lazy(() => QuerySchema).optional().describe('Subquery instead of object'),
})
);
/**
* Window Function Enum
* Advanced analytical functions for row-based calculations.
*
* Window Functions:
* - **row_number**: Sequential number within partition (SQL: ROW_NUMBER() OVER (...))
* - **rank**: Rank with gaps for ties (SQL: RANK() OVER (...))
* - **dense_rank**: Rank without gaps (SQL: DENSE_RANK() OVER (...))
* - **percent_rank**: Relative rank as percentage (SQL: PERCENT_RANK() OVER (...))
* - **lag**: Access previous row value (SQL: LAG(field) OVER (...))
* - **lead**: Access next row value (SQL: LEAD(field) OVER (...))
* - **first_value**: First value in window (SQL: FIRST_VALUE(field) OVER (...))
* - **last_value**: Last value in window (SQL: LAST_VALUE(field) OVER (...))
* - **sum/avg/count/min/max**: Aggregates over window (SQL: SUM(field) OVER (...))
*
* @example
* // SQL: SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) as rank
* // FROM orders
* {
* object: 'order',
* fields: ['id', 'customer_id', 'amount'],
* windowFunctions: [
* {
* function: 'row_number',
* alias: 'rank',
* over: {
* partitionBy: ['customer_id'],
* orderBy: [{ field: 'amount', order: 'desc' }]
* }
* }
* ]
* }
*
* @example
* // SQL: Running total with SUM() OVER (...)
* {
* object: 'transaction',
* fields: ['date', 'amount'],
* windowFunctions: [
* {
* function: 'sum',
* field: 'amount',
* alias: 'running_total',
* over: {
* orderBy: [{ field: 'date', order: 'asc' }],
* frame: {
* type: 'rows',
* start: 'UNBOUNDED PRECEDING',
* end: 'CURRENT ROW'
* }
* }
* }
* ]
* }
*/
export const WindowFunction = z.enum([
'row_number', 'rank', 'dense_rank', 'percent_rank',
'lag', 'lead', 'first_value', 'last_value',
'sum', 'avg', 'count', 'min', 'max'
]);
/**
* Window Specification
* Defines PARTITION BY and ORDER BY for window functions.
*
* Window specifications control how window functions compute values:
* - **partitionBy**: Divide rows into groups (like GROUP BY but without collapsing rows)
* - **orderBy**: Define order for ranking and offset functions
* - **frame**: Specify which rows to include in aggregate calculations
*
* @example
* // Partition by department, order by salary
* {
* partitionBy: ['department'],
* orderBy: [{ field: 'salary', order: 'desc' }]
* }
*
* @example
* // Moving average with frame specification
* {
* orderBy: [{ field: 'date', order: 'asc' }],
* frame: {
* type: 'rows',
* start: '6 PRECEDING',
* end: 'CURRENT ROW'
* }
* }
*/
export const WindowSpecSchema = z.object({
partitionBy: z.array(z.string()).optional().describe('PARTITION BY fields'),
orderBy: z.array(SortNodeSchema).optional().describe('ORDER BY specification'),
frame: z.object({
type: z.enum(['rows', 'range']).optional(),
start: z.string().optional().describe('Frame start (e.g., "UNBOUNDED PRECEDING", "1 PRECEDING")'),
end: z.string().optional().describe('Frame end (e.g., "CURRENT ROW", "1 FOLLOWING")'),
}).optional().describe('Window frame specification'),
});
/**
* Window Function Node
* Represents window function with OVER clause.
*
* Window functions perform calculations across a set of rows related to the current row,
* without collapsing the result set (unlike GROUP BY aggregations).
*
* @example
* // SQL: Top 3 products per category
* // SELECT *, ROW_NUMBER() OVER (PARTITION BY category ORDER BY sales DESC) as rank
* // FROM products
* {
* object: 'product',
* fields: ['name', 'category', 'sales'],
* windowFunctions: [
* {
* function: 'row_number',
* alias: 'category_rank',
* over: {
* partitionBy: ['category'],
* orderBy: [{ field: 'sales', order: 'desc' }]
* }
* }
* ]
* }
*
* @example
* // SQL: Year-over-year comparison with LAG
* {
* object: 'monthly_sales',
* fields: ['month', 'revenue'],
* windowFunctions: [
* {
* function: 'lag',
* field: 'revenue',
* alias: 'prev_year_revenue',
* over: {
* orderBy: [{ field: 'month', order: 'asc' }]
* }
* }
* ]
* }
*/
export const WindowFunctionNodeSchema = z.object({
function: WindowFunction.describe('Window function name'),
field: z.string().optional().describe('Field to operate on (for aggregate window functions)'),
alias: z.string().describe('Result column alias'),
over: WindowSpecSchema.describe('Window specification (OVER clause)'),
});
/**
* Field Selection Node
* Represents "Select" attributes, including joins.
*/
export const FieldNodeSchema: z.ZodType<any> = z.lazy(() =>
z.union([
z.string(), // Primitive field: "name"
z.object({
field: z.string(), // Relationship field: "owner"
fields: z.array(FieldNodeSchema).optional(), // Nested select: ["name", "email"]
alias: z.string().optional()
})
])
);
/**
* Full-Text Search Configuration
* Defines full-text search parameters for text queries.
*
* Supports:
* - Multi-field search
* - Relevance scoring
* - Fuzzy matching
* - Language-specific analyzers
*
* @example
* {
* query: "John Smith",
* fields: ["name", "email", "description"],
* fuzzy: true,
* boost: { "name": 2.0, "email": 1.5 }
* }
*/
export const FullTextSearchSchema = z.object({
query: z.string().describe('Search query text'),
fields: z.array(z.string()).optional().describe('Fields to search in (if not specified, searches all text fields)'),
fuzzy: z.boolean().optional().default(false).describe('Enable fuzzy matching (tolerates typos)'),
operator: z.enum(['and', 'or']).optional().default('or').describe('Logical operator between terms'),
boost: z.record(z.string(), z.number()).optional().describe('Field-specific relevance boosting (field name -> boost factor)'),
minScore: z.number().optional().describe('Minimum relevance score threshold'),
language: z.string().optional().describe('Language for text analysis (e.g., "en", "zh", "es")'),
highlight: z.boolean().optional().default(false).describe('Enable search result highlighting'),
});
export type FullTextSearch = z.infer<typeof FullTextSearchSchema>;
/**
* Query AST Schema
* The universal data retrieval contract defined in `ast-structure.mdx`.
*
* This schema represents ObjectQL - a universal query language that abstracts
* SQL, NoSQL, and SaaS APIs into a single unified interface.
*
* Updates (v2):
* - Aligned with modern ORM standards (Prisma/TypeORM)
* - Added `cursor` based pagination support
* - Renamed `top`/`skip` to `limit`/`offset`
* - Unified filtering syntax with `FilterConditionSchema`
*
* Updates (v3):
* - Added `search` parameter for full-text search (P2 requirement)
*
* @example
* // Simple query: SELECT name, email FROM account WHERE status = 'active'
* {
* object: 'account',
* fields: ['name', 'email'],
* where: { status: 'active' }
* }
*
* @example
* // Pagination with Limit/Offset
* {
* object: 'post',
* where: { published: true },
* orderBy: [{ field: 'created_at', order: 'desc' }],
* limit: 20,
* offset: 40
* }
*
* @example
* // Full-text search
* {
* object: 'article',
* search: {
* query: "machine learning",
* fields: ["title", "content"],
* fuzzy: true,
* boost: { "title": 2.0 }
* },
* limit: 10
* }
*/
const BaseQuerySchema = z.object({
/** Target Entity */
object: z.string().describe('Object name (e.g. account)'),
/** Select Clause */
fields: z.array(FieldNodeSchema).optional().describe('Fields to retrieve'),
/** Where Clause (Filtering) */
where: FilterConditionSchema.optional().describe('Filtering criteria (WHERE)'),
/** Full-Text Search */
search: FullTextSearchSchema.optional().describe('Full-text search configuration ($search parameter)'),
/** Order By Clause (Sorting) */
orderBy: z.array(SortNodeSchema).optional().describe('Sorting instructions (ORDER BY)'),
/** Pagination */
limit: z.number().optional().describe('Max records to return (LIMIT)'),
offset: z.number().optional().describe('Records to skip (OFFSET)'),
top: z.number().optional().describe('Alias for limit (OData compatibility)'),
cursor: z.record(z.string(), z.unknown()).optional().describe('Cursor for keyset pagination'),
/** Joins */
joins: z.array(JoinNodeSchema).optional().describe('Explicit Table Joins'),
/** Aggregations */
aggregations: z.array(AggregationNodeSchema).optional().describe('Aggregation functions'),
/** Group By Clause */
groupBy: z.array(z.string()).optional().describe('GROUP BY fields'),
/** Having Clause */
having: FilterConditionSchema.optional().describe('HAVING clause for aggregation filtering'),
/** Window Functions */
windowFunctions: z.array(WindowFunctionNodeSchema).optional().describe('Window functions with OVER clause'),
/** Subquery flag */
distinct: z.boolean().optional().describe('SELECT DISTINCT flag'),
});
/**
* QueryAST — Abstract Syntax Tree for data queries.
*
* The `expand` property enables recursive loading of related records through
* lookup and master_detail fields. Each key is a relationship field name; the
* value is a nested QueryAST that can further filter, select, sort, and expand
* the related records (up to a default max depth of 3).
*
* @example
* ```ts
* const ast: QueryAST = {
* object: 'task',
* fields: ['title', 'assignee'],
* expand: {
* assignee: { object: 'user', fields: ['name', 'email'] },
* project: {
* object: 'project',
* expand: { org: { object: 'org' } } // nested expand
* }
* }
* };
* ```
*/
export type QueryAST = z.infer<typeof BaseQuerySchema> & {
expand?: Record<string, QueryAST>;
};
export type QueryInput = z.input<typeof BaseQuerySchema> & {
expand?: Record<string, QueryInput>;
};
export const QuerySchema: z.ZodType<QueryAST> = BaseQuerySchema.extend({
expand: z.lazy(() => z.record(z.string(), QuerySchema)).optional().describe(
'Recursive relation loading map. Keys are lookup/master_detail field names; '
+ 'values are nested QueryAST objects that control select, filter, sort, and '
+ 'further expansion on the related object. The engine resolves expand via '
+ 'batch $in queries (driver-agnostic) with a default max depth of 3.'
),
});
export type SortNode = z.infer<typeof SortNodeSchema>;
export type AggregationNode = z.infer<typeof AggregationNodeSchema>;
export type JoinNode = z.infer<typeof JoinNodeSchema>;
export type WindowFunctionNode = z.infer<typeof WindowFunctionNodeSchema>;
export type WindowSpec = z.infer<typeof WindowSpecSchema>;