spice-couchbase 2.0.50 → 2.0.52

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/build/index.js CHANGED
@@ -14,12 +14,6 @@ var _ = require("lodash");
14
14
 
15
15
  var couchbase = require("couchbase");
16
16
 
17
- var {
18
- default: axios
19
- } = require("axios");
20
-
21
- var qs = require("qs");
22
-
23
17
  var {
24
18
  ConflictResolutionType
25
19
  } = require("couchbase");
@@ -166,11 +160,6 @@ module.exports = class Database {
166
160
  console.log(e);
167
161
  }
168
162
  })();
169
- }
170
-
171
- getCouchbaseHost() {
172
- var default_port = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8091;
173
- return (this.db_config.api_base || "http://".concat(_.last(_.first(this.db_config.nodes.split(",")).split("://")))) + ":" + default_port;
174
163
  } //create wait function
175
164
 
176
165
 
@@ -180,6 +169,14 @@ module.exports = class Database {
180
169
  })();
181
170
  }
182
171
 
172
+ quoteIdentifier(identifier) {
173
+ return "`".concat(String(identifier).replace(/`/g, "``"), "`");
174
+ }
175
+
176
+ collectionPath(scope_name, collection_name) {
177
+ return "default:".concat(this.quoteIdentifier(this.db_config.bucket), ".").concat(this.quoteIdentifier(scope_name), ".").concat(this.quoteIdentifier(collection_name));
178
+ }
179
+
183
180
  upsertCollection() {
184
181
  var _this3 = this;
185
182
 
@@ -207,46 +204,24 @@ module.exports = class Database {
207
204
  try {
208
205
  var _spice2, _spice2$db, _spice2$db$collection;
209
206
 
210
- var that = _this4;
211
-
212
- function loadAllCollections() {
213
- return _loadAllCollections.apply(this, arguments);
214
- }
215
-
216
- function _loadAllCollections() {
217
- _loadAllCollections = _asyncToGenerator(function* () {
218
- var all_scopes = yield axios.get("".concat(that.getCouchbaseHost(), "/pools/default/buckets/").concat(that.db_config.bucket, "/scopes"), {
219
- auth: {
220
- username: that.db_config.username,
221
- password: that.db_config.password
222
- }
223
- });
224
-
225
- var scope = _.find(all_scopes.data.scopes, {
226
- name: scope_name
227
- });
228
-
229
- var collectionSet = new Set();
230
-
231
- _.each(scope.collections, collection => {
232
- collectionSet.add(collection.name);
233
- });
234
-
235
- return collectionSet;
236
- });
237
- return _loadAllCollections.apply(this, arguments);
238
- }
239
-
240
207
  if ((_spice2 = spice) === null || _spice2 === void 0 ? void 0 : (_spice2$db = _spice2.db) === null || _spice2$db === void 0 ? void 0 : (_spice2$db$collection = _spice2$db.collections) === null || _spice2$db$collection === void 0 ? void 0 : _spice2$db$collection.has(collection_name)) {
241
208
  return true;
242
209
  } else {
243
- var _spice3, _spice3$db, _spice3$db$collection;
210
+ var response = yield _this4.cluster.query("SELECT RAW name\n FROM system:keyspaces\n WHERE bucket_id = ?\n AND scope_id = ?\n AND name = ?\n LIMIT 1", {
211
+ parameters: [_this4.db_config.bucket, scope_name, collection_name],
212
+ scanConsistency: QueryScanConsistency.RequestPlus
213
+ });
214
+
215
+ if (Array.isArray(response === null || response === void 0 ? void 0 : response.rows) && response.rows.length > 0) {
216
+ spice.db.collections.add(collection_name);
217
+ return true;
218
+ }
244
219
 
245
- spice.db.collections = yield loadAllCollections();
246
- return (_spice3 = spice) === null || _spice3 === void 0 ? void 0 : (_spice3$db = _spice3.db) === null || _spice3$db === void 0 ? void 0 : (_spice3$db$collection = _spice3$db.collections) === null || _spice3$db$collection === void 0 ? void 0 : _spice3$db$collection.has(collection_name);
220
+ return false;
247
221
  }
248
222
  } catch (e) {
249
223
  console.log("Exists error happened", e);
224
+ return false;
250
225
  }
251
226
  })();
252
227
  }
@@ -256,22 +231,21 @@ module.exports = class Database {
256
231
 
257
232
  return _asyncToGenerator(function* () {
258
233
  try {
259
- var token = "".concat(_this5.db_config.username, ":").concat(_this5.db_config.password);
260
- var encodedToken = Buffer.from(token).toString("base64");
261
- var headers = {
262
- Authorization: "Basic " + encodedToken,
263
- "Content-Type": "application/x-www-form-urlencoded"
264
- };
265
- var response = yield axios({
266
- method: "post",
267
- url: "".concat(_this5.getCouchbaseHost(), "/pools/default/buckets/").concat(_this5.db_config.bucket, "/scopes/").concat(scope_name, "/collections"),
268
- headers,
269
- data: qs.stringify({
270
- name: connection_name
271
- })
272
- }).data;
234
+ var response = yield _this5.cluster.query("CREATE COLLECTION ".concat(_this5.collectionPath(scope_name, connection_name)), {
235
+ scanConsistency: QueryScanConsistency.RequestPlus
236
+ });
237
+ spice.db.collections.add(connection_name);
273
238
  return response;
274
- } catch (e) {}
239
+ } catch (e) {
240
+ var _e$cause, _e$cause2;
241
+
242
+ if (e instanceof couchbase.CollectionExistsError || (e === null || e === void 0 ? void 0 : (_e$cause = e.cause) === null || _e$cause === void 0 ? void 0 : _e$cause.first_error_code) === 12003 || /collection .*already exists|already exists/i.test((e === null || e === void 0 ? void 0 : e.message) || (e === null || e === void 0 ? void 0 : (_e$cause2 = e.cause) === null || _e$cause2 === void 0 ? void 0 : _e$cause2.first_error_message) || "")) {
243
+ spice.db.collections.add(connection_name);
244
+ return;
245
+ }
246
+
247
+ console.log("CREATE Collection :::", e);
248
+ }
275
249
  })();
276
250
  }
277
251
 
@@ -280,15 +254,11 @@ module.exports = class Database {
280
254
 
281
255
  return _asyncToGenerator(function* () {
282
256
  try {
283
- var response = yield _this6.cluster.query("SELECT RAW name\n FROM system:indexes\n WHERE bucket_id = $bucket\n AND scope_id = $scope\n AND keyspace_id = $collection\n AND is_primary = true\n LIMIT 1", {
284
- namedParameters: {
285
- bucket: _this6.db_config.bucket,
286
- scope: scope_name,
287
- collection: col_name
288
- },
257
+ var response = yield _this6.cluster.query("SELECT RAW name\n FROM system:indexes\n WHERE bucket_id = ?\n AND scope_id = ?\n AND keyspace_id = ?\n AND is_primary = true\n LIMIT 1", {
258
+ parameters: [_this6.db_config.bucket, scope_name, col_name],
289
259
  scanConsistency: QueryScanConsistency.RequestPlus
290
260
  });
291
- return Array.isArray(response && response.rows) && response.rows.length > 0;
261
+ return Array.isArray(response === null || response === void 0 ? void 0 : response.rows) && response.rows.length > 0;
292
262
  } catch (e) {
293
263
  console.log("Primary index lookup failed:", e);
294
264
  return false;
@@ -297,28 +267,34 @@ module.exports = class Database {
297
267
  }
298
268
 
299
269
  createPrimaryIndex(scope_name, col_name) {
300
- var _this6 = this;
270
+ var _this7 = this;
301
271
 
302
272
  return _asyncToGenerator(function* () {
303
273
  try {
304
- if (yield _this6.primaryIndexExists(scope_name, col_name)) {
274
+ if (yield _this7.primaryIndexExists(scope_name, col_name)) {
305
275
  return;
306
276
  }
307
277
 
308
- var response = yield _this6.query("CREATE PRIMARY INDEX ON default:`".concat(_this6.db_config.bucket, "`.`").concat(scope_name, "`.`").concat(col_name, "`"));
278
+ var response = yield _this7.query("CREATE PRIMARY INDEX ON ".concat(_this7.collectionPath(scope_name, col_name)));
309
279
  return response;
310
280
  } catch (e) {
281
+ var _e$cause3, _e$cause4;
282
+
283
+ if (e instanceof couchbase.IndexExistsError || (e === null || e === void 0 ? void 0 : (_e$cause3 = e.cause) === null || _e$cause3 === void 0 ? void 0 : _e$cause3.first_error_code) === 4300 || /index .*already exists|index_exists/i.test((e === null || e === void 0 ? void 0 : e.message) || (e === null || e === void 0 ? void 0 : (_e$cause4 = e.cause) === null || _e$cause4 === void 0 ? void 0 : _e$cause4.first_error_message) || "")) {
284
+ return;
285
+ }
286
+
311
287
  console.log("CREATE Index :::", e);
312
288
  }
313
289
  })();
314
290
  }
315
291
 
316
292
  createScope(scope_name) {
317
- var _this7 = this;
293
+ var _this8 = this;
318
294
 
319
295
  return _asyncToGenerator(function* () {
320
296
  try {
321
- yield _this7.collection_manager.createScope(scope_name);
297
+ yield _this8.collection_manager.createScope(scope_name);
322
298
  } catch (e) {
323
299
  if (e instanceof couchbase.ScopeExistsError) {
324
300
  console.log("The scope already exists");
@@ -330,7 +306,7 @@ module.exports = class Database {
330
306
  }
331
307
 
332
308
  get(doc_id) {
333
- var _this8 = this;
309
+ var _this9 = this;
334
310
 
335
311
  var {
336
312
  columns = []
@@ -338,7 +314,7 @@ module.exports = class Database {
338
314
  return _asyncToGenerator(function* () {
339
315
  try {
340
316
  var useLookupIn = columns.length > 0;
341
- var collection = _this8.use_bucket_name ? _this8.connection : _this8.collection;
317
+ var collection = _this9.use_bucket_name ? _this9.connection : _this9.collection;
342
318
 
343
319
  if (!useLookupIn) {
344
320
  var response = yield collection.get(doc_id);
@@ -379,36 +355,36 @@ module.exports = class Database {
379
355
  }
380
356
 
381
357
  insert(doc_id, document, expiry) {
382
- var _this9 = this;
358
+ var _this10 = this;
383
359
 
384
360
  return _asyncToGenerator(function* () {
385
361
  try {
386
- yield (_this9.use_bucket_name ? _this9.connection : _this9.collection).insert(doc_id, document, {
362
+ yield (_this10.use_bucket_name ? _this10.connection : _this10.collection).insert(doc_id, document, {
387
363
  expiry: expiry
388
364
  });
389
365
  } catch (e) {
390
366
  console.log(e.message, e, doc_id);
391
367
  }
392
368
 
393
- return yield _this9.get(doc_id);
369
+ return yield _this10.get(doc_id);
394
370
  })();
395
371
  }
396
372
 
397
373
  touch(doc_id) {
398
- var _this10 = this;
374
+ var _this11 = this;
399
375
 
400
376
  var expiry = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
401
377
  return _asyncToGenerator(function* () {
402
- yield (_this10.use_bucket_name ? _this10.connection : _this10.collection).touch(doc_id, expiry);
403
- return yield _this10.get(doc_id);
378
+ yield (_this11.use_bucket_name ? _this11.connection : _this11.collection).touch(doc_id, expiry);
379
+ return yield _this11.get(doc_id);
404
380
  })();
405
381
  }
406
382
 
407
383
  count(doc_id, adjustment, initial_value) {
408
- var _this11 = this;
384
+ var _this12 = this;
409
385
 
410
386
  return _asyncToGenerator(function* () {
411
- var res = yield (_this11.use_bucket_name ? _this11.connection : _this11.collection).counter(doc_id, adjustment, {
387
+ var res = yield (_this12.use_bucket_name ? _this12.connection : _this12.collection).counter(doc_id, adjustment, {
412
388
  initial: initial_value
413
389
  });
414
390
  return res.value;
@@ -416,10 +392,10 @@ module.exports = class Database {
416
392
  }
417
393
 
418
394
  update(doc_id, document, expiry) {
419
- var _this12 = this;
395
+ var _this13 = this;
420
396
 
421
397
  return _asyncToGenerator(function* () {
422
- var res = yield (_this12.use_bucket_name ? _this12.connection : _this12.collection).replace(doc_id, document, {
398
+ var res = yield (_this13.use_bucket_name ? _this13.connection : _this13.collection).replace(doc_id, document, {
423
399
  expiry: expiry
424
400
  });
425
401
  return res.value;
@@ -427,16 +403,16 @@ module.exports = class Database {
427
403
  }
428
404
 
429
405
  delete(doc_id) {
430
- var _this13 = this;
406
+ var _this14 = this;
431
407
 
432
408
  return _asyncToGenerator(function* () {
433
- var res = yield (_this13.use_bucket_name ? _this13.connection : _this13.collection).remove(doc_id);
409
+ var res = yield (_this14.use_bucket_name ? _this14.connection : _this14.collection).remove(doc_id);
434
410
  return res.value;
435
411
  })();
436
412
  }
437
413
 
438
414
  multi_get(keys) {
439
- var _this14 = this;
415
+ var _this15 = this;
440
416
 
441
417
  var {
442
418
  keep_type = true,
@@ -449,7 +425,7 @@ module.exports = class Database {
449
425
 
450
426
  if (_.isArray(keys) && keys.length > 0) {
451
427
  var useLookupIn = columns.length > 0;
452
- var collection = _this14.use_bucket_name ? _this14.connection : _this14.collection;
428
+ var collection = _this15.use_bucket_name ? _this15.connection : _this15.collection;
453
429
 
454
430
  if (!useLookupIn) {
455
431
  // Regular get - no batching needed
@@ -609,7 +585,7 @@ module.exports = class Database {
609
585
  }
610
586
 
611
587
  search(type) {
612
- var _this15 = this;
588
+ var _this16 = this;
613
589
 
614
590
  var columns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
615
591
  var query = arguments.length > 2 ? arguments[2] : undefined;
@@ -620,8 +596,8 @@ module.exports = class Database {
620
596
  var query_scope = arguments.length > 7 ? arguments[7] : undefined;
621
597
  var join = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : "";
622
598
  return _asyncToGenerator(function* () {
623
- var is_legacy = _this15.scope_name !== "_default" && _this15.collection_name !== "_default";
624
- var bucket = "`".concat(_this15.use_bucket_name ? _this15.bucket : _this15.collection_name, "`");
599
+ var is_legacy = _this16.scope_name !== "_default" && _this16.collection_name !== "_default";
600
+ var bucket = "`".concat(_this16.use_bucket_name ? _this16.bucket : _this16.collection_name, "`");
625
601
 
626
602
  function processColumns(columnsStr) {
627
603
  // If columns is empty or *, return default
@@ -666,7 +642,7 @@ module.exports = class Database {
666
642
  var front_query = "SELECT ".concat(columns, " FROM ").concat(bucket, " ").concat(join);
667
643
  var conditions = [];
668
644
 
669
- if (_this15.use_bucket_name) {
645
+ if (_this16.use_bucket_name) {
670
646
  conditions.push("type = '".concat(type, "'"));
671
647
  }
672
648
 
@@ -682,11 +658,11 @@ module.exports = class Database {
682
658
  var limit_clause = limit > 0 ? " LIMIT ".concat(limit) : "";
683
659
  var offset_clause = offset > 0 ? " OFFSET ".concat(offset) : "";
684
660
  query = query + order_by_clause + limit_clause + offset_clause;
685
- var active_query_space = query_scope || !_this15.use_bucket_name ? "scope" : "cluster";
686
- var queries = [_this15.getData(query, active_query_space)];
661
+ var active_query_space = query_scope || !_this16.use_bucket_name ? "scope" : "cluster";
662
+ var queries = [_this16.getData(query, active_query_space)];
687
663
 
688
664
  if (do_count != "false") {
689
- queries.push(_this15.getCount(count_query, active_query_space));
665
+ queries.push(_this16.getCount(count_query, active_query_space));
690
666
  }
691
667
 
692
668
  var responses = yield Promise.all(queries);
@@ -770,21 +746,21 @@ module.exports = class Database {
770
746
  }
771
747
 
772
748
  getCount(count_query_element) {
773
- var _this16 = this;
749
+ var _this17 = this;
774
750
 
775
751
  var query_scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "cluster";
776
752
  return _asyncToGenerator(function* () {
777
- var response = yield _this16.query(count_query_element, query_scope);
753
+ var response = yield _this17.query(count_query_element, query_scope);
778
754
  return response.rows[0].count;
779
755
  })();
780
756
  }
781
757
 
782
758
  getData(query_element) {
783
- var _this17 = this;
759
+ var _this18 = this;
784
760
 
785
761
  var query_scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "cluster";
786
762
  return _asyncToGenerator(function* () {
787
- var response = yield _this17.query(query_element, query_scope);
763
+ var response = yield _this18.query(query_element, query_scope);
788
764
  return response.rows;
789
765
  })();
790
766
  }
@@ -826,7 +802,7 @@ module.exports = class Database {
826
802
  }
827
803
 
828
804
  optimize(query, exec_scope) {
829
- var _this18 = this;
805
+ var _this19 = this;
830
806
 
831
807
  return _asyncToGenerator(function* () {
832
808
  try {
@@ -842,16 +818,16 @@ module.exports = class Database {
842
818
 
843
819
  var plan = explainResponse === null || explainResponse === void 0 ? void 0 : (_explainResponse$rows = explainResponse.rows) === null || _explainResponse$rows === void 0 ? void 0 : _explainResponse$rows[0];
844
820
 
845
- if (!_this18.hasFetchOperator(plan)) {
821
+ if (!_this19.hasFetchOperator(plan)) {
846
822
  // Query is already covered, no need to create index
847
823
  return;
848
824
  } // 3. Build covering index from the query
849
825
 
850
826
 
851
827
  var indexStatement = buildCoveringIndex(query, {
852
- bucket: _this18.bucket,
853
- scope: _this18.scope_name,
854
- collection: _this18.collection_name
828
+ bucket: _this19.bucket,
829
+ scope: _this19.scope_name,
830
+ collection: _this19.collection_name
855
831
  }); // 4. Execute the index creation if we got a valid statement
856
832
 
857
833
  if (indexStatement) {
@@ -863,19 +839,19 @@ module.exports = class Database {
863
839
  }
864
840
 
865
841
  query(query) {
866
- var _this19 = this;
842
+ var _this20 = this;
867
843
 
868
844
  var query_scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "cluster";
869
845
  return _asyncToGenerator(function* () {
870
- var scope = query_scope || _this19.query_scope;
846
+ var scope = query_scope || _this20.query_scope;
871
847
  var sanitizedQuery = query; //sanitization step to be implemented
872
848
 
873
849
  var exec_scope = null;
874
850
 
875
851
  if (scope === "cluster") {
876
- exec_scope = _this19.cluster;
852
+ exec_scope = _this20.cluster;
877
853
  } else {
878
- exec_scope = _this19.scope;
854
+ exec_scope = _this20.scope;
879
855
  } // Start time
880
856
 
881
857
 
@@ -890,11 +866,11 @@ module.exports = class Database {
890
866
  var durationInMilliseconds = (endTime - startTime) / BigInt(1000000); // optimize if response time is greater than 1 second
891
867
 
892
868
  if (durationInMilliseconds > 2000) {
893
- _this19.optimize(query, exec_scope);
869
+ _this20.optimize(query, exec_scope);
894
870
  }
895
871
 
896
872
  return response;
897
873
  })();
898
874
  }
899
875
 
900
- };
876
+ };
package/build/utility.js CHANGED
@@ -389,4 +389,4 @@ module.exports = {
389
389
  extractOrderByFields,
390
390
  extractOrderByIndexFields,
391
391
  generateHash
392
- };
392
+ };
@@ -831,4 +831,4 @@ test("field order: WHERE -> GROUP BY -> ORDER BY -> SELECT", () => {
831
831
  console.log("\n========================================");
832
832
  console.log("Tests: ".concat(passed + failed, " | Passed: ").concat(passed, " | Failed: ").concat(failed));
833
833
  console.log("========================================\n");
834
- process.exit(failed > 0 ? 1 : 0);
834
+ process.exit(failed > 0 ? 1 : 0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spice-couchbase",
3
- "version": "2.0.50",
3
+ "version": "2.0.52",
4
4
  "description": "",
5
5
  "main": "build/index.js",
6
6
  "scripts": {
@@ -9,10 +9,8 @@
9
9
  "author": "Chad Fraser <chad@sonover.com> (http://sonover.com)",
10
10
  "license": "ISC",
11
11
  "dependencies": {
12
- "axios": "^0.26.1",
13
12
  "couchbase": "^4.6.0",
14
- "lodash": "^4.17.15",
15
- "qs": "^6.10.3"
13
+ "lodash": "^4.17.15"
16
14
  },
17
15
  "devDependencies": {
18
16
  "@babel/cli": "^7.7.7",
package/src/index.js CHANGED
@@ -2,8 +2,6 @@
2
2
 
3
3
  let _ = require("lodash");
4
4
  let couchbase = require("couchbase");
5
- const { default: axios } = require("axios");
6
- var qs = require("qs");
7
5
  const { ConflictResolutionType } = require("couchbase");
8
6
  const { QueryScanConsistency } = require("couchbase");
9
7
 
@@ -163,22 +161,21 @@ module.exports = class Database {
163
161
  }
164
162
  }
165
163
 
166
- getCouchbaseHost(default_port = 8091) {
167
- return (
168
- (this.db_config.api_base ||
169
- `http://${_.last(
170
- _.first(this.db_config.nodes.split(",")).split("://"),
171
- )}`) +
172
- ":" +
173
- default_port
174
- );
175
- }
176
-
177
164
  //create wait function
178
165
  async wait(ms) {
179
166
  return new Promise((resolve) => setTimeout(resolve, ms));
180
167
  }
181
168
 
169
+ quoteIdentifier(identifier) {
170
+ return `\`${String(identifier).replace(/`/g, "``")}\``;
171
+ }
172
+
173
+ collectionPath(scope_name, collection_name) {
174
+ return `default:${this.quoteIdentifier(this.db_config.bucket)}.${this.quoteIdentifier(
175
+ scope_name,
176
+ )}.${this.quoteIdentifier(collection_name)}`;
177
+ }
178
+
182
179
  async upsertCollection() {
183
180
  try {
184
181
  if (!this.checkGlobelConnectionObject(this.collection_name)) {
@@ -199,55 +196,56 @@ module.exports = class Database {
199
196
 
200
197
  async collectionExists(collection_name, scope_name) {
201
198
  try {
202
- let that = this;
203
- async function loadAllCollections() {
204
- let all_scopes = await axios.get(
205
- `${that.getCouchbaseHost()}/pools/default/buckets/${
206
- that.db_config.bucket
207
- }/scopes`,
208
- {
209
- auth: {
210
- username: that.db_config.username,
211
- password: that.db_config.password,
212
- },
213
- },
214
- );
215
- let scope = _.find(all_scopes.data.scopes, { name: scope_name });
216
- let collectionSet = new Set();
217
- _.each(scope.collections, (collection) => {
218
- collectionSet.add(collection.name);
219
- });
220
- return collectionSet;
221
- }
222
199
  if (spice?.db?.collections?.has(collection_name)) {
223
200
  return true;
224
201
  } else {
225
- spice.db.collections = await loadAllCollections();
226
- return spice?.db?.collections?.has(collection_name);
202
+ let response = await this.cluster.query(
203
+ `SELECT RAW name
204
+ FROM system:keyspaces
205
+ WHERE bucket_id = ?
206
+ AND scope_id = ?
207
+ AND name = ?
208
+ LIMIT 1`,
209
+ {
210
+ parameters: [this.db_config.bucket, scope_name, collection_name],
211
+ scanConsistency: QueryScanConsistency.RequestPlus,
212
+ },
213
+ );
214
+ if (Array.isArray(response?.rows) && response.rows.length > 0) {
215
+ spice.db.collections.add(collection_name);
216
+ return true;
217
+ }
218
+ return false;
227
219
  }
228
220
  } catch (e) {
229
221
  console.log("Exists error happened", e);
222
+ return false;
230
223
  }
231
224
  }
232
225
 
233
226
  async createCollection(connection_name, scope_name) {
234
227
  try {
235
- const token = `${this.db_config.username}:${this.db_config.password}`;
236
- const encodedToken = Buffer.from(token).toString("base64");
237
- const headers = {
238
- Authorization: "Basic " + encodedToken,
239
- "Content-Type": "application/x-www-form-urlencoded",
240
- };
241
- let response = await axios({
242
- method: "post",
243
- url: `${this.getCouchbaseHost()}/pools/default/buckets/${
244
- this.db_config.bucket
245
- }/scopes/${scope_name}/collections`,
246
- headers,
247
- data: qs.stringify({ name: connection_name }),
248
- }).data;
228
+ let response = await this.cluster.query(
229
+ `CREATE COLLECTION ${this.collectionPath(scope_name, connection_name)}`,
230
+ {
231
+ scanConsistency: QueryScanConsistency.RequestPlus,
232
+ },
233
+ );
234
+ spice.db.collections.add(connection_name);
249
235
  return response;
250
- } catch (e) {}
236
+ } catch (e) {
237
+ if (
238
+ e instanceof couchbase.CollectionExistsError ||
239
+ e?.cause?.first_error_code === 12003 ||
240
+ /collection .*already exists|already exists/i.test(
241
+ e?.message || e?.cause?.first_error_message || "",
242
+ )
243
+ ) {
244
+ spice.db.collections.add(connection_name);
245
+ return;
246
+ }
247
+ console.log("CREATE Collection :::", e);
248
+ }
251
249
  }
252
250
 
253
251
  async primaryIndexExists(scope_name, col_name) {
@@ -255,17 +253,13 @@ module.exports = class Database {
255
253
  let response = await this.cluster.query(
256
254
  `SELECT RAW name
257
255
  FROM system:indexes
258
- WHERE bucket_id = $bucket
259
- AND scope_id = $scope
260
- AND keyspace_id = $collection
256
+ WHERE bucket_id = ?
257
+ AND scope_id = ?
258
+ AND keyspace_id = ?
261
259
  AND is_primary = true
262
260
  LIMIT 1`,
263
261
  {
264
- namedParameters: {
265
- bucket: this.db_config.bucket,
266
- scope: scope_name,
267
- collection: col_name,
268
- },
262
+ parameters: [this.db_config.bucket, scope_name, col_name],
269
263
  scanConsistency: QueryScanConsistency.RequestPlus,
270
264
  },
271
265
  );
@@ -282,10 +276,19 @@ module.exports = class Database {
282
276
  return;
283
277
  }
284
278
  let response = await this.query(
285
- `CREATE PRIMARY INDEX ON default:\`${this.db_config.bucket}\`.\`${scope_name}\`.\`${col_name}\``,
279
+ `CREATE PRIMARY INDEX ON ${this.collectionPath(scope_name, col_name)}`,
286
280
  );
287
281
  return response;
288
282
  } catch (e) {
283
+ if (
284
+ e instanceof couchbase.IndexExistsError ||
285
+ e?.cause?.first_error_code === 4300 ||
286
+ /index .*already exists|index_exists/i.test(
287
+ e?.message || e?.cause?.first_error_message || "",
288
+ )
289
+ ) {
290
+ return;
291
+ }
289
292
  console.log("CREATE Index :::", e);
290
293
  }
291
294
  }