context.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Copyright (c) 2015-present, Vitaly Tomilov
  3. *
  4. * See the LICENSE file at the top-level directory of this distribution
  5. * for licensing information.
  6. *
  7. * Removal or modification of this copyright notice is prohibited.
  8. */
  9. /**
  10. * @class ConnectionContext
  11. * @private
  12. * @summary Internal connection context.
  13. *
  14. * @param {object} cc
  15. * Connection Context.
  16. *
  17. * @param {object} cc.cn
  18. * Connection details
  19. *
  20. * @param {*} cc.dc
  21. * Database Context
  22. *
  23. * @param {object} cc.options
  24. * Library's Initialization Options
  25. *
  26. * @param {object} cc.db
  27. * Database Session we're attached to, if any.
  28. *
  29. * @param {number} cc.level
  30. * Task Level
  31. *
  32. * @param {number} cc.txLevel
  33. * Transaction Level
  34. *
  35. * @param {object} cc.parentCtx
  36. * Connection Context of the parent operation, if any.
  37. *
  38. */
  39. class ConnectionContext {
  40. constructor(cc) {
  41. this.cn = cc.cn; // connection details;
  42. this.dc = cc.dc; // database context;
  43. this.options = cc.options; // library options;
  44. this.db = cc.db; // database session;
  45. this.level = cc.level; // task level;
  46. this.txLevel = cc.txLevel; // transaction level;
  47. this.parentCtx = null; // parent context
  48. this.taskCtx = null; // task context
  49. this.start = null; // Date/Time when connected
  50. this.txCount = 0;
  51. }
  52. connect(db) {
  53. this.db = db;
  54. this.start = new Date();
  55. }
  56. disconnect(kill) {
  57. if (this.db) {
  58. const p = this.db.release(kill);
  59. this.db = null;
  60. return p;
  61. }
  62. }
  63. clone() {
  64. const obj = new ConnectionContext(this);
  65. obj.parent = this;
  66. obj.parentCtx = this.taskCtx;
  67. return obj;
  68. }
  69. get nextTxCount() {
  70. let txCurrent = this, txTop = this;
  71. while (txCurrent.parent) {
  72. txCurrent = txCurrent.parent;
  73. if (txCurrent.taskCtx && txCurrent.taskCtx.isTX) {
  74. txTop = txCurrent;
  75. }
  76. }
  77. return txTop.txCount++;
  78. }
  79. }
  80. /**
  81. * Connection Context
  82. * @module context
  83. * @author Vitaly Tomilov
  84. * @private
  85. */
  86. module.exports = {ConnectionContext};