Import
Refer to the TypeScript reference page for information about the types and interfaces referenced below.
Import/parser functions take a string or object representing a query in a specific language and translate it to a query suitable for the query
or defaultQuery
props in a <QueryBuilder />
component.
The optional second parameter is an options object to configure the parsing behavior or query generation (see Configuration).
SQL
function parseSQL(sql: string, options?: ParseSQLOptions): RuleGroupTypeAny;
parseSQL
accepts a SQL SELECT
statement (either the full statement or the WHERE
clause by itself).
Click the "Import SQL" button in the demo to try it out.
Options
In addition to the standard configuration options, parseSQL
accepts two options that configure the handling of named or anonymous bind variables within the SQL string.
params
(any[] | Record<string, any>
): An array of parameter values or a parameter-to-value mapping object.paramPrefix
(string
): Ignores this string at the beginning of parameter identifiers when matching to parameter names in theparams
object.
Usage
Running any of the following statements will produce the same result (see output below).
parseSQL(`SELECT * FROM t WHERE firstName = 'Steve' AND lastName = 'Vai'`);
parseSQL(`SELECT * FROM t WHERE firstName = ? AND lastName = ?`, {
params: ['Steve', 'Vai'],
});
parseSQL(`SELECT * FROM t WHERE firstName = :p1 AND lastName = :p2`, {
params: { p1: 'Steve', p2: 'Vai' },
});
parseSQL(`SELECT * FROM t WHERE firstName = $p1 AND lastName = $p2`, {
params: { p1: 'Steve', p2: 'Vai' },
paramPrefix: '$',
});
Output (RuleGroupType
):
{
"combinator": "and",
"rules": [
{
"field": "firstName",
"operator": "=",
"value": "Steve"
},
{
"field": "lastName",
"operator": "=",
"value": "Vai"
}
]
}
Since v5.0, parseSQL
can detect XOR
operators and convert the expressions into rule groups with combinator "xor". However, since "xor" is not one of the members of defaultCombinators
, you will need to specify defaultCombinatorsExtended
(or some derivation of that) in your <QueryBuilder />
props if you believe the original SQL might contain XOR
clauses.
import { defaultCombinatorsExtended, parseSQL, QueryBuilder } from 'react-querybuilder';
const query = parseSQL(`SELECT * FROM tbl WHERE a = 'b' XOR c = 'd';`);
const App = () => {
return (
<QueryBuilder
query={query}
combinators={defaultCombinatorsExtended}
/>
);
};
MongoDB
function parseMongoDB(
mongoDbQuery: string | Record<string, any>,
options?: ParseMongoDbOptions
): RuleGroupTypeAny;
parseMongoDB
takes a MongoDB query as a JSON object or JSON.parse
-able string.
Click the "Import MongoDB" button in the demo to try it out.
Usage
parseMongoDB(`{ "firstName": "Steve", "lastName": { $eq: "Vai" } }`);
// OR
parseMongoDB({ firstName: 'Steve', lastName: { $eq: 'Vai' } });
Output (RuleGroupType
):
{
"combinator": "and",
"rules": [
{
"field": "firstName",
"operator": "=",
"value": "Steve"
},
{
"field": "lastName",
"operator": "=",
"value": "Vai"
}
]
}
Valid MongoDB query strings may not strictly conform to the JSON specification. To cover the extended format, you may want to pre-parse query strings with a library like mongodb-query-parser before passing them to parseMongoDB
.
Common Expression Language (CEL)
function parseCEL(celQuery: string, options?: ParseCELOptions): RuleGroupTypeAny;
parseCEL
takes a CEL string.
Click the "Import CEL" button in the demo to try it out.
Usage
parseCEL(`firstName == "Steve" && lastName == "Vai"`);
Output (RuleGroupType
):
{
"combinator": "and",
"rules": [
{
"field": "firstName",
"operator": "=",
"value": "Steve"
},
{
"field": "lastName",
"operator": "=",
"value": "Vai"
}
]
}
JsonLogic
function parseJsonLogic(
jsonLogic: string | JsonLogic,
options?: ParseJsonLogicOptions
): RuleGroupTypeAny;
parseJsonLogic
takes a JsonLogic object or JSON.parse
-able string.
Click the "Import JsonLogic" button in the demo to try it out.
Usage
parseJsonLogic(
`{ "and": [{ "===": [{ "var": "firstName" }, "Steve"] }, { "===": [{ "var": "lastName" }, "Vai"] }] }`
);
// OR
parseJsonLogic({
and: [{ '===': [{ var: 'firstName' }, 'Steve'] }, { '===': [{ var: 'lastName' }, 'Vai'] }],
});
Output (RuleGroupType
):
{
"combinator": "and",
"rules": [
{
"field": "firstName",
"operator": "=",
"value": "Steve"
},
{
"field": "lastName",
"operator": "=",
"value": "Vai"
}
]
}
Custom operations
By default, parseJsonLogic
handles the standard JsonLogic operations that correspond to one of the default operators in React Query Builder. To handle custom operations, use the jsonLogicOperations
option.
jsonLogicOperations
is Record<string, (val: any) => RuleType | RuleGroupTypeAny
. The keys of the object should be the custom operations, and the corresponding values should be functions that return a rule or group.
Including any of the standard JsonLogic operations as keys in the jsonLogicOperations
object will override the default parseJsonLogic
behavior for those operations.
The example below uses a custom "regex" operation to produce a rule with the "contains" operator, the value
being the source
of the regular expression in the JsonLogic rule.
parseJsonLogic(
{ regex: [{ var: 'firstName' }, /^Stev/] },
{
jsonLogicOperations: {
regex: val => ({ field: val[0].var, operator: 'contains', value: val[1].source }),
},
}
);
Output (RuleGroupType
):
{
"combinator": "and",
"rules": [
{
"field": "firstName",
"operator": "contains",
"value": "^Stev"
}
]
}
Configuration
Lists as arrays
To generate arrays instead of comma-separated strings for lists of values following "in"- and "between"-type operators, use the listsAsArrays
option.
parseSQL(`SELECT * FROM t WHERE lastName IN ('Vai', 'Vaughan') AND age BETWEEN 20 AND 100`, {
listsAsArrays: true;
});
Output:
{
"combinator": "and",
"rules": [
{
"field": "lastName",
"operator": "in",
"value": ["Vai", "Vaughan"]
},
{
"field": "age",
"operator": "between",
"value": [20, 100]
}
]
}
Independent combinators
When the independentCombinators
option is true
, parse*
functions will output a query with combinator identifiers between sibling rules/groups instead of the group level. (For these queries to be valid for the <QueryBuilder />
query
prop, the independentCombinators
prop must also be true
.)
parseSQL(`SELECT * FROM t WHERE firstName = 'Steve' AND lastName = 'Vai'`, {
independentCombinators: true,
});
Output (RuleGroupTypeIC
):
{
"rules": [
{
"field": "firstName",
"operator": "=",
"value": "Steve"
},
"and",
{
"field": "lastName",
"operator": "=",
"value": "Vai"
}
]
}
Fields as value source
When the fields
option (which accepts the same types as the fields
prop) 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) can also be provided to help validate rules.
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
function return value, or 3) the field's valueSources
property itself. The code below demonstrates all three methods.
parseSQL(`SELECT * FROM t WHERE firstName = lastName`, {
fields: [
{ name: 'firstName', label: 'First Name', valueSources: ['value', 'field'] },
{ name: 'lastName', label: 'Last Name', valueSources: () => ['value', 'field'] },
],
getValueSources: () => ['value', 'field'],
});
Output:
{
"combinator": "and",
"rules": [
{
"field": "firstName",
"operator": "=",
"value": "lastName",
"valueSource": "field"
}
]
}
parse*
functions will only validate clauses where "field" is the only detected value source. Operators like "between" and "in" that take multiple values must only have field names or only scalar values to the right of the operator, not a mix of field names and scalar values. See examples below.
Clauses that will be deemed invalid
// 1 is a scalar value and `iq` is a field name
parseSQL(`SELECT * FROM tbl WHERE age between 1 and iq`);
// List contains a mix of scalar values and field names
parseSQL(`SELECT * FROM tbl WHERE firstName IN (lastName, 'Steve', 'Stevie')`);
Clauses that will (probably) be deemed valid
// Both are field names
parseSQL(`SELECT * FROM tbl WHERE age between numChildren and iq`);
// Both are scalar values
parseSQL(`SELECT * FROM tbl WHERE age between 26 and 52`);
// All items are field names
parseSQL(`SELECT * FROM tbl WHERE firstName IN (lastName, middleName)`);
// All items are scalar values
parseSQL(`SELECT * FROM tbl WHERE firstName IN ('Steve', 'Stevie')`);