couchset 0.0.8 → 0.0.12
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.
- package/README.md +5 -0
- package/dist/automate/model/client.js +1 -1
- package/dist/automate/model/client.js.map +1 -1
- package/dist/automate/model/index.js +18 -19
- package/dist/automate/model/index.js.map +1 -1
- package/dist/automate/morpheus/index.js +9 -9
- package/dist/automate/morpheus/index.js.map +1 -1
- package/dist/automate/writer/index.js +2 -2
- package/dist/automate/writer/index.js.map +1 -1
- package/dist/connection.d.ts +1 -0
- package/dist/connection.js +3 -0
- package/dist/connection.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/model/index.d.ts +9 -9
- package/dist/model/index.js +15 -14
- package/dist/model/index.js.map +1 -1
- package/dist/query/exceptions.js +4 -4
- package/dist/query/exceptions.js.map +1 -1
- package/dist/query/helpers/builders.js +51 -51
- package/dist/query/helpers/builders.js.map +1 -1
- package/dist/query/utils.js +3 -3
- package/dist/query/utils.js.map +1 -1
- package/dist/shared/common.model.js +2 -2
- package/dist/shared/common.model.js.map +1 -1
- package/dist/utils/log.js +2 -2
- package/dist/utils/log.js.map +1 -1
- package/package.json +5 -4
package/dist/model/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/model/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,6DAAgD;AAChD,4CAAyC;AACzC,gCAAqC;AACrC,kCAAkD;AAClD,oCAA6D;AAC7D,wCAA4F;AAiB5F;IAUI,eAAY,IAAY,EAAE,OAAsB;QAPhD,UAAK,GAAG,UAAU,CAAC;QACnB,WAAM,GAAgC;YAClC,SAAS,EAAE,MAAM;YACjB,SAAS,EAAE,MAAM;SACpB,CAAC;QACF,gBAAW,GAAG,IAAI,CAAC;QA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AAK;AAiQlB,kBAAe,KAAK,CAAC","sourcesContent":["import {Collection} from 'couchbase';\n\nimport CouchbaseConnection from '../connection';\nimport {Pagination} from '../pagination';\nimport {generateUUID} from '../uuid';\nimport {parseSchema, SchemaTypes} from '../utils';\nimport {CustomQuery, CustomQueryPagination} from '../search';\nimport {automateImplementation, AutomaticMethodOptions, AutomaticOutput} from '../automate';\n\nexport interface AutoModelFields {\n id: string;\n createdAt: Date;\n updatedAt?: Date;\n deleted?: Date;\n _type: string; // type for models/collections\n _scope: string; // scope for collections\n}\n\ninterface ModalOptions {\n scope?: string;\n schema?: Record<string, SchemaTypes>;\n graphqlType?: any;\n}\n\nexport class Model {\n collection: Collection;\n collectionName: string;\n scope = '_default';\n schema: Record<string, SchemaTypes> = {\n createdAt: 'date',\n updatedAt: 'date',\n };\n graphqlType = null;\n\n constructor(name: string, options?: ModalOptions) {\n // this.collection = CouchbaseConnection.Instance.getCollection();\n this.collectionName = name;\n if (options) {\n this.graphqlType = (options && options.graphqlType) || null;\n this.scope = (options && options.scope) || '_default';\n this.schema = {\n ...((options && options.schema) || {}),\n createdAt: 'date',\n updatedAt: 'date',\n };\n }\n }\n\n /**\n * Set setGraphqlType\n * setGraphqlType\n */\n public setGraphqlType(gqlType: any): Model {\n this.graphqlType = gqlType;\n return this;\n }\n\n /**\n * Refresh and get default collection from CouchbaseConnection\n * Because CouchbaseConnection is a singleton, sometimes it might be undefined depending when model was created\n * So we have to call it from all model methods\n * to avoid error `Cannot read property 'defaultCollection' of null`\n */\n public fresh(): void {\n // if couchbase connection has been init\n if (CouchbaseConnection.Instance.bucketName) {\n this.collection = CouchbaseConnection.Instance.getCollection();\n }\n }\n\n /** Get this collection\n * getCollection\n */\n public getBucketName(): string {\n return CouchbaseConnection.Instance.bucketName;\n }\n\n /** Get this collection\n * getCollection\n */\n public couchbaseConnection(): CouchbaseConnection {\n return CouchbaseConnection.Instance;\n }\n\n /** Get this collection\n * getCollection\n */\n public getCollection(): Collection {\n this.fresh();\n return this.collection;\n }\n\n /**\n * create\n */\n public async create<T>(data: T): Promise<T & AutoModelFields> {\n this.fresh();\n const id = generateUUID();\n const createdData = {\n id, // let id be override\n ...data,\n createdAt: new Date(),\n updatedAt: new Date(), // same as created at\n _type: this.collectionName,\n _scope: this.scope,\n };\n\n try {\n await this.collection.upsert(createdData.id, createdData);\n return parseSchema(this.schema, createdData);\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * findById\n */\n public async findById(id: string): Promise<any & AutoModelFields> {\n this.fresh();\n try {\n const data = await this.collection.get(id);\n return parseSchema(this.schema, data.content);\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * update\n */\n public async updateById<T>(id: string, data: T): Promise<T> {\n this.fresh();\n const updatedDocument = {\n ...data,\n id,\n updatedAt: new Date(),\n _type: this.collectionName, // type and scope must be defined\n _scope: this.scope,\n };\n\n try {\n await this.collection.replace(id, updatedDocument);\n return parseSchema(this.schema, updatedDocument);\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * save\n */\n public async save<T>(data: T & {id: string}): Promise<T> {\n this.fresh();\n\n const id = data && data.id;\n\n const updatedDocument = {\n ...data,\n id, // id's must match\n updatedAt: new Date(),\n _type: this.collectionName, // type and scope must be defined\n _scope: this.scope,\n };\n\n try {\n if (!id) {\n throw new Error('document must have id');\n }\n await this.collection.replace(id, updatedDocument);\n return parseSchema(this.schema, updatedDocument);\n } catch (error) {\n console.error(error);\n throw error;\n }\n }\n\n public async delete(id: string): Promise<boolean> {\n this.fresh();\n try {\n await this.collection.remove(id);\n return true;\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * Pagination\n * \n select = ['id', 'createdAt']\n where = {\n where: { owner: { $eq: \"stoqey\" }, _type: { $eq: \"Trade\" } },\n },\n page = 0,\n limit = 10,\n orderBy = { createdAt: \"DESC\" },\n * @param args PaginationArgs\n */\n public async pagination({\n select,\n where,\n orderBy,\n limit,\n page,\n customQuery = {},\n }: {\n select?: any[] | string;\n where?: any;\n orderBy?: any;\n limit?: number;\n page?: number;\n customQuery?: any; // can be $and or any other valid quries\n }): Promise<any[]> {\n this.fresh(); // refresh\n // Where begins here\n let whereEx = {_type: {$eq: this.collectionName}};\n\n if (where) {\n whereEx = {\n ...whereEx,\n ...where,\n };\n }\n\n const bucketName = CouchbaseConnection.Instance.bucketName;\n\n const rows = await Pagination({\n bucketName,\n select,\n where: {where: whereEx, ...customQuery},\n limit,\n page,\n orderBy,\n });\n\n return rows.map((r) => parseSchema(this.schema, r));\n }\n\n /**\n * Run a custom query with model parsing\n * @param { select, query }\n * @returns\n */\n public async customQuery<T>({\n params,\n limit,\n query,\n }: {\n params: any;\n limit: number;\n query: string;\n }): Promise<[T[], CustomQueryPagination]> {\n this.fresh(); // refresh\n // Where begins here\n\n const response = await CustomQuery<T>({\n limit,\n params,\n query,\n });\n\n return response;\n }\n\n public parse<T>(data: T): T {\n this.fresh(); // refresh\n return parseSchema(this.schema, data);\n }\n\n /**\n *\n * @param args AutomaticModelOptions\n * @returns\n */\n public automate(args?: Partial<AutomaticMethodOptions>): AutomaticOutput {\n this.fresh(); // refresh\n return automateImplementation(this.graphqlType, {model: this, ...args});\n }\n}\n\nexport default Model;\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/model/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,wCAA4F;AAC5F,oCAA6D;AAC7D,kCAAkD;AAClD,6DAAgD;AAChD,4CAAyC;AACzC,gCAAqC;AAiBrC;IAUI,eAAY,IAAY,EAAE,OAAsB;QAPhD,UAAK,GAAG,UAAU,CAAC;QACnB,WAAM,GAAgC;YAClC,SAAS,EAAE,MAAM;YACjB,SAAS,EAAE,MAAM;SACpB,CAAC;QACF,gBAAW,GAAG,IAAI,CAAC;QAGf,kEAAkE;QAClE,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC3B,IAAI,OAAO,EAAE;YACT,IAAI,CA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ACL,YAAC;AAAD,CAAC,AA/PD,IA+PC;AA/PY,sBAAK;AAiQlB,kBAAe,KAAK,CAAC","sourcesContent":["import {Collection, GetOptions, RemoveOptions, ReplaceOptions, UpsertOptions} from 'couchbase';\n\nimport {AutomaticMethodOptions, AutomaticOutput, automateImplementation} from '../automate';\nimport {CustomQuery, CustomQueryPagination} from '../search';\nimport {SchemaTypes, parseSchema} from '../utils';\nimport CouchbaseConnection from '../connection';\nimport {Pagination} from '../pagination';\nimport {generateUUID} from '../uuid';\n\nexport interface AutoModelFields {\n id: string;\n createdAt: Date;\n updatedAt?: Date;\n deleted?: Date;\n _type: string; // type for models/collections\n _scope: string; // scope for collections\n}\n\ninterface ModalOptions {\n scope?: string;\n schema?: Record<string, SchemaTypes>;\n graphqlType?: any;\n}\n\nexport class Model {\n collection: Collection;\n collectionName: string;\n scope = '_default';\n schema: Record<string, SchemaTypes> = {\n createdAt: 'date',\n updatedAt: 'date',\n };\n graphqlType = null;\n\n constructor(name: string, options?: ModalOptions) {\n // this.collection = CouchbaseConnection.Instance.getCollection();\n this.collectionName = name;\n if (options) {\n this.graphqlType = (options && options.graphqlType) || null;\n this.scope = (options && options.scope) || '_default';\n this.schema = {\n ...((options && options.schema) || {}),\n createdAt: 'date',\n updatedAt: 'date',\n };\n }\n }\n\n /**\n * Set setGraphqlType\n * setGraphqlType\n */\n public setGraphqlType(gqlType: any): Model {\n this.graphqlType = gqlType;\n return this;\n }\n\n /**\n * Refresh and get default collection from CouchbaseConnection\n * Because CouchbaseConnection is a singleton, sometimes it might be undefined depending when model was created\n * So we have to call it from all model methods\n * to avoid error `Cannot read property 'defaultCollection' of null`\n */\n public fresh(): void {\n // if couchbase connection has been init\n if (CouchbaseConnection.Instance.bucketName) {\n this.collection = CouchbaseConnection.Instance.getCollection();\n }\n }\n\n /** Get this collection\n * getCollection\n */\n public getBucketName(): string {\n return CouchbaseConnection.Instance?.getBucket();\n }\n\n /** Get this collection\n * getCollection\n */\n public couchbaseConnection(): CouchbaseConnection {\n return CouchbaseConnection.Instance;\n }\n\n /** Get this collection\n * getCollection\n */\n public getCollection(): Collection {\n this.fresh();\n return this.collection;\n }\n\n /**\n * create\n */\n public async create<T>(data: T, options?: UpsertOptions): Promise<T & AutoModelFields> {\n this.fresh();\n const id = generateUUID();\n const createdData = {\n id, // let id be override\n ...data,\n createdAt: new Date(),\n updatedAt: new Date(), // same as created at\n _type: this.collectionName,\n _scope: this.scope,\n };\n\n try {\n await this.collection.upsert(createdData.id, createdData, options);\n return parseSchema(this.schema, createdData);\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * findById\n */\n public async findById(id: string, options?: GetOptions): Promise<any & AutoModelFields> {\n this.fresh();\n try {\n const data = await this.collection.get(id, options);\n return parseSchema(this.schema, data.content);\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * update\n */\n public async updateById<T>(id: string, data: T, options?: ReplaceOptions): Promise<T> {\n this.fresh();\n const updatedDocument = {\n ...data,\n id,\n updatedAt: new Date(),\n _type: this.collectionName, // type and scope must be defined\n _scope: this.scope,\n };\n\n try {\n await this.collection.replace(id, updatedDocument, options);\n return parseSchema(this.schema, updatedDocument);\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * save\n */\n public async save<T>(data: T & {id: string}, options?: ReplaceOptions): Promise<T> {\n this.fresh();\n\n const id = data && data.id;\n\n const updatedDocument = {\n ...data,\n id, // id's must match\n updatedAt: new Date(),\n _type: this.collectionName, // type and scope must be defined\n _scope: this.scope,\n };\n\n try {\n if (!id) {\n throw new Error('document must have id');\n }\n await this.collection.replace(id, updatedDocument, options);\n return parseSchema(this.schema, updatedDocument);\n } catch (error) {\n console.error(error);\n throw error;\n }\n }\n\n public async delete(id: string, options?: RemoveOptions): Promise<boolean> {\n this.fresh();\n try {\n await this.collection.remove(id, options);\n return true;\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * Pagination\n * \n select = ['id', 'createdAt']\n where = {\n where: { owner: { $eq: \"stoqey\" }, _type: { $eq: \"Trade\" } },\n },\n page = 0,\n limit = 10,\n orderBy = { createdAt: \"DESC\" },\n * @param args PaginationArgs\n */\n public async pagination({\n select,\n where,\n orderBy,\n limit,\n page,\n customQuery = {},\n }: {\n select?: any[] | string;\n where?: any;\n orderBy?: any;\n limit?: number;\n page?: number;\n customQuery?: any; // can be $and or any other valid quries\n }): Promise<any[]> {\n this.fresh(); // refresh\n // Where begins here\n let whereEx = {_type: {$eq: this.collectionName}};\n\n if (where) {\n whereEx = {\n ...whereEx,\n ...where,\n };\n }\n\n const bucketName = CouchbaseConnection.Instance.bucketName;\n\n const rows = await Pagination({\n bucketName,\n select,\n where: {where: whereEx, ...customQuery},\n limit,\n page,\n orderBy,\n });\n\n return rows.map((r) => parseSchema(this.schema, r));\n }\n\n /**\n * Run a custom query with model parsing\n * @param { select, query }\n * @returns\n */\n public async customQuery<T>({\n params,\n limit,\n query,\n }: {\n params: any;\n limit: number;\n query: string;\n }): Promise<[T[], CustomQueryPagination]> {\n this.fresh(); // refresh\n // Where begins here\n\n const response = await CustomQuery<T>({\n limit,\n params,\n query,\n });\n\n return response;\n }\n\n public parse<T>(data: T): T {\n this.fresh(); // refresh\n return parseSchema(this.schema, data);\n }\n\n /**\n *\n * @param args AutomaticModelOptions\n * @returns\n */\n public automate(args?: Partial<AutomaticMethodOptions>): AutomaticOutput {\n this.fresh(); // refresh\n return automateImplementation(this.graphqlType, {model: this, ...args});\n }\n}\n\nexport default Model;\n"]}
|
package/dist/query/exceptions.js
CHANGED
|
@@ -46,7 +46,7 @@ exports.InWithinOperatorExceptions = InWithinOperatorExceptions;
|
|
|
46
46
|
var MultipleQueryTypesException = /** @class */ (function (_super) {
|
|
47
47
|
__extends(MultipleQueryTypesException, _super);
|
|
48
48
|
function MultipleQueryTypesException(type1, type2) {
|
|
49
|
-
return _super.call(this, "Cannot combine multiple query types (ex: "
|
|
49
|
+
return _super.call(this, "Cannot combine multiple query types (ex: ".concat(type1, " with ").concat(type2)) || this;
|
|
50
50
|
}
|
|
51
51
|
return MultipleQueryTypesException;
|
|
52
52
|
}(Error));
|
|
@@ -55,7 +55,7 @@ var QueryOperatorNotFoundException = /** @class */ (function (_super) {
|
|
|
55
55
|
__extends(QueryOperatorNotFoundException, _super);
|
|
56
56
|
function QueryOperatorNotFoundException(operator) {
|
|
57
57
|
var _this = _super.call(this) || this;
|
|
58
|
-
_this.message = "Operator not found: "
|
|
58
|
+
_this.message = "Operator not found: ".concat(operator);
|
|
59
59
|
return _this;
|
|
60
60
|
}
|
|
61
61
|
return QueryOperatorNotFoundException;
|
|
@@ -74,7 +74,7 @@ exports.QueryGroupByParamsException = QueryGroupByParamsException;
|
|
|
74
74
|
var IndexParamsOnExceptions = /** @class */ (function (_super) {
|
|
75
75
|
__extends(IndexParamsOnExceptions, _super);
|
|
76
76
|
function IndexParamsOnExceptions(clause) {
|
|
77
|
-
return _super.call(this, "The ON parameter can only be applied in the following clauses: "
|
|
77
|
+
return _super.call(this, "The ON parameter can only be applied in the following clauses: ".concat(JSON.stringify(clause))) || this;
|
|
78
78
|
}
|
|
79
79
|
return IndexParamsOnExceptions;
|
|
80
80
|
}(Error));
|
|
@@ -82,7 +82,7 @@ exports.IndexParamsOnExceptions = IndexParamsOnExceptions;
|
|
|
82
82
|
var IndexParamsUsingGSIExceptions = /** @class */ (function (_super) {
|
|
83
83
|
__extends(IndexParamsUsingGSIExceptions, _super);
|
|
84
84
|
function IndexParamsUsingGSIExceptions(clause) {
|
|
85
|
-
return _super.call(this, "The USING GSI parameter can only be applied in the following clauses: "
|
|
85
|
+
return _super.call(this, "The USING GSI parameter can only be applied in the following clauses: ".concat(JSON.stringify(clause))) || this;
|
|
86
86
|
}
|
|
87
87
|
return IndexParamsUsingGSIExceptions;
|
|
88
88
|
}(Error));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exceptions.js","sourceRoot":"","sources":["../../src/query/exceptions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA;IAA2C,yCAAK;IAC5C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C;IAAoD,kDAAoB;IACpE,wCAAY,QAAgB;QAA5B,YACI,iBAAO,SAEV;QADG,KAAI,CAAC,OAAO,GAAG,8BAAuB,QAAQ,CAAE,CAAC;;IACrD,CAAC;IACL,qCAAC;AAAD,CAAC,AALD,CAAoD,oBAAoB,GAKvE;AALY,wEAA8B;AAO3C;IAAiD,+CAAoB;IACjE;QAAA,YACI,iBAAO,SAEV;QADG,KAAI,CAAC,OAAO,GAAG,2EAA2E,CAAC;;IAC/F,CAAC;IACL,kCAAC;AAAD,CAAC,AALD,CAAiD,oBAAoB,GAKpE;AALY,kEAA2B;AAOxC;IAA6C,2CAAK;IAC9C,iCAAY,MAAgB;eACxB,kBACI,yEAAkE,IAAI,CAAC,SAAS,CAC5E,MAAM,CACT,CAAE,CACN;IACL,CAAC;IACL,8BAAC;AAAD,CAAC,AARD,CAA6C,KAAK,GAQjD;AARY,0DAAuB;AAUpC;IAAmD,iDAAK;IACpD,uCAAY,MAAgB;eACxB,kBACI,gFAAyE,IAAI,CAAC,SAAS,CACnF,MAAM,CACT,CAAE,CACN;IACL,CAAC;IACL,oCAAC;AAAD,CAAC,AARD,CAAmD,KAAK,GAQvD;AARY,sEAA6B","sourcesContent":["export class SelectClauseException extends Error {\n constructor() {\n // todo update message\n super('The SELECT clause does not have the proper structure');\n }\n}\n\nexport class WhereClauseException extends Error {\n constructor() {\n super('The WHERE clause does not have the proper structure');\n }\n}\n\nexport class InWithinOperatorExceptions extends WhereClauseException {\n constructor() {\n super();\n this.message = `The search_expr, target_expr and operator (IN | WITHIN) values are required for collection operators.`;\n }\n}\nexport class MultipleQueryTypesException extends Error {\n constructor(type1: string, type2: string) {\n super(`Cannot combine multiple query types (ex: ${type1} with ${type2}`);\n }\n}\n\nexport class QueryOperatorNotFoundException extends WhereClauseException {\n constructor(operator: string) {\n super();\n this.message = `Operator not found: ${operator}`;\n }\n}\n\nexport class QueryGroupByParamsException extends WhereClauseException {\n constructor() {\n super();\n this.message = `The GROUP BY clause must be defined to use the LETTING and HAVING clauses`;\n }\n}\n\nexport class IndexParamsOnExceptions extends Error {\n constructor(clause: string[]) {\n super(\n `The ON parameter can only be applied in the following clauses: ${JSON.stringify(\n clause\n )}`\n );\n }\n}\n\nexport class IndexParamsUsingGSIExceptions extends Error {\n constructor(clause: string[]) {\n super(\n `The USING GSI parameter can only be applied in the following clauses: ${JSON.stringify(\n clause\n )}`\n );\n }\n}\n"]}
|
|
@@ -29,11 +29,11 @@ var selectBuilder = function (collection, select, letExpr, where, orderBy, limit
|
|
|
29
29
|
expr = (0, exports.buildSelectArrayExpr)(select);
|
|
30
30
|
}
|
|
31
31
|
var _collection = collection.indexOf(' ') !== -1
|
|
32
|
-
?
|
|
32
|
+
? "`".concat(collection).replace(' ', '` ')
|
|
33
33
|
: collection.indexOf('`') !== -1
|
|
34
34
|
? collection
|
|
35
|
-
: "`"
|
|
36
|
-
return "SELECT "
|
|
35
|
+
: "`".concat(collection, "`");
|
|
36
|
+
return "SELECT ".concat(expr, " FROM ").concat(_collection).concat(plainJoinExpr ? " ".concat(plainJoinExpr, " ") : '').concat(_buildUseKeysExpr(useExpr)).concat(_buildLetExpr(letExpr)).concat((0, exports.buildWhereExpr)(where)).concat(_buildGroupByExpr(groupByExpr, lettingExpr, havingExpr)).concat(_buildOrderByExpr(orderBy)).concat(_buildLimitExpr(limit)).concat(_buildOffsetExpr(offset));
|
|
37
37
|
}
|
|
38
38
|
catch (exception) {
|
|
39
39
|
if (exception instanceof exceptions_1.WhereClauseException) {
|
|
@@ -47,16 +47,16 @@ exports.selectBuilder = selectBuilder;
|
|
|
47
47
|
* @ignore
|
|
48
48
|
* */
|
|
49
49
|
var _buildAS = function (c) {
|
|
50
|
-
return c.hasOwnProperty('as') ? " AS "
|
|
50
|
+
return c.hasOwnProperty('as') ? " AS ".concat(c['as']) : '';
|
|
51
51
|
};
|
|
52
52
|
/**
|
|
53
53
|
* @ignore
|
|
54
54
|
* */
|
|
55
55
|
var _buildField = function (clause) {
|
|
56
56
|
if (clause.hasOwnProperty('name')) {
|
|
57
|
-
return ""
|
|
57
|
+
return "".concat((0, utils_1.escapeReservedWords)(clause['name'])).concat(_buildAS(clause));
|
|
58
58
|
}
|
|
59
|
-
return ""
|
|
59
|
+
return "".concat((0, utils_1.escapeReservedWords)(clause));
|
|
60
60
|
};
|
|
61
61
|
/**
|
|
62
62
|
* Create N1QL queries from select array params
|
|
@@ -65,7 +65,7 @@ var _buildField = function (clause) {
|
|
|
65
65
|
* @return N1QL SELECT Query
|
|
66
66
|
* */
|
|
67
67
|
var buildSelectArrayExpr = function (clause) {
|
|
68
|
-
return ""
|
|
68
|
+
return "".concat(clause.map(function (c) { return (0, exports.buildSelectExpr)('', c); }).join(','));
|
|
69
69
|
};
|
|
70
70
|
exports.buildSelectArrayExpr = buildSelectArrayExpr;
|
|
71
71
|
/**
|
|
@@ -82,14 +82,14 @@ var buildSelectExpr = function (n1ql, clause) {
|
|
|
82
82
|
}
|
|
83
83
|
var key = Object.keys(clause)[0];
|
|
84
84
|
if (dictionary_1.ReturnResultDict.hasOwnProperty(key)) {
|
|
85
|
-
return dictionary_1.ReturnResultDict[key]
|
|
85
|
+
return "".concat(dictionary_1.ReturnResultDict[key], " ").concat((0, exports.buildSelectExpr)(n1ql, clause[key]));
|
|
86
86
|
}
|
|
87
87
|
if (dictionary_1.ResultExprDict.hasOwnProperty(key)) {
|
|
88
|
-
return dictionary_1.ResultExprDict[key]
|
|
88
|
+
return "".concat(dictionary_1.ResultExprDict[key], " ").concat((0, exports.buildSelectExpr)(n1ql, clause[key]));
|
|
89
89
|
}
|
|
90
90
|
if (dictionary_1.AggDict.hasOwnProperty(key)) {
|
|
91
91
|
// todo check if have AS expr inside of Agg function.
|
|
92
|
-
return dictionary_1.AggDict[key]
|
|
92
|
+
return "".concat(dictionary_1.AggDict[key], "(").concat(_buildAggDictExpr(clause, key)).concat((0, exports.buildSelectExpr)(n1ql, clause[key]), ")").concat(_buildAS(clause[key]));
|
|
93
93
|
}
|
|
94
94
|
throw new exceptions_1.SelectClauseException();
|
|
95
95
|
}
|
|
@@ -104,7 +104,7 @@ exports.buildSelectExpr = buildSelectExpr;
|
|
|
104
104
|
var _buildAggDictExpr = function (clause, key) {
|
|
105
105
|
if (dictionary_1.AggDict.hasOwnProperty(key)) {
|
|
106
106
|
if (clause[key].hasOwnProperty('ro')) {
|
|
107
|
-
return dictionary_1.ReturnResultDict[clause[key]['ro']]
|
|
107
|
+
return "".concat(dictionary_1.ReturnResultDict[clause[key]['ro']], " ");
|
|
108
108
|
}
|
|
109
109
|
}
|
|
110
110
|
return '';
|
|
@@ -114,9 +114,9 @@ var _buildAggDictExpr = function (clause, key) {
|
|
|
114
114
|
* */
|
|
115
115
|
var _buildLetExpr = function (letExpr, clause) {
|
|
116
116
|
return Array.isArray(letExpr)
|
|
117
|
-
? " "
|
|
118
|
-
.map(function (value) { return (0, utils_1.escapeReservedWords)(value.key)
|
|
119
|
-
.join(',')
|
|
117
|
+
? " ".concat(clause ? clause : 'LET', " ").concat(letExpr
|
|
118
|
+
.map(function (value) { return "".concat((0, utils_1.escapeReservedWords)(value.key), "=").concat(value.value); })
|
|
119
|
+
.join(','))
|
|
120
120
|
: '';
|
|
121
121
|
};
|
|
122
122
|
/**
|
|
@@ -124,28 +124,28 @@ var _buildLetExpr = function (letExpr, clause) {
|
|
|
124
124
|
* */
|
|
125
125
|
var _buildOrderByExpr = function (orderExpr) {
|
|
126
126
|
return !!orderExpr
|
|
127
|
-
? " ORDER BY "
|
|
128
|
-
.map(function (value) { return (0, utils_1.escapeReservedWords)(value)
|
|
129
|
-
.join(',')
|
|
127
|
+
? " ORDER BY ".concat(Object.keys(orderExpr)
|
|
128
|
+
.map(function (value) { return "".concat((0, utils_1.escapeReservedWords)(value), " ").concat(orderExpr[value]); })
|
|
129
|
+
.join(','))
|
|
130
130
|
: '';
|
|
131
131
|
};
|
|
132
132
|
/**
|
|
133
133
|
* @ignore
|
|
134
134
|
* */
|
|
135
135
|
var _buildLimitExpr = function (limit) {
|
|
136
|
-
return Number.isInteger(limit) ? " LIMIT "
|
|
136
|
+
return Number.isInteger(limit) ? " LIMIT ".concat(limit) : '';
|
|
137
137
|
};
|
|
138
138
|
/**
|
|
139
139
|
* @ignore
|
|
140
140
|
* */
|
|
141
141
|
var _buildOffsetExpr = function (offset) {
|
|
142
|
-
return Number.isInteger(offset) ? " OFFSET "
|
|
142
|
+
return Number.isInteger(offset) ? " OFFSET ".concat(offset) : '';
|
|
143
143
|
};
|
|
144
144
|
/**
|
|
145
145
|
* @ignore
|
|
146
146
|
* */
|
|
147
147
|
var _buildUseKeysExpr = function (useKeys) {
|
|
148
|
-
return Array.isArray(useKeys) ? " USE KEYS "
|
|
148
|
+
return Array.isArray(useKeys) ? " USE KEYS ".concat(stringifyValues(useKeys)) : '';
|
|
149
149
|
};
|
|
150
150
|
// end select expression functions
|
|
151
151
|
//group by expression functions
|
|
@@ -160,7 +160,7 @@ var _buildGroupByExpr = function (groupByExpr, lettingExpr, havingExpr) {
|
|
|
160
160
|
if (!groupByExpr) {
|
|
161
161
|
return '';
|
|
162
162
|
}
|
|
163
|
-
return " "
|
|
163
|
+
return " ".concat(_buildGroupBy(groupByExpr)).concat(_buildLetExpr(lettingExpr, 'LETTING')).concat((0, exports.buildWhereExpr)(havingExpr, 'HAVING'));
|
|
164
164
|
}
|
|
165
165
|
catch (_a) {
|
|
166
166
|
throw new exceptions_1.QueryGroupByParamsException();
|
|
@@ -170,11 +170,11 @@ var _buildGroupByExpr = function (groupByExpr, lettingExpr, havingExpr) {
|
|
|
170
170
|
*@ignore
|
|
171
171
|
*/
|
|
172
172
|
var _buildGroupBy = function (groupByExpr) {
|
|
173
|
-
return "GROUP BY "
|
|
173
|
+
return "GROUP BY ".concat(groupByExpr
|
|
174
174
|
.map(function (value) {
|
|
175
|
-
return ""
|
|
175
|
+
return "".concat((0, utils_1.escapeReservedWords)(value.expr)).concat(value.as ? " AS ".concat(value.as) : '');
|
|
176
176
|
})
|
|
177
|
-
.join(',');
|
|
177
|
+
.join(','));
|
|
178
178
|
};
|
|
179
179
|
//end group by expression functions
|
|
180
180
|
// where expression functions
|
|
@@ -185,7 +185,7 @@ var _buildGroupBy = function (groupByExpr) {
|
|
|
185
185
|
* @return N1QL WHERE Expression
|
|
186
186
|
* */
|
|
187
187
|
var buildWhereExpr = function (expr, clause) {
|
|
188
|
-
return expr ? " "
|
|
188
|
+
return expr ? " ".concat(clause ? clause : 'WHERE', " ").concat((0, exports.buildWhereClauseExpr)('', expr)) : '';
|
|
189
189
|
};
|
|
190
190
|
exports.buildWhereExpr = buildWhereExpr;
|
|
191
191
|
/**
|
|
@@ -219,20 +219,20 @@ var buildWhereClauseExpr = function (n1ql, clause) {
|
|
|
219
219
|
.map(function (key) {
|
|
220
220
|
var _a;
|
|
221
221
|
if (dictionary_1.CollectionSelectOperatorDict[key]) {
|
|
222
|
-
return ""
|
|
222
|
+
return "".concat(_buildWhereCollectionExpr(key, clause[key]));
|
|
223
223
|
}
|
|
224
224
|
if (dictionary_1.CollectionInWithinOperatorDict[key]) {
|
|
225
|
-
return ""
|
|
225
|
+
return "".concat(_buildCollectionInWithinOperator(key, clause[key]));
|
|
226
226
|
}
|
|
227
227
|
if (Array.isArray(clause[key])) {
|
|
228
|
-
var prefix = key === '$not' ? dictionary_1.LogicalOperatorDict[key]
|
|
229
|
-
var joinOp = key === '$not' ? " AND " : " "
|
|
230
|
-
return prefix
|
|
228
|
+
var prefix = key === '$not' ? "".concat(dictionary_1.LogicalOperatorDict[key], " ") : '';
|
|
229
|
+
var joinOp = key === '$not' ? " AND " : " ".concat(dictionary_1.LogicalOperatorDict[key], " ");
|
|
230
|
+
return "".concat(prefix, "(").concat(clause[key]
|
|
231
231
|
.map(function (value) { return (0, exports.buildWhereClauseExpr)(n1ql, value); })
|
|
232
|
-
.join(joinOp)
|
|
232
|
+
.join(joinOp), ")");
|
|
233
233
|
}
|
|
234
234
|
else {
|
|
235
|
-
return ""
|
|
235
|
+
return "".concat((0, exports.buildWhereClauseExpr)(n1ql, (_a = {}, _a[key] = clause[key], _a)));
|
|
236
236
|
}
|
|
237
237
|
})
|
|
238
238
|
.join(' AND ');
|
|
@@ -252,16 +252,16 @@ var _buildFieldClauseExpr = function (field) {
|
|
|
252
252
|
try {
|
|
253
253
|
var expr = Object.keys(field).map(function (value) {
|
|
254
254
|
if (typeof field[value] === 'object' && !Array.isArray(field[value])) {
|
|
255
|
-
return ""
|
|
255
|
+
return "".concat(_buildComparisionClauseExpr(value, field[value]));
|
|
256
256
|
}
|
|
257
257
|
if (!value.includes('$')) {
|
|
258
258
|
if (typeof field[value] === 'string') {
|
|
259
|
-
return (0, utils_1.escapeReservedWords)(value)
|
|
259
|
+
return "".concat((0, utils_1.escapeReservedWords)(value), "=").concat(stringifyValues(field[value]));
|
|
260
260
|
}
|
|
261
261
|
if (typeof field[value] === 'number' ||
|
|
262
262
|
typeof field[value] === 'boolean' ||
|
|
263
263
|
Array.isArray(field[value])) {
|
|
264
|
-
return (0, utils_1.escapeReservedWords)(value)
|
|
264
|
+
return "".concat((0, utils_1.escapeReservedWords)(value), "=").concat(stringifyValues(field[value]));
|
|
265
265
|
}
|
|
266
266
|
}
|
|
267
267
|
throw new exceptions_1.QueryOperatorNotFoundException(value);
|
|
@@ -284,23 +284,23 @@ var _buildComparisionClauseExpr = function (fieldName, comparison) {
|
|
|
284
284
|
.map(function (value) {
|
|
285
285
|
if (!!comparison[value]) {
|
|
286
286
|
if (dictionary_1.ComparisonEmptyOperatorDict.hasOwnProperty(value)) {
|
|
287
|
-
return (0, utils_1.escapeReservedWords)(fieldName)
|
|
287
|
+
return "".concat((0, utils_1.escapeReservedWords)(fieldName), " ").concat(dictionary_1.ComparisonEmptyOperatorDict[value]);
|
|
288
288
|
}
|
|
289
289
|
if (dictionary_1.ComparisonSingleOperatorDict.hasOwnProperty(value)) {
|
|
290
|
-
return ""
|
|
290
|
+
return "".concat((0, utils_1.escapeReservedWords)(fieldName)).concat(dictionary_1.ComparisonSingleOperatorDict[value]).concat(stringifyValues(comparison[value]));
|
|
291
291
|
}
|
|
292
292
|
if (dictionary_1.ComparisonSingleStringOperatorDict.hasOwnProperty(value)) {
|
|
293
|
-
return (0, utils_1.escapeReservedWords)(fieldName)
|
|
293
|
+
return "".concat((0, utils_1.escapeReservedWords)(fieldName), " ").concat(dictionary_1.ComparisonSingleStringOperatorDict[value], " ").concat(stringifyValues(comparison[value]));
|
|
294
294
|
}
|
|
295
295
|
if (dictionary_1.ComparisonMultipleOperatorDict.hasOwnProperty(value) &&
|
|
296
296
|
Array.isArray(comparison[value])) {
|
|
297
|
-
return (0, utils_1.escapeReservedWords)(fieldName)
|
|
297
|
+
return "".concat((0, utils_1.escapeReservedWords)(fieldName), " ").concat(dictionary_1.ComparisonMultipleOperatorDict[value], " ").concat(comparison[value].map(function (v) { return stringifyValues(v); }).join(' AND '));
|
|
298
298
|
}
|
|
299
299
|
}
|
|
300
300
|
throw new exceptions_1.QueryOperatorNotFoundException(value);
|
|
301
301
|
})
|
|
302
302
|
.join(" AND ");
|
|
303
|
-
return Object.keys(comparison).length > 1 ? "("
|
|
303
|
+
return Object.keys(comparison).length > 1 ? "(".concat(expr, ")") : expr;
|
|
304
304
|
}
|
|
305
305
|
catch (exception) {
|
|
306
306
|
if (exception instanceof exceptions_1.WhereClauseException) {
|
|
@@ -316,7 +316,7 @@ var _buildCollectionInWithinOperator = function (op, expr, excludeOperator) {
|
|
|
316
316
|
if (!op || !expr.target_expr || !expr.search_expr) {
|
|
317
317
|
throw new exceptions_1.InWithinOperatorExceptions();
|
|
318
318
|
}
|
|
319
|
-
return ""
|
|
319
|
+
return "".concat(expr.search_expr).concat(!excludeOperator && expr.$not ? ' NOT ' : ' ').concat(dictionary_1.CollectionInWithinOperatorDict[op], " ").concat(excludeOperator ? expr.target_expr : stringifyValues(expr.target_expr));
|
|
320
320
|
};
|
|
321
321
|
var stringifyValues = function (value) {
|
|
322
322
|
return JSON.stringify(value).replace(/\\/gi, '');
|
|
@@ -329,15 +329,15 @@ var _buildCollectionInWithIn = function (collection) {
|
|
|
329
329
|
if (!op) {
|
|
330
330
|
throw new Error('The Collection Operator needs to have the following clauses declared (IN | WITHIN) and SATISFIES.');
|
|
331
331
|
}
|
|
332
|
-
return ""
|
|
332
|
+
return "".concat(_buildCollectionInWithinOperator(op, collection[op], true));
|
|
333
333
|
};
|
|
334
334
|
/**
|
|
335
335
|
* @ignore
|
|
336
336
|
* */
|
|
337
337
|
var _buildWhereCollectionExpr = function (op, expr) {
|
|
338
|
-
return dictionary_1.CollectionSelectOperatorDict[op]
|
|
338
|
+
return "".concat(dictionary_1.CollectionSelectOperatorDict[op], " ").concat(expr.$expr
|
|
339
339
|
.map(function (value) { return _buildCollectionInWithIn(value); })
|
|
340
|
-
.join(',')
|
|
340
|
+
.join(','), " ").concat(dictionary_1.CollectionSatisfiesOperatorDict['$satisfies'], " ").concat((0, exports.buildWhereClauseExpr)('', expr.$satisfied), " END");
|
|
341
341
|
};
|
|
342
342
|
// end where expression functions
|
|
343
343
|
// index expression functions
|
|
@@ -355,10 +355,10 @@ var _buildWhereCollectionExpr = function (op, expr) {
|
|
|
355
355
|
* */
|
|
356
356
|
var buildIndexExpr = function (collection, type, name, on, where, usingGSI, withExpr) {
|
|
357
357
|
if (['BUILD', 'CREATE', 'CREATE PRIMARY'].includes(type) && on) {
|
|
358
|
-
return type
|
|
358
|
+
return "".concat(type, " INDEX `").concat(name, "` ON `").concat(collection, "`(").concat(buildOnExpr(on), ")").concat((0, exports.buildWhereExpr)(where), " ").concat(usingGSI ? 'USING GSI' : '', " ").concat(buildWithExpr(withExpr));
|
|
359
359
|
}
|
|
360
360
|
else {
|
|
361
|
-
return type
|
|
361
|
+
return "".concat(type, " INDEX `").concat(collection, "`.`").concat(name, "`").concat(usingGSI ? ' USING GSI' : '');
|
|
362
362
|
}
|
|
363
363
|
};
|
|
364
364
|
exports.buildIndexExpr = buildIndexExpr;
|
|
@@ -368,7 +368,7 @@ exports.buildIndexExpr = buildIndexExpr;
|
|
|
368
368
|
var buildOnExpr = function (on) {
|
|
369
369
|
return on
|
|
370
370
|
.map(function (value) {
|
|
371
|
-
return ""
|
|
371
|
+
return "".concat((0, utils_1.escapeReservedWords)(value.name)).concat(buildOnSortExpr(value));
|
|
372
372
|
})
|
|
373
373
|
.join(',');
|
|
374
374
|
};
|
|
@@ -377,7 +377,7 @@ var buildOnExpr = function (on) {
|
|
|
377
377
|
* */
|
|
378
378
|
var buildOnSortExpr = function (onExpr) {
|
|
379
379
|
if (onExpr && onExpr.hasOwnProperty('sort')) {
|
|
380
|
-
return "[\""
|
|
380
|
+
return "[\"".concat(onExpr.sort, "\"]");
|
|
381
381
|
}
|
|
382
382
|
return '';
|
|
383
383
|
};
|
|
@@ -393,13 +393,13 @@ var buildWithExpr = function (withExpr) {
|
|
|
393
393
|
return buildWithNodesExpr(withExpr[value]);
|
|
394
394
|
case 'defer_build':
|
|
395
395
|
case 'num_replica':
|
|
396
|
-
return "\""
|
|
396
|
+
return "\"".concat(value, "\": ").concat(withExpr[value]);
|
|
397
397
|
default:
|
|
398
398
|
throw new Error('The WITH clause has an incorrect syntax');
|
|
399
399
|
}
|
|
400
400
|
})
|
|
401
401
|
.join(',');
|
|
402
|
-
return !!resultExpr ? "WITH {"
|
|
402
|
+
return !!resultExpr ? "WITH {".concat(resultExpr, "}") : '';
|
|
403
403
|
}
|
|
404
404
|
return '';
|
|
405
405
|
};
|
|
@@ -408,7 +408,7 @@ var buildWithExpr = function (withExpr) {
|
|
|
408
408
|
* */
|
|
409
409
|
var buildWithNodesExpr = function (withNodesExpr) {
|
|
410
410
|
if (withNodesExpr) {
|
|
411
|
-
return "\"nodes\": "
|
|
411
|
+
return "\"nodes\": ".concat(stringifyValues(withNodesExpr));
|
|
412
412
|
}
|
|
413
413
|
};
|
|
414
414
|
// end index expression functions
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builders.js","sourceRoot":"","sources":["../../../src/query/helpers/builders.ts"],"names":[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ClE;QACL,CAAC,CAAC;aACD,IAAI,CAAC,GAAG,CAAC,CAAC;QACf,OAAO,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,WAAS,UAAU,MAAG,CAAC,CAAC,CAAC,EAAE,CAAC;KACrD;IACD,OAAO,EAAE,CAAC;AACd,CAAC,CAAC;AAEF;;KAEK;AACL,IAAM,kBAAkB,GAAG,UAAC,aAAwB;IAChD,IAAI,aAAa,EAAE;QACf,OAAO,gBAAY,eAAe,CAAC,aAAa,CAAG,CAAC;KACvD;AACL,CAAC,CAAC;AAEF,iCAAiC","sourcesContent":["import {\n CollectionExpressionType,\n CollectionInWithinOperator,\n CollectionInWithinOperatorType,\n CollectionInWithinOperatorValue,\n CollectionSelectOperator,\n ComparisonWhereExpr,\n IField,\n IGroupBy,\n IIndexOnParams,\n IIndexWithParams,\n ILetExpr,\n IndexType,\n ISelectAggType,\n ISelectType,\n LogicalWhereExpr,\n SortType,\n} from '../interface/query.types';\nimport {\n InWithinOperatorExceptions,\n QueryGroupByParamsException,\n QueryOperatorNotFoundException,\n SelectClauseException,\n WhereClauseException,\n} from '../exceptions';\nimport {escapeReservedWords} from '../utils';\n\nimport {\n AggDict,\n CollectionInWithinOperatorDict,\n CollectionSatisfiesOperatorDict,\n CollectionSelectOperatorDict,\n ComparisonEmptyOperatorDict,\n ComparisonMultipleOperatorDict,\n ComparisonSingleOperatorDict,\n ComparisonSingleStringOperatorDict,\n LogicalOperatorDict,\n ResultExprDict,\n ReturnResultDict,\n} from './dictionary';\n\n// select expressions functions\n/**\n * Build a SELECT N1QL query from user-specified parameters.\n * {@link https://docs.couchbase.com/server/6.5/n1ql/n1ql-language-reference/select-syntax.html}\n * @param collection Collection name\n * @param select SELECT Clause param\n * @param letExpr LET Clause param\n * @param where WHERE Clause param\n * @param orderBy ORDER BY Clause param\n * @param limit LIMIT Clause param\n * @param offset OFFSET Clause param\n * @param useExpr USE Clause param\n *\n * @return N1QL SELECT Query\n * */\nexport const selectBuilder = (\n collection: string,\n select: ISelectType[] | string,\n letExpr?: ILetExpr[],\n where?: LogicalWhereExpr,\n orderBy?: Record<string, SortType>,\n limit?: number,\n offset?: number,\n useExpr?: string[],\n groupByExpr?: IGroupBy[],\n lettingExpr?: ILetExpr[],\n havingExpr?: LogicalWhereExpr,\n plainJoinExpr?: string\n): string => {\n try {\n let expr = '';\n if (typeof select === 'string') {\n expr = select;\n }\n if (Array.isArray(select)) {\n expr = buildSelectArrayExpr(select);\n }\n const _collection =\n collection.indexOf(' ') !== -1\n ? `\\`${collection}`.replace(' ', '` ')\n : collection.indexOf('`') !== -1\n ? collection\n : `\\`${collection}\\``;\n return `SELECT ${expr} FROM ${_collection}${\n plainJoinExpr ? ` ${plainJoinExpr} ` : ''\n }${_buildUseKeysExpr(useExpr)}${_buildLetExpr(letExpr)}${buildWhereExpr(\n where\n )}${_buildGroupByExpr(groupByExpr, lettingExpr, havingExpr)}${_buildOrderByExpr(\n orderBy\n )}${_buildLimitExpr(limit)}${_buildOffsetExpr(offset)}`;\n } catch (exception) {\n if (exception instanceof WhereClauseException) {\n throw exception;\n }\n throw new SelectClauseException();\n }\n};\n\n/**\n * @ignore\n * */\nconst _buildAS = (c: ISelectAggType | IField) => {\n return c.hasOwnProperty('as') ? ` AS ${c['as']}` : '';\n};\n\n/**\n * @ignore\n * */\nconst _buildField = (clause: IField | string) => {\n if (clause.hasOwnProperty('name')) {\n return `${escapeReservedWords(clause['name'])}${_buildAS(clause as IField)}`;\n }\n return `${escapeReservedWords(clause as string)}`;\n};\n\n/**\n * Create N1QL queries from select array params\n * @param clause SELECT Clause param\n *\n * @return N1QL SELECT Query\n * */\nexport const buildSelectArrayExpr = (clause: ISelectType[]): string => {\n return `${clause.map((c) => buildSelectExpr('', c)).join(',')}`;\n};\n\n/**\n * Recursive function to create N1QL queries.\n * @param n1ql N1QL Query String\n * @param clause SELECT Clause param\n *\n * @return N1QL SELECT Query\n * */\nexport const buildSelectExpr = (n1ql: string, clause: ISelectType): string => {\n try {\n if (clause.hasOwnProperty('$field')) {\n return _buildField(clause['$field']);\n }\n const key = Object.keys(clause)[0];\n if (ReturnResultDict.hasOwnProperty(key)) {\n return `${ReturnResultDict[key]} ${buildSelectExpr(n1ql, clause[key])}`;\n }\n if (ResultExprDict.hasOwnProperty(key)) {\n return `${ResultExprDict[key]} ${buildSelectExpr(n1ql, clause[key])}`;\n }\n if (AggDict.hasOwnProperty(key)) {\n // todo check if have AS expr inside of Agg function.\n return `${AggDict[key]}(${_buildAggDictExpr(\n clause as ISelectAggType,\n key\n )}${buildSelectExpr(n1ql, clause[key])})${_buildAS(clause[key])}`;\n }\n throw new SelectClauseException();\n } catch {\n throw new SelectClauseException();\n }\n};\n\n/**\n * @ignore\n * */\nconst _buildAggDictExpr = (clause: ISelectAggType, key: string) => {\n if (AggDict.hasOwnProperty(key)) {\n if (clause[key].hasOwnProperty('ro')) {\n return `${ReturnResultDict[clause[key]['ro']]} `;\n }\n }\n return '';\n};\n\n/**\n * @ignore\n * */\nconst _buildLetExpr = (letExpr: ILetExpr[] | undefined, clause?: string) => {\n return Array.isArray(letExpr)\n ? ` ${clause ? clause : 'LET'} ${letExpr\n .map((value: ILetExpr) => `${escapeReservedWords(value.key)}=${value.value}`)\n .join(',')}`\n : '';\n};\n\n/**\n * @ignore\n * */\nconst _buildOrderByExpr = (orderExpr: Record<string, SortType> | undefined) => {\n return !!orderExpr\n ? ` ORDER BY ${Object.keys(orderExpr)\n .map((value: string) => `${escapeReservedWords(value)} ${orderExpr[value]}`)\n .join(',')}`\n : '';\n};\n\n/**\n * @ignore\n * */\nconst _buildLimitExpr = (limit: number | undefined) => {\n return Number.isInteger(limit) ? ` LIMIT ${limit}` : '';\n};\n\n/**\n * @ignore\n * */\nconst _buildOffsetExpr = (offset: number | undefined) => {\n return Number.isInteger(offset) ? ` OFFSET ${offset}` : '';\n};\n\n/**\n * @ignore\n * */\nconst _buildUseKeysExpr = (useKeys: string[] | undefined) => {\n return Array.isArray(useKeys) ? ` USE KEYS ${stringifyValues(useKeys)}` : '';\n};\n\n// end select expression functions\n\n//group by expression functions\n/**\n *@ignore\n */\nconst _buildGroupByExpr = (\n groupByExpr?: IGroupBy[],\n lettingExpr?: ILetExpr[],\n havingExpr?: LogicalWhereExpr\n) => {\n try {\n if ((lettingExpr || havingExpr) && !groupByExpr) {\n throw new QueryGroupByParamsException();\n }\n if (!groupByExpr) {\n return '';\n }\n return ` ${_buildGroupBy(groupByExpr)}${_buildLetExpr(\n lettingExpr,\n 'LETTING'\n )}${buildWhereExpr(havingExpr as LogicalWhereExpr, 'HAVING')}`;\n } catch {\n throw new QueryGroupByParamsException();\n }\n};\n\n/**\n *@ignore\n */\nconst _buildGroupBy = (groupByExpr: IGroupBy[]) => {\n return `GROUP BY ${groupByExpr\n .map((value: IGroupBy) => {\n return `${escapeReservedWords(value.expr)}${value.as ? ` AS ${value.as}` : ''}`;\n })\n .join(',')}`;\n};\n\n//end group by expression functions\n\n// where expression functions\n\n/**\n * Create WHERE N1QL Expressions.\n * {@link https://docs.couchbase.com/server/6.5/n1ql/n1ql-language-reference/where.html}\n * @param clause WHERE Clause param\n * @return N1QL WHERE Expression\n * */\nexport const buildWhereExpr = (expr: LogicalWhereExpr | undefined, clause?: string): string => {\n return expr ? ` ${clause ? clause : 'WHERE'} ${buildWhereClauseExpr('', expr)}` : '';\n};\n\n/**\n * @ignore\n *\n **/\nexport const verifyWhereObjectKey = (clause: LogicalWhereExpr) => {\n let exist = false;\n for (const key in clause) {\n if (['$and', '$or', '$not', '$any', '$$every', '$in', '$within'].includes(key)) {\n exist = true;\n break;\n }\n }\n return exist;\n};\n\n/**\n * Recursive function to create WHERE N1QL Expressions.\n * @param n1ql N1QL Query String\n * @param clause WHERE Clause param\n *\n * @return N1QL WHERE Expression\n * */\nexport const buildWhereClauseExpr = (n1ql: string, clause: LogicalWhereExpr): string => {\n try {\n if (!verifyWhereObjectKey(clause)) {\n return _buildFieldClauseExpr(\n clause as Record<string, string | number | boolean | ComparisonWhereExpr>\n );\n }\n\n return Object.keys(clause)\n .map((key) => {\n if (CollectionSelectOperatorDict[key]) {\n return `${_buildWhereCollectionExpr(\n key as CollectionSelectOperator,\n clause[key]\n )}`;\n }\n if (CollectionInWithinOperatorDict[key]) {\n return `${_buildCollectionInWithinOperator(\n key as CollectionInWithinOperator,\n clause[key]\n )}`;\n }\n if (Array.isArray(clause[key])) {\n const prefix = key === '$not' ? `${LogicalOperatorDict[key]} ` : '';\n const joinOp = key === '$not' ? ` AND ` : ` ${LogicalOperatorDict[key]} `;\n return `${prefix}(${clause[key]\n .map((value) => buildWhereClauseExpr(n1ql, value as LogicalWhereExpr))\n .join(joinOp)})`;\n } else {\n return `${buildWhereClauseExpr(n1ql, {[key]: clause[key]})}`;\n }\n })\n .join(' AND ');\n } catch (exception) {\n if (exception instanceof WhereClauseException) {\n throw exception;\n }\n throw new WhereClauseException();\n }\n};\n\n/**\n * @ignore\n * */\nconst _buildFieldClauseExpr = (\n field: Record<string, string | number | boolean | ComparisonWhereExpr>\n) => {\n try {\n const expr = Object.keys(field).map((value: string) => {\n if (typeof field[value] === 'object' && !Array.isArray(field[value])) {\n return `${_buildComparisionClauseExpr(value, field[value] as ComparisonWhereExpr)}`;\n }\n if (!value.includes('$')) {\n if (typeof field[value] === 'string') {\n return `${escapeReservedWords(value)}=${stringifyValues(field[value])}`;\n }\n if (\n typeof field[value] === 'number' ||\n typeof field[value] === 'boolean' ||\n Array.isArray(field[value])\n ) {\n return `${escapeReservedWords(value)}=${stringifyValues(field[value])}`;\n }\n }\n throw new QueryOperatorNotFoundException(value);\n });\n return expr.join(' AND ');\n } catch (exception) {\n if (exception instanceof WhereClauseException) {\n throw exception;\n }\n throw new WhereClauseException();\n }\n};\n\n/**\n * @ignore\n * */\nconst _buildComparisionClauseExpr = (fieldName: string, comparison: ComparisonWhereExpr) => {\n try {\n const expr = Object.keys(comparison)\n .map((value: string) => {\n if (!!comparison[value]) {\n if (ComparisonEmptyOperatorDict.hasOwnProperty(value)) {\n return `${escapeReservedWords(fieldName)} ${\n ComparisonEmptyOperatorDict[value]\n }`;\n }\n if (ComparisonSingleOperatorDict.hasOwnProperty(value)) {\n return `${escapeReservedWords(fieldName)}${\n ComparisonSingleOperatorDict[value]\n }${stringifyValues(comparison[value])}`;\n }\n if (ComparisonSingleStringOperatorDict.hasOwnProperty(value)) {\n return `${escapeReservedWords(fieldName)} ${\n ComparisonSingleStringOperatorDict[value]\n } ${stringifyValues(comparison[value])}`;\n }\n if (\n ComparisonMultipleOperatorDict.hasOwnProperty(value) &&\n Array.isArray(comparison[value])\n ) {\n return `${escapeReservedWords(fieldName)} ${\n ComparisonMultipleOperatorDict[value]\n } ${comparison[value].map((v) => stringifyValues(v)).join(' AND ')}`;\n }\n }\n throw new QueryOperatorNotFoundException(value);\n })\n .join(` AND `);\n return Object.keys(comparison).length > 1 ? `(${expr})` : expr;\n } catch (exception) {\n if (exception instanceof WhereClauseException) {\n throw exception;\n }\n throw new WhereClauseException();\n }\n};\n\n/**\n * @ignore\n * */\nconst _buildCollectionInWithinOperator = (\n op: CollectionInWithinOperator,\n expr: CollectionInWithinOperatorValue,\n excludeOperator?: boolean\n): string => {\n if (!op || !expr.target_expr || !expr.search_expr) {\n throw new InWithinOperatorExceptions();\n }\n return `${expr.search_expr}${!excludeOperator && expr.$not ? ' NOT ' : ' '}${\n CollectionInWithinOperatorDict[op]\n } ${excludeOperator ? expr.target_expr : stringifyValues(expr.target_expr)}`;\n};\n\nconst stringifyValues = (value: unknown) => {\n return JSON.stringify(value).replace(/\\\\/gi, '');\n};\n\n/**\n * @ignore\n * */\nconst _buildCollectionInWithIn = (collection: CollectionInWithinOperatorType) => {\n const op = collection.$in ? '$in' : collection.$within ? '$within' : undefined;\n if (!op) {\n throw new Error(\n 'The Collection Operator needs to have the following clauses declared (IN | WITHIN) and SATISFIES.'\n );\n }\n return `${_buildCollectionInWithinOperator(\n op,\n collection[op] as CollectionInWithinOperatorValue,\n true\n )}`;\n};\n\n/**\n * @ignore\n * */\nconst _buildWhereCollectionExpr = (\n op: CollectionSelectOperator,\n expr: CollectionExpressionType\n) => {\n return `${CollectionSelectOperatorDict[op]} ${expr.$expr\n .map((value) => _buildCollectionInWithIn(value))\n .join(',')} ${CollectionSatisfiesOperatorDict['$satisfies']} ${buildWhereClauseExpr(\n '',\n expr.$satisfied\n )} END`;\n};\n\n// end where expression functions\n\n// index expression functions\n\n/**\n * Build a INDEX N1QL query from user-specified parameters.\n * {@link https://docs.couchbase.com/server/6.5/n1ql/n1ql-language-reference/createindex.html}\n * @param collection Collection name\n * @param type INDEX clause types can be 'CREATE' | 'BUILD' | 'DROP' | 'CREATE PRIMARY'\n * @param on ON Clause param\n * @param where WHERE Clause param\n * @param usingGSI use a Global Secondary Index(GSI).\n * @param withExpr WITH Clause param\n *\n * @return N1QL INDEX Query\n * */\nexport const buildIndexExpr = (\n collection: string,\n type: IndexType,\n name: string,\n on?: IIndexOnParams[],\n where?: LogicalWhereExpr,\n usingGSI?: boolean,\n withExpr?: IIndexWithParams\n): string => {\n if (['BUILD', 'CREATE', 'CREATE PRIMARY'].includes(type) && on) {\n return `${type} INDEX \\`${name}\\` ON \\`${collection}\\`(${buildOnExpr(on)})${buildWhereExpr(\n where\n )} ${usingGSI ? 'USING GSI' : ''} ${buildWithExpr(withExpr)}`;\n } else {\n return `${type} INDEX \\`${collection}\\`.\\`${name}\\`${usingGSI ? ' USING GSI' : ''}`;\n }\n};\n\n/**\n * @ignore\n * */\nconst buildOnExpr = (on: IIndexOnParams[]) => {\n return on\n .map((value: IIndexOnParams) => {\n return `${escapeReservedWords(value.name)}${buildOnSortExpr(value)}`;\n })\n .join(',');\n};\n\n/**\n * @ignore\n * */\nconst buildOnSortExpr = (onExpr?: IIndexOnParams) => {\n if (onExpr && onExpr.hasOwnProperty('sort')) {\n return `[\"${onExpr.sort}\"]`;\n }\n return '';\n};\n\n/**\n * @ignore\n * */\nconst buildWithExpr = (withExpr?: IIndexWithParams) => {\n if (withExpr) {\n const resultExpr = Object.keys(withExpr)\n .map((value: string) => {\n switch (value) {\n case 'nodes':\n return buildWithNodesExpr(withExpr[value]);\n case 'defer_build':\n case 'num_replica':\n return `\"${value}\": ${withExpr[value]}`;\n default:\n throw new Error('The WITH clause has an incorrect syntax');\n }\n })\n .join(',');\n return !!resultExpr ? `WITH {${resultExpr}}` : '';\n }\n return '';\n};\n\n/**\n * @ignore\n * */\nconst buildWithNodesExpr = (withNodesExpr?: string[]) => {\n if (withNodesExpr) {\n return `\"nodes\": ${stringifyValues(withNodesExpr)}`;\n }\n};\n\n// end index expression functions\n"]}
|
|
1
|
+
{"version":3,"file":"builders.js","sourceRoot":"","sources":["../../../src/query/helpers/builders.ts"],"names":[],"mappings":";;;AAkBA,4CAMuB;AACvB,kCAA6C;AAE7C,2CAYsB;AAEtB,+BAA+B;AAC/B;;;;;;;;;;;;;KAaK;AACE,IAAM,aAAa,GAAG,UACzB,UAAkB,EAClB,MAA8B,EAC9B,OAAoB,EACpB,KAAwB,EACxB,OAAkC,EAClC,KAAc,EACd,MAAe,EACf,OAAkB,EAClB,WAAwB,EACxB,WAAwB,EACxB,UAA6B,EAC7B,aAAsB;IAEtB,IAAI;QACA,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;YAC5B,IAAI,GAAG,MAAM,CAAC;SACjB;QACD,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;YACvB,IAAI,GAAG,IAAA,4BAAoB,EAAC,MAAM,CAAC,CAAC;SACvC;QACD,IAAM,WAAW,GACb,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YAC1B,CAAC,CAAC,WAAK,UAAU,CAAE,CAAC,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC;YACtC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;gBAChC,CAAC,CAAC,UAAU;gBACZ,CAAC,CAAC,WAA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;IACzE,CAAC,CAAC;SACD,IAAI,CAAC,GAAG,CAAC,CAAC;AACnB,CAAC,CAAC;AAEF;;KAEK;AACL,IAAM,eAAe,GAAG,UAAC,MAAuB;IAC5C,IAAI,MAAM,IAAI,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE;QACzC,OAAO,aAAK,MAAM,CAAC,IAAI,QAAI,CAAC;KAC/B;IACD,OAAO,EAAE,CAAC;AACd,CAAC,CAAC;AAEF;;KAEK;AACL,IAAM,aAAa,GAAG,UAAC,QAA2B;IAC9C,IAAI,QAAQ,EAAE;QACV,IAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;aACnC,GAAG,CAAC,UAAC,KAAa;YACf,QAAQ,KAAK,EAAE;gBACX,KAAK,OAAO;oBACR,OAAO,kBAAkB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;gBAC/C,KAAK,aAAa,CAAC;gBACnB,KAAK,aAAa;oBACd,OAAO,YAAI,KAAK,iBAAM,QAAQ,CAAC,KAAK,CAAC,CAAE,CAAC;gBAC5C;oBACI,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;aAClE;QACL,CAAC,CAAC;aACD,IAAI,CAAC,GAAG,CAAC,CAAC;QACf,OAAO,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,gBAAS,UAAU,MAAG,CAAC,CAAC,CAAC,EAAE,CAAC;KACrD;IACD,OAAO,EAAE,CAAC;AACd,CAAC,CAAC;AAEF;;KAEK;AACL,IAAM,kBAAkB,GAAG,UAAC,aAAwB;IAChD,IAAI,aAAa,EAAE;QACf,OAAO,qBAAY,eAAe,CAAC,aAAa,CAAC,CAAE,CAAC;KACvD;AACL,CAAC,CAAC;AAEF,iCAAiC","sourcesContent":["import {\n CollectionExpressionType,\n CollectionInWithinOperator,\n CollectionInWithinOperatorType,\n CollectionInWithinOperatorValue,\n CollectionSelectOperator,\n ComparisonWhereExpr,\n IField,\n IGroupBy,\n IIndexOnParams,\n IIndexWithParams,\n ILetExpr,\n IndexType,\n ISelectAggType,\n ISelectType,\n LogicalWhereExpr,\n SortType,\n} from '../interface/query.types';\nimport {\n InWithinOperatorExceptions,\n QueryGroupByParamsException,\n QueryOperatorNotFoundException,\n SelectClauseException,\n WhereClauseException,\n} from '../exceptions';\nimport {escapeReservedWords} from '../utils';\n\nimport {\n AggDict,\n CollectionInWithinOperatorDict,\n CollectionSatisfiesOperatorDict,\n CollectionSelectOperatorDict,\n ComparisonEmptyOperatorDict,\n ComparisonMultipleOperatorDict,\n ComparisonSingleOperatorDict,\n ComparisonSingleStringOperatorDict,\n LogicalOperatorDict,\n ResultExprDict,\n ReturnResultDict,\n} from './dictionary';\n\n// select expressions functions\n/**\n * Build a SELECT N1QL query from user-specified parameters.\n * {@link https://docs.couchbase.com/server/6.5/n1ql/n1ql-language-reference/select-syntax.html}\n * @param collection Collection name\n * @param select SELECT Clause param\n * @param letExpr LET Clause param\n * @param where WHERE Clause param\n * @param orderBy ORDER BY Clause param\n * @param limit LIMIT Clause param\n * @param offset OFFSET Clause param\n * @param useExpr USE Clause param\n *\n * @return N1QL SELECT Query\n * */\nexport const selectBuilder = (\n collection: string,\n select: ISelectType[] | string,\n letExpr?: ILetExpr[],\n where?: LogicalWhereExpr,\n orderBy?: Record<string, SortType>,\n limit?: number,\n offset?: number,\n useExpr?: string[],\n groupByExpr?: IGroupBy[],\n lettingExpr?: ILetExpr[],\n havingExpr?: LogicalWhereExpr,\n plainJoinExpr?: string\n): string => {\n try {\n let expr = '';\n if (typeof select === 'string') {\n expr = select;\n }\n if (Array.isArray(select)) {\n expr = buildSelectArrayExpr(select);\n }\n const _collection =\n collection.indexOf(' ') !== -1\n ? `\\`${collection}`.replace(' ', '` ')\n : collection.indexOf('`') !== -1\n ? collection\n : `\\`${collection}\\``;\n return `SELECT ${expr} FROM ${_collection}${\n plainJoinExpr ? ` ${plainJoinExpr} ` : ''\n }${_buildUseKeysExpr(useExpr)}${_buildLetExpr(letExpr)}${buildWhereExpr(\n where\n )}${_buildGroupByExpr(groupByExpr, lettingExpr, havingExpr)}${_buildOrderByExpr(\n orderBy\n )}${_buildLimitExpr(limit)}${_buildOffsetExpr(offset)}`;\n } catch (exception) {\n if (exception instanceof WhereClauseException) {\n throw exception;\n }\n throw new SelectClauseException();\n }\n};\n\n/**\n * @ignore\n * */\nconst _buildAS = (c: ISelectAggType | IField) => {\n return c.hasOwnProperty('as') ? ` AS ${c['as']}` : '';\n};\n\n/**\n * @ignore\n * */\nconst _buildField = (clause: IField | string) => {\n if (clause.hasOwnProperty('name')) {\n return `${escapeReservedWords(clause['name'])}${_buildAS(clause as IField)}`;\n }\n return `${escapeReservedWords(clause as string)}`;\n};\n\n/**\n * Create N1QL queries from select array params\n * @param clause SELECT Clause param\n *\n * @return N1QL SELECT Query\n * */\nexport const buildSelectArrayExpr = (clause: ISelectType[]): string => {\n return `${clause.map((c) => buildSelectExpr('', c)).join(',')}`;\n};\n\n/**\n * Recursive function to create N1QL queries.\n * @param n1ql N1QL Query String\n * @param clause SELECT Clause param\n *\n * @return N1QL SELECT Query\n * */\nexport const buildSelectExpr = (n1ql: string, clause: ISelectType): string => {\n try {\n if (clause.hasOwnProperty('$field')) {\n return _buildField(clause['$field']);\n }\n const key = Object.keys(clause)[0];\n if (ReturnResultDict.hasOwnProperty(key)) {\n return `${ReturnResultDict[key]} ${buildSelectExpr(n1ql, clause[key])}`;\n }\n if (ResultExprDict.hasOwnProperty(key)) {\n return `${ResultExprDict[key]} ${buildSelectExpr(n1ql, clause[key])}`;\n }\n if (AggDict.hasOwnProperty(key)) {\n // todo check if have AS expr inside of Agg function.\n return `${AggDict[key]}(${_buildAggDictExpr(\n clause as ISelectAggType,\n key\n )}${buildSelectExpr(n1ql, clause[key])})${_buildAS(clause[key])}`;\n }\n throw new SelectClauseException();\n } catch {\n throw new SelectClauseException();\n }\n};\n\n/**\n * @ignore\n * */\nconst _buildAggDictExpr = (clause: ISelectAggType, key: string) => {\n if (AggDict.hasOwnProperty(key)) {\n if (clause[key].hasOwnProperty('ro')) {\n return `${ReturnResultDict[clause[key]['ro']]} `;\n }\n }\n return '';\n};\n\n/**\n * @ignore\n * */\nconst _buildLetExpr = (letExpr: ILetExpr[] | undefined, clause?: string) => {\n return Array.isArray(letExpr)\n ? ` ${clause ? clause : 'LET'} ${letExpr\n .map((value: ILetExpr) => `${escapeReservedWords(value.key)}=${value.value}`)\n .join(',')}`\n : '';\n};\n\n/**\n * @ignore\n * */\nconst _buildOrderByExpr = (orderExpr: Record<string, SortType> | undefined) => {\n return !!orderExpr\n ? ` ORDER BY ${Object.keys(orderExpr)\n .map((value: string) => `${escapeReservedWords(value)} ${orderExpr[value]}`)\n .join(',')}`\n : '';\n};\n\n/**\n * @ignore\n * */\nconst _buildLimitExpr = (limit: number | undefined) => {\n return Number.isInteger(limit) ? ` LIMIT ${limit}` : '';\n};\n\n/**\n * @ignore\n * */\nconst _buildOffsetExpr = (offset: number | undefined) => {\n return Number.isInteger(offset) ? ` OFFSET ${offset}` : '';\n};\n\n/**\n * @ignore\n * */\nconst _buildUseKeysExpr = (useKeys: string[] | undefined) => {\n return Array.isArray(useKeys) ? ` USE KEYS ${stringifyValues(useKeys)}` : '';\n};\n\n// end select expression functions\n\n//group by expression functions\n/**\n *@ignore\n */\nconst _buildGroupByExpr = (\n groupByExpr?: IGroupBy[],\n lettingExpr?: ILetExpr[],\n havingExpr?: LogicalWhereExpr\n) => {\n try {\n if ((lettingExpr || havingExpr) && !groupByExpr) {\n throw new QueryGroupByParamsException();\n }\n if (!groupByExpr) {\n return '';\n }\n return ` ${_buildGroupBy(groupByExpr)}${_buildLetExpr(\n lettingExpr,\n 'LETTING'\n )}${buildWhereExpr(havingExpr as LogicalWhereExpr, 'HAVING')}`;\n } catch {\n throw new QueryGroupByParamsException();\n }\n};\n\n/**\n *@ignore\n */\nconst _buildGroupBy = (groupByExpr: IGroupBy[]) => {\n return `GROUP BY ${groupByExpr\n .map((value: IGroupBy) => {\n return `${escapeReservedWords(value.expr)}${value.as ? ` AS ${value.as}` : ''}`;\n })\n .join(',')}`;\n};\n\n//end group by expression functions\n\n// where expression functions\n\n/**\n * Create WHERE N1QL Expressions.\n * {@link https://docs.couchbase.com/server/6.5/n1ql/n1ql-language-reference/where.html}\n * @param clause WHERE Clause param\n * @return N1QL WHERE Expression\n * */\nexport const buildWhereExpr = (expr: LogicalWhereExpr | undefined, clause?: string): string => {\n return expr ? ` ${clause ? clause : 'WHERE'} ${buildWhereClauseExpr('', expr)}` : '';\n};\n\n/**\n * @ignore\n *\n **/\nexport const verifyWhereObjectKey = (clause: LogicalWhereExpr) => {\n let exist = false;\n for (const key in clause) {\n if (['$and', '$or', '$not', '$any', '$$every', '$in', '$within'].includes(key)) {\n exist = true;\n break;\n }\n }\n return exist;\n};\n\n/**\n * Recursive function to create WHERE N1QL Expressions.\n * @param n1ql N1QL Query String\n * @param clause WHERE Clause param\n *\n * @return N1QL WHERE Expression\n * */\nexport const buildWhereClauseExpr = (n1ql: string, clause: LogicalWhereExpr): string => {\n try {\n if (!verifyWhereObjectKey(clause)) {\n return _buildFieldClauseExpr(\n clause as Record<string, string | number | boolean | ComparisonWhereExpr>\n );\n }\n\n return Object.keys(clause)\n .map((key) => {\n if (CollectionSelectOperatorDict[key]) {\n return `${_buildWhereCollectionExpr(\n key as CollectionSelectOperator,\n clause[key]\n )}`;\n }\n if (CollectionInWithinOperatorDict[key]) {\n return `${_buildCollectionInWithinOperator(\n key as CollectionInWithinOperator,\n clause[key]\n )}`;\n }\n if (Array.isArray(clause[key])) {\n const prefix = key === '$not' ? `${LogicalOperatorDict[key]} ` : '';\n const joinOp = key === '$not' ? ` AND ` : ` ${LogicalOperatorDict[key]} `;\n return `${prefix}(${clause[key]\n .map((value) => buildWhereClauseExpr(n1ql, value as LogicalWhereExpr))\n .join(joinOp)})`;\n } else {\n return `${buildWhereClauseExpr(n1ql, {[key]: clause[key]})}`;\n }\n })\n .join(' AND ');\n } catch (exception) {\n if (exception instanceof WhereClauseException) {\n throw exception;\n }\n throw new WhereClauseException();\n }\n};\n\n/**\n * @ignore\n * */\nconst _buildFieldClauseExpr = (\n field: Record<string, string | number | boolean | ComparisonWhereExpr>\n) => {\n try {\n const expr = Object.keys(field).map((value: string) => {\n if (typeof field[value] === 'object' && !Array.isArray(field[value])) {\n return `${_buildComparisionClauseExpr(value, field[value] as ComparisonWhereExpr)}`;\n }\n if (!value.includes('$')) {\n if (typeof field[value] === 'string') {\n return `${escapeReservedWords(value)}=${stringifyValues(field[value])}`;\n }\n if (\n typeof field[value] === 'number' ||\n typeof field[value] === 'boolean' ||\n Array.isArray(field[value])\n ) {\n return `${escapeReservedWords(value)}=${stringifyValues(field[value])}`;\n }\n }\n throw new QueryOperatorNotFoundException(value);\n });\n return expr.join(' AND ');\n } catch (exception) {\n if (exception instanceof WhereClauseException) {\n throw exception;\n }\n throw new WhereClauseException();\n }\n};\n\n/**\n * @ignore\n * */\nconst _buildComparisionClauseExpr = (fieldName: string, comparison: ComparisonWhereExpr) => {\n try {\n const expr = Object.keys(comparison)\n .map((value: string) => {\n if (!!comparison[value]) {\n if (ComparisonEmptyOperatorDict.hasOwnProperty(value)) {\n return `${escapeReservedWords(fieldName)} ${\n ComparisonEmptyOperatorDict[value]\n }`;\n }\n if (ComparisonSingleOperatorDict.hasOwnProperty(value)) {\n return `${escapeReservedWords(fieldName)}${\n ComparisonSingleOperatorDict[value]\n }${stringifyValues(comparison[value])}`;\n }\n if (ComparisonSingleStringOperatorDict.hasOwnProperty(value)) {\n return `${escapeReservedWords(fieldName)} ${\n ComparisonSingleStringOperatorDict[value]\n } ${stringifyValues(comparison[value])}`;\n }\n if (\n ComparisonMultipleOperatorDict.hasOwnProperty(value) &&\n Array.isArray(comparison[value])\n ) {\n return `${escapeReservedWords(fieldName)} ${\n ComparisonMultipleOperatorDict[value]\n } ${comparison[value].map((v) => stringifyValues(v)).join(' AND ')}`;\n }\n }\n throw new QueryOperatorNotFoundException(value);\n })\n .join(` AND `);\n return Object.keys(comparison).length > 1 ? `(${expr})` : expr;\n } catch (exception) {\n if (exception instanceof WhereClauseException) {\n throw exception;\n }\n throw new WhereClauseException();\n }\n};\n\n/**\n * @ignore\n * */\nconst _buildCollectionInWithinOperator = (\n op: CollectionInWithinOperator,\n expr: CollectionInWithinOperatorValue,\n excludeOperator?: boolean\n): string => {\n if (!op || !expr.target_expr || !expr.search_expr) {\n throw new InWithinOperatorExceptions();\n }\n return `${expr.search_expr}${!excludeOperator && expr.$not ? ' NOT ' : ' '}${\n CollectionInWithinOperatorDict[op]\n } ${excludeOperator ? expr.target_expr : stringifyValues(expr.target_expr)}`;\n};\n\nconst stringifyValues = (value: unknown) => {\n return JSON.stringify(value).replace(/\\\\/gi, '');\n};\n\n/**\n * @ignore\n * */\nconst _buildCollectionInWithIn = (collection: CollectionInWithinOperatorType) => {\n const op = collection.$in ? '$in' : collection.$within ? '$within' : undefined;\n if (!op) {\n throw new Error(\n 'The Collection Operator needs to have the following clauses declared (IN | WITHIN) and SATISFIES.'\n );\n }\n return `${_buildCollectionInWithinOperator(\n op,\n collection[op] as CollectionInWithinOperatorValue,\n true\n )}`;\n};\n\n/**\n * @ignore\n * */\nconst _buildWhereCollectionExpr = (\n op: CollectionSelectOperator,\n expr: CollectionExpressionType\n) => {\n return `${CollectionSelectOperatorDict[op]} ${expr.$expr\n .map((value) => _buildCollectionInWithIn(value))\n .join(',')} ${CollectionSatisfiesOperatorDict['$satisfies']} ${buildWhereClauseExpr(\n '',\n expr.$satisfied\n )} END`;\n};\n\n// end where expression functions\n\n// index expression functions\n\n/**\n * Build a INDEX N1QL query from user-specified parameters.\n * {@link https://docs.couchbase.com/server/6.5/n1ql/n1ql-language-reference/createindex.html}\n * @param collection Collection name\n * @param type INDEX clause types can be 'CREATE' | 'BUILD' | 'DROP' | 'CREATE PRIMARY'\n * @param on ON Clause param\n * @param where WHERE Clause param\n * @param usingGSI use a Global Secondary Index(GSI).\n * @param withExpr WITH Clause param\n *\n * @return N1QL INDEX Query\n * */\nexport const buildIndexExpr = (\n collection: string,\n type: IndexType,\n name: string,\n on?: IIndexOnParams[],\n where?: LogicalWhereExpr,\n usingGSI?: boolean,\n withExpr?: IIndexWithParams\n): string => {\n if (['BUILD', 'CREATE', 'CREATE PRIMARY'].includes(type) && on) {\n return `${type} INDEX \\`${name}\\` ON \\`${collection}\\`(${buildOnExpr(on)})${buildWhereExpr(\n where\n )} ${usingGSI ? 'USING GSI' : ''} ${buildWithExpr(withExpr)}`;\n } else {\n return `${type} INDEX \\`${collection}\\`.\\`${name}\\`${usingGSI ? ' USING GSI' : ''}`;\n }\n};\n\n/**\n * @ignore\n * */\nconst buildOnExpr = (on: IIndexOnParams[]) => {\n return on\n .map((value: IIndexOnParams) => {\n return `${escapeReservedWords(value.name)}${buildOnSortExpr(value)}`;\n })\n .join(',');\n};\n\n/**\n * @ignore\n * */\nconst buildOnSortExpr = (onExpr?: IIndexOnParams) => {\n if (onExpr && onExpr.hasOwnProperty('sort')) {\n return `[\"${onExpr.sort}\"]`;\n }\n return '';\n};\n\n/**\n * @ignore\n * */\nconst buildWithExpr = (withExpr?: IIndexWithParams) => {\n if (withExpr) {\n const resultExpr = Object.keys(withExpr)\n .map((value: string) => {\n switch (value) {\n case 'nodes':\n return buildWithNodesExpr(withExpr[value]);\n case 'defer_build':\n case 'num_replica':\n return `\"${value}\": ${withExpr[value]}`;\n default:\n throw new Error('The WITH clause has an incorrect syntax');\n }\n })\n .join(',');\n return !!resultExpr ? `WITH {${resultExpr}}` : '';\n }\n return '';\n};\n\n/**\n * @ignore\n * */\nconst buildWithNodesExpr = (withNodesExpr?: string[]) => {\n if (withNodesExpr) {\n return `\"nodes\": ${stringifyValues(withNodesExpr)}`;\n }\n};\n\n// end index expression functions\n"]}
|
package/dist/query/utils.js
CHANGED
|
@@ -12,7 +12,7 @@ var parseStringSelectExpr = function (expr) {
|
|
|
12
12
|
}
|
|
13
13
|
var resultExpr = expr.replace(/[()]/g, '');
|
|
14
14
|
replaceList.forEach(function (value) {
|
|
15
|
-
resultExpr = resultExpr.replace(new RegExp("/["
|
|
15
|
+
resultExpr = resultExpr.replace(new RegExp("/[".concat(value, "]/"), 'g'), '');
|
|
16
16
|
});
|
|
17
17
|
return resultExpr.split(',').map(function (v) {
|
|
18
18
|
return extractAsValue(v);
|
|
@@ -34,7 +34,7 @@ var extractAsValue = function (expr) {
|
|
|
34
34
|
*/
|
|
35
35
|
var escapeReservedWords = function (field) {
|
|
36
36
|
if (helpers_1.n1qlReservedWords.includes(field.toUpperCase())) {
|
|
37
|
-
return "`"
|
|
37
|
+
return "`".concat(field, "`");
|
|
38
38
|
}
|
|
39
39
|
if (field.match(/(\-)|(\.)|(\[\d+\])/g)) {
|
|
40
40
|
var expr = field;
|
|
@@ -42,7 +42,7 @@ var escapeReservedWords = function (field) {
|
|
|
42
42
|
.split('.')
|
|
43
43
|
.map(function (value) {
|
|
44
44
|
if (helpers_1.n1qlReservedWords.includes(value.toUpperCase())) {
|
|
45
|
-
return "`"
|
|
45
|
+
return "`".concat(value, "`");
|
|
46
46
|
}
|
|
47
47
|
return value;
|
|
48
48
|
})
|