@kivacore/api-client 0.0.0 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2057 @@
1
+ # Data Source Query Guide
2
+
3
+ Comprehensive reference for querying data sources using the `ZodSelectQueryPayload` schema. This document covers every parameter, operator, and feature with detailed examples.
4
+
5
+ ---
6
+
7
+ ## Table of Contents
8
+
9
+ 1. [Overview](#overview)
10
+ 2. [Query Payload Structure](#query-payload-structure)
11
+ 3. [Common Parameters](#common-parameters)
12
+ 4. [Columns](#columns)
13
+ 5. [Filters](#filters)
14
+ 6. [Filter Keyword](#filter-keyword)
15
+ 7. [Order By](#order-by)
16
+ 8. [Pagination (limit / offset)](#pagination)
17
+ 9. [Calculations (Aggregations)](#calculations)
18
+ 10. [Formulas](#formulas)
19
+ 11. [Pivot](#pivot)
20
+ 12. [Child Queries](#child-queries)
21
+ 13. [Expand](#expand)
22
+ 14. [Query Mode](#query-mode)
23
+ 15. [Distinct Columns](#distinct-columns)
24
+ 16. [Full Count](#full-count)
25
+ 17. [Cursor-Based Sync](#cursor-based-sync)
26
+ 18. [Filter Operators Reference](#filter-operators-reference)
27
+ 19. [Allowed Functions Reference](#allowed-functions-reference)
28
+ 20. [Allowed Aggregates Reference](#allowed-aggregates-reference)
29
+ 21. [Allowed Cast Types](#allowed-cast-types)
30
+ 22. [Complete Examples](#complete-examples)
31
+
32
+ ---
33
+
34
+ ## Overview
35
+
36
+ All data source reads go through a unified select query payload. The payload is validated by `ZodSelectQueryPayload` (defined in `libs/shared/src/database/schemas.ts`). It supports:
37
+
38
+ - **Column selection** with relation expansion, aliasing, spread, and functions
39
+ - **Filtering** with nested AND/OR groups, dozens of operators, and relation field filtering
40
+ - **Keyword search** via full-text search
41
+ - **Sorting** by one or more fields with direction
42
+ - **Pagination** with limit/offset
43
+ - **Aggregations** (count, sum, avg, min, max, etc.) with grouping
44
+ - **Formulas** — computed virtual columns (simple and block/AST-based)
45
+ - **Pivot** — advanced cross-tab grouping with date range series and matrix CTEs
46
+ - **Child queries** — fetch related child records as nested JSON arrays
47
+ - **Field expansion** — automatically expand relation/user/enum fields
48
+
49
+ ---
50
+
51
+ ## Query Payload Structure
52
+
53
+ The full `ZodSelectQueryPayload` type:
54
+
55
+ ```typescript
56
+ interface ISelectQueryParams {
57
+ // --- Identity ---
58
+ dataSourceId?: string | null;
59
+ dataSourceFullSlug?: string | null;
60
+ connectionId?: string | null;
61
+ connectionAccountId?: string | null;
62
+ parentRecord?: Record<string, any> | null;
63
+
64
+ // --- Filtering ---
65
+ filters?: IQueryFilterGroup | null;
66
+ filterKeyword?: string | null;
67
+
68
+ // --- Column Selection ---
69
+ columns?: string | null;
70
+ distinctColumns?: string[] | null;
71
+
72
+ // --- Computed Columns ---
73
+ formulas?: Record<string, IQueryFormula> | null;
74
+
75
+ // --- Aggregation ---
76
+ calculations?: ISelectQueryCalculationRule[] | null;
77
+ showGroupSummaries?: boolean;
78
+
79
+ // --- Sorting ---
80
+ orderBy?: string | ISelectQueryOrderBy | ISelectQueryOrderBy[];
81
+
82
+ // --- Pagination ---
83
+ limit?: number; // default: 100
84
+ offset?: number; // default: 0
85
+
86
+ // --- Expansion ---
87
+ expandTypes?: ("user" | "enum" | "relation")[] | null;
88
+ expand?: string[] | null;
89
+
90
+ // --- Misc ---
91
+ queryMode?: "OLTP" | "OLAP" | "EXPORT";
92
+ fullCount?: boolean;
93
+ cursorDateStart?: string | null;
94
+ cursorDateEnd?: string | null;
95
+
96
+ // --- Advanced ---
97
+ childQueries?: Record<string, IQueryChildQueryParams> | null;
98
+ pivot?: {
99
+ matrix: ISelectPivotMatrixQuery[];
100
+ hideEmptyRows?: boolean;
101
+ orderBy?: string | ISelectQueryOrderBy | ISelectQueryOrderBy[];
102
+ limit?: number;
103
+ } | null;
104
+ }
105
+ ```
106
+
107
+ ---
108
+
109
+ ## Common Parameters
110
+
111
+ These parameters identify which data source to query.
112
+
113
+ | Parameter | Type | Description |
114
+ |---|---|---|
115
+ | `dataSourceId` | `string \| null` | UUID of the data source |
116
+ | `dataSourceFullSlug` | `string \| null` | Full slug in `appSlug_slug` format (e.g. `crm_account`) |
117
+ | `connectionId` | `string \| null` | Connection ID for external data sources |
118
+ | `connectionAccountId` | `string \| null` | Account ID for the connection |
119
+ | `parentRecord` | `object \| null` | Parent record context for relation/formula resolution |
120
+
121
+ > **Note:** You need either `dataSourceId` or `dataSourceFullSlug` to identify the target data source.
122
+
123
+ ---
124
+
125
+ ## Columns
126
+
127
+ **Parameter:** `columns` — `string | null`
128
+
129
+ Use a comma-separated list of field slugs to select specific columns.
130
+
131
+ ### Basic Selection
132
+
133
+ ```
134
+ "columns": "task_name, created_on, record_owner"
135
+ ```
136
+
137
+ ### Aliasing with `:`
138
+
139
+ Use `:` to give a column an alias (shorter name in the result).
140
+
141
+ ```
142
+ "columns": "ra:related_account"
143
+ ```
144
+
145
+ **Result:**
146
+ ```json
147
+ [
148
+ {
149
+ "ra": {
150
+ "id": "uuid",
151
+ "name": "account name"
152
+ }
153
+ }
154
+ ]
155
+ ```
156
+
157
+ ### Relation Expansion with `()`
158
+
159
+ Use parentheses to select specific columns from a related record. Works with `field-relation`, `field-select`, and `field-userSelect` type fields.
160
+
161
+ ```
162
+ "columns": "task_name, related_account(name:account_name, phone:account_phone)"
163
+ ```
164
+
165
+ **Result:**
166
+ ```json
167
+ [
168
+ {
169
+ "task_name": "Task Name",
170
+ "related_account": {
171
+ "name": "Account Name",
172
+ "phone": "05556668899"
173
+ }
174
+ }
175
+ ]
176
+ ```
177
+
178
+ ### Spread Operator `...`
179
+
180
+ Use the spread operator to flatten selected columns from a related record into the root object (no nesting).
181
+
182
+ ```
183
+ "columns": "task_name, ...related_account(account_name, phone:account_phone)"
184
+ ```
185
+
186
+ **Result:**
187
+ ```json
188
+ [
189
+ {
190
+ "task_name": "Task Name",
191
+ "account_name": "Account Name",
192
+ "phone": "05556668899"
193
+ }
194
+ ]
195
+ ```
196
+
197
+ ### Functions with `@`
198
+
199
+ Use `@` to apply a pre-defined function to a column.
200
+
201
+ ```
202
+ "columns": "task_name, ...related_account(an:account_name@upper, ap:account_phone)"
203
+ ```
204
+
205
+ **Result:**
206
+ ```json
207
+ [
208
+ {
209
+ "task_name": "Task Name",
210
+ "an": "ACCOUNT NAME",
211
+ "ap": "05556668899"
212
+ }
213
+ ]
214
+ ```
215
+
216
+ ### Special Date/DateTime Formulas for Aggregations
217
+
218
+ Use the `@` symbol with special date formulas to format date intervals. These are typically used with a date interval filter to group data for a specific period. Values outside the current period are grouped as `"OLDER"` and `"UPCOMING"`.
219
+
220
+ **Format:** `<formula>@<date_or_datetime_field>`
221
+
222
+ | Formula | Description | Example |
223
+ |---|---|---|
224
+ | `hours_of_today` | Groups by hour for today | `hours_of_today@created_on` |
225
+ | `days_of_week` | Groups by day for the current week | `days_of_week@created_on` |
226
+ | `days_of_month` | Groups by day for the current month | `days_of_month@created_on` |
227
+ | `weeks_of_month` | Groups by week number for the current month | `weeks_of_month@created_on` |
228
+ | `weeks_of_quarter` | Groups by week number for the current quarter | `weeks_of_quarter@created_on` |
229
+ | `months_of_quarter` | Groups by month for the current quarter | `months_of_quarter@created_on` |
230
+ | `months_of_year` | Groups by month for the current year (YYYY-MM) | `months_of_year@created_on` |
231
+ | `quarters_of_year` | Groups by quarter for the current year (YYYY-Q) | `quarters_of_year@created_on` |
232
+
233
+ ### Column Syntax with `to_char` Function
234
+
235
+ Use `to_char` with brackets `[]` for date formatting:
236
+
237
+ ```
238
+ "columns": "day:to_char[DD/MM/YYYY]@created_on"
239
+ ```
240
+
241
+ This formats the `created_on` field as `DD/MM/YYYY` and aliases it as `day`.
242
+
243
+ ---
244
+
245
+ ## Filters
246
+
247
+ **Parameter:** `filters` — `IQueryFilterGroup | null`
248
+
249
+ Filters use a recursive group structure with combinators (`and` / `or`) and rules.
250
+
251
+ ### Filter Group Structure
252
+
253
+ ```typescript
254
+ interface IQueryFilterGroup {
255
+ rules: (IQueryFilterRule | IQueryFilterGroup)[];
256
+ combinator?: "and" | "or"; // default: "and"
257
+ not?: boolean; // negate the entire group
258
+ }
259
+
260
+ interface IQueryFilterRule {
261
+ field?: string;
262
+ operator: IFilterOperator;
263
+ value?: any;
264
+ filterType?: QueryFilterType | null;
265
+ }
266
+ ```
267
+
268
+ ### Filter Types (for value casting)
269
+
270
+ | FilterType | Use For |
271
+ |---|---|
272
+ | `NUMERIC` | Number fields |
273
+ | `ALPHA` | Text/string fields |
274
+ | `BOOL` | Boolean fields |
275
+ | `DATE` | Date fields |
276
+ | `TIME` | Time fields |
277
+ | `DATETIME` | DateTime fields |
278
+ | `MULTISELECT` | Multi-select fields |
279
+ | `LIST` | List fields |
280
+ | `RELATION` | Relation fields |
281
+ | `OWNER` | Owner/user fields |
282
+ | `FOLLOWER` | Follower fields |
283
+ | `APPROVAL` | Approval fields |
284
+
285
+ ### Example: Basic AND Filter
286
+
287
+ ```json
288
+ {
289
+ "filters": {
290
+ "combinator": "and",
291
+ "rules": [
292
+ {
293
+ "field": "task_status",
294
+ "operator": "=",
295
+ "value": 1
296
+ },
297
+ {
298
+ "field": "priority",
299
+ "operator": ">=",
300
+ "value": 3
301
+ }
302
+ ]
303
+ }
304
+ }
305
+ ```
306
+
307
+ ### Example: Nested AND + OR
308
+
309
+ Filter records created between two dates, AND where either email is empty OR phone is not empty:
310
+
311
+ ```json
312
+ {
313
+ "filters": {
314
+ "combinator": "and",
315
+ "rules": [
316
+ {
317
+ "field": "created_on",
318
+ "operator": "between",
319
+ "value": ["2025-10-01", "2025-11-01"]
320
+ },
321
+ {
322
+ "combinator": "or",
323
+ "rules": [
324
+ {
325
+ "field": "email",
326
+ "operator": "empty"
327
+ },
328
+ {
329
+ "field": "phone",
330
+ "operator": "not empty"
331
+ }
332
+ ]
333
+ }
334
+ ]
335
+ }
336
+ }
337
+ ```
338
+
339
+ ### Example: Filtering by Related Record's Field
340
+
341
+ Use the `rel_{{relation_field_slug}}/{{field_slug}}` syntax to filter by a parent/related table's field:
342
+
343
+ ```json
344
+ {
345
+ "filters": {
346
+ "combinator": "and",
347
+ "rules": [
348
+ {
349
+ "field": "task_status",
350
+ "operator": "in",
351
+ "value": [1, 2, 3]
352
+ },
353
+ {
354
+ "field": "rel_client/account_status",
355
+ "operator": "=",
356
+ "value": 2
357
+ }
358
+ ]
359
+ }
360
+ }
361
+ ```
362
+
363
+ ### Example: Negated Filter Group
364
+
365
+ ```json
366
+ {
367
+ "filters": {
368
+ "combinator": "and",
369
+ "not": true,
370
+ "rules": [
371
+ {
372
+ "field": "status",
373
+ "operator": "=",
374
+ "value": "archived"
375
+ }
376
+ ]
377
+ }
378
+ }
379
+ ```
380
+
381
+ ### Example: Date Shortcut Operators
382
+
383
+ ```json
384
+ {
385
+ "filters": {
386
+ "rules": [
387
+ {
388
+ "field": "created_on",
389
+ "operator": "this_month"
390
+ }
391
+ ]
392
+ }
393
+ }
394
+ ```
395
+
396
+ ### Example: User-Related Operators
397
+
398
+ ```json
399
+ {
400
+ "filters": {
401
+ "rules": [
402
+ {
403
+ "field": "record_owner",
404
+ "operator": "active_user"
405
+ }
406
+ ]
407
+ }
408
+ }
409
+ ```
410
+
411
+ ### Example: X Days Operators
412
+
413
+ ```json
414
+ {
415
+ "filters": {
416
+ "rules": [
417
+ {
418
+ "field": "due_date",
419
+ "operator": "in_next_x_days",
420
+ "value": 7
421
+ }
422
+ ]
423
+ }
424
+ }
425
+ ```
426
+
427
+ ---
428
+
429
+ ## Filter Keyword
430
+
431
+ **Parameter:** `filterKeyword` — `string | null`
432
+
433
+ Performs a full-text search across all searchable fields.
434
+
435
+ ```json
436
+ {
437
+ "filterKeyword": "John Doe",
438
+ "columns": "id, name, email"
439
+ }
440
+ ```
441
+
442
+ ---
443
+
444
+ ## Order By
445
+
446
+ **Parameter:** `orderBy` — `string | ISelectQueryOrderBy | ISelectQueryOrderBy[]`
447
+
448
+ Use comma-separated field and direction pairs to sort data.
449
+
450
+ ### String Format
451
+
452
+ ```json
453
+ {
454
+ "orderBy": "created_on DESC"
455
+ }
456
+ ```
457
+
458
+ Multiple fields:
459
+
460
+ ```json
461
+ {
462
+ "orderBy": "firstname ASC, lastname DESC"
463
+ }
464
+ ```
465
+
466
+ ### Object Format
467
+
468
+ ```json
469
+ {
470
+ "orderBy": {
471
+ "field": "created_on",
472
+ "direction": "desc"
473
+ }
474
+ }
475
+ ```
476
+
477
+ ### Array Format
478
+
479
+ ```json
480
+ {
481
+ "orderBy": [
482
+ { "field": "firstname", "direction": "asc" },
483
+ { "field": "lastname", "direction": "desc" }
484
+ ]
485
+ }
486
+ ```
487
+
488
+ ### Sorting by Related Field
489
+
490
+ Use parentheses to sort by a field of a related table:
491
+
492
+ ```json
493
+ {
494
+ "orderBy": "relation_field_slug(field_name DESC), id ASC"
495
+ }
496
+ ```
497
+
498
+ ---
499
+
500
+ ## Pagination
501
+
502
+ ### `limit`
503
+
504
+ **Type:** `number` (positive integer)
505
+ **Default:** `100`
506
+
507
+ Maximum number of records to return.
508
+
509
+ ### `offset`
510
+
511
+ **Type:** `number` (non-negative integer)
512
+ **Default:** `0`
513
+
514
+ Number of records to skip for pagination.
515
+
516
+ ### Example
517
+
518
+ ```json
519
+ {
520
+ "columns": "id, name",
521
+ "limit": 25,
522
+ "offset": 50,
523
+ "orderBy": "created_on DESC"
524
+ }
525
+ ```
526
+
527
+ This fetches records 51–75 (page 3 with 25 per page).
528
+
529
+ ---
530
+
531
+ ## Calculations
532
+
533
+ **Parameter:** `calculations` — `ISelectQueryCalculationRule[] | null`
534
+
535
+ Use calculations to group and aggregate data.
536
+
537
+ ### Calculation Rule Structure
538
+
539
+ ```typescript
540
+ interface ISelectQueryCalculationRule {
541
+ func: string; // "count" | "sum" | "avg" | "min" | "max" | "jsonb_agg" | "json_agg" | "array_agg"
542
+ field: string; // field/column to aggregate
543
+ name?: string; // alias for the result column
544
+ isDistinct?: boolean; // aggregate unique values only (default: false)
545
+ minValue?: number; // aggregate values greater than this
546
+ maxValue?: number; // aggregate values less than this
547
+ numberType?: "bigint" | "int" | "decimal"; // result number type
548
+ }
549
+ ```
550
+
551
+ ### Rules
552
+
553
+ - Always use the `id` field for counting records.
554
+ - Use the aggregated field's slug for other functions (sum, avg, etc.).
555
+ - Skip `numberType` unless it is specifically required.
556
+ - Use `name` to alias the calculation result column (keep it short).
557
+
558
+ ### Example: Count per Group
559
+
560
+ Count open tasks per user:
561
+
562
+ ```json
563
+ {
564
+ "columns": "record_owner(name)",
565
+ "calculations": [
566
+ {
567
+ "field": "id",
568
+ "func": "count",
569
+ "name": "count_of_open_tasks"
570
+ }
571
+ ],
572
+ "filters": {
573
+ "combinator": "and",
574
+ "rules": [
575
+ {
576
+ "field": "task_status",
577
+ "operator": "=",
578
+ "value": 1
579
+ }
580
+ ]
581
+ }
582
+ }
583
+ ```
584
+
585
+ **Result:**
586
+ ```json
587
+ [
588
+ {
589
+ "record_owner": {
590
+ "name": "User Name"
591
+ },
592
+ "count_of_open_tasks": 10
593
+ }
594
+ ]
595
+ ```
596
+
597
+ ### Example: Distinct Count
598
+
599
+ Count unique emails:
600
+
601
+ ```json
602
+ {
603
+ "calculations": [
604
+ {
605
+ "field": "email",
606
+ "func": "count",
607
+ "name": "unique_emails",
608
+ "isDistinct": true
609
+ }
610
+ ]
611
+ }
612
+ ```
613
+
614
+ **Result:**
615
+ ```json
616
+ [
617
+ {
618
+ "unique_emails": 10
619
+ }
620
+ ]
621
+ ```
622
+
623
+ ### Example: Multiple Aggregations
624
+
625
+ ```json
626
+ {
627
+ "columns": "category",
628
+ "calculations": [
629
+ {
630
+ "field": "id",
631
+ "func": "count",
632
+ "name": "total"
633
+ },
634
+ {
635
+ "field": "amount",
636
+ "func": "sum",
637
+ "name": "totalAmount"
638
+ },
639
+ {
640
+ "field": "amount",
641
+ "func": "avg",
642
+ "name": "avgAmount"
643
+ },
644
+ {
645
+ "field": "amount",
646
+ "func": "min",
647
+ "name": "minAmount"
648
+ },
649
+ {
650
+ "field": "amount",
651
+ "func": "max",
652
+ "name": "maxAmount"
653
+ }
654
+ ]
655
+ }
656
+ ```
657
+
658
+ ### `showGroupSummaries`
659
+
660
+ **Type:** `boolean`
661
+ **Default:** `false`
662
+
663
+ When `true` and aggregation is used, includes group summary rows in the output.
664
+
665
+ ---
666
+
667
+ ## Formulas
668
+
669
+ **Parameter:** `formulas` — `Record<string, IQueryFormula> | null`
670
+
671
+ Formulas are virtual computed columns injected into `SELECT` queries at build time. Keys are the formula names (used as column aliases), values are formula definitions.
672
+
673
+ There are three formula formats:
674
+
675
+ ### 1. Simple Formula
676
+
677
+ Single-depth function call with positional arguments. Column references use `{column_name}` syntax.
678
+
679
+ ```typescript
680
+ interface IQuerySimpleFormula {
681
+ func: string; // function name (e.g. "to_char")
682
+ args: Array<string | number>; // arguments, column refs use {col}
683
+ }
684
+ ```
685
+
686
+ **Example: Format a Date**
687
+
688
+ ```json
689
+ {
690
+ "columns": "id, name, formatted_date",
691
+ "formulas": {
692
+ "formatted_date": {
693
+ "func": "to_char",
694
+ "args": ["{created_on}", "DD/MM/YYYY"]
695
+ }
696
+ }
697
+ }
698
+ ```
699
+
700
+ > SQL: `to_char("t0"."created_on", $1::text) as "formatted_date"`
701
+
702
+ **Example: Uppercase a Name**
703
+
704
+ ```json
705
+ {
706
+ "formulas": {
707
+ "upper_name": {
708
+ "func": "upper",
709
+ "args": ["{name}"]
710
+ }
711
+ }
712
+ }
713
+ ```
714
+
715
+ **Example: Concatenate Fields**
716
+
717
+ ```json
718
+ {
719
+ "formulas": {
720
+ "full_name": {
721
+ "func": "concat",
722
+ "args": ["{first_name}", " ", "{last_name}"]
723
+ }
724
+ }
725
+ }
726
+ ```
727
+
728
+ ### 2. Block Inline Formula
729
+
730
+ AST-based formula that compiles to an inline SQL expression. Uses a block tree with `kind` discriminator.
731
+
732
+ ```typescript
733
+ interface IQueryBlockInlineFormulaSchema {
734
+ alias?: string;
735
+ inputs: IQueryFormulaBlock[]; // exactly 1 root block
736
+ }
737
+ ```
738
+
739
+ **Example: Simple Division**
740
+
741
+ ```json
742
+ {
743
+ "columns": "id, name, basic_formula",
744
+ "formulas": {
745
+ "basic_formula": {
746
+ "inputs": [{
747
+ "kind": "math",
748
+ "op": "/",
749
+ "inputs": [
750
+ { "kind": "column", "name": "balance" },
751
+ { "kind": "literal", "literal": 100 }
752
+ ]
753
+ }]
754
+ }
755
+ }
756
+ }
757
+ ```
758
+
759
+ > SQL: `("t0"."balance" / $1) as "basic_formula"`
760
+
761
+ ### 3. Block Subquery Formula
762
+
763
+ Compiles to a correlated subquery against a child data source.
764
+
765
+ ```typescript
766
+ interface IQueryBlockSubqueryFormulaSchema {
767
+ alias?: string;
768
+ inputs: IQueryFormulaBlock[];
769
+ from: string; // child table full slug
770
+ with: string | Record<string, string>; // join condition(s)
771
+ filters?: IQueryFilterGroup;
772
+ }
773
+ ```
774
+
775
+ **Example: Count Child Records**
776
+
777
+ ```json
778
+ {
779
+ "columns": "id, name, children_count",
780
+ "formulas": {
781
+ "children_count": {
782
+ "from": "app_child_table",
783
+ "with": "parent_field",
784
+ "inputs": [{
785
+ "kind": "aggregate",
786
+ "name": "count",
787
+ "inputs": []
788
+ }]
789
+ }
790
+ }
791
+ }
792
+ ```
793
+
794
+ > SQL: `(SELECT count(*) FROM "schema"."child_table" AS "t0_child" WHERE "t0_child"."parent_field" = "t0"."id") AS "children_count"`
795
+
796
+ **Example: Subquery with Filters**
797
+
798
+ ```json
799
+ {
800
+ "formulas": {
801
+ "active_children": {
802
+ "from": "app_child_table",
803
+ "with": "parent_id",
804
+ "filters": {
805
+ "rules": [
806
+ { "field": "status", "operator": "=", "value": "active" }
807
+ ]
808
+ },
809
+ "inputs": [{
810
+ "kind": "aggregate",
811
+ "name": "count",
812
+ "inputs": []
813
+ }]
814
+ }
815
+ }
816
+ }
817
+ ```
818
+
819
+ **Example: Multi-Field Subquery Join**
820
+
821
+ ```json
822
+ {
823
+ "formulas": {
824
+ "related_sum": {
825
+ "from": "app_child",
826
+ "with": {
827
+ "child_field1": "parent_field1",
828
+ "child_field2": "parent_field2"
829
+ },
830
+ "inputs": [{
831
+ "kind": "aggregate",
832
+ "name": "sum",
833
+ "inputs": [{ "kind": "column", "name": "amount" }]
834
+ }]
835
+ }
836
+ }
837
+ }
838
+ ```
839
+
840
+ **Example: Compatibility Wrapper**
841
+
842
+ Block subquery formulas can also be wrapped under an `expression` key:
843
+
844
+ ```json
845
+ {
846
+ "formulas": {
847
+ "children_count": {
848
+ "expression": {
849
+ "from": "app_child_table",
850
+ "with": "parent_field",
851
+ "inputs": [{
852
+ "kind": "aggregate",
853
+ "name": "count",
854
+ "distinct": true,
855
+ "inputs": [{ "kind": "column", "name": "id" }]
856
+ }]
857
+ }
858
+ }
859
+ }
860
+ }
861
+ ```
862
+
863
+ ### Block Formula Kinds Reference
864
+
865
+ Every block has a `kind` discriminator and optional `tz` (timezone) and `cast` (type cast) properties.
866
+
867
+ #### `literal` — Static Values
868
+
869
+ ```json
870
+ { "kind": "literal", "literal": "Hello World" }
871
+ { "kind": "literal", "literal": 42 }
872
+ { "kind": "literal", "literal": true }
873
+ { "kind": "literal", "literal": null }
874
+ { "kind": "literal", "literal": ["active", "pending", "approved"] }
875
+ ```
876
+
877
+ #### `column` — Table Column Reference
878
+
879
+ ```json
880
+ { "kind": "column", "name": "fullname" }
881
+ { "kind": "column", "name": ["col1", "col2"] }
882
+ ```
883
+
884
+ #### `builtin` — SQL Constants
885
+
886
+ ```json
887
+ { "kind": "builtin", "name": "current_date" }
888
+ { "kind": "builtin", "name": "now" }
889
+ ```
890
+
891
+ Allowed values: `current_date`, `current_time`, `current_timestamp`, `now`
892
+
893
+ #### `function` — SQL Function Calls
894
+
895
+ ```json
896
+ {
897
+ "kind": "function",
898
+ "name": "concat",
899
+ "inputs": [
900
+ { "kind": "literal", "literal": "Hello " },
901
+ { "kind": "column", "name": "fullname" }
902
+ ]
903
+ }
904
+ ```
905
+
906
+ > Only whitelisted functions are allowed (see [Allowed Functions Reference](#allowed-functions-reference)).
907
+
908
+ #### `extract` — Date Part Extraction
909
+
910
+ ```json
911
+ {
912
+ "kind": "extract",
913
+ "part": "month",
914
+ "inputs": [{ "kind": "column", "name": "created_on" }]
915
+ }
916
+ ```
917
+
918
+ > SQL: `extract(month from "t0"."created_on")`
919
+
920
+ Parts: `year`, `month`, `day`, `hour`, `minute`, `second`
921
+
922
+ #### `aggregate` — Aggregate Functions
923
+
924
+ ```json
925
+ { "kind": "aggregate", "name": "count", "inputs": [] }
926
+ ```
927
+
928
+ > SQL: `count(*)`
929
+
930
+ ```json
931
+ {
932
+ "kind": "aggregate",
933
+ "name": "count",
934
+ "distinct": true,
935
+ "inputs": [{ "kind": "column", "name": "product_code" }]
936
+ }
937
+ ```
938
+
939
+ > SQL: `count(distinct "t0"."product_code")`
940
+
941
+ Allowed aggregates: `count`, `sum`, `avg`, `min`, `max`, `jsonb_agg`, `json_agg`, `array_agg`
942
+
943
+ #### `math` — Arithmetic Operations
944
+
945
+ ```json
946
+ {
947
+ "kind": "math",
948
+ "op": "*",
949
+ "inputs": [
950
+ { "kind": "column", "name": "quantity" },
951
+ { "kind": "column", "name": "unit_price" }
952
+ ]
953
+ }
954
+ ```
955
+
956
+ > SQL: `("t0"."quantity" * "t0"."unit_price")`
957
+
958
+ Operators: `+`, `-`, `*`, `/`, `%`
959
+ Requires at least 2 operands. For 3+: `((a op b) op c)`.
960
+
961
+ #### `case` — Conditional Expressions
962
+
963
+ ```json
964
+ {
965
+ "kind": "case",
966
+ "cases": [{
967
+ "when": {
968
+ "kind": "compare",
969
+ "op": ">",
970
+ "left": { "kind": "column", "name": "price" },
971
+ "right": { "kind": "literal", "literal": 100 }
972
+ },
973
+ "then": { "kind": "literal", "literal": "expensive" }
974
+ }],
975
+ "else": { "kind": "literal", "literal": "cheap" }
976
+ }
977
+ ```
978
+
979
+ > SQL: `case when "t0"."price" > $1 then $2 else $3 end`
980
+
981
+ #### `compare` — Comparison Operations
982
+
983
+ ```json
984
+ {
985
+ "kind": "compare",
986
+ "op": "in",
987
+ "left": { "kind": "column", "name": "status" },
988
+ "right": { "kind": "literal", "literal": ["active", "pending"] }
989
+ }
990
+ ```
991
+
992
+ > SQL: `"t0"."status" in ($1, $2)`
993
+
994
+ Operators: `=`, `!=`, `<>`, `>`, `<`, `>=`, `<=`, `like`, `ilike`, `in`, `not in`
995
+
996
+ #### `boolean` — Logical Operations
997
+
998
+ ```json
999
+ {
1000
+ "kind": "boolean",
1001
+ "op": "and",
1002
+ "inputs": [
1003
+ {
1004
+ "kind": "compare", "op": ">",
1005
+ "left": { "kind": "column", "name": "price" },
1006
+ "right": { "kind": "literal", "literal": 100 }
1007
+ },
1008
+ {
1009
+ "kind": "compare", "op": "ilike",
1010
+ "left": { "kind": "column", "name": "name" },
1011
+ "right": { "kind": "literal", "literal": "%pro%" }
1012
+ }
1013
+ ]
1014
+ }
1015
+ ```
1016
+
1017
+ > SQL: `(("t0"."price" > $1) and ("t0"."name" ilike $2))`
1018
+
1019
+ Operators: `and`, `or`, `not`
1020
+
1021
+ ### Block Formula: Type Casting
1022
+
1023
+ Any block can include a `cast` property:
1024
+
1025
+ ```json
1026
+ { "kind": "column", "name": "price", "cast": "decimal" }
1027
+ ```
1028
+
1029
+ > SQL: `("t0"."price")::decimal`
1030
+
1031
+ ### Block Formula: Timezone Handling
1032
+
1033
+ Any block can include a `tz` property:
1034
+
1035
+ ```json
1036
+ { "kind": "function", "name": "now", "tz": "UTC" }
1037
+ ```
1038
+
1039
+ > SQL: `now() at time zone $1`
1040
+
1041
+ ### Advanced Formula Examples
1042
+
1043
+ **Nested Functions with Aggregates:** Round the sum of (quantity × unit_price)
1044
+
1045
+ ```json
1046
+ {
1047
+ "formulas": {
1048
+ "rounded_total": {
1049
+ "alias": "rounded_total",
1050
+ "inputs": [{
1051
+ "kind": "function",
1052
+ "name": "round",
1053
+ "inputs": [
1054
+ {
1055
+ "kind": "aggregate",
1056
+ "name": "sum",
1057
+ "inputs": [{
1058
+ "kind": "math",
1059
+ "op": "*",
1060
+ "inputs": [
1061
+ { "kind": "column", "name": "quantity" },
1062
+ { "kind": "column", "name": "unit_price" }
1063
+ ]
1064
+ }]
1065
+ },
1066
+ { "kind": "literal", "literal": 2 }
1067
+ ]
1068
+ }]
1069
+ }
1070
+ }
1071
+ }
1072
+ ```
1073
+
1074
+ > SQL: `round(sum(("t0"."quantity" * "t0"."unit_price")), $1) as "rounded_total"`
1075
+
1076
+ **CASE with Boolean Logic:** Categorize rows
1077
+
1078
+ ```json
1079
+ {
1080
+ "formulas": {
1081
+ "category": {
1082
+ "inputs": [{
1083
+ "kind": "case",
1084
+ "cases": [{
1085
+ "when": {
1086
+ "kind": "boolean",
1087
+ "op": "and",
1088
+ "inputs": [
1089
+ {
1090
+ "kind": "compare", "op": ">",
1091
+ "left": { "kind": "column", "name": "price" },
1092
+ "right": { "kind": "literal", "literal": 100 }
1093
+ },
1094
+ {
1095
+ "kind": "compare", "op": "ilike",
1096
+ "left": { "kind": "column", "name": "name" },
1097
+ "right": { "kind": "literal", "literal": "%pro%" }
1098
+ }
1099
+ ]
1100
+ },
1101
+ "then": { "kind": "literal", "literal": "premium" }
1102
+ }],
1103
+ "else": { "kind": "literal", "literal": "standard" }
1104
+ }]
1105
+ }
1106
+ }
1107
+ }
1108
+ ```
1109
+
1110
+ **Null Handling with COALESCE:**
1111
+
1112
+ ```json
1113
+ {
1114
+ "formulas": {
1115
+ "safe_desc": {
1116
+ "inputs": [{
1117
+ "kind": "function",
1118
+ "name": "coalesce",
1119
+ "inputs": [
1120
+ { "kind": "column", "name": "description" },
1121
+ { "kind": "literal", "literal": "No description" }
1122
+ ]
1123
+ }]
1124
+ }
1125
+ }
1126
+ }
1127
+ ```
1128
+
1129
+ **Timezone Conversion:**
1130
+
1131
+ ```json
1132
+ {
1133
+ "formulas": {
1134
+ "local_time": {
1135
+ "inputs": [{
1136
+ "kind": "function",
1137
+ "name": "to_char",
1138
+ "inputs": [
1139
+ { "kind": "function", "name": "now", "tz": "UTC" },
1140
+ { "kind": "literal", "literal": "YYYY-MM-DD HH24:MI:SS" }
1141
+ ]
1142
+ }]
1143
+ }
1144
+ }
1145
+ }
1146
+ ```
1147
+
1148
+ > SQL: `to_char(now() at time zone $1, $2)`
1149
+
1150
+ ---
1151
+
1152
+ ## Pivot
1153
+
1154
+ **Parameter:** `pivot` — `{ matrix, hideEmptyRows?, orderBy?, limit? } | null`
1155
+
1156
+ Use `pivot` to perform advanced cross-tab grouping queries with aggregations. Each matrix object is executed as a CTE query. All CTEs are cross-joined to create a full matrix, then the main data is left-joined. This ensures all combinations appear in results, even when no matching records exist.
1157
+
1158
+ ### Pivot Structure
1159
+
1160
+ ```typescript
1161
+ interface IPivot {
1162
+ matrix: ISelectPivotMatrixQuery[];
1163
+ hideEmptyRows?: boolean;
1164
+ orderBy?: string | ISelectQueryOrderBy | ISelectQueryOrderBy[];
1165
+ limit?: number;
1166
+ }
1167
+
1168
+ interface ISelectPivotMatrixQuery {
1169
+ using: string; // field in main query to join the CTE on
1170
+ columns: string; // columns to select (supports alias, spread, functions)
1171
+ spread?: boolean; // spread jsonb columns as separate columns
1172
+ filters?: IQueryFilterGroup;
1173
+ limit?: number;
1174
+ dateRange?: {
1175
+ interval: "day" | "week" | "month" | "year" | "hour" | "minute" | "second";
1176
+ increment?: number; // number of intervals to increment (default: 1)
1177
+ min: string; // minimum datetime value (ISO format)
1178
+ max: string; // maximum datetime value (ISO format)
1179
+ };
1180
+ }
1181
+ ```
1182
+
1183
+ ### How Pivot Works
1184
+
1185
+ 1. Each `matrix` entry generates a CTE (Common Table Expression):
1186
+ - If `dateRange` is provided, a date range series is generated
1187
+ - Otherwise, records are fetched from the related data source
1188
+ 2. All CTEs are cross-joined to create the full cartesian product (matrix)
1189
+ 3. The main query data is left-joined to the matrix
1190
+ 4. This ensures all combinations appear, even with zero matching records
1191
+
1192
+ ### Example: Orders per Day, per User, per Status
1193
+
1194
+ ```json
1195
+ {
1196
+ "columns": "...order_status(orderStatus:name)",
1197
+ "pivot": {
1198
+ "matrix": [
1199
+ {
1200
+ "using": "created_on",
1201
+ "columns": "day:to_char[DD/MM/YYYY]@created_on",
1202
+ "dateRange": {
1203
+ "interval": "day",
1204
+ "min": "2025-09-01T00:00:00Z",
1205
+ "max": "2025-09-02T00:00:00Z"
1206
+ },
1207
+ "spread": true
1208
+ },
1209
+ {
1210
+ "using": "record_owner",
1211
+ "columns": "userName:name",
1212
+ "spread": true,
1213
+ "filters": {
1214
+ "combinator": "and",
1215
+ "rules": [
1216
+ {
1217
+ "field": "primary_role",
1218
+ "operator": "=",
1219
+ "value": "1cdefd30-9f6d-4c7e-94c9-5b8a7e1c9f31"
1220
+ }
1221
+ ]
1222
+ }
1223
+ }
1224
+ ]
1225
+ },
1226
+ "calculations": [
1227
+ {
1228
+ "field": "id",
1229
+ "func": "count",
1230
+ "name": "total"
1231
+ },
1232
+ {
1233
+ "field": "amount",
1234
+ "func": "sum",
1235
+ "name": "totalSold"
1236
+ }
1237
+ ]
1238
+ }
1239
+ ```
1240
+
1241
+ **What each matrix entry does:**
1242
+
1243
+ 1. **First matrix** (`using: "created_on"`): Creates a date range series from 2025-09-01 to 2025-09-02 with `day` intervals. Even if there are no orders on a given day, that day still appears in results.
1244
+ 2. **Second matrix** (`using: "record_owner"`): Fetches users filtered by role. Even if a user has no orders on a day, they still appear in the cross-join.
1245
+
1246
+ **Result:**
1247
+ ```json
1248
+ [
1249
+ {
1250
+ "userName": "User 1",
1251
+ "orderStatus": 1,
1252
+ "day": "01/09/2025",
1253
+ "total": 10,
1254
+ "totalSold": 3000
1255
+ },
1256
+ {
1257
+ "userName": "User 2",
1258
+ "orderStatus": 5,
1259
+ "day": "01/09/2025",
1260
+ "total": 5,
1261
+ "totalSold": 1500
1262
+ },
1263
+ {
1264
+ "userName": "User 1",
1265
+ "orderStatus": 1,
1266
+ "day": "02/09/2025",
1267
+ "total": 10,
1268
+ "totalSold": 3000
1269
+ },
1270
+ {
1271
+ "userName": "User 2",
1272
+ "orderStatus": 3,
1273
+ "day": "02/09/2025",
1274
+ "total": 5,
1275
+ "totalSold": 1500
1276
+ }
1277
+ ]
1278
+ ```
1279
+
1280
+ ### Date Range Intervals
1281
+
1282
+ | Interval | Description |
1283
+ |---|---|
1284
+ | `day` | Generate one row per day |
1285
+ | `week` | Generate one row per week |
1286
+ | `month` | Generate one row per month |
1287
+ | `year` | Generate one row per year |
1288
+ | `hour` | Generate one row per hour |
1289
+ | `minute` | Generate one row per minute |
1290
+ | `second` | Generate one row per second |
1291
+
1292
+ ### Pivot Options
1293
+
1294
+ | Option | Type | Description |
1295
+ |---|---|---|
1296
+ | `hideEmptyRows` | `boolean` | Don't include rows where no matching data exists |
1297
+ | `orderBy` | `string \| object \| array` | Sort the pivot results |
1298
+ | `limit` | `number` | Maximum number of pivot result rows (default: 1000) |
1299
+
1300
+ ---
1301
+
1302
+ ## Child Queries
1303
+
1304
+ **Parameter:** `childQueries` — `Record<string, IQueryChildQueryParams> | null`
1305
+
1306
+ Use `childQueries` to fetch related records from a child data source as a nested JSON array for each parent record. This is similar to a `LEFT JOIN` but returns results as an aggregated JSON array in a single column.
1307
+
1308
+ ### Child Query Structure
1309
+
1310
+ ```typescript
1311
+ interface IQueryChildQueryParams {
1312
+ from: string; // child data source slug in "appSlug_slug" format
1313
+ using: string; // field in the child DS that references the parent record
1314
+ columns?: string | null; // comma-separated columns to select from child
1315
+ filters?: IQueryFilterGroup; // optional filters on child records
1316
+ calculations?: ISelectQueryCalculationRule[]; // optional aggregations
1317
+ orderBy?: string | ISelectQueryOrderBy | ISelectQueryOrderBy[];
1318
+ limit?: number; // max child records per parent (default: 100)
1319
+ }
1320
+ ```
1321
+
1322
+ ### Example: Clients with Their Matters
1323
+
1324
+ ```json
1325
+ {
1326
+ "columns": "id, name, matters",
1327
+ "childQueries": {
1328
+ "matters": {
1329
+ "from": "attornaid_matter",
1330
+ "using": "client",
1331
+ "columns": "name",
1332
+ "filters": {
1333
+ "rules": [
1334
+ { "field": "created_on", "operator": "<", "value": "2025-12-01" }
1335
+ ]
1336
+ }
1337
+ }
1338
+ }
1339
+ }
1340
+ ```
1341
+
1342
+ **Result:**
1343
+ ```json
1344
+ [
1345
+ {
1346
+ "id": "uuid",
1347
+ "name": "Client Name",
1348
+ "matters": [
1349
+ { "name": "Matter 1" },
1350
+ { "name": "Matter 2" }
1351
+ ]
1352
+ }
1353
+ ]
1354
+ ```
1355
+
1356
+ ### Key Rules
1357
+
1358
+ - The child query key (e.g. `"matters"`) must also appear in the parent's `columns` string.
1359
+ - `from` uses `appSlug_slug` format (e.g. `"attornaid_matter"`).
1360
+ - `using` is the field in the **child** data source that references the parent record's `id`.
1361
+ - All parent query parameters (`columns`, `filters`, `calculations`, `orderBy`, `limit`) are supported within child queries.
1362
+
1363
+ ### Example: Products with Recent Orders (limited, sorted)
1364
+
1365
+ ```json
1366
+ {
1367
+ "columns": "id, product_name, recent_orders",
1368
+ "childQueries": {
1369
+ "recent_orders": {
1370
+ "from": "shop_order_item",
1371
+ "using": "product",
1372
+ "columns": "order_date, quantity, total_price",
1373
+ "orderBy": "order_date DESC",
1374
+ "limit": 5,
1375
+ "filters": {
1376
+ "rules": [
1377
+ { "field": "order_date", "operator": "last_30_days" }
1378
+ ]
1379
+ }
1380
+ }
1381
+ }
1382
+ }
1383
+ ```
1384
+
1385
+ ### Example: Child Query with Aggregations
1386
+
1387
+ ```json
1388
+ {
1389
+ "columns": "id, name, order_stats",
1390
+ "childQueries": {
1391
+ "order_stats": {
1392
+ "from": "shop_order",
1393
+ "using": "customer",
1394
+ "calculations": [
1395
+ { "field": "id", "func": "count", "name": "total_orders" },
1396
+ { "field": "amount", "func": "sum", "name": "total_spent" }
1397
+ ]
1398
+ }
1399
+ }
1400
+ }
1401
+ ```
1402
+
1403
+ ---
1404
+
1405
+ ## Expand
1406
+
1407
+ ### `expandTypes` (Deprecated)
1408
+
1409
+ **Type:** `("user" | "enum" | "relation")[] | null`
1410
+
1411
+ Automatically expand all columns of the specified field types. Replaced by `expand`.
1412
+
1413
+ ```json
1414
+ {
1415
+ "expandTypes": ["user", "relation"]
1416
+ }
1417
+ ```
1418
+
1419
+ ### `expand`
1420
+
1421
+ **Type:** `string[] | null`
1422
+
1423
+ List of specific field slugs to expand. Expanded fields return their full object representation instead of just the ID/value.
1424
+
1425
+ ```json
1426
+ {
1427
+ "expand": ["record_owner", "related_account", "status"]
1428
+ }
1429
+ ```
1430
+
1431
+ ---
1432
+
1433
+ ## Query Mode
1434
+
1435
+ **Parameter:** `queryMode` — `"OLTP" | "OLAP" | "EXPORT"`
1436
+ **Default:** `"OLTP"`
1437
+
1438
+ | Mode | Description |
1439
+ |---|---|
1440
+ | `OLTP` | Standard transactional queries. Default. Lower limits for interactive use. |
1441
+ | `OLAP` | Analytical queries. Allows larger result sets. |
1442
+ | `EXPORT` | Export mode. Highest limits for bulk data extraction. |
1443
+
1444
+ ---
1445
+
1446
+ ## Distinct Columns
1447
+
1448
+ **Parameter:** `distinctColumns` — `string[] | null`
1449
+
1450
+ List of columns to deduplicate results on. Should be avoided unless strictly necessary for performance reasons.
1451
+
1452
+ ```json
1453
+ {
1454
+ "columns": "email, name",
1455
+ "distinctColumns": ["email"]
1456
+ }
1457
+ ```
1458
+
1459
+ ---
1460
+
1461
+ ## Full Count
1462
+
1463
+ **Parameter:** `fullCount` — `boolean`
1464
+
1465
+ When `true`, returns the total count of records matching the filters using a window function, alongside the paginated results.
1466
+
1467
+ ```json
1468
+ {
1469
+ "columns": "id, name",
1470
+ "limit": 10,
1471
+ "offset": 0,
1472
+ "fullCount": true
1473
+ }
1474
+ ```
1475
+
1476
+ ---
1477
+
1478
+ ## Cursor-Based Sync
1479
+
1480
+ | Parameter | Type | Description |
1481
+ |---|---|---|
1482
+ | `cursorDateStart` | `string \| null` | ISO datetime cursor start for data sync |
1483
+ | `cursorDateEnd` | `string \| null` | ISO datetime cursor end for data sync |
1484
+
1485
+ Used for incremental data synchronization, fetching only records modified within the cursor window.
1486
+
1487
+ ```json
1488
+ {
1489
+ "cursorDateStart": "2025-10-01T00:00:00Z",
1490
+ "cursorDateEnd": "2025-10-02T00:00:00Z"
1491
+ }
1492
+ ```
1493
+
1494
+ ---
1495
+
1496
+ ## Filter Operators Reference
1497
+
1498
+ ### Basic Comparison
1499
+
1500
+ | Operator | Description | Value Type |
1501
+ |---|---|---|
1502
+ | `=` | Equals | any |
1503
+ | `!=` | Not equals | any |
1504
+ | `<>` | Not equals (alias) | any |
1505
+ | `>` | Greater than | number/date |
1506
+ | `<` | Less than | number/date |
1507
+ | `>=` | Greater than or equal | number/date |
1508
+ | `<=` | Less than or equal | number/date |
1509
+ | `between` | Between two values | `[min, max]` |
1510
+
1511
+ ### Text Search
1512
+
1513
+ | Operator | Description | Value Type |
1514
+ |---|---|---|
1515
+ | `like` | Pattern match (case-sensitive) | string with `%` wildcards |
1516
+ | `not like` | Negated pattern match | string with `%` wildcards |
1517
+ | `starts with` | Starts with value | string |
1518
+ | `ends with` | Ends with value | string |
1519
+
1520
+ ### Collection
1521
+
1522
+ | Operator | Description | Value Type |
1523
+ |---|---|---|
1524
+ | `in` | Value is in list | array |
1525
+ | `not in` | Value is not in list | array |
1526
+ | `exists` | Record exists | — |
1527
+ | `contains any` | Contains any of the values | array |
1528
+ | `contains all` | Contains all of the values | array |
1529
+ | `not contains` | Does not contain | any |
1530
+
1531
+ ### Null/Empty Checks
1532
+
1533
+ | Operator | Description | Value Type |
1534
+ |---|---|---|
1535
+ | `is` | Is value | any |
1536
+ | `is not` | Is not value | any |
1537
+ | `empty` | Field is empty/null | — |
1538
+ | `not empty` | Field is not empty/null | — |
1539
+ | `null` | Field is null | — |
1540
+ | `not null` | Field is not null | — |
1541
+
1542
+ ### Boolean
1543
+
1544
+ | Operator | Description | Value Type |
1545
+ |---|---|---|
1546
+ | `true` | Field is true | — |
1547
+ | `false` | Field is false | — |
1548
+
1549
+ ### User-Related
1550
+
1551
+ | Operator | Description |
1552
+ |---|---|
1553
+ | `active_user` | Field equals the current logged-in user |
1554
+ | `not_active_user` | Field does not equal the current user |
1555
+ | `in_active_user_scope` | Field is within active user's scope |
1556
+ | `not_in_active_user_scope` | Field is outside active user's scope |
1557
+ | `in_role` | User has specified role |
1558
+ | `not_in_role` | User does not have specified role |
1559
+ | `in_team` | User is in specified team |
1560
+ | `not_in_team` | User is not in specified team |
1561
+ | `in_active_user_team` | User is in active user's team |
1562
+ | `not_in_active_user_team` | User is not in active user's team |
1563
+ | `in_unit` | User is in specified org unit |
1564
+ | `not_in_unit` | User is not in specified org unit |
1565
+ | `in_sub_unit` | User is in sub-unit |
1566
+ | `not_in_sub_unit` | User is not in sub-unit |
1567
+
1568
+ ### Record Sharing
1569
+
1570
+ | Operator | Description |
1571
+ |---|---|
1572
+ | `shared_to_me` | Record is shared to the current user |
1573
+
1574
+ ### Follower-Related
1575
+
1576
+ | Operator | Description |
1577
+ |---|---|
1578
+ | `contains_active_user` | Followers contain the active user |
1579
+ | `not_contains_active_user` | Followers do not contain the active user |
1580
+ | `contains_member_of_active_user_team` | Followers contain a member of active user's team |
1581
+
1582
+ ### Date Shortcuts
1583
+
1584
+ | Operator | Description |
1585
+ |---|---|
1586
+ | `today` | Is today |
1587
+ | `tomorrow` | Is tomorrow |
1588
+ | `yesterday` | Is yesterday |
1589
+ | `last_7_days` | Within last 7 days |
1590
+ | `last_15_days` | Within last 15 days |
1591
+ | `last_30_days` | Within last 30 days |
1592
+ | `last_60_days` | Within last 60 days |
1593
+ | `last_90_days` | Within last 90 days |
1594
+ | `last_120_days` | Within last 120 days |
1595
+ | `next_7_days` | Within next 7 days |
1596
+ | `next_15_days` | Within next 15 days |
1597
+ | `next_30_days` | Within next 30 days |
1598
+ | `next_60_days` | Within next 60 days |
1599
+ | `next_90_days` | Within next 90 days |
1600
+ | `next_120_days` | Within next 120 days |
1601
+ | `last_week` | During last week |
1602
+ | `this_week` | During this week |
1603
+ | `next_week` | During next week |
1604
+ | `last_month` | During last month |
1605
+ | `this_month` | During this month |
1606
+ | `next_month` | During next month |
1607
+ | `before_today` | Before today |
1608
+ | `after_today` | After today |
1609
+ | `last_year` | During last year |
1610
+ | `this_year` | During this year |
1611
+ | `next_year` | During next year |
1612
+ | `first_quarter` | During Q1 of current year |
1613
+ | `second_quarter` | During Q2 of current year |
1614
+ | `third_quarter` | During Q3 of current year |
1615
+ | `fourth_quarter` | During Q4 of current year |
1616
+ | `last_3_months` | Within last 3 months |
1617
+ | `last_6_months` | Within last 6 months |
1618
+
1619
+ ### Dynamic Date Operators (require value)
1620
+
1621
+ | Operator | Value | Description |
1622
+ |---|---|---|
1623
+ | `x_days_ago` | number | Exactly X days ago |
1624
+ | `x_days_later` | number | Exactly X days later |
1625
+ | `before_last_x_days` | number | Before the last X days |
1626
+ | `in_last_x_days` | number | Within the last X days |
1627
+ | `after_last_x_days` | number | After the last X days |
1628
+ | `in_next_x_days` | number | Within the next X days |
1629
+
1630
+ ---
1631
+
1632
+ ## Allowed Functions Reference
1633
+
1634
+ ### Postgres Functions
1635
+
1636
+ | Category | Functions |
1637
+ |---|---|
1638
+ | **String** | `length`, `lower`, `upper`, `substr`, `replace`, `concat`, `trim`, `ltrim`, `rtrim`, `btrim`, `split_part`, `initcap`, `reverse`, `strpos`, `lpad`, `rpad` |
1639
+ | **Number** | `abs`, `ceil`, `floor`, `round`, `sqrt`, `power`, `mod`, `gcd`, `lcm`, `exp`, `ln`, `log`, `log10`, `log1p`, `pi`, `sign`, `width_bucket`, `trunc`, `greatest`, `least` |
1640
+ | **Date/Time** | `now`, `age`, `clock_timestamp`, `date_part`, `date_trunc`, `extract`, `isfinite`, `justify_days`, `justify_hours`, `make_date`, `make_time`, `make_timestamp`, `make_timestamptz`, `timeofday`, `to_timestamp`, `to_char`, `to_date`, `to_time` |
1641
+ | **Utility** | `coalesce` |
1642
+ | **JSON/JSONB** | `jsonb_array_length`, `jsonb_extract_path`, `jsonb_extract_path_text`, `jsonb_object_keys`, `jsonb_build_object`, `json_build_object`, `jsonb_agg`, `json_agg`, `array_agg`, `array_to_json`, `row_to_json` |
1643
+ | **Internal** | `noselect`, `anyvalue` |
1644
+
1645
+ ### MySQL Functions
1646
+
1647
+ | Category | Functions |
1648
+ |---|---|
1649
+ | **String** | `length`, `lower`, `upper`, `substr`, `substring`, `replace`, `concat`, `trim`, `ltrim`, `rtrim`, `left`, `right`, `reverse`, `locate`, `lpad`, `rpad` |
1650
+ | **Number** | `abs`, `ceil`, `ceiling`, `floor`, `round`, `sqrt`, `power`, `pow`, `mod`, `exp`, `ln`, `log`, `log10`, `sign`, `truncate`, `greatest`, `least` |
1651
+ | **Date/Time** | `now`, `curdate`, `curtime`, `current_date`, `current_time`, `current_timestamp`, `date`, `time`, `year`, `month`, `day`, `hour`, `minute`, `second`, `date_format`, `str_to_date`, `unix_timestamp`, `from_unixtime` |
1652
+ | **Utility** | `coalesce`, `ifnull`, `format` |
1653
+ | **JSON** | `json_value`, `json_extract` |
1654
+
1655
+ ### ClickHouse Functions
1656
+
1657
+ | Category | Functions |
1658
+ |---|---|
1659
+ | **String** | `length`, `lower`, `upper`, `substr`, `substring`, `replace`, `concat`, `trim`, `ltrim`, `rtrim`, `reverse`, `position`, `leftPad`, `rightPad` |
1660
+ | **Number** | `abs`, `ceil`, `floor`, `round`, `sqrt`, `pow`, `mod`, `exp`, `ln`, `log`, `log10`, `sign`, `trunc`, `greatest`, `least` |
1661
+ | **Date/Time** | `now`, `today`, `yesterday`, `toYear`, `toMonth`, `toDayOfMonth`, `toHour`, `toMinute`, `toSecond`, `formatDateTime`, `parseDateTime` |
1662
+ | **Utility** | `coalesce`, `ifnull`, `multiif` |
1663
+
1664
+ ### Postgres Literals (used as raw SQL)
1665
+
1666
+ `current_date`, `current_time`, `current_timestamp`
1667
+
1668
+ ---
1669
+
1670
+ ## Allowed Aggregates Reference
1671
+
1672
+ These aggregate functions work across all dialects:
1673
+
1674
+ | Aggregate | Description |
1675
+ |---|---|
1676
+ | `count` | Count of rows/values |
1677
+ | `sum` | Sum of values |
1678
+ | `avg` | Average of values |
1679
+ | `min` | Minimum value |
1680
+ | `max` | Maximum value |
1681
+ | `jsonb_agg` | Aggregate values as JSONB array |
1682
+ | `json_agg` | Aggregate values as JSON array |
1683
+ | `array_agg` | Aggregate values as PostgreSQL array |
1684
+
1685
+ ---
1686
+
1687
+ ## Allowed Cast Types
1688
+
1689
+ Valid types for the `cast` property in block formulas and `numberType` in calculations:
1690
+
1691
+ `int`, `int[]`, `int2`, `int2[]`, `int4`, `int4[]`, `int8`, `int8[]`, `bigint`, `bigint[]`, `real`, `real[]`, `float`, `float[]`, `float4`, `float4[]`, `float8`, `float8[]`, `numeric`, `numeric[]`, `double`, `double[]`, `decimal`, `decimal[]`, `money`, `money[]`, `timestamp`, `timestamp[]`, `timestamptz`, `timestamptz[]`, `date`, `date[]`, `time`, `time[]`, `interval`, `interval[]`, `bool`, `bool[]`, `boolean`, `boolean[]`, `uuid`, `uuid[]`, `text`, `text[]`
1692
+
1693
+ ---
1694
+
1695
+ ## Complete Examples
1696
+
1697
+ ### Example 1: Full-Featured Select Query
1698
+
1699
+ Fetch tasks with filters, sorting, pagination, and relation expansion:
1700
+
1701
+ ```json
1702
+ {
1703
+ "dataSourceFullSlug": "crm_task",
1704
+ "columns": "id, task_name, ...record_owner(owner_name:name, owner_email:email), ...related_account(account_name:name)",
1705
+ "filters": {
1706
+ "combinator": "and",
1707
+ "rules": [
1708
+ { "field": "task_status", "operator": "in", "value": [1, 2] },
1709
+ { "field": "due_date", "operator": "in_next_x_days", "value": 7 },
1710
+ { "field": "record_owner", "operator": "in_active_user_team" }
1711
+ ]
1712
+ },
1713
+ "orderBy": "due_date ASC, task_name ASC",
1714
+ "limit": 50,
1715
+ "offset": 0,
1716
+ "fullCount": true
1717
+ }
1718
+ ```
1719
+
1720
+ ### Example 2: Aggregation Dashboard
1721
+
1722
+ Monthly sales report grouped by category:
1723
+
1724
+ ```json
1725
+ {
1726
+ "dataSourceFullSlug": "shop_order",
1727
+ "columns": "months_of_year@created_on, ...category(cat:name)",
1728
+ "calculations": [
1729
+ { "field": "id", "func": "count", "name": "order_count" },
1730
+ { "field": "total_amount", "func": "sum", "name": "revenue" },
1731
+ { "field": "total_amount", "func": "avg", "name": "avg_order" }
1732
+ ],
1733
+ "filters": {
1734
+ "rules": [
1735
+ { "field": "created_on", "operator": "this_year" },
1736
+ { "field": "order_status", "operator": "!=", "value": "cancelled" }
1737
+ ]
1738
+ },
1739
+ "orderBy": "months_of_year@created_on ASC"
1740
+ }
1741
+ ```
1742
+
1743
+ ### Example 3: Pivot — Weekly Sales by Salesperson
1744
+
1745
+ ```json
1746
+ {
1747
+ "dataSourceFullSlug": "shop_order",
1748
+ "columns": "...order_status(status_name:name)",
1749
+ "pivot": {
1750
+ "matrix": [
1751
+ {
1752
+ "using": "created_on",
1753
+ "columns": "week:to_char[IYYY-IW]@created_on",
1754
+ "dateRange": {
1755
+ "interval": "week",
1756
+ "min": "2025-01-01T00:00:00Z",
1757
+ "max": "2025-03-31T23:59:59Z"
1758
+ },
1759
+ "spread": true
1760
+ },
1761
+ {
1762
+ "using": "salesperson",
1763
+ "columns": "sp_name:name",
1764
+ "spread": true
1765
+ }
1766
+ ],
1767
+ "orderBy": "week ASC"
1768
+ },
1769
+ "calculations": [
1770
+ { "field": "id", "func": "count", "name": "deals" },
1771
+ { "field": "amount", "func": "sum", "name": "revenue" }
1772
+ ]
1773
+ }
1774
+ ```
1775
+
1776
+ ### Example 4: Child Queries — Customers with Orders and Tickets
1777
+
1778
+ ```json
1779
+ {
1780
+ "dataSourceFullSlug": "crm_customer",
1781
+ "columns": "id, name, email, recent_orders, open_tickets",
1782
+ "childQueries": {
1783
+ "recent_orders": {
1784
+ "from": "shop_order",
1785
+ "using": "customer",
1786
+ "columns": "id, order_date, total_amount, ...status(status_label:name)",
1787
+ "orderBy": "order_date DESC",
1788
+ "limit": 10,
1789
+ "filters": {
1790
+ "rules": [
1791
+ { "field": "order_date", "operator": "last_90_days" }
1792
+ ]
1793
+ }
1794
+ },
1795
+ "open_tickets": {
1796
+ "from": "support_ticket",
1797
+ "using": "customer",
1798
+ "columns": "id, subject, priority, created_on",
1799
+ "orderBy": "created_on DESC",
1800
+ "limit": 5,
1801
+ "filters": {
1802
+ "rules": [
1803
+ { "field": "status", "operator": "!=", "value": "closed" }
1804
+ ]
1805
+ }
1806
+ }
1807
+ },
1808
+ "filters": {
1809
+ "rules": [
1810
+ { "field": "status", "operator": "=", "value": "active" }
1811
+ ]
1812
+ },
1813
+ "limit": 25
1814
+ }
1815
+ ```
1816
+
1817
+ ### Example 5: Formulas — Computed Columns with Subquery
1818
+
1819
+ Fetch accounts with an inline profit margin formula and a subquery counting active deals:
1820
+
1821
+ ```json
1822
+ {
1823
+ "dataSourceFullSlug": "crm_account",
1824
+ "columns": "id, name, profit_margin, active_deals",
1825
+ "formulas": {
1826
+ "profit_margin": {
1827
+ "inputs": [{
1828
+ "kind": "math",
1829
+ "op": "*",
1830
+ "inputs": [
1831
+ {
1832
+ "kind": "math",
1833
+ "op": "/",
1834
+ "inputs": [
1835
+ {
1836
+ "kind": "math",
1837
+ "op": "-",
1838
+ "inputs": [
1839
+ { "kind": "column", "name": "revenue" },
1840
+ { "kind": "column", "name": "cost" }
1841
+ ]
1842
+ },
1843
+ { "kind": "column", "name": "revenue", "cast": "decimal" }
1844
+ ]
1845
+ },
1846
+ { "kind": "literal", "literal": 100 }
1847
+ ]
1848
+ }]
1849
+ },
1850
+ "active_deals": {
1851
+ "from": "crm_deal",
1852
+ "with": "account",
1853
+ "filters": {
1854
+ "rules": [
1855
+ { "field": "stage", "operator": "!=", "value": "lost" },
1856
+ { "field": "stage", "operator": "!=", "value": "won" }
1857
+ ]
1858
+ },
1859
+ "inputs": [{
1860
+ "kind": "aggregate",
1861
+ "name": "count",
1862
+ "inputs": []
1863
+ }]
1864
+ }
1865
+ },
1866
+ "orderBy": "profit_margin DESC",
1867
+ "limit": 20
1868
+ }
1869
+ ```
1870
+
1871
+ ### Example 6: Combined Pivot + Calculations + Filters
1872
+
1873
+ Daily hourly breakdown of support tickets per agent for today:
1874
+
1875
+ ```json
1876
+ {
1877
+ "dataSourceFullSlug": "support_ticket",
1878
+ "columns": "...priority(priority_name:name)",
1879
+ "pivot": {
1880
+ "matrix": [
1881
+ {
1882
+ "using": "created_on",
1883
+ "columns": "hour:hours_of_today@created_on",
1884
+ "dateRange": {
1885
+ "interval": "hour",
1886
+ "min": "2025-10-15T00:00:00Z",
1887
+ "max": "2025-10-15T23:59:59Z"
1888
+ },
1889
+ "spread": true
1890
+ },
1891
+ {
1892
+ "using": "assigned_agent",
1893
+ "columns": "agent:name",
1894
+ "spread": true,
1895
+ "filters": {
1896
+ "rules": [
1897
+ { "field": "is_active", "operator": "true" }
1898
+ ]
1899
+ }
1900
+ }
1901
+ ],
1902
+ "hideEmptyRows": false
1903
+ },
1904
+ "calculations": [
1905
+ { "field": "id", "func": "count", "name": "ticket_count" }
1906
+ ],
1907
+ "filters": {
1908
+ "rules": [
1909
+ { "field": "created_on", "operator": "today" }
1910
+ ]
1911
+ }
1912
+ }
1913
+ ```
1914
+
1915
+ ### Example 7: Complex Nested Filters
1916
+
1917
+ ```json
1918
+ {
1919
+ "dataSourceFullSlug": "crm_deal",
1920
+ "columns": "id, name, amount, stage, record_owner(name)",
1921
+ "filters": {
1922
+ "combinator": "and",
1923
+ "rules": [
1924
+ {
1925
+ "field": "amount",
1926
+ "operator": ">",
1927
+ "value": 10000
1928
+ },
1929
+ {
1930
+ "combinator": "or",
1931
+ "rules": [
1932
+ {
1933
+ "combinator": "and",
1934
+ "rules": [
1935
+ { "field": "stage", "operator": "=", "value": "negotiation" },
1936
+ { "field": "created_on", "operator": "this_month" }
1937
+ ]
1938
+ },
1939
+ {
1940
+ "combinator": "and",
1941
+ "rules": [
1942
+ { "field": "stage", "operator": "=", "value": "proposal" },
1943
+ { "field": "record_owner", "operator": "active_user" }
1944
+ ]
1945
+ }
1946
+ ]
1947
+ },
1948
+ {
1949
+ "field": "rel_account/industry",
1950
+ "operator": "in",
1951
+ "value": ["technology", "finance", "healthcare"]
1952
+ }
1953
+ ]
1954
+ },
1955
+ "orderBy": "amount DESC",
1956
+ "limit": 100
1957
+ }
1958
+ ```
1959
+
1960
+ ### Example 8: CASE Formula with Multiple Conditions
1961
+
1962
+ ```json
1963
+ {
1964
+ "dataSourceFullSlug": "crm_deal",
1965
+ "columns": "id, name, amount, deal_tier",
1966
+ "formulas": {
1967
+ "deal_tier": {
1968
+ "inputs": [{
1969
+ "kind": "case",
1970
+ "cases": [
1971
+ {
1972
+ "when": {
1973
+ "kind": "compare", "op": ">=",
1974
+ "left": { "kind": "column", "name": "amount" },
1975
+ "right": { "kind": "literal", "literal": 100000 }
1976
+ },
1977
+ "then": { "kind": "literal", "literal": "Enterprise" }
1978
+ },
1979
+ {
1980
+ "when": {
1981
+ "kind": "compare", "op": ">=",
1982
+ "left": { "kind": "column", "name": "amount" },
1983
+ "right": { "kind": "literal", "literal": 25000 }
1984
+ },
1985
+ "then": { "kind": "literal", "literal": "Mid-Market" }
1986
+ },
1987
+ {
1988
+ "when": {
1989
+ "kind": "compare", "op": ">=",
1990
+ "left": { "kind": "column", "name": "amount" },
1991
+ "right": { "kind": "literal", "literal": 5000 }
1992
+ },
1993
+ "then": { "kind": "literal", "literal": "SMB" }
1994
+ }
1995
+ ],
1996
+ "else": { "kind": "literal", "literal": "Micro" }
1997
+ }]
1998
+ }
1999
+ }
2000
+ }
2001
+ ```
2002
+
2003
+ ### Example 9: Date Formatting with Simple Formula
2004
+
2005
+ ```json
2006
+ {
2007
+ "dataSourceFullSlug": "crm_activity",
2008
+ "columns": "id, subject, formatted_date, formatted_time",
2009
+ "formulas": {
2010
+ "formatted_date": {
2011
+ "func": "to_char",
2012
+ "args": ["{created_on}", "DD Mon YYYY"]
2013
+ },
2014
+ "formatted_time": {
2015
+ "func": "to_char",
2016
+ "args": ["{created_on}", "HH24:MI"]
2017
+ }
2018
+ },
2019
+ "orderBy": "created_on DESC",
2020
+ "limit": 50
2021
+ }
2022
+ ```
2023
+
2024
+ ### Example 10: Distinct Count with Min/Max Bounds
2025
+
2026
+ ```json
2027
+ {
2028
+ "dataSourceFullSlug": "shop_order",
2029
+ "columns": "category",
2030
+ "calculations": [
2031
+ {
2032
+ "field": "id",
2033
+ "func": "count",
2034
+ "name": "total_orders"
2035
+ },
2036
+ {
2037
+ "field": "amount",
2038
+ "func": "sum",
2039
+ "name": "valid_revenue",
2040
+ "minValue": 0,
2041
+ "maxValue": 1000000
2042
+ },
2043
+ {
2044
+ "field": "amount",
2045
+ "func": "avg",
2046
+ "name": "avg_amount",
2047
+ "numberType": "decimal"
2048
+ },
2049
+ {
2050
+ "field": "product_code",
2051
+ "func": "count",
2052
+ "name": "unique_products",
2053
+ "isDistinct": true
2054
+ }
2055
+ ]
2056
+ }
2057
+ ```