@jetstreamapp/soql-parser-js 6.0.0

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.
Files changed (50) hide show
  1. package/AUTHORS.md +1 -0
  2. package/CHANGELOG.md +959 -0
  3. package/LICENSE.txt +12 -0
  4. package/README.md +949 -0
  5. package/bin/soql-parser-js +3 -0
  6. package/dist/cjs/index.js +2 -0
  7. package/dist/cjs/index.js.LICENSE.txt +1 -0
  8. package/dist/cjs/main.licenses.txt +898 -0
  9. package/dist/cjs/src/api/api-models.d.ts +175 -0
  10. package/dist/cjs/src/api/api-models.js +2 -0
  11. package/dist/cjs/src/api/public-utils.d.ts +29 -0
  12. package/dist/cjs/src/api/public-utils.js +175 -0
  13. package/dist/cjs/src/composer/composer.d.ts +32 -0
  14. package/dist/cjs/src/composer/composer.js +295 -0
  15. package/dist/cjs/src/formatter/formatter.d.ts +42 -0
  16. package/dist/cjs/src/formatter/formatter.js +236 -0
  17. package/dist/cjs/src/index.d.ts +5 -0
  18. package/dist/cjs/src/index.js +23 -0
  19. package/dist/cjs/src/models.d.ts +266 -0
  20. package/dist/cjs/src/models.js +2 -0
  21. package/dist/cjs/src/parser/lexer.d.ts +186 -0
  22. package/dist/cjs/src/parser/lexer.js +954 -0
  23. package/dist/cjs/src/parser/parser.d.ts +89 -0
  24. package/dist/cjs/src/parser/parser.js +697 -0
  25. package/dist/cjs/src/parser/visitor.d.ts +4 -0
  26. package/dist/cjs/src/parser/visitor.js +856 -0
  27. package/dist/cjs/src/utils.d.ts +42 -0
  28. package/dist/cjs/src/utils.js +245 -0
  29. package/dist/cli/index.js +113 -0
  30. package/dist/esm/api/api-models.js +1 -0
  31. package/dist/esm/api/public-utils.js +153 -0
  32. package/dist/esm/composer/composer.js +273 -0
  33. package/dist/esm/formatter/formatter.js +223 -0
  34. package/dist/esm/index.js +4 -0
  35. package/dist/esm/models.js +1 -0
  36. package/dist/esm/parser/lexer.js +947 -0
  37. package/dist/esm/parser/parser.js +667 -0
  38. package/dist/esm/parser/visitor.js +823 -0
  39. package/dist/esm/utils.js +200 -0
  40. package/dist/src/api/api-models.js +2 -0
  41. package/dist/src/api/public-utils.js +203 -0
  42. package/dist/src/composer/composer.js +358 -0
  43. package/dist/src/formatter/formatter.js +263 -0
  44. package/dist/src/index.js +28 -0
  45. package/dist/src/models.js +2 -0
  46. package/dist/src/parser/lexer.js +997 -0
  47. package/dist/src/parser/parser.js +711 -0
  48. package/dist/src/parser/visitor.js +862 -0
  49. package/dist/src/utils.js +251 -0
  50. package/package.json +78 -0
package/README.md ADDED
@@ -0,0 +1,949 @@
1
+ <img src="./assets/soql-parser-js-logo.svg">
2
+
3
+ [![build](https://api.travis-ci.com/jetstreamapp/soql-parser-js.png?branch=master)](https://travis-ci.com/jetstreamapp/soql-parser-js)
4
+ [![npm version](https://badge.fury.io/js/soql-parser-js.svg)](https://badge.fury.io/js/soql-parser-js)
5
+ [![dependencies](https://david-dm.org/jetstreamapp/soql-parser-js.svg)](https://david-dm.org/jetstreamapp/soql-parser-js)
6
+
7
+ ## Description
8
+
9
+ **This library allows parsing and composing SOQL queries from Salesforce using JavaScript or Typescript.**
10
+
11
+ ### Installation
12
+
13
+ 👉 **As of version 6.0.0**, this package is now part of the `@jetstreamapp` npm organization.
14
+
15
+ ```bash
16
+ npm install @jetstreamapp/soql-parser-js
17
+ ```
18
+
19
+ **Available Features:**
20
+
21
+ 1. Parse SOQL queries into a common `Query` data structure.
22
+ 2. Deterministically compose a `Query` data structure back into a SOQL query string.
23
+ 3. Validate a query to check if the syntax is valid.
24
+ 1. _Even if a query is returned as valid, it might still be invalid based on your Salesforce configuration_
25
+
26
+ Migrating from version 1 to version 2? [Check out the changelog](CHANGELOG.md#200) for a full list of changes.
27
+
28
+ Migrating from version 2 to version 3? [Check out the changelog](CHANGELOG.md#300) for a full list of changes.
29
+
30
+ ## Documentation
31
+
32
+ **[Read the documentation on our docs site](https://paustint.github.io/soql-parser-js/)**.
33
+
34
+ ## Compatibility
35
+
36
+ **Node**: version 11 or higher, or a polyfill for [Array.flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat)
37
+ **Browser**: Tested in all modern browsers, may not work with older browsers.
38
+
39
+ The **commander** dependency is only required for the cli, the other two dependencies **chevrotain** and **lodash.get** are bundled with the non-cli code.
40
+
41
+ ## Quick Start
42
+
43
+ ```javascript
44
+ import { parseQuery, composeQuery, isQueryValid } from 'soql-parser-js';
45
+
46
+ const query = parseQuery(`SELECT Id FROM Account WHERE Id = 'FOO'`);
47
+ console.log('query', query);
48
+
49
+ const soql = composeQuery(query);
50
+ console.log('soql', soql); // SELECT Id FROM Account WHERE Id = 'FOO'
51
+
52
+ isQueryValid('SELECT Id, Foo FROM Baz'); // true
53
+ isQueryValid('SELECT Id Foo FROM Baz'); // false
54
+ ```
55
+
56
+ ## Available Features
57
+
58
+ | Function | Description | Arguments |
59
+ | ------------ | ------------------------------------------------------ | ------------------------------------------ |
60
+ | parseQuery | Parse a SOQL query string into a Query data structure. | soql: Query<br> config?: ParseQueryConfig |
61
+ | isQueryValid | Returns true if the query was able to be parsed. | soql: Query<br> config?: ParseQueryConfig |
62
+ | composeQuery | Turn a Query object back into a SOQL statement. | soql: Query<br> config?: SoqlComposeConfig |
63
+ | formatQuery | Format a SOQL query string. | soql: Query<br> config?: FormatOptions |
64
+
65
+ ## Utility Functions
66
+
67
+ **General Utility**
68
+
69
+ Many of hte utility functions are provided to easily determine the shape of specific data since there are many variants. If you are using Typescript in strict mode, you can use these to narrow your types.
70
+
71
+ | Function | Description | Arguments |
72
+ | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
73
+ | hasAlias | Returns `true` if the field passed in has the `alias` property. | input: `string \| ComposeFieldInput` |
74
+ | getField | Convenience method to construct fields in the correct format when using `composeQuery()`. Look in the data models section below for the structure of `ComposeFieldInput`. | input: `string \| ComposeFieldInput` |
75
+ | getFlattenedFields | Flatten a Salesforce record based on the parsed SOQL Query. this is useful if you have relationships in your query and want to show the results in a table, using `.` dot notation for the relationship field headings. | soql: `Query \| Subquery \| FieldSubquery`<br> config?: `SoqlComposeConfig` |
76
+ | isSubquery | Returns `true` if the data passed in is a subquery. | query: `Query \| Subquery` |
77
+ | isFieldSubquery | Returns `true` if the data passed in is a FieldSubquery. | value: `any` |
78
+ | isWhereClauseWithRightCondition | Returns `true` if the value passed in is a `WhereClause` with an `operator` and `right` property | value: `WhereClause` |
79
+ | isHavingClauseWithRightCondition | Returns `true` if the value passed in is a `HavingClause` with an `operator` and `right` property | value: `HavingClause` |
80
+ | isWhereOrHavingClauseWithRightCondition | Returns `true` if the value passed in is a `WhereClause` or `HavingClause` with an `operator` and `right` property | value: `WhereClause \| HavingClause` |
81
+ | isValueCondition | Returns `true` if the value passed in has `field`, `operator` and `value` properties | value: `Condition` |
82
+ | isValueWithDateLiteralCondition | Returns `true` if the value passed in has `field`, `operator` and `value` properties and has a `literalType` property that is `DATE_LITERAL` of `['DATE_LITERAL',...]` | value: `Condition` |
83
+ | isValueWithDateNLiteralCondition | Returns `true` if the value passed in has `field`, `operator`, `value` and `dateLiteralVariable` properties | value: `Condition` |
84
+ | isValueFunctionCondition | Returns `true` if the value passed in has `fn`, `operator` and `value` properties | value: `Condition` |
85
+ | isNegationCondition | Returns `true` if the value passed in has a `openParen` property and does not have `fn`, `field`, `operator`, `value`, and `closeParen` properties | value: `Condition` |
86
+ | isValueQueryCondition | Returns `true` if the value passed in has `field`, `operator` and `valueQuery` properties and does not have a `value` property | value: `Condition \| ValueQueryCondition` |
87
+ | isOrderByField | Returns `true` if the value passed in has `field` property | value: `OrderByClause` |
88
+ | isOrderByFn | Returns `true` if the value passed in has `fn` property | value: `OrderByClause` |
89
+ | isGroupByField | Returns `true` if the value passed in has `field` property | value: `GroupByClause` |
90
+ | isGroupByFn | Returns `true` if the value passed in has `fn` property | value: `GroupByClause` |
91
+
92
+ **ParseQueryConfig**
93
+
94
+ | Property | Type | Description | required | default |
95
+ | ---------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- |
96
+ | allowApexBindVariables | boolean | Determines if apex variables are allowed in parsed query. Example: `WHERE Id IN :accountIds`. Only simple Apex is supported. Function calls are not supported. (e.x. `accountMap.keyset()` is not supported) | FALSE | FALSE |
97
+ | allowPartialQuery | boolean | If provided, you can provide an incomplete soql query. This is useful if you need to parse WHERE clauses, for example. Subqueries are required to be valid. | FALSE | FALSE |
98
+ | ignoreParseErrors | boolean | If set to true, then queries with partially invalid syntax will still be parsed, but any clauses with invalid parts will be omitted. The SELECT clause and FROM clause must always be valid, but all other clauses can contain invalid parts. | FALSE | FALSE |
99
+ | logErrors | boolean | If true, parsing and lexing errors will be logged to the console. | FALSE | FALSE |
100
+
101
+ **SoqlComposeConfig**
102
+
103
+ | Property | Type | Description | required | default |
104
+ | ------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ------- |
105
+ | format | boolean | Apply formatting the the composed query. This will result in a multi-line soql statement. | FALSE | TRUE |
106
+ | formatOptions | FormatOptions | Options to apply to the formatter. | FALSE | |
107
+ | autoCompose | boolean | If you need to compose just part of a query, you can create your own instance of the Compose class and set this to false, then call any methods that you need to just for what you would like to turn into a SOQL query. | FALSE | TRUE |
108
+ | logging | boolean | Print out logging statements to the console about the format operation. | FALSE | FALSE |
109
+
110
+ **FormatOptions**
111
+
112
+ | Property | Type | Description | required | default |
113
+ | -------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- |
114
+ | numIndent | number | The number of tab characters to indent. | FALSE | 1 |
115
+ | fieldMaxLineLength | number | The number of characters that the fields should take up before making a new line. Set this to 1 to have every field on its own line. | FALSE | 60 |
116
+ | fieldSubqueryParensOnOwnLine | boolean | If true, the opening and closing parentheses will be on their own line for subqueries. | FALSE | TRUE |
117
+ | newLineAfterKeywords | boolean | Adds a new line and indent after all keywords (such as SELECT, FROM, WHERE, ORDER BY, etc..) Setting this to true will add new lines in other places as well, such as complex WHERE clauses | FALSE | FALSE |
118
+ | ~~whereClauseOperatorsIndented~~ | boolean | **Deprecated** If true, indents the where clause operators. | FALSE | FALSE |
119
+ | logging | boolean | Print out logging statements to the console about the format operation. | FALSE | FALSE |
120
+
121
+ ## Examples
122
+
123
+ ### Parsing Queries
124
+
125
+ Parsing a SOQL query can be completed by calling `parseQuery(soqlQueryString)`. A `Query` data structure will be returned.
126
+
127
+ ```typescript
128
+ import { parseQuery } from 'soql-parser-js';
129
+
130
+ const soql = `
131
+ SELECT UserId, COUNT(Id)
132
+ FROM LoginHistory
133
+ WHERE LoginTime > 2010-09-20T22:16:30.000Z
134
+ AND LoginTime < 2010-09-21T22:16:30.000Z
135
+ GROUP BY UserId
136
+ `;
137
+
138
+ const soqlQuery = parseQuery(soql);
139
+
140
+ console.log(JSON.stringify(soqlQuery, null, 2));
141
+ ```
142
+
143
+ <details>
144
+ <summary><b>Results (click to show)</b></summary>
145
+
146
+ ```json
147
+ {
148
+ "fields": [
149
+ {
150
+ "type": "Field",
151
+ "field": "UserId"
152
+ },
153
+ {
154
+ "type": "FieldFunctionExpression",
155
+ "functionName": "COUNT",
156
+ "parameters": ["Id"],
157
+ "isAggregateFn": true,
158
+ "rawValue": "COUNT(Id)"
159
+ }
160
+ ],
161
+ "sObject": "LoginHistory",
162
+ "where": {
163
+ "left": {
164
+ "field": "LoginTime",
165
+ "operator": ">",
166
+ "value": "2010-09-20T22:16:30.000Z",
167
+ "literalType": "DATETIME"
168
+ },
169
+ "operator": "AND",
170
+ "right": {
171
+ "left": {
172
+ "field": "LoginTime",
173
+ "operator": "<",
174
+ "value": "2010-09-21T22:16:30.000Z",
175
+ "literalType": "DATETIME"
176
+ }
177
+ }
178
+ },
179
+ "groupBy": {
180
+ "field": "UserId"
181
+ }
182
+ }
183
+ ```
184
+
185
+ </details>
186
+
187
+ ### Parsing a partial query
188
+
189
+ Added support for `allowPartialQuery` in version `4.4.0`
190
+
191
+ ```typescript
192
+ import { parseQuery } from 'soql-parser-js';
193
+
194
+ const soql = `
195
+ WHERE LoginTime > 2010-09-20T22:16:30.000Z
196
+ AND LoginTime < 2010-09-21T22:16:30.000Z
197
+ GROUP BY UserId
198
+ `;
199
+
200
+ const soqlQuery = parseQuery(soql, { allowPartialQuery: true });
201
+
202
+ console.log(JSON.stringify(soqlQuery, null, 2));
203
+ ```
204
+
205
+ <details>
206
+ <summary><b>Results (click to show)</b></summary>
207
+
208
+ ```json
209
+ {
210
+ "where": {
211
+ "left": {
212
+ "field": "LoginTime",
213
+ "operator": ">",
214
+ "value": "2010-09-20T22:16:30.000Z",
215
+ "literalType": "DATETIME"
216
+ },
217
+ "operator": "AND",
218
+ "right": {
219
+ "left": {
220
+ "field": "LoginTime",
221
+ "operator": "<",
222
+ "value": "2010-09-21T22:16:30.000Z",
223
+ "literalType": "DATETIME"
224
+ }
225
+ }
226
+ },
227
+ "groupBy": {
228
+ "field": "UserId"
229
+ }
230
+ }
231
+ ```
232
+
233
+ </details>
234
+
235
+ ### Validating Queries
236
+
237
+ ```typescript
238
+ import { isQueryValid } from 'soql-parser-js';
239
+
240
+ const invalidSoql = `SELECT UserId, COUNT(Id) Account`;
241
+ const validSoql = `SELECT UserId, COUNT(Id) Account`;
242
+
243
+ console.log(isQueryValid(soql));
244
+ console.log(isQueryValid(soql));
245
+ ```
246
+
247
+ ### Composing Queries
248
+
249
+ Build a `Query` data structure to have it converted back into a SOQL query.
250
+
251
+ Composing a query will turn a Query object back to a SOQL query string. The exact same data structure returned from `parseQuery()` can be used,
252
+ but depending on your use-case, you may need to build your own data structure to compose a query.
253
+ These examples show building your own Query object with the minimum required fields.
254
+
255
+ Some utility methods have been provided to make it easier to build the field data structures.
256
+
257
+ **Note:** Some operators may be converted to uppercase (e.x. NOT, AND)
258
+
259
+ **Note:** There are a number of fields populated on the Query object when `parseQuery()` is called that are not required to compose a query. Look at the examples below and the comments in the data model for more information.
260
+
261
+ ```typescript
262
+ import { composeQuery, getField, Query } from 'soql-parser-js';
263
+
264
+ // Build a subquery
265
+ const oppLineItemsSubquery = {
266
+ fields: [
267
+ getField('Quantity'),
268
+ getField('ListPrice'),
269
+ getField({
270
+ field: 'UnitPrice',
271
+ relationships: ['PricebookEntry'],
272
+ }),
273
+ getField({
274
+ field: 'Name',
275
+ relationships: ['PricebookEntry'],
276
+ }),
277
+ ],
278
+ relationshipName: 'OpportunityLineItems',
279
+ };
280
+
281
+ // build the main query and add the subquery as a field
282
+ const soqlQuery: Query = {
283
+ fields: [
284
+ getField('Id'),
285
+ getField('Name'),
286
+ getField({
287
+ functionName: 'FORMAT',
288
+ parameters: 'Amount',
289
+ alias: 'MyFormattedAmount',
290
+ }),
291
+ getField({ subquery: oppLineItemsSubquery }),
292
+ ],
293
+ sObject: 'Opportunity',
294
+ where: {
295
+ left: {
296
+ field: 'CreatedDate',
297
+ operator: '>',
298
+ value: 'LAST_N_YEARS:1',
299
+ },
300
+ operator: 'AND',
301
+ right: {
302
+ left: {
303
+ field: 'StageName',
304
+ operator: '=',
305
+ value: 'Closed Won',
306
+ // literalType is optional, but if set to STRING and our value is not already wrapped in "'", they will be added
307
+ // All other literalType values are ignored when composing a query
308
+ literalType: 'STRING',
309
+ },
310
+ },
311
+ },
312
+ limit: 150,
313
+ };
314
+
315
+ const composedQuery = composeQuery(soqlQuery, { format: true });
316
+
317
+ console.log(composedQuery);
318
+ ```
319
+
320
+ **Results**
321
+
322
+ ```sql
323
+ SELECT Id, Name, FORMAT(Amount) MyFormattedAmount,
324
+ (
325
+ SELECT Quantity, ListPrice, PricebookEntry.UnitPrice,
326
+ PricebookEntry.Name
327
+ FROM OpportunityLineItems
328
+ )
329
+ FROM Opportunity
330
+ WHERE CreatedDate > LAST_N_YEARS:1
331
+ AND StageName = 'Closed Won'
332
+ LIMIT 150
333
+ ```
334
+
335
+ ### Composing a partial query
336
+
337
+ Starting in version `4.4`, compose will not fail if there are missing `SELECT` and `FROM` clauses in your query.
338
+
339
+ Partial compose support it supported without any additional steps.
340
+
341
+ ```typescript
342
+ import { Compose, parseQuery } from 'soql-parser-js';
343
+
344
+ const soql = `WHERE Name LIKE 'A%' AND MailingCity = 'California`;
345
+ const parsedQuery = parseQuery(soql, { allowPartialQuery: true });
346
+
347
+ // Results of Parsed Query:
348
+ /**
349
+ {
350
+ where: {
351
+ left: { field: 'Name', operator: 'LIKE', value: "'A%'", literalType: 'STRING' },
352
+ operator: 'AND',
353
+ right: { left: { field: 'MailingCity', operator: '=', value: "'California'", literalType: 'STRING' } },
354
+ },
355
+ }
356
+ */
357
+
358
+ const composedQuery = composeQuery(soqlQuery, { format: true });
359
+
360
+ console.log(composedQuery);
361
+ ```
362
+
363
+ **Results**
364
+
365
+ ```sql
366
+ WHERE Name LIKE 'A%' AND MailingCity = 'California
367
+ ```
368
+
369
+ <details>
370
+ <summary><b>See the alternate way to compose partial queries by calling the Compose class directly</b></summary>
371
+
372
+ If you need to compose just a part of a query instead of the entire query, you can create an instance of the Compose class directly.
373
+
374
+ For example, if you just need the `WHERE` clause from a query as a string, you can do the following:
375
+
376
+ ```typescript
377
+ import { Compose, parseQuery } from 'soql-parser-js';
378
+
379
+ const soql = `SELECT Id FROM Account WHERE Name = 'Foo'`;
380
+ const parsedQuery = parseQuery(soql);
381
+
382
+ // Results of Parsed Query:
383
+ // const parsedQuery = {
384
+ // fields: [
385
+ // {
386
+ // type: 'Field',
387
+ // field: 'Id',
388
+ // },
389
+ // ],
390
+ // sObject: 'Account',
391
+ // where: {
392
+ // left: {
393
+ // field: 'Name',
394
+ // operator: '=',
395
+ // value: "'Foo'",
396
+ // literalType: 'STRING',
397
+ // },
398
+ // },
399
+ // };
400
+
401
+ // Create a new instance of the compose class and set the autoCompose to false to avoid composing the entire query
402
+ const composer = new Compose(parsedQuery, { autoCompose: false });
403
+
404
+
405
+ const whereClause = composer.parseWhereOrHavingClause(parsedQuery.where);
406
+
407
+ console.log(whereClause);
408
+ }
409
+ ```
410
+
411
+ #### Available methods on the `Compose` class
412
+
413
+ These are used internally, but are public and available for use.
414
+
415
+ ```typescript
416
+ parseQuery(query: Query | Subquery): string;
417
+ parseFields(fields: FieldType[]): { text: string; typeOfClause?: string[] }[];
418
+ parseTypeOfField(typeOfField: FieldTypeOf): string[];
419
+ parseWhereOrHavingClause(whereOrHaving: WhereClause | HavingClause, tabOffset = 0, priorConditionIsNegation = false): string;
420
+ parseGroupByClause(groupBy: GroupByClause | GroupByClause[]): string;
421
+ parseOrderBy(orderBy: OrderByClause | OrderByClause[]): string;
422
+ parseWithDataCategory(withDataCategory: WithDataCategoryClause): string;
423
+ ```
424
+
425
+ </details>
426
+
427
+ ## Format Query
428
+
429
+ This function is provided as a convenience and just calls parse and compose.
430
+ [Check out the demo](https://jetstreamapp.github.io/soql-parser-js/) to see the outcome of the various format options.
431
+
432
+ ```typescript
433
+ import { formatQuery } from 'soql-parser-js';
434
+
435
+ const query = `SELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue, BillingAddress, BillingCity, BillingCountry, BillingGeocodeAccuracy, ShippingStreet, Sic, SicDesc, Site, SystemModstamp, TickerSymbol, Type, Website, (SELECT Id, Name, AccountId, Amount, CampaignId, CloseDate, CreatedById, Type FROM Opportunities), (SELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue, BillingAddress, Website FROM ChildAccounts) FROM Account WHERE Name LIKE 'a%' OR Name LIKE 'b%' OR Name LIKE 'c%'`;
436
+
437
+ const formattedQuery1 = formatQuery(query);
438
+ const formattedQuery2 = formatQuery(query, {
439
+ fieldMaxLineLength: 20,
440
+ fieldSubqueryParensOnOwnLine: false,
441
+ whereClauseOperatorsIndented: true,
442
+ });
443
+ const formattedQuery3 = formatQuery(query, { fieldSubqueryParensOnOwnLine: true, whereClauseOperatorsIndented: true });
444
+ ```
445
+
446
+ ```sql
447
+ -- formattedQuery1
448
+ SELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue,
449
+ BillingAddress, BillingCity, BillingCountry, BillingGeocodeAccuracy,
450
+ ShippingStreet, Sic, SicDesc, Site, SystemModstamp, TickerSymbol, Type,
451
+ Website,
452
+ (
453
+ SELECT Id, Name, AccountId, Amount, CampaignId, CloseDate,
454
+ CreatedById, Type
455
+ FROM Opportunities
456
+ ),
457
+ (
458
+ SELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue,
459
+ BillingAddress, Website
460
+ FROM ChildAccounts
461
+ )
462
+ FROM Account
463
+ WHERE Name LIKE 'a%'
464
+ OR Name LIKE 'b%'
465
+ OR Name LIKE 'c%'
466
+
467
+ -- formattedQuery2
468
+ SELECT Id, Name,
469
+ AccountNumber, AccountSource,
470
+ AnnualRevenue, BillingAddress,
471
+ BillingCity, BillingCountry,
472
+ BillingGeocodeAccuracy, ShippingStreet,
473
+ Sic, SicDesc, Site,
474
+ SystemModstamp, TickerSymbol, Type,
475
+ Website,
476
+ (SELECT Id, Name,
477
+ AccountId, Amount, CampaignId,
478
+ CloseDate, CreatedById, Type
479
+ FROM Opportunities),
480
+ (SELECT Id, Name,
481
+ AccountNumber, AccountSource,
482
+ AnnualRevenue, BillingAddress,
483
+ Website
484
+ FROM ChildAccounts)
485
+ FROM Account
486
+ WHERE Name LIKE 'a%'
487
+ OR Name LIKE 'b%'
488
+ OR Name LIKE 'c%'
489
+
490
+
491
+ -- formattedQuery3
492
+ SELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue,
493
+ BillingAddress, BillingCity, BillingCountry, BillingGeocodeAccuracy,
494
+ ShippingStreet, Sic, SicDesc, Site, SystemModstamp, TickerSymbol, Type,
495
+ Website,
496
+ (
497
+ SELECT Id, Name, AccountId, Amount, CampaignId, CloseDate,
498
+ CreatedById, Type
499
+ FROM Opportunities
500
+ ),
501
+ (
502
+ SELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue,
503
+ BillingAddress, Website
504
+ FROM ChildAccounts
505
+ )
506
+ FROM Account
507
+ WHERE Name LIKE 'a%'
508
+ OR Name LIKE 'b%'
509
+ OR Name LIKE 'c%'
510
+ ```
511
+
512
+ ## CLI
513
+
514
+ Install globally or use `npx` to interact with the cli.
515
+
516
+ ### Available Commands
517
+
518
+ - `soql-parser-js --help` (or using `npx`: `npx soql-parser-js --help`)
519
+ - `soql-parser-js parse --help`
520
+ - `soql-parser-js compose --help`
521
+ - `soql-parser-js format --help`
522
+
523
+ ### Examples
524
+
525
+ #### Parse
526
+
527
+ `npx soql-parser-js parse "SELECT Id FROM Account"`
528
+
529
+ ```bash
530
+ {"fields":[{"type":"Field","field":"Id"}],"sObject":"Account"}
531
+ ```
532
+
533
+ #### Compose
534
+
535
+ `npx soql-parser-js compose "{\"fields\":[{\"type\":\"Field\",\"field\":\"Id\"}],\"sObject\":\"Account\"}"`
536
+
537
+ ```bash
538
+ SELECT Id FROM Account
539
+ ```
540
+
541
+ `npx soql-parser-js compose "{\"fields\":[{\"type\":\"Field\",\"field\":\"Id\"}],\"sObject\":\"Account\"}" --json` or -j
542
+
543
+ ```json
544
+ { "query": "SELECT Id FROM Account" }
545
+ ```
546
+
547
+ #### Format
548
+
549
+ `npx soql-parser-js format "SELECT Name, COUNT(Id) FROM Account GROUP BY Name HAVING COUNT(Id) > 1"`
550
+
551
+ ```bash
552
+ SELECT Name, COUNT(Id)
553
+ FROM Account
554
+ GROUP BY Name
555
+ HAVING COUNT(Id) > 1
556
+ ```
557
+
558
+ `npx soql-parser-js format "SELECT Name, COUNT(Id) FROM Account GROUP BY Name HAVING COUNT(Id) > 1 -j`
559
+
560
+ ```json
561
+ { "query": "SELECT Name, COUNT(Id)\nFROM Account\nGROUP BY Name\nHAVING COUNT(Id) > 1" }
562
+ ```
563
+
564
+ #### Is Valid
565
+
566
+ `npx soql-parser-js valid "SELECT Id FROM Account"`
567
+
568
+ ```bash
569
+ true
570
+ ```
571
+
572
+ `npx soql-parser-js valid "SELECT Id invalid FROM Account"`
573
+
574
+ ℹ️ this returns an exit code of 1
575
+
576
+ ```bash
577
+ false
578
+ ```
579
+
580
+ `npx soql-parser-js valid "SELECT Id FROM Account" -j`
581
+
582
+ ```json
583
+ { "isValid": true }
584
+ ```
585
+
586
+ `npx soql-parser-js valid "SELECT Id invalid invalid FROM Account" -j`
587
+
588
+ ℹ️ this returns an exit code of 0
589
+
590
+ ```json
591
+ { "isValid": false }
592
+ ```
593
+
594
+ ### List of options
595
+
596
+ `soql-parser-js --help`
597
+
598
+ ```bash
599
+ Usage: soql-parser-js [options] [command]
600
+
601
+ Options:
602
+ -h, --help output usage information
603
+
604
+ Commands:
605
+ parse [options] <sql>
606
+ compose [options] <query>
607
+ format [options] <sql>
608
+ valid <sql>
609
+ ```
610
+
611
+ `soql-parser-js parse --help`
612
+
613
+ ```bash
614
+ Usage: parse [options] <sql>
615
+
616
+ Options:
617
+ -a, --allow-apex allow apex bind variables
618
+ -p, --allow-partial allow partial queries
619
+ -i, --ignore-errors ignore parse errors, return as much of query as possible
620
+ -h, --help output usage information
621
+ ```
622
+
623
+ `soql-parser-js compose --help`
624
+
625
+ ```bash
626
+ Usage: compose [options] <query>
627
+
628
+ Options:
629
+ -f, --format format output
630
+ -i --indent <chars> number of tab characters to indent (default: 1)
631
+ -m --line-length <chars> max number of characters per lins (default: 60)
632
+ -s --subquery-parens-new-line subquery parens on own line
633
+ -k --keywords-new-line new line after keywords
634
+ -j, --json output as JSON
635
+ -h, --help output usage information
636
+ ```
637
+
638
+ `soql-parser-js format --help`
639
+
640
+ ```bash
641
+ Usage: format [options] <sql>
642
+
643
+ Options:
644
+ -a, --allow-apex allow apex bind variables
645
+ -p, --allow-partial allow partial queries
646
+ -i --indent <chars> number of tab characters to indent (default: 1)
647
+ -m --line-length <chars> max number of characters per lins (default: 60)
648
+ -s --subquery-parens-new-line subquery parens on own line
649
+ -k --keywords-new-line new line after keywords
650
+ -j, --json output as JSON
651
+ -h, --help output usage information
652
+ ```
653
+
654
+ `soql-parser-js valid --help`
655
+
656
+ ```bash
657
+ Usage: valid [options] <sql>
658
+
659
+ Options:
660
+ -a, --allow-apex allow apex bind variables
661
+ -p, --allow-partial allow partial queries
662
+ -j, --json output as JSON
663
+ -h, --help output usage information
664
+ ```
665
+
666
+ ## Data Models
667
+
668
+ ### Query
669
+
670
+ ```typescript
671
+ export type LogicalOperator = 'AND' | 'OR' | 'NOT';
672
+ export type Operator = '=' | '!=' | '<=' | '>=' | '>' | '<' | 'LIKE' | 'IN' | 'NOT IN' | 'INCLUDES' | 'EXCLUDES';
673
+ export type FieldTypeOfConditionType = 'WHEN' | 'ELSE';
674
+ export type GroupSelector = 'ABOVE' | 'AT' | 'BELOW' | 'ABOVE_OR_BELOW';
675
+ export type ForClause = 'VIEW' | 'UPDATE' | 'REFERENCE';
676
+ export type UpdateClause = 'TRACKING' | 'VIEWSTAT';
677
+ export type LiteralType =
678
+ | 'STRING'
679
+ | 'INTEGER'
680
+ | 'DECIMAL'
681
+ | 'INTEGER_WITH_CURRENCY_PREFIX'
682
+ | 'DECIMAL_WITH_CURRENCY_PREFIX'
683
+ | 'BOOLEAN'
684
+ | 'NULL'
685
+ | 'DATETIME'
686
+ | 'DATE'
687
+ | 'DATE_LITERAL'
688
+ | 'DATE_N_LITERAL'
689
+ | 'APEX_BIND_VARIABLE';
690
+ export type FieldType =
691
+ | Field
692
+ | FieldWithAlias
693
+ | FieldFunctionExpression
694
+ | FieldRelationship
695
+ | FieldRelationshipWithAlias
696
+ | FieldSubquery
697
+ | FieldTypeOf;
698
+ export type OrderByCriterion = 'ASC' | 'DESC';
699
+ export type NullsOrder = 'FIRST' | 'LAST';
700
+ export type GroupByType = 'CUBE' | 'ROLLUP';
701
+ export type DateLiteral =
702
+ | 'YESTERDAY'
703
+ | 'TODAY'
704
+ | 'TOMORROW'
705
+ | 'LAST_WEEK'
706
+ | 'THIS_WEEK'
707
+ | 'NEXT_WEEK'
708
+ | 'LAST_MONTH'
709
+ | 'THIS_MONTH'
710
+ | 'NEXT_MONTH'
711
+ | 'LAST_90_DAYS'
712
+ | 'NEXT_90_DAYS'
713
+ | 'THIS_QUARTER'
714
+ | 'LAST_QUARTER'
715
+ | 'NEXT_QUARTER'
716
+ | 'THIS_YEAR'
717
+ | 'LAST_YEAR'
718
+ | 'NEXT_YEAR'
719
+ | 'THIS_FISCAL_QUARTER'
720
+ | 'LAST_FISCAL_QUARTER'
721
+ | 'NEXT_FISCAL_QUARTER'
722
+ | 'THIS_FISCAL_YEAR'
723
+ | 'LAST_FISCAL_YEAR'
724
+ | 'NEXT_FISCAL_YEAR';
725
+
726
+ export type DateNLiteral =
727
+ | 'YESTERDAY'
728
+ | 'NEXT_N_DAYS'
729
+ | 'LAST_N_DAYS'
730
+ | 'N_DAYS_AGO'
731
+ | 'NEXT_N_WEEKS'
732
+ | 'LAST_N_WEEKS'
733
+ | 'N_WEEKS_AGO'
734
+ | 'NEXT_N_MONTHS'
735
+ | 'LAST_N_MONTHS'
736
+ | 'N_MONTHS_AGO'
737
+ | 'NEXT_N_QUARTERS'
738
+ | 'LAST_N_QUARTERS'
739
+ | 'N_QUARTERS_AGO'
740
+ | 'NEXT_N_YEARS'
741
+ | 'LAST_N_YEARS'
742
+ | 'N_YEARS_AGO'
743
+ | 'NEXT_N_FISCAL_QUARTERS'
744
+ | 'LAST_N_FISCAL_QUARTERS'
745
+ | 'N_FISCAL_QUARTERS_AGO'
746
+ | 'NEXT_N_FISCAL_YEARS'
747
+ | 'LAST_N_FISCAL_YEARS'
748
+ | 'N_FISCAL_YEARS_AGO';
749
+
750
+ export interface Field {
751
+ type: 'Field';
752
+ field: string;
753
+ alias?: string;
754
+ }
755
+
756
+ export interface FieldWithAlias extends Field {
757
+ objectPrefix: string;
758
+ rawValue: string;
759
+ }
760
+
761
+ export interface FieldFunctionExpression {
762
+ type: 'FieldFunctionExpression';
763
+ functionName: string;
764
+ parameters: (string | FieldFunctionExpression)[];
765
+ alias?: string;
766
+ isAggregateFn?: boolean; // not required for compose, will be populated if SOQL is parsed
767
+ rawValue?: string; // not required for compose, will be populated if SOQL is parsed
768
+ }
769
+
770
+ export interface FieldRelationship {
771
+ type: 'FieldRelationship';
772
+ field: string;
773
+ relationships: string[];
774
+ rawValue?: string; // not required for compose, will be populated if SOQL is parsed with the raw value of the entire field
775
+ }
776
+
777
+ export interface FieldRelationshipWithAlias extends FieldRelationship {
778
+ objectPrefix: string;
779
+ alias: string;
780
+ }
781
+
782
+ export interface FieldSubquery {
783
+ type: 'FieldSubquery';
784
+ subquery: Subquery;
785
+ }
786
+
787
+ export interface FieldTypeOf {
788
+ type: 'FieldTypeof';
789
+ field: string;
790
+ conditions: FieldTypeOfCondition[];
791
+ }
792
+
793
+ export interface FieldTypeOfCondition {
794
+ type: FieldTypeOfConditionType;
795
+ objectType?: string; // not present when ELSE
796
+ fieldList: string[];
797
+ }
798
+
799
+ export interface QueryBase {
800
+ fields?: FieldType[];
801
+ sObjectAlias?: string;
802
+ usingScope?: string;
803
+ where?: WhereClause;
804
+ limit?: number;
805
+ offset?: number;
806
+ groupBy?: GroupByClause;
807
+ orderBy?: OrderByClause | OrderByClause[];
808
+ withDataCategory?: WithDataCategoryClause;
809
+ withSecurityEnforced?: boolean;
810
+ withAccessLevel?: boolean;
811
+ for?: ForClause;
812
+ update?: UpdateClause;
813
+ }
814
+
815
+ export interface Query extends QueryBase {
816
+ sObject?: string;
817
+ }
818
+
819
+ export interface Subquery extends QueryBase {
820
+ relationshipName: string;
821
+ sObjectPrefix?: string[];
822
+ }
823
+
824
+ export type WhereClause = WhereClauseWithoutOperator | WhereClauseWithRightCondition;
825
+
826
+ export interface WhereClauseWithoutOperator {
827
+ left: ConditionWithValueQuery;
828
+ }
829
+
830
+ export interface WhereClauseWithRightCondition extends WhereClauseWithoutOperator {
831
+ operator: LogicalOperator;
832
+ right: WhereClause;
833
+ }
834
+
835
+ export type Condition =
836
+ | ValueCondition
837
+ | ValueWithDateLiteralCondition
838
+ | ValueWithDateNLiteralCondition
839
+ | ValueFunctionCondition
840
+ | NegationCondition;
841
+
842
+ export type ConditionWithValueQuery = Condition | ValueQueryCondition;
843
+
844
+ export interface OptionalParentheses {
845
+ openParen?: number;
846
+ closeParen?: number;
847
+ }
848
+
849
+ export interface ValueCondition extends OptionalParentheses {
850
+ field: string;
851
+ operator: Operator;
852
+ value: string | string[];
853
+ literalType?: LiteralType | LiteralType[];
854
+ }
855
+
856
+ export interface ValueWithDateLiteralCondition extends OptionalParentheses {
857
+ field: string;
858
+ operator: Operator;
859
+ value: DateLiteral | DateLiteral[];
860
+ literalType?: 'DATE_LITERAL' | 'DATE_LITERAL'[];
861
+ }
862
+
863
+ export interface ValueWithDateNLiteralCondition extends OptionalParentheses {
864
+ field: string;
865
+ operator: Operator;
866
+ value: string | string[];
867
+ literalType?: 'DATE_N_LITERAL' | 'DATE_N_LITERAL'[];
868
+ dateLiteralVariable: number | number[];
869
+ }
870
+
871
+ export interface ValueQueryCondition extends OptionalParentheses {
872
+ field: string;
873
+ operator: Operator;
874
+ valueQuery: Query;
875
+ }
876
+
877
+ export interface ValueFunctionCondition extends OptionalParentheses {
878
+ fn: FunctionExp;
879
+ operator: Operator;
880
+ value: string | string[];
881
+ literalType?: LiteralType | LiteralType[];
882
+ }
883
+
884
+ export interface NegationCondition {
885
+ openParen: number;
886
+ }
887
+
888
+ export type OrderByClause = OrderByFieldClause | OrderByFnClause;
889
+
890
+ export interface OrderByOptionalFieldsClause {
891
+ order?: OrderByCriterion;
892
+ nulls?: NullsOrder;
893
+ }
894
+
895
+ export interface OrderByFieldClause extends OrderByOptionalFieldsClause {
896
+ field: string;
897
+ }
898
+
899
+ export interface OrderByFnClause extends OrderByOptionalFieldsClause {
900
+ fn: FunctionExp;
901
+ }
902
+
903
+ export type GroupByClause = GroupByFieldClause | GroupByFnClause;
904
+
905
+ export interface GroupByOptionalFieldsClause {
906
+ having?: HavingClause;
907
+ }
908
+
909
+ export interface GroupByFieldClause extends GroupByOptionalFieldsClause {
910
+ field: string | string[];
911
+ }
912
+
913
+ export interface GroupByFnClause extends GroupByOptionalFieldsClause {
914
+ fn: FunctionExp;
915
+ }
916
+
917
+ export type HavingClause = HavingClauseWithoutOperator | HavingClauseWithRightCondition;
918
+
919
+ export interface HavingClauseWithoutOperator {
920
+ left: Condition;
921
+ }
922
+
923
+ export interface HavingClauseWithRightCondition extends HavingClauseWithoutOperator {
924
+ operator: LogicalOperator;
925
+ right: HavingClause;
926
+ }
927
+
928
+ export interface FunctionExp {
929
+ rawValue?: string; // only used for compose fields if useRawValueForFn=true. Should be formatted like this: Count(Id)
930
+ functionName?: string; // only used for compose fields if useRawValueForFn=false, will be populated if SOQL is parsed
931
+ alias?: string;
932
+ parameters?: (string | FunctionExp)[]; // only used for compose fields if useRawValueForFn=false, will be populated if SOQL is parsed
933
+ isAggregateFn?: boolean; // not used for compose, will be populated if SOQL is parsed
934
+ }
935
+
936
+ export interface WithDataCategoryClause {
937
+ conditions: WithDataCategoryCondition[];
938
+ }
939
+
940
+ export interface WithDataCategoryCondition {
941
+ groupName: string;
942
+ selector: GroupSelector;
943
+ parameters: string[];
944
+ }
945
+ ```
946
+
947
+ ## Contributing
948
+
949
+ All contributions are welcome on the project. Please read the [contribution guidelines](https://github.com/jetstreamapp/soql-parser-js/blob/master/CONTRIBUTING.md).