You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`formatQuery`parses a given query into one of the following formats:
19
+
`formatQuery`converts a given query into one of the following formats:
20
20
21
21
- JSON (with or without `id`s)
22
22
- SQL `WHERE` clause
@@ -88,7 +88,7 @@ The output will be a multi-line string representation of the query using 2 space
88
88
89
89
### JSON without identifiers
90
90
91
-
To export the internal query representation without formatting (single-line, no indentation) and without the `id`attribute on each object, use the "json_without_ids" format. This is useful if you need to serialize the query for storage.
91
+
To export the internal query representation without formatting (single-line, no indentation) and without the `id`or `path` attributes on each object, use the "json_without_ids" format. This is useful if you need to serialize the query for storage.
To avoid information loss, this option is more strict about what qualifies as "numeric" than [the standard `parseFloat` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat). Put simply, `parseFloat` works with any string that _starts_ with a numeric sequence, ignoring the rest of the string beginning with the first non-numeric character. When`parseNumbers` is `true`, `formatQuery` will only convert a `value` to a `number` if it appears to be numeric _in its entirety_ (after trimming whitespace).
258
+
To avoid information loss, this option is more strict about what qualifies as "numeric" than [the standard `parseFloat` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat). To oversimplify a bit, `parseFloat` works with any string that _starts_ with a numeric sequence, ignoring the rest of the string beginning with the first non-numeric character. In contrast, when`parseNumbers` is `true`, `formatQuery` will only convert a `value` to a `number` if it appears to be numeric _in its entirety_ (after trimming whitespace).
259
259
260
260
The following expressions all evaluate to `true`:
261
261
@@ -277,7 +277,7 @@ formatQuery(
277
277
278
278
### Value processor
279
279
280
-
If you need to control the way the value portion of the output is processed, you can specify a custom `valueProcessor` (only applicable for "sql" format).
280
+
If you need to control the way the value portion of the output is processed, you can specify a custom `valueProcessor` (only applicable for certain formats).
// Returns: "(instrument in ('Guitar','Vocals') and lastName = 'Vai')"
310
311
```
311
312
312
313
:::caution
313
314
314
-
When using the "mongodb"export format, `valueProcessor` functions must produce the entire MongoDB rule object and not just the value portion like with other formats.
315
+
When using the "mongodb", "cel", or "spel" export formats, `valueProcessor` functions must produce the entire MongoDB rule object or CEL/SpEL rule string, not just the expression on the right-hand side of the operator like with SQL-based formats.
315
316
316
317
:::
317
318
319
+
#### Enhanced `valueProcessor` behavior
320
+
321
+
`formatQuery` will invoke custom `valueProcessor` functions with different arguments based on the function's `length` property, which is the number of arguments a function accepts excluding those with default values.
322
+
323
+
If the `valueProcessor` function accepts fewer than three (3) arguments, it will be called like this:
324
+
325
+
```ts
326
+
valueProcessor(rule, { parseNumbers });
327
+
```
328
+
329
+
The first argument is the `RuleType` object directly from the query. The second argument is of type `ValueProcessorOptions`, which is equivalent to `Pick<FormatQueryOptions, "parseNumbers">`).
330
+
331
+
Invoking `valueProcessor` with the full `RuleType` object provides access to much more information about each rule. Standard properties that were previously unavailable include `path`, `id`, and `disabled`, but any custom properties will also be accessible.
332
+
333
+
The default value processors have not changed from the legacy function signature, but alternate functions using the new `fn(rule, options)` signature are now available:
To maintain the legacy signature (`valueProcessor(field, operator, value, valueSource)`), make sure your custom `valueProcessor` function accepts at least three arguments _with no default values_ (i.e. do not use `=` for the first three arguments). For example, the following code will log `length: 1` and the function would be called with the `(rule, options)` arguments:
Removing `= ...` from the `operator` and `value` argument declarations would increase the function's `length` to 3.
348
+
349
+
If you use TypeScript, these conditions will be enforced automatically.
350
+
318
351
### Quote field names
319
352
320
353
Some database engines wrap field names in backticks (`` ` ``). This can be configured with the `quoteFieldNamesWith` option.
@@ -352,7 +385,7 @@ The `fallbackExpression` is a string that will be part of the output when `forma
352
385
353
386
### Value sources
354
387
355
-
When the `valueSource` property for a rule is set to "field", `formatQuery` will place the bare, unquoted value (which should be a valid field name) in the result for the "sql", "parameterized", "parameterized_named", "mongodb", and "cel" formats. No parameters will be generated for such rules.
388
+
When the `valueSource` property for a rule is set to "field", `formatQuery` will place the bare, unquoted value (which should be a valid field name) in the result for the "sql", "parameterized", "parameterized_named", "mongodb", "cel", and "spel" formats. No parameters will be generated for such rules.
356
389
357
390
```ts
358
391
const pf =formatQuery(
@@ -382,7 +415,7 @@ Any rule where the `field` or `operator` matches the placeholder value (default
382
415
383
416
## Validation
384
417
385
-
The validation options (`validator` and `fields` – see [Validation](./validation) for more information) only affect the output when `format` is "sql", "parameterized", "parameterized_named", "mongodb", or "cel". If the `validator` function returns `false`, the `fallbackExpression` will be returned. Otherwise, groups and rules marked as invalid (either by the validation map produced by the `validator` function or the result of the field-based `validator` function) will be ignored.
418
+
The validation options (`validator` and `fields` – see [Validation](./validation) for more information) only affect the output when `format` is not "json" or "json_without_ids". If the `validator` function returns `false`, the `fallbackExpression` will be returned. Otherwise, groups and rules marked as invalid (either by the validation map produced by the `validator` function or the result of the field-based `validator` function) will be ignored.
386
419
387
420
Example:
388
421
@@ -431,8 +464,8 @@ formatQuery(query, {
431
464
432
465
### Automatic validation
433
466
434
-
A basic form of validation will be used by `formatQuery` for the "in", "notIn", "between", and "notBetween" operators when the output format is "sql", "parameterized", "parameterized_named", "mongodb", or "cel". This validation is used regardless of the presence of any `validator` options either at the query or field level:
467
+
A basic form of validation will be used by `formatQuery` for the "in", "notIn", "between", and "notBetween" operators when the output format is not "json" or "json_without_ids". This validation is used regardless of the presence of any `validator` options at either the query level or field level:
435
468
436
469
- Rules that specify an "in" or "notIn" `operator` will be deemed invalid if the rule's `value` is neither an array with at least one element (i.e. `value.length > 0`) nor a non-empty string.
437
-
- Rules that specify a "between" or "notBetween" `operator` will be deemed invalid if the rule's `value` is neither an array of length two (`value.length === 2`) nor a string with exactly one comma that isn't the first or last character (i.e. `value.split(',').length === 2` and neither element is an empty string).
438
-
- Rules where the following expression is true will be deemed invalid: `field === placeholderFieldName || operator === placeholderOperatorName`.
470
+
- Rules that specify a "between" or "notBetween" `operator` will be deemed invalid if the rule's `value` is neither an array with length of at least two (`value.length >= 2`) nor a string with at least one comma that isn't the first or last character (i.e. `value.split(',').length >= 2`, and neither element is an empty string).
471
+
- Rules where either the `field` or `operator` match their respective placeholder will be deemed invalid (`field === placeholderFieldName || operator === placeholderOperatorName`).
Use the `parseSQL` function to convert SQL `SELECT` statements into a format suitable for the `<QueryBuilder />` component's `query` prop. The function signature is:
11
13
12
14
```ts
@@ -17,7 +19,7 @@ function parseSQL(sql: string, options?: ParseSQLOptions): RuleGroupTypeAny;
17
19
18
20
The optional second parameter to `parseSQL` is an options object that configures how the function handles named or anonymous bind variables within the SQL string.
19
21
20
-
## Basic usage
22
+
###Basic usage
21
23
22
24
Running any of the following statements will produce the same result (see below):
23
25
@@ -58,6 +60,20 @@ Output (`RuleGroupType`):
58
60
}
59
61
```
60
62
63
+
## Common Expression Language (CEL)
64
+
65
+
`parseCEL` takes a [CEL](https://github.com/google/cel-spec) string and converts it to `RuleGroupType`.
66
+
67
+
Click the "Import from CEL" button in [the demo](https://react-querybuilder.js.org/react-querybuilder) to try it out.
68
+
69
+
## JsonLogic
70
+
71
+
`parseJsonLogic` takes a [JsonLogic](https://jsonlogic.com/) object and converts it to `RuleGroupType`.
72
+
73
+
Click the "Import from JsonLogic" button in [the demo](https://react-querybuilder.js.org/react-querybuilder) to try it out.
74
+
75
+
## Configuration
76
+
61
77
### Lists as arrays
62
78
63
79
To generate actual arrays instead of comma-separated strings for lists of values following `IN` and `BETWEEN` operators, use the `listsAsArrays` option.
@@ -88,9 +104,9 @@ Output:
88
104
}
89
105
```
90
106
91
-
## Independent combinators
107
+
###Independent combinators
92
108
93
-
When the `independentCombinators` option is `true`, `parseSQL` will output a query with combinator identifiers between sibling rules/groups.
109
+
When the `independentCombinators` option is `true`, `parse*` functions will output a query with combinator identifiers between sibling rules/groups.
94
110
95
111
```ts
96
112
parseSQL(`SELECT * FROM t WHERE firstName = 'Steve' AND lastName = 'Vai'`, {
@@ -118,11 +134,11 @@ Output (`RuleGroupTypeIC`):
118
134
}
119
135
```
120
136
121
-
## Fields as value source
137
+
###Fields as value source
122
138
123
-
When the `fields` option (which accepts the same types as the [`fields` prop](./querybuilder#fields)) is provided, and _only_ if it is provided, then `parseSQL`will validate clauses that have a field identifier to the right of the operator instead of a primitive value. A `getValueSources` function can also be provided to help validate rules.
139
+
When the `fields` option (which accepts the same types as the [`fields` prop](./querybuilder#fields)) is provided, and _only_ if it is provided, then `parse*` functions will validate clauses that have a field identifier to the right of the operator instead of a primitive value. A `getValueSources` function (with the same signature as the [prop of the same name](./querybuilder#getvaluesources)) can also be provided to help validate rules.
124
140
125
-
In order for such a rule to be considered valid, either the `getValueSources` return value, the field's `valueSources` property return value, or the field's `valueSources` property itself must be an array that includes the string "field".
141
+
In order for such a rule to be considered valid, one of the following must be an array that includes the string "field": 1) the `getValueSources` return value, 2) the field's `valueSources` property return value, or 3) the field's `valueSources` property itself.
126
142
127
143
```ts
128
144
parseSQL(`SELECT * FROM t WHERE firstName = lastName`, {
@@ -152,6 +168,6 @@ Output:
152
168
153
169
:::note
154
170
155
-
`parseSQL` will only validate clauses where "field" is the _only_ value source. Operators that take multiple values, like "between" and "in", must only have field names to the right of the operator, not a mix of field names and primitive values.
171
+
`parse*` functions will only validate clauses where "field" is the _only_ value source. Operators that take multiple values, like "between" and "in", must only have field names to the right of the operator, not a mix of field names and primitive values.
@@ -25,7 +25,7 @@ You can see an example of the default validator in action in the [demo](https://
25
25
### `findPath`
26
26
27
27
```ts
28
-
function findPath(path:number[], query:RuleGroupType):RuleType|RuleGroupType;
28
+
function findPath(path:number[], query:RuleGroupTypeAny):RuleType|RuleGroupTypeAny;
29
29
```
30
30
31
31
`findPath` is a utility function for finding the rule or group within the query hierarchy that has a given `path`. Useful in custom [`onAddRule`](./querybuilder#onaddrule) and [`onAddGroup`](./querybuilder#onaddgroup) functions.
@@ -42,6 +42,22 @@ function convertQuery(query: RuleGroupTypeIC): RuleGroupType;
42
42
43
43
`convertToIC` and `convertFromIC` do the same thing as `convertQuery`, but only in one direction.
44
44
45
+
### `transformQuery`
46
+
47
+
```ts
48
+
function transformQuery(query:RuleGroupTypeAny, options:QueryTransformerOptions):any;
49
+
```
50
+
51
+
This function recursively steps through nested `rules` arrays in a `RuleGroupType` or `RuleGroupTypeIC`, passing each `RuleType` object to a provided `ruleProcessor` function. Several other options are also available:
52
+
53
+
-`ruleGroupProcessor`: Custom processing for each rule group. (The `rules` property will be overwritten.)
54
+
-`propertyMap`: Keys in the rule or group objects that match keys in this object will be renamed to the corresponding value.
55
+
-`combinatorMap`: Best explained with an example: `{and: "&&", or: "||"}` would translate "and"/"or" combinators to "&&"/"||", respectively.
56
+
-`operatorMap`: Convert operators that match the keys in this object to the corresponding values, e.g. `{"=": "=="}`.
57
+
-`deleteRemappedProperties`: Defaults to `true`; pass `false` to leave the remapped properties _and_ the original properties in the resulting object.
58
+
59
+
See the [test suite](https://github.com/react-querybuilder/react-querybuilder/blob/main/packages/react-querybuilder/src/utils/transformQuery.test.ts) for example usage.
60
+
45
61
## Query tools
46
62
47
63
Several methods are available to assist with manipulation of query objects outside the context of the `<QueryBuilder />` component:
@@ -60,8 +76,7 @@ The following default configuration objects are exported for convenience.
60
76
-`defaultCombinators` (see [`combinators` prop](./querybuilder#combinators))
61
77
-`defaultOperators` (see [`operators` prop](./querybuilder#operators))
62
78
-`defaultTranslations` (see [`translations` prop](./querybuilder#translations))
63
-
-`defaultValueProcessor` (see [Export](./export) > [Value processor](./export#value-processor))
64
-
-`defaultMongoDBValueProcessor` (see [Export](./export) > [Value processor](./export#value-processor))
79
+
-`defaultValueProcessor` and variants for non-SQL formats (see [Export](./export) > [Value processor](./export#value-processor))
65
80
-`defaultFields` (see [`fields` prop](./querybuilder#fields))
66
81
-`standardClassnames` (see [CSS classes](./classnames))
0 commit comments