Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add documentation for valueSources feature
  • Loading branch information
jakeboone02 committed Jan 30, 2022
commit 54e28754aa6933d1baecd216a69f414a472c0f4d
9 changes: 9 additions & 0 deletions docs/api/classnames.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ import { standardClassnames as sc } from 'react-querybuilder';
defaultValue: 'This rule is invalid',
validator: () => false,
},
{
name: 'f3',
label: `.${sc.valueSource}`,
valueSources: ['value', 'field'],
},
]}
combinators={[{ name: 'and', label: `.${sc.combinators}` }]}
getOperators={() => [{ name: '=', label: `.${sc.operators}` }]}
Expand Down Expand Up @@ -106,6 +111,9 @@ import { standardClassnames as sc } from 'react-querybuilder';
label: `.${sc.lockGroupDisabled}`,
title: `.${sc.lockGroupDisabled}`,
},
valueSourceSelector: {
title: `.${sc.valueSource}`,
},
}}
defaultQuery={{
combinator: 'and',
Expand All @@ -129,6 +137,7 @@ import { standardClassnames as sc } from 'react-querybuilder';
},
],
},
{ field: 'f3', operator: '=', value: 'f1' },
],
}}
/>
26 changes: 26 additions & 0 deletions docs/api/export.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,32 @@ The `fallbackExpression` is a string that will be part of the output when `forma

By default, `fallbackExpression` is `"(1 = 1)"` for the "sql", "parameterized", and "parameterized_named" formats, and `"{$and:[{$expr:true}]}"` for the "mongodb" format.

### Value sources

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", and "mongodb" formats. No parameters will be generated for such rules.

```ts
const pf = formatQuery(
{
combinator: 'and',
rules: [
{ field: 'firstName', operator: '=', value: 'lastName', valueSource: 'field' },
{ field: 'firstName', operator: 'beginsWith', value: 'middleName', valueSource: 'field' },
],
},
'parameterized_named'
);
```

Output:

```ts
{
sql: "(firstName = lastName and firstName like middleName || '%')",
params: {},
}
```

## Validation

The validation options (`validator` and `fields` – see [Validation](./validation) for more information) only affect the output when `format` is "sql", "parameterized", "parameterized_named", or "mongodb". 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.
Expand Down
42 changes: 41 additions & 1 deletion docs/api/import.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,11 @@ To generate actual arrays instead of comma-separated strings for lists of values
parseSQL(`SELECT * FROM t WHERE lastName IN ('Vai', 'Vaughan') AND age BETWEEN 20 AND 100`, {
listsAsArrays: true;
});
// Output:
```

Output:

```ts
{
combinator: "and",
rules: [
Expand Down Expand Up @@ -113,3 +117,39 @@ Output (`RuleGroupTypeIC`):
];
}
```

## Fields as value source

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.

```ts
parseSQL(`SELECT * FROM t WHERE firstName = lastName`, {
fields: [
{ name: 'firstName', label: 'First Name' },
{ name: 'lastName', label: 'Last Name' },
],
getValueSources: () => ['value', 'field'],
});
```

Output:

```ts
{
combinator: "and",
rules: [
{
field: "firstName",
operator: "=",
value: "lastName",
valueSource: "field",
},
],
}
```

:::note

`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.

:::
31 changes: 31 additions & 0 deletions docs/api/querybuilder.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ interface Controls {
rule?: React.ComponentType<RuleProps>;
ruleGroup?: React.ComponentType<RuleGroupProps>;
valueEditor?: React.ComponentType<ValueEditorProps>;
valueSourceSelector?: React.ComponentType<ValueSourceSelectorProps>;
}
```

Expand Down Expand Up @@ -408,6 +409,25 @@ interface ValueEditorProps {
}
```

#### `valueSourceSelector`

By default a `<select />` is used. The following props are passed:

```ts
interface ValueSourceSelectorProps {
field: string; // Field name corresponding to this rule
fieldData: Field; // The entire object from the fields array for this field
options: ValueSourceOption[] | OptionGroup<ValueSourceOption>[]; // Return value of getValueSources(field, operator)
value: ValueSource; // Selected value source from the existing query representation, if any
title: string; // translations.valueSourceSelector.title, e.g. "Value source"
className: string; // CSS classNames to be applied
handleOnChange: (value: any) => void; // Callback function to update query representation
level: number; // The level the group this rule belongs to
context: any; // Container for custom props that are passed to all components
validation: boolean | ValidationResult; // validation result of this rule
}
```

#### `notToggle`

By default, `<label><input type="checkbox" />Not</label>` is used. The following props are passed:
Expand Down Expand Up @@ -438,6 +458,8 @@ interface RuleGroupProps {
schema: Schema; // See `Schema` on the TypeScript page
not: boolean; // Whether or not to invert this group
context: any; // Container for custom props that are passed to all components
disabled?: boolean; // Whether the rule itself is disabled
parentDisabled?: boolean; // Whether an ancestor of this rule is disabled
}
```

Expand All @@ -452,9 +474,12 @@ interface RuleProps {
field: string; // Field name for this rule
operator: string; // Operator name for this rule
value: any; // Value for this rule
valueSource?: ValueSource; // Value source for this rule's value
translations: Translations; // The full translations object
schema: Schema; // See `Schema` on the TypeScript page
context: any; // Container for custom props that are passed to all components
disabled?: boolean; // Whether the rule itself is disabled
parentDisabled?: boolean; // Whether an ancestor of this rule is disabled
}
```

Expand All @@ -470,6 +495,12 @@ This is a callback function invoked to get the list of allowed operators for the

This is a callback function invoked to get the type of `ValueEditor` for the given field and operator. Allowed values are `"text"` (the default if the function is not provided or if `null` is returned), `"select"`, `"checkbox"`, and `"radio"`.

### `getValueSources`

`(field: string, operator: string) => ValueSources`;

This is a callback function invoked to get the list of allowed value sources for a given field and operator. The return value must be an array including at least "value" or "field", but may also contain both (in any order). If this function is not provided, `() => ["value"]` is used.

### `getInputType`

`(field: string, operator: string) => string`
Expand Down
12 changes: 12 additions & 0 deletions docs/typescript.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ interface Field {
defaultValue?: any; // Default value for this field (if not provided, then `getDefaultValue()` will be used)
placeholder?: string; // Value to be displayed in the placeholder of the text field
validator?: RuleValidator; // Called when a rule specifies this field
valueSources?: ValueSources | ((operator: string) => ValueSources); // List of allowed value sources (must contain "value", "field", or both)
comparator?: string | ((f: Field) => boolean); // Determines which (other) fields to include in the list when valueSource is "field"
}
```

Expand All @@ -36,14 +38,17 @@ interface Field {
type RuleType = {
path?: number[];
id?: string;
disabled?: boolean;
field: string;
operator: string;
value: any;
valueSource?: ValueSource;
};

type RuleGroupType = {
path?: number[];
id?: string;
disabled?: boolean;
combinator: string;
rules: (RuleType | RuleGroupType)[];
not?: boolean;
Expand All @@ -52,6 +57,7 @@ type RuleGroupType = {
type RuleGroupTypeIC = {
path?: number[];
id?: string;
disabled?: boolean;
rules: (RuleType | RuleGroupTypeIC | string)[]; // see note below
not?: boolean;
};
Expand Down Expand Up @@ -141,6 +147,8 @@ interface ParseSQLOptions {
paramPrefix?: string;
params?: any[] | { [p: string]: any };
listsAsArrays?: boolean;
fields?: Field[] | OptionGroup<Field>[] | Record<string, Field>;
getValueSources?: (field: string, operator: string) => ValueSources;
}
```

Expand Down Expand Up @@ -187,6 +195,10 @@ type ValueEditorType =
| 'time'
| null;

type ValueSource = 'value' | 'field';

type ValueSources = ['value'] | ['value', 'field'] | ['field', 'value'] | ['field'];

interface Schema {
fields: Field[] | OptionGroup<NameLabelPair>[];
fieldMap: { [k: string]: Field };
Expand Down