@ragestudio/scylla-odm 0.19.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/batch/index.d.ts +24 -0
  2. package/batch/index.js +1 -0
  3. package/client.d.ts +2 -0
  4. package/client.js +1 -1
  5. package/cql_gen/create_keyspace.js +1 -1
  6. package/cql_gen/create_table.js +1 -1
  7. package/document/index.d.ts +2 -3
  8. package/document/index.js +1 -1
  9. package/driver/auth/index.d.ts +0 -12
  10. package/driver/auth/index.js +1 -1
  11. package/driver/auth/no-auth-provider.js +1 -1
  12. package/driver/auth/plain-text-auth-provider.js +1 -1
  13. package/driver/auth/provider.js +1 -1
  14. package/driver/client-options.js +1 -1
  15. package/driver/client.js +1 -1
  16. package/driver/concurrent/index.d.ts +1 -25
  17. package/driver/concurrent/index.js +1 -1
  18. package/driver/connection.js +1 -1
  19. package/driver/control-connection.js +1 -1
  20. package/driver/encoder.js +1 -1
  21. package/driver/errors.js +1 -1
  22. package/driver/execution-options.js +1 -1
  23. package/driver/execution-profile.js +1 -1
  24. package/driver/host-connection-pool.js +1 -1
  25. package/driver/host.js +1 -1
  26. package/driver/index.d.ts +3 -95
  27. package/driver/index.js +1 -1
  28. package/driver/mapping/cache.js +1 -1
  29. package/driver/mapping/doc-info-adapter.js +1 -1
  30. package/driver/mapping/mapper.js +1 -1
  31. package/driver/mapping/mapping-handler.js +1 -1
  32. package/driver/mapping/model-batch-item.js +1 -1
  33. package/driver/mapping/model-batch-mapper.js +1 -1
  34. package/driver/mapping/model-mapper.js +1 -1
  35. package/driver/mapping/model-mapping-info.js +1 -1
  36. package/driver/mapping/object-selector.js +1 -1
  37. package/driver/mapping/q.js +1 -1
  38. package/driver/mapping/query-generator.js +9 -9
  39. package/driver/mapping/result-mapper.js +2 -2
  40. package/driver/mapping/result.js +1 -1
  41. package/driver/mapping/table-mappings.js +1 -1
  42. package/driver/mapping/tree.js +1 -1
  43. package/driver/metadata/aggregate.js +1 -1
  44. package/driver/metadata/client-state.js +1 -1
  45. package/driver/metadata/data-collection.js +1 -1
  46. package/driver/metadata/event-debouncer.js +1 -1
  47. package/driver/metadata/index.js +1 -1
  48. package/driver/metadata/materialized-view.js +1 -1
  49. package/driver/metadata/schema-function.js +1 -1
  50. package/driver/metadata/schema-index.js +1 -1
  51. package/driver/metadata/schema-parser.js +1 -1
  52. package/driver/metadata/table-metadata.js +1 -1
  53. package/driver/operation-state.js +1 -1
  54. package/driver/policies/address-resolution.js +1 -1
  55. package/driver/policies/index.js +1 -1
  56. package/driver/policies/load-balancing.js +1 -1
  57. package/driver/policies/reconnection.js +1 -1
  58. package/driver/policies/retry.js +1 -1
  59. package/driver/policies/speculative-execution.js +1 -1
  60. package/driver/policies/timestamp-generation.js +1 -1
  61. package/driver/prepare-handler.js +1 -1
  62. package/driver/promise-utils.js +1 -1
  63. package/driver/readers.js +1 -1
  64. package/driver/request-execution.js +1 -1
  65. package/driver/request-handler.js +1 -1
  66. package/driver/requests.js +1 -1
  67. package/driver/stream-id-stack.js +1 -1
  68. package/driver/streams.js +1 -1
  69. package/driver/token.js +1 -1
  70. package/driver/tokenizer.js +1 -1
  71. package/driver/types/big-decimal.js +1 -1
  72. package/driver/types/duration.js +1 -1
  73. package/driver/types/index.js +1 -1
  74. package/driver/types/inet-address.js +1 -1
  75. package/driver/types/integer.js +1 -1
  76. package/driver/types/local-date.js +1 -1
  77. package/driver/types/local-time.js +1 -1
  78. package/driver/types/mutable-long.js +1 -1
  79. package/driver/types/result-set.js +1 -1
  80. package/driver/types/result-stream.js +1 -1
  81. package/driver/types/row.js +1 -1
  82. package/driver/types/time-uuid.js +1 -1
  83. package/driver/types/tuple.js +1 -1
  84. package/driver/types/uuid.js +1 -1
  85. package/driver/types/vector.js +1 -1
  86. package/driver/types/version-number.js +1 -1
  87. package/driver/utils.js +2 -2
  88. package/driver/writers.js +1 -1
  89. package/index.d.ts +2 -1
  90. package/index.js +1 -1
  91. package/logger/index.js +1 -1
  92. package/model/index.d.ts +36 -5
  93. package/model/index.js +1 -1
  94. package/operations/countAll.js +1 -1
  95. package/operations/delete.d.ts +3 -2
  96. package/operations/delete.js +1 -1
  97. package/operations/find.js +1 -1
  98. package/operations/findOne.js +1 -1
  99. package/operations/insert.d.ts +8 -0
  100. package/operations/insert.js +1 -0
  101. package/operations/sync.js +1 -1
  102. package/operations/tableExists.js +2 -2
  103. package/operations/update.d.ts +3 -2
  104. package/operations/update.js +1 -1
  105. package/package.js +1 -1
  106. package/package.json +1 -1
  107. package/schema/index.js +1 -1
  108. package/types.d.ts +17 -1
  109. package/utils/buildMapper.js +1 -1
  110. package/utils/delay.js +1 -1
  111. package/utils/fillDefaults.js +1 -1
  112. package/utils/isPlainObject.js +1 -1
  113. package/utils/loadModels.js +1 -1
  114. package/utils/queryParser.js +1 -1
  115. package/utils/typeChecker.js +1 -1
  116. package/_virtual/_rolldown/runtime.js +0 -1
  117. package/driver/auth/base-dse-authenticator.js +0 -1
  118. package/driver/auth/dse-gssapi-auth-provider.js +0 -1
  119. package/driver/auth/dse-plain-text-auth-provider.js +0 -1
  120. package/driver/auth/gssapi-client.js +0 -1
  121. package/driver/datastax/graph/complex-type-helper.js +0 -1
  122. package/driver/datastax/graph/custom-type-serializers.js +0 -1
  123. package/driver/datastax/graph/graph-executor.js +0 -1
  124. package/driver/datastax/graph/graph-serializer.js +0 -1
  125. package/driver/datastax/graph/index.d.ts +0 -63
  126. package/driver/datastax/graph/index.js +0 -1
  127. package/driver/datastax/graph/options.js +0 -1
  128. package/driver/datastax/graph/result-set.js +0 -1
  129. package/driver/datastax/graph/structure.js +0 -1
  130. package/driver/datastax/graph/type-serializers.js +0 -1
  131. package/driver/datastax/graph/wrappers.js +0 -1
  132. package/driver/datastax/index.d.ts +0 -7
  133. package/driver/datastax/search/date-range.js +0 -1
  134. package/driver/datastax/search/index.d.ts +0 -49
  135. package/driver/datastax/search/index.js +0 -1
  136. package/driver/geometry/geometry.js +0 -1
  137. package/driver/geometry/index.d.ts +0 -49
  138. package/driver/geometry/index.js +0 -1
  139. package/driver/geometry/line-string.js +0 -1
  140. package/driver/geometry/point.js +0 -1
  141. package/driver/geometry/polygon.js +0 -1
  142. package/driver/insights-client.js +0 -1
  143. package/driver/metrics/client-metrics.js +0 -1
  144. package/driver/metrics/default-metrics.js +0 -1
  145. package/driver/metrics/index.d.ts +0 -44
  146. package/driver/metrics/index.js +0 -1
  147. package/driver/tracker/index.d.ts +0 -45
  148. package/driver/tracker/index.js +0 -1
  149. package/driver/tracker/request-logger.js +0 -1
  150. package/driver/tracker/request-tracker.js +0 -1
@@ -1 +1 @@
1
- import e from"./promise-utils.js";import t from"./utils.js";import n from"./types/index.js";function r(e,n){if(typeof e!=`string`)throw TypeError(`Execution profile name must be a string`);n||=t.emptyObject;let r=n.graphOptions||t.emptyObject;this.name=e,this.consistency=n.consistency,this.loadBalancing=n.loadBalancing,this.readTimeout=n.readTimeout,this.retry=n.retry,this.serialConsistency=n.serialConsistency,this.graphOptions={language:r.language,results:r.results,name:r.name,readConsistency:r.readConsistency,source:r.source,writeConsistency:r.writeConsistency}}var i=class{constructor(e){this._profiles=e.profiles||[],this._defaultConfiguredRetryPolicy=void 0,this._setDefault(e),this._loadBalancingPolicies=[],this._profilesMap={},this._customPayloadCache={},this._graphOptionsCache={},this._profiles.forEach(function(e){return this._profilesMap[e.name]=e,e.loadBalancing=e.loadBalancing||this._defaultProfile.loadBalancing,this._loadBalancingPolicies.indexOf(e.loadBalancing)===-1&&this._loadBalancingPolicies.push(e.loadBalancing),e},this)}async init(t,n){for(let r of this._loadBalancingPolicies)await e.fromCallback(e=>r.init(t,n,e))}getDistance(e){let t=n.distance.ignored;for(let r=0;r<this._loadBalancingPolicies.length;r++){let i=this._loadBalancingPolicies[r].getDistance(e);if(i<t&&(t=i,t===n.distance.local))break}return e.setDistance(t),t}getProfile(e){return e instanceof r?e:this._profilesMap[e||`default`]}getDefault(){return this._defaultProfile}getDefaultLoadBalancing(){return this._defaultProfile.loadBalancing}getOrCreateGraphOptions(e,t){let n=this._graphOptionsCache[e.name];return n||=this._graphOptionsCache[e.name]=t(),n}_setDefault(e){this._defaultProfile=this._profiles.filter(function(e){return e.name===`default`})[0],this._defaultProfile||this._profiles.push(this._defaultProfile=new r(`default`)),this._defaultConfiguredRetryPolicy=this._defaultProfile.retry,this._defaultProfile.loadBalancing=this._defaultProfile.loadBalancing||e.policies.loadBalancing,this._defaultProfile.retry=this._defaultProfile.retry||e.policies.retry}getAll(){return this._profiles}getDefaultConfiguredRetryPolicy(){return this._defaultConfiguredRetryPolicy}};export{r as ExecutionProfile,i as ProfileManager};
1
+ import e from"./promise-utils.js";import t from"./utils.js";import n from"./types/index.js";function ExecutionProfile(e,n){if(typeof e!=`string`)throw TypeError(`Execution profile name must be a string`);n||=t.emptyObject;let r=n.graphOptions||t.emptyObject;this.name=e,this.consistency=n.consistency,this.loadBalancing=n.loadBalancing,this.readTimeout=n.readTimeout,this.retry=n.retry,this.serialConsistency=n.serialConsistency,this.graphOptions={language:r.language,results:r.results,name:r.name,readConsistency:r.readConsistency,source:r.source,writeConsistency:r.writeConsistency}}var ProfileManager=class{constructor(e){this._profiles=e.profiles||[],this._defaultConfiguredRetryPolicy=void 0,this._setDefault(e),this._loadBalancingPolicies=[],this._profilesMap={},this._customPayloadCache={},this._graphOptionsCache={},this._profiles.forEach(function(e){return this._profilesMap[e.name]=e,e.loadBalancing=e.loadBalancing||this._defaultProfile.loadBalancing,this._loadBalancingPolicies.indexOf(e.loadBalancing)===-1&&this._loadBalancingPolicies.push(e.loadBalancing),e},this)}async init(t,n){for(let r of this._loadBalancingPolicies)await e.fromCallback(e=>r.init(t,n,e))}getDistance(e){let t=n.distance.ignored;for(let r=0;r<this._loadBalancingPolicies.length;r++){let i=this._loadBalancingPolicies[r].getDistance(e);if(i<t&&(t=i,t===n.distance.local))break}return e.setDistance(t),t}getProfile(e){return e instanceof ExecutionProfile?e:this._profilesMap[e||`default`]}getDefault(){return this._defaultProfile}getDefaultLoadBalancing(){return this._defaultProfile.loadBalancing}getOrCreateGraphOptions(e,t){let n=this._graphOptionsCache[e.name];return n||=this._graphOptionsCache[e.name]=t(),n}_setDefault(e){this._defaultProfile=this._profiles.filter(function(e){return e.name===`default`})[0],this._defaultProfile||this._profiles.push(this._defaultProfile=new ExecutionProfile(`default`)),this._defaultConfiguredRetryPolicy=this._defaultProfile.retry,this._defaultProfile.loadBalancing=this._defaultProfile.loadBalancing||e.policies.loadBalancing,this._defaultProfile.retry=this._defaultProfile.retry||e.policies.retry}getAll(){return this._profiles}getDefaultConfiguredRetryPolicy(){return this._defaultConfiguredRetryPolicy}};export{ExecutionProfile,ProfileManager};
@@ -1 +1 @@
1
- import e from"./errors.js";import t from"./promise-utils.js";import n from"./utils.js";import r from"./client-options.js";import i from"./connection.js";import a from"util";import o from"events";let s=0;const c=2**15;let l;const u={initial:0,closing:1,shuttingDown:2,shutDown:4};var d=class r extends o.EventEmitter{constructor(e,t){super(),this._address=e.address,this._newConnectionTimeout=null,this._state=u.initial,this._opening=!1,this._host=e,this.responseCounter=0,this.options=e.options,this.protocolVersion=t,this.coreConnectionsLength=1,this.connections=n.emptyArray,this.setMaxListeners(0),this.log=n.log}getInFlight(){let e=this.connections.length;if(e===1)return this.connections[0].getInFlight();let t=0;for(let n=0;n<e;n++)t+=this.connections[n].getInFlight();return t}borrowConnection(t){if(this.connections.length===0)throw Error(`No connection available`);let n=this.options.pooling.maxRequestsPerConnection,i=r.minInFlight(this.connections,n,t);if(i.getInFlight()>=n)throw new e.BusyConnectionError(this._address,n,this.connections.length);return i}static minInFlight(e,t,n){let r=e.length;if(r===1)return e[0];s++,s>=c&&(s=0);let i;for(let a=s;a<s+r;a++){i=e[a%r],i===n&&(i=e[++a%r]);let o=e[(a+1)%r];if(o===n&&(o=e[(a+2)%r]),o.getInFlight()<i.getInFlight()&&(i=o),i.getInFlight()<t)break}return i}async warmup(e){if(this.connections.length<this.coreConnectionsLength){for(;this.connections.length<this.coreConnectionsLength;)await this._attemptNewConnection();this.log(`info`,`Connection pool to host ${this._address} created with ${this.connections.length} connection(s)`)}else this.log(`info`,`Connection pool to host ${this._address} contains ${this.connections.length} connection(s)`);if(e)try{for(let t of this.connections)await t.changeKeyspace(e)}catch{this.log(`warning`,`Connection(s) to host ${this._address} could not be switched to keyspace ${e}`)}}_createConnection(){let e=new i(this.options.sni?this._host.hostId.toString():this._address,this.protocolVersion,this.options);return this._addListeners(e),e}_addListeners(e){e.on(`responseDequeued`,()=>this.responseCounter++);let t=this;function n(){t.remove(e)}e.on(`idleRequestError`,n),e.on(`socketClose`,n)}addExistingConnection(e){this._addListeners(e),this.connections=this.connections.slice(0),this.connections.push(e)}clearNewConnectionAttempt(){this._newConnectionTimeout&&=(clearTimeout(this._newConnectionTimeout),null)}async _attemptNewConnection(){if(this._opening)return await t.fromEvent(this,`open`);this._opening=!0;let e=this._createConnection(),n;try{await e.openAsync()}catch(e){n=e,this.log(`warning`,`Connection to ${this._address} could not be created: ${n}`,n)}if(this.isClosing()&&(this.log(`info`,`Connection to ${this._address} opened successfully but pool was being closed`),n=Error(`Connection closed`)),n)t.toBackground(e.closeAsync());else{let t=this.connections.slice(0);t.push(e),this.connections=t,this.log(`info`,`Connection to ${this._address} opened successfully`)}if(this._opening=!1,this.emit(`open`,n,e),n)throw n}attemptNewConnectionImmediate(){let e=this;function t(){e.clearNewConnectionAttempt(),e.scheduleNewConnectionAttempt(0)}if(this._state===u.initial)return t();if(this._state===u.closing)return this.once(`close`,t)}remove(e){let t=this.connections.indexOf(e);if(t<0)return;let n=this.connections.slice(0);n.splice(t,1),this.connections=n,setImmediate(function(){e.close()}),this.emit(`remove`)}scheduleNewConnectionAttempt(e){if(this.isClosing())return;let n=this;this._newConnectionTimeout=setTimeout(function(){if(n._newConnectionTimeout=null,!(n.connections.length>=n.coreConnectionsLength)){if(e>0&&n.options.sni){t.toBackground(n.options.sni.addressResolver.refresh().then(()=>n._attemptNewConnection()));return}t.toBackground(n._attemptNewConnection())}},e)}hasScheduledNewConnection(){return!!this._newConnectionTimeout||this._opening}increaseSize(){this.connections.length<this.coreConnectionsLength&&!this.hasScheduledNewConnection()&&this.scheduleNewConnectionAttempt(0)}getAndResetResponseCounter(){let e=this.responseCounter;return this.responseCounter=0,e}isClosing(){return this._state!==u.initial}drainAndShutdown(){if(this.isClosing())return;if(this._state=u.closing,this.clearNewConnectionAttempt(),this.connections.length===0)return this._afterClosing();let e=this,t=this.connections;this.connections=n.emptyArray;let r=0;this.log(`info`,a.format(`Draining and closing %d connections to %s`,t.length,this._address));let i=!1,o;for(let e=0;e<t.length;e++){let n=t[e];if(n.getInFlight()===0){s(n)();continue}n.emitDrain=!0,n.once(`drain`,s(n))}function s(n){return function(){n.close(),!(++r<t.length)&&(i||(i=!0,o&&clearTimeout(o),e._afterClosing()))}}let c=(this.options.socketOptions.readTimeout||f().socketOptions.readTimeout)+100;o=setTimeout(function(){i=!0,t.forEach(function(e){e.close()}),e._afterClosing()},c)}_afterClosing(){let e=this;function t(){e._state===u.shuttingDown?e._state=u.shutDown:e._state=u.initial,e.emit(`close`),e._state===u.shutDown&&e.emit(`shutdown`)}if(this._opening)return this.once(`open`,t);t()}async shutdown(){if(this.clearNewConnectionAttempt(),!this.connections.length){this._state=u.shutDown;return}let e=this._state;if(this._state=u.shuttingDown,e===u.closing||e===u.shuttingDown)return t.fromEvent(this,`shutdown`);await this._closeAllConnections(),this._state=u.shutDown,this.emit(`shutdown`)}async _closeAllConnections(){let e=this.connections;this.connections=n.emptyArray,e.length!==0&&(this.log(`info`,a.format(`Closing %d connections to %s`,e.length,this._address)),await Promise.all(e.map(e=>e.closeAsync())))}};function f(){return l===void 0&&(l=r.defaultOptions()),l}export{d as default};
1
+ import e from"./errors.js";import t from"./promise-utils.js";import n from"./utils.js";import r from"./client-options.js";import i from"./connection.js";import a from"util";import o from"events";let s=0;const c=2**15;let l;const u={initial:0,closing:1,shuttingDown:2,shutDown:4};var d=class HostConnectionPool extends o.EventEmitter{constructor(e,t){super(),this._address=e.address,this._newConnectionTimeout=null,this._state=u.initial,this._opening=!1,this._host=e,this.responseCounter=0,this.options=e.options,this.protocolVersion=t,this.coreConnectionsLength=1,this.connections=n.emptyArray,this.setMaxListeners(0),this.log=n.log}getInFlight(){let e=this.connections.length;if(e===1)return this.connections[0].getInFlight();let t=0;for(let n=0;n<e;n++)t+=this.connections[n].getInFlight();return t}borrowConnection(t){if(this.connections.length===0)throw Error(`No connection available`);let n=this.options.pooling.maxRequestsPerConnection,r=HostConnectionPool.minInFlight(this.connections,n,t);if(r.getInFlight()>=n)throw new e.BusyConnectionError(this._address,n,this.connections.length);return r}static minInFlight(e,t,n){let r=e.length;if(r===1)return e[0];s++,s>=c&&(s=0);let i;for(let a=s;a<s+r;a++){i=e[a%r],i===n&&(i=e[++a%r]);let o=e[(a+1)%r];if(o===n&&(o=e[(a+2)%r]),o.getInFlight()<i.getInFlight()&&(i=o),i.getInFlight()<t)break}return i}async warmup(e){if(this.connections.length<this.coreConnectionsLength){for(;this.connections.length<this.coreConnectionsLength;)await this._attemptNewConnection();this.log(`info`,`Connection pool to host ${this._address} created with ${this.connections.length} connection(s)`)}else this.log(`info`,`Connection pool to host ${this._address} contains ${this.connections.length} connection(s)`);if(e)try{for(let t of this.connections)await t.changeKeyspace(e)}catch{this.log(`warning`,`Connection(s) to host ${this._address} could not be switched to keyspace ${e}`)}}_createConnection(){let e=new i(this.options.sni?this._host.hostId.toString():this._address,this.protocolVersion,this.options);return this._addListeners(e),e}_addListeners(e){e.on(`responseDequeued`,()=>this.responseCounter++);let t=this;function connectionErrorCallback(){t.remove(e)}e.on(`idleRequestError`,connectionErrorCallback),e.on(`socketClose`,connectionErrorCallback)}addExistingConnection(e){this._addListeners(e),this.connections=this.connections.slice(0),this.connections.push(e)}clearNewConnectionAttempt(){this._newConnectionTimeout&&=(clearTimeout(this._newConnectionTimeout),null)}async _attemptNewConnection(){if(this._opening)return await t.fromEvent(this,`open`);this._opening=!0;let e=this._createConnection(),n;try{await e.openAsync()}catch(e){n=e,this.log(`warning`,`Connection to ${this._address} could not be created: ${n}`,n)}if(this.isClosing()&&(this.log(`info`,`Connection to ${this._address} opened successfully but pool was being closed`),n=Error(`Connection closed`)),n)t.toBackground(e.closeAsync());else{let t=this.connections.slice(0);t.push(e),this.connections=t,this.log(`info`,`Connection to ${this._address} opened successfully`)}if(this._opening=!1,this.emit(`open`,n,e),n)throw n}attemptNewConnectionImmediate(){let e=this;function openConnection(){e.clearNewConnectionAttempt(),e.scheduleNewConnectionAttempt(0)}if(this._state===u.initial)return openConnection();if(this._state===u.closing)return this.once(`close`,openConnection)}remove(e){let t=this.connections.indexOf(e);if(t<0)return;let n=this.connections.slice(0);n.splice(t,1),this.connections=n,setImmediate(function(){e.close()}),this.emit(`remove`)}scheduleNewConnectionAttempt(e){if(this.isClosing())return;let n=this;this._newConnectionTimeout=setTimeout(function(){if(n._newConnectionTimeout=null,!(n.connections.length>=n.coreConnectionsLength)){if(e>0&&n.options.sni){t.toBackground(n.options.sni.addressResolver.refresh().then(()=>n._attemptNewConnection()));return}t.toBackground(n._attemptNewConnection())}},e)}hasScheduledNewConnection(){return!!this._newConnectionTimeout||this._opening}increaseSize(){this.connections.length<this.coreConnectionsLength&&!this.hasScheduledNewConnection()&&this.scheduleNewConnectionAttempt(0)}getAndResetResponseCounter(){let e=this.responseCounter;return this.responseCounter=0,e}isClosing(){return this._state!==u.initial}drainAndShutdown(){if(this.isClosing())return;if(this._state=u.closing,this.clearNewConnectionAttempt(),this.connections.length===0)return this._afterClosing();let e=this,t=this.connections;this.connections=n.emptyArray;let r=0;this.log(`info`,a.format(`Draining and closing %d connections to %s`,t.length,this._address));let i=!1,o;for(let e=0;e<t.length;e++){let n=t[e];if(n.getInFlight()===0){getDelayedClose(n)();continue}n.emitDrain=!0,n.once(`drain`,getDelayedClose(n))}function getDelayedClose(n){return function(){n.close(),!(++r<t.length)&&(i||(i=!0,o&&clearTimeout(o),e._afterClosing()))}}let s=(this.options.socketOptions.readTimeout||getDefaultOptions().socketOptions.readTimeout)+100;o=setTimeout(function(){i=!0,t.forEach(function(e){e.close()}),e._afterClosing()},s)}_afterClosing(){let e=this;function resetState(){e._state===u.shuttingDown?e._state=u.shutDown:e._state=u.initial,e.emit(`close`),e._state===u.shutDown&&e.emit(`shutdown`)}if(this._opening)return this.once(`open`,resetState);resetState()}async shutdown(){if(this.clearNewConnectionAttempt(),!this.connections.length){this._state=u.shutDown;return}let e=this._state;if(this._state=u.shuttingDown,e===u.closing||e===u.shuttingDown)return t.fromEvent(this,`shutdown`);await this._closeAllConnections(),this._state=u.shutDown,this.emit(`shutdown`)}async _closeAllConnections(){let e=this.connections;this.connections=n.emptyArray,e.length!==0&&(this.log(`info`,a.format(`Closing %d connections to %s`,e.length,this._address)),await Promise.all(e.map(e=>e.closeAsync())))}};function getDefaultOptions(){return l===void 0&&(l=r.defaultOptions()),l}export{d as default};
package/driver/host.js CHANGED
@@ -1 +1 @@
1
- import e from"./promise-utils.js";import t from"./utils.js";import n from"./types/index.js";import r from"./host-connection-pool.js";import i from"./prepare-handler.js";import a from"events";var o=class extends a.EventEmitter{constructor(i,a,o,s){super(),this.address=i,this.setDownAt=0,this.log=t.log,this.isUpSince=null,Object.defineProperty(this,`options`,{value:o,enumerable:!1,writable:!1}),Object.defineProperty(this,`pool`,{value:new r(this,a),enumerable:!1}),this.pool.on(`open`,t=>e.toBackground(this._onNewConnectionOpen(t))),this.pool.on(`remove`,()=>this._checkPoolState()),this.cassandraVersion=null,this.datacenter=null,this.rack=null,this.tokens=null,this.hostId=null,this.dseVersion=null,this.workloads=t.emptyArray,this._distance=n.distance.ignored,this._healthResponseCounter=0,Object.defineProperty(this,`_metadata`,{value:s,enumerable:!1}),Object.defineProperty(this,`_healthResponseCountTimer`,{value:null,enumerable:!1,writable:!0}),this.reconnectionSchedule=this.options.policies.reconnection.newSchedule(),this.reconnectionDelay=0}setDown(){this.setDownAt===0&&(this.pool.isClosing()||(this.setDownAt=Date.now(),this.pool.coreConnectionsLength>0?this.log(`warning`,`Host ${this.address} considered as DOWN. Reconnection delay ${this.reconnectionDelay}ms.`):this.log(`info`,`Host ${this.address} considered as DOWN.`),this.emit(`down`),this._checkPoolState()))}setUp(e){this.setDownAt&&(this.log(`info`,`Setting host ${this.address} as UP`),this.setDownAt=0,this.isUpSince=Date.now(),this.reconnectionSchedule=this.options.policies.reconnection.newSchedule(),e&&this.pool.clearNewConnectionAttempt(),this.emit(`up`))}checkIsUp(){this.isUp()||(this.reconnectionSchedule=this.options.policies.reconnection.newSchedule(),this.reconnectionDelay=0,this.pool.attemptNewConnectionImmediate())}shutdown(e){return this._healthResponseCountTimer&&clearInterval(this._healthResponseCountTimer),e?(this.pool.drainAndShutdown(),Promise.resolve()):this.pool.shutdown()}isUp(){return!this.setDownAt}canBeConsideredAsUp(){let e=this;function t(){return new Date().getTime()-e.setDownAt>=e.reconnectionDelay}return!this.setDownAt||t()}setDistance(e){let t=this._distance;return this._distance=e||n.distance.local,this.options.pooling.coreConnectionsPerHost?this.pool.coreConnectionsLength=this.options.pooling.coreConnectionsPerHost[this._distance]||0:this.pool.coreConnectionsLength=1,this._distance===t?this._distance:(this._healthResponseCountTimer&&clearInterval(this._healthResponseCountTimer),this._distance===n.distance.ignored?(this.emit(`ignore`),this.pool.drainAndShutdown()):(this.isUp()||this.checkIsUp(),this._healthResponseCountTimer=setInterval(()=>{this._healthResponseCounter=this.pool.getAndResetResponseCounter()},200)),this._distance)}setProtocolVersion(e){this.pool.protocolVersion=e}borrowConnection(e){return this.pool.borrowConnection(e)}warmupPool(e){return this.pool.warmup(e)}initializePool(){this.pool.increaseSize()}getActiveConnection(){return!this.isUp()||!this.pool.connections.length?null:this.pool.connections[0]}getResponseCount(){return this._healthResponseCounter+this.pool.responseCounter}checkHealth(e){e.timedOutOperations<=this.options.socketOptions.defunctReadTimeoutThreshold||this.removeFromPool(e)}removeFromPool(e){this.pool.remove(e),this._checkPoolState()}getInFlight(){return this.pool.getInFlight()}_checkPoolState(){this.pool.isClosing()||(this.pool.connections.length<this.pool.coreConnectionsLength&&(this.pool.hasScheduledNewConnection()||(this.reconnectionDelay=this.reconnectionSchedule.next().value,this.pool.scheduleNewConnectionAttempt(this.reconnectionDelay))),this._distance!==n.distance.ignored&&this.pool.coreConnectionsLength>0&&this.pool.connections.length===0&&this.setDown())}async _onNewConnectionOpen(e){if(e){this._checkPoolState();return}if(!this.isUp()&&this.options.rePrepareOnUp){this.log(`info`,`Re-preparing all queries on host ${this.address} before setting it as UP`);let e=this._metadata.getAllPrepared();try{await i.prepareAllQueries(this,e)}catch(e){this.log(`warning`,`Failed re-preparing on host ${this.address}: ${e}`,e)}}this.setUp(),this.pool.increaseSize()}getCassandraVersion(){return this.cassandraVersion?this.cassandraVersion.split(`-`)[0].split(`.`).map(e=>parseInt(e,10)):t.emptyArray}getDseVersion(){return this.dseVersion?this.dseVersion.split(`-`)[0].split(`.`).map(e=>parseInt(e,10)):t.emptyArray}},s=class extends a.EventEmitter{constructor(){super(),this._items=new Map,this._values=null,Object.defineProperty(this,`length`,{get:()=>this.values().length,enumerable:!0})}forEach(e){let t=this._items;for(let[n,r]of t)e(r,n)}get(e){return this._items.get(e)}keys(){return Array.from(this._items.keys())}remove(e){let t=this._items.get(e);if(t===void 0)return;this._values=null;let n=new Map(this._items);n.delete(e),this._items=n,this.emit(`remove`,t)}removeMultiple(e){this._values=null;let t=new Map(this._items),n=[];for(let r of e){let e=t.get(r);e&&(n.push(e),t.delete(r))}this._items=t,n.forEach(e=>this.emit(`remove`,e))}set(e,t){this._values=null;let n=this._items.get(e);if(n){this._items.set(e,t),this.emit(`remove`,n),this.emit(`add`,t);return}let r=new Map(this._items);return r.set(e,t),this._items=r,this.emit(`add`,t),t}slice(e,t){return!e&&!t?this.values():this.values().slice(e||0,t)}push(e,t){this.set(e,t)}values(){return this._values||=Object.freeze(Array.from(this._items.values())),this._values}clear(){let e=this.values();return this._values=null,this._items=new Map,e.forEach(e=>this.emit(`remove`,e)),e}inspect(){return this._items}toJSON(){if(Object.fromEntries)return Object.fromEntries(this._items);let e={};for(let[t,n]of this._items)e[t]=n;return e}};export{o as Host,s as HostMap};
1
+ import e from"./promise-utils.js";import t from"./utils.js";import n from"./types/index.js";import r from"./host-connection-pool.js";import i from"./prepare-handler.js";import a from"events";var Host=class extends a.EventEmitter{constructor(i,a,o,s){super(),this.address=i,this.setDownAt=0,this.log=t.log,this.isUpSince=null,Object.defineProperty(this,`options`,{value:o,enumerable:!1,writable:!1}),Object.defineProperty(this,`pool`,{value:new r(this,a),enumerable:!1}),this.pool.on(`open`,t=>e.toBackground(this._onNewConnectionOpen(t))),this.pool.on(`remove`,()=>this._checkPoolState()),this.cassandraVersion=null,this.datacenter=null,this.rack=null,this.tokens=null,this.hostId=null,this.dseVersion=null,this.workloads=t.emptyArray,this._distance=n.distance.ignored,this._healthResponseCounter=0,Object.defineProperty(this,`_metadata`,{value:s,enumerable:!1}),Object.defineProperty(this,`_healthResponseCountTimer`,{value:null,enumerable:!1,writable:!0}),this.reconnectionSchedule=this.options.policies.reconnection.newSchedule(),this.reconnectionDelay=0}setDown(){this.setDownAt===0&&(this.pool.isClosing()||(this.setDownAt=Date.now(),this.pool.coreConnectionsLength>0?this.log(`warning`,`Host ${this.address} considered as DOWN. Reconnection delay ${this.reconnectionDelay}ms.`):this.log(`info`,`Host ${this.address} considered as DOWN.`),this.emit(`down`),this._checkPoolState()))}setUp(e){this.setDownAt&&(this.log(`info`,`Setting host ${this.address} as UP`),this.setDownAt=0,this.isUpSince=Date.now(),this.reconnectionSchedule=this.options.policies.reconnection.newSchedule(),e&&this.pool.clearNewConnectionAttempt(),this.emit(`up`))}checkIsUp(){this.isUp()||(this.reconnectionSchedule=this.options.policies.reconnection.newSchedule(),this.reconnectionDelay=0,this.pool.attemptNewConnectionImmediate())}shutdown(e){return this._healthResponseCountTimer&&clearInterval(this._healthResponseCountTimer),e?(this.pool.drainAndShutdown(),Promise.resolve()):this.pool.shutdown()}isUp(){return!this.setDownAt}canBeConsideredAsUp(){let e=this;function hasTimePassed(){return new Date().getTime()-e.setDownAt>=e.reconnectionDelay}return!this.setDownAt||hasTimePassed()}setDistance(e){let t=this._distance;return this._distance=e||n.distance.local,this.options.pooling.coreConnectionsPerHost?this.pool.coreConnectionsLength=this.options.pooling.coreConnectionsPerHost[this._distance]||0:this.pool.coreConnectionsLength=1,this._distance===t?this._distance:(this._healthResponseCountTimer&&clearInterval(this._healthResponseCountTimer),this._distance===n.distance.ignored?(this.emit(`ignore`),this.pool.drainAndShutdown()):(this.isUp()||this.checkIsUp(),this._healthResponseCountTimer=setInterval(()=>{this._healthResponseCounter=this.pool.getAndResetResponseCounter()},200)),this._distance)}setProtocolVersion(e){this.pool.protocolVersion=e}borrowConnection(e){return this.pool.borrowConnection(e)}warmupPool(e){return this.pool.warmup(e)}initializePool(){this.pool.increaseSize()}getActiveConnection(){return!this.isUp()||!this.pool.connections.length?null:this.pool.connections[0]}getResponseCount(){return this._healthResponseCounter+this.pool.responseCounter}checkHealth(e){e.timedOutOperations<=this.options.socketOptions.defunctReadTimeoutThreshold||this.removeFromPool(e)}removeFromPool(e){this.pool.remove(e),this._checkPoolState()}getInFlight(){return this.pool.getInFlight()}_checkPoolState(){this.pool.isClosing()||(this.pool.connections.length<this.pool.coreConnectionsLength&&(this.pool.hasScheduledNewConnection()||(this.reconnectionDelay=this.reconnectionSchedule.next().value,this.pool.scheduleNewConnectionAttempt(this.reconnectionDelay))),this._distance!==n.distance.ignored&&this.pool.coreConnectionsLength>0&&this.pool.connections.length===0&&this.setDown())}async _onNewConnectionOpen(e){if(e){this._checkPoolState();return}if(!this.isUp()&&this.options.rePrepareOnUp){this.log(`info`,`Re-preparing all queries on host ${this.address} before setting it as UP`);let e=this._metadata.getAllPrepared();try{await i.prepareAllQueries(this,e)}catch(e){this.log(`warning`,`Failed re-preparing on host ${this.address}: ${e}`,e)}}this.setUp(),this.pool.increaseSize()}getCassandraVersion(){return this.cassandraVersion?this.cassandraVersion.split(`-`)[0].split(`.`).map(e=>parseInt(e,10)):t.emptyArray}getDseVersion(){return this.dseVersion?this.dseVersion.split(`-`)[0].split(`.`).map(e=>parseInt(e,10)):t.emptyArray}},HostMap=class extends a.EventEmitter{constructor(){super(),this._items=new Map,this._values=null,Object.defineProperty(this,`length`,{get:()=>this.values().length,enumerable:!0})}forEach(e){let t=this._items;for(let[n,r]of t)e(r,n)}get(e){return this._items.get(e)}keys(){return Array.from(this._items.keys())}remove(e){let t=this._items.get(e);if(t===void 0)return;this._values=null;let n=new Map(this._items);n.delete(e),this._items=n,this.emit(`remove`,t)}removeMultiple(e){this._values=null;let t=new Map(this._items),n=[];for(let r of e){let e=t.get(r);e&&(n.push(e),t.delete(r))}this._items=t,n.forEach(e=>this.emit(`remove`,e))}set(e,t){this._values=null;let n=this._items.get(e);if(n){this._items.set(e,t),this.emit(`remove`,n),this.emit(`add`,t);return}let r=new Map(this._items);return r.set(e,t),this._items=r,this.emit(`add`,t),t}slice(e,t){return!e&&!t?this.values():this.values().slice(e||0,t)}push(e,t){this.set(e,t)}values(){return this._values||=Object.freeze(Array.from(this._items.values())),this._values}clear(){let e=this.values();return this._values=null,this._items=new Map,e.forEach(e=>this.emit(`remove`,e)),e}inspect(){return this._items}toJSON(){if(Object.fromEntries)return Object.fromEntries(this._items);let e={};for(let[t,n]of this._items)e[t]=n;return e}};export{Host,HostMap};
package/driver/index.d.ts CHANGED
@@ -1,18 +1,12 @@
1
1
  import { auth } from "./auth/index.js";
2
2
  import { types } from "./types/index.js";
3
3
  import { policies } from "./policies/index.js";
4
- import { metrics } from "./metrics/index.js";
5
- import { tracker } from "./tracker/index.js";
6
4
  import { metadata } from "./metadata/index.js";
7
- import { concurrent } from "./concurrent/index.js";
8
5
  import { mapping } from "./mapping/index.js";
9
- import { geometry } from "./geometry/index.js";
10
6
  import * as events$1 from "events";
11
7
  import * as tls$1 from "tls";
12
8
 
13
9
  //#region src/driver/index.d.ts
14
- declare const version: number;
15
- declare function defaultOptions(): ClientOptions;
16
10
  type ValueCallback<T> = (err: Error, val: T) => void;
17
11
  type EmptyCallback = (err: Error) => void;
18
12
  type ArrayOrObject = any[] | {
@@ -22,24 +16,14 @@ declare class Client extends events$1.EventEmitter {
22
16
  hosts: HostMap;
23
17
  keyspace: string;
24
18
  metadata: metadata.Metadata;
25
- metrics: metrics.ClientMetrics;
26
- constructor(options: DseClientOptions);
19
+ metrics: null;
20
+ constructor(options: ClientOptions);
27
21
  connect(): Promise<void>;
28
22
  connect(callback: EmptyCallback): void;
29
23
  execute(query: string, params?: ArrayOrObject, options?: QueryOptions): Promise<types.ResultSet>;
30
24
  execute(query: string, params: ArrayOrObject, options: QueryOptions, callback: ValueCallback<types.ResultSet>): void;
31
25
  execute(query: string, params: ArrayOrObject, callback: ValueCallback<types.ResultSet>): void;
32
26
  execute(query: string, callback: ValueCallback<types.ResultSet>): void;
33
- executeGraph(traversal: string, parameters: {
34
- [name: string]: any;
35
- } | undefined, options: GraphQueryOptions, callback: ValueCallback<graph.GraphResultSet>): void;
36
- executeGraph(traversal: string, parameters: {
37
- [name: string]: any;
38
- } | undefined, callback: ValueCallback<graph.GraphResultSet>): void;
39
- executeGraph(traversal: string, callback: ValueCallback<graph.GraphResultSet>): void;
40
- executeGraph(traversal: string, parameters?: {
41
- [name: string]: any;
42
- }, options?: GraphQueryOptions): Promise<graph.GraphResultSet>;
43
27
  eachRow(query: string, params: ArrayOrObject, options: QueryOptions, rowCallback: (n: number, row: types.Row) => void, callback?: ValueCallback<types.ResultSet>): void;
44
28
  eachRow(query: string, params: ArrayOrObject, rowCallback: (n: number, row: types.Row) => void, callback?: ValueCallback<types.ResultSet>): void;
45
29
  eachRow(query: string, rowCallback: (n: number, row: types.Row) => void): void;
@@ -124,7 +108,6 @@ interface ClientOptions {
124
108
  };
125
109
  isMetadataSyncEnabled?: boolean;
126
110
  maxPrepared?: number;
127
- metrics?: metrics.ClientMetrics;
128
111
  policies?: {
129
112
  addressResolution?: policies.addressResolution.AddressTranslator;
130
113
  loadBalancing?: policies.loadBalancing.LoadBalancingPolicy;
@@ -153,7 +136,6 @@ interface ClientOptions {
153
136
  queryOptions?: QueryOptions;
154
137
  refreshSchemaDelay?: number;
155
138
  rePrepareOnUp?: boolean;
156
- requestTracker?: tracker.RequestTracker;
157
139
  socketOptions?: {
158
140
  coalescingThreshold?: number;
159
141
  connectTimeout?: number;
@@ -189,30 +171,6 @@ interface QueryOptions {
189
171
  timestamp?: number | Long;
190
172
  traceQuery?: boolean;
191
173
  }
192
- interface DseClientOptions extends ClientOptions {
193
- id?: Uuid;
194
- applicationName?: string;
195
- applicationVersion?: string;
196
- monitorReporting?: {
197
- enabled?: boolean;
198
- };
199
- graphOptions?: GraphOptions;
200
- }
201
- interface GraphQueryOptions extends QueryOptions {
202
- graphLanguage?: string;
203
- graphName?: string;
204
- graphReadConsistency?: types.consistencies;
205
- graphSource?: string;
206
- graphWriteConsistency?: types.consistencies;
207
- }
208
- type GraphOptions = {
209
- language?: string;
210
- name?: string;
211
- readConsistency?: types.consistencies;
212
- readTimeout?: number;
213
- source?: string;
214
- writeConsistency?: types.consistencies;
215
- };
216
174
  declare class ExecutionProfile {
217
175
  consistency?: types.consistencies;
218
176
  loadBalancing?: policies.loadBalancing.LoadBalancingPolicy;
@@ -220,64 +178,14 @@ declare class ExecutionProfile {
220
178
  readTimeout?: number;
221
179
  retry?: policies.retry.RetryPolicy;
222
180
  serialConsistency?: types.consistencies;
223
- graphOptions?: {
224
- name?: string;
225
- language?: string;
226
- source?: string;
227
- readConsistency?: types.consistencies;
228
- writeConsistency?: types.consistencies;
229
- };
230
181
  constructor(name: string, options: {
231
182
  consistency?: types.consistencies;
232
183
  loadBalancing?: policies.loadBalancing.LoadBalancingPolicy;
233
184
  readTimeout?: number;
234
185
  retry?: policies.retry.RetryPolicy;
235
186
  serialConsistency?: types.consistencies;
236
- graphOptions?: {
237
- name?: string;
238
- language?: string;
239
- source?: string;
240
- readConsistency?: types.consistencies;
241
- writeConsistency?: types.consistencies;
242
- };
243
187
  });
244
188
  }
245
- declare namespace errors {
246
- class ArgumentError extends DriverError {
247
- constructor(message: string);
248
- }
249
- class AuthenticationError extends DriverError {
250
- constructor(message: string);
251
- }
252
- class BusyConnectionError extends DriverError {
253
- constructor(address: string, maxRequestsPerConnection: number, connectionLength: number);
254
- }
255
- class VIntOutOfRangeException extends DriverError {
256
- constructor(long: Long);
257
- }
258
- abstract class DriverError extends Error {
259
- info: string;
260
- constructor(message: string, constructor?: any);
261
- }
262
- class DriverInternalError extends DriverError {
263
- constructor(message: string);
264
- }
265
- class NoHostAvailableError extends DriverError {
266
- innerErrors: any;
267
- constructor(innerErrors: any, message?: string);
268
- }
269
- class NotSupportedError extends DriverError {
270
- constructor(message: string);
271
- }
272
- class OperationTimedOutError extends DriverError {
273
- host?: string;
274
- constructor(message: string, host?: string);
275
- }
276
- class ResponseError extends DriverError {
277
- code: number;
278
- constructor(code: number, message: string);
279
- }
280
- }
281
189
  declare namespace token {
282
190
  interface Token {
283
191
  compare(other: Token): number;
@@ -301,4 +209,4 @@ declare namespace token {
301
209
  }
302
210
  }
303
211
  //#endregion
304
- export { ArrayOrObject, Client, ClientOptions, DseClientOptions, EmptyCallback, ExecutionOptions, ExecutionProfile, GraphOptions, GraphQueryOptions, Host, HostMap, QueryOptions, ValueCallback, auth, concurrent, defaultOptions, errors, geometry, mapping, metadata, metrics, policies, token, tracker, types, version };
212
+ export { Client, ClientOptions, EmptyCallback, ExecutionOptions, Host, HostMap, ValueCallback, token };
package/driver/index.js CHANGED
@@ -1 +1 @@
1
- import e from"./errors.js";import t from"./types/index.js";import n from"./policies/index.js";import r from"./tracker/index.js";import i from"./metrics/index.js";import a from"./auth/index.js";import o from"./client-options.js";import{ExecutionProfile as s}from"./execution-profile.js";import{ExecutionOptions as c}from"./execution-options.js";import{version as l}from"../package.js";import{Token as u,TokenRange as d}from"./token.js";import f from"./geometry/index.js";import p from"./encoder.js";import m from"./metadata/index.js";import h from"./client.js";import g from"./mapping/index.js";import _ from"./concurrent/index.js";const v={Token:u,TokenRange:d},y={Metadata:m};function b(){return o.defaultOptions()}const x={Client:h,ExecutionProfile:s,ExecutionOptions:c,types:t,errors:e,policies:n,auth:a,mapping:g,tracker:r,metrics:i,concurrent:_,token:v,metadata:y,Encoder:p,geometry:f,defaultOptions:b,version:l};export{x as default};
1
+ import e from"./errors.js";import t from"./types/index.js";import n from"./policies/index.js";import r from"./auth/index.js";import i from"./client-options.js";import{ExecutionProfile as a}from"./execution-profile.js";import{ExecutionOptions as o}from"./execution-options.js";import{version as s}from"../package.js";import{Token as c,TokenRange as l}from"./token.js";import u from"./encoder.js";import d from"./metadata/index.js";import f from"./client.js";import p from"./mapping/index.js";import m from"./concurrent/index.js";const h={Token:c,TokenRange:l},g={Metadata:d};function defaultOptions(){return i.defaultOptions()}const _={Client:f,ExecutionProfile:a,ExecutionOptions:o,types:t,errors:e,policies:n,auth:r,mapping:p,concurrent:m,token:h,metadata:g,Encoder:u,defaultOptions,version:s};export{_ as default};
@@ -1 +1 @@
1
- import{QueryAssignment as e,QueryOperator as t}from"./q.js";var n=class n{static*getSelectKey(e,t,r){yield*n._yieldKeyAndOperators(e,t),yield*n._getSelectDocInfo(r)}static*getSelectAllKey(e){yield`root`,yield*n._getSelectDocInfo(e)}static*_getSelectDocInfo(e){if(e&&(e.fields&&e.fields.length>0&&(yield`|f|`,yield*e.fields),typeof e.limit==`number`&&(yield`|l|`),e.orderBy)){yield`|o|`;let t=Object.keys(e.orderBy);for(let n=0;n<t.length;n++){let r=t[n];yield r,yield e.orderBy[r]}}}static*getInsertKey(e,t){yield*e,t&&(t.fields&&t.fields.length>0&&(yield`|f|`,yield*t.fields),typeof t.ttl==`number`&&(yield`|t|`),t.ifNotExists&&(yield`|e|`))}static*getUpdateKey(e,t,r){yield*n._yieldKeyAndAllQs(e,t),r&&(r.fields&&r.fields.length>0&&(yield`|f|`,yield*r.fields),typeof r.ttl==`number`&&(yield`|t|`),r.ifExists&&(yield`|e|`),r.when&&(yield*n._yieldKeyAndOperators(Object.keys(r.when),r.when)))}static*getRemoveKey(e,t,r){yield*n._yieldKeyAndOperators(e,t),r&&(r.fields&&r.fields.length>0&&(yield`|f|`,yield*r.fields),r.ifExists&&(yield`|e|`),r.deleteOnlyColumns&&(yield`|dc|`),r.when&&(yield*n._yieldKeyAndOperators(Object.keys(r.when),r.when)))}static*_yieldKeyAndOperators(e,t){for(let r=0;r<e.length;r++){let i=e[r];yield i,yield*n._yieldOperators(t[i])}}static*_yieldOperators(e){e!=null&&e instanceof t&&(yield e.key,e.hasChildValues&&(yield*n._yieldOperators(e.value[0]),yield`|/|`,yield*n._yieldOperators(e.value[1])))}static*_yieldKeyAndAllQs(r,i){for(let a=0;a<r.length;a++){let o=r[a];yield o;let s=i[o];s!=null&&(s instanceof t?yield*n._yieldOperators(s):s instanceof e&&(yield s.sign,yield s.inverted))}}};export{n as default};
1
+ import{QueryAssignment as e,QueryOperator as t}from"./q.js";var n=class Cache{static*getSelectKey(e,t,n){yield*Cache._yieldKeyAndOperators(e,t),yield*Cache._getSelectDocInfo(n)}static*getSelectAllKey(e){yield`root`,yield*Cache._getSelectDocInfo(e)}static*_getSelectDocInfo(e){if(e&&(e.fields&&e.fields.length>0&&(yield`|f|`,yield*e.fields),typeof e.limit==`number`&&(yield`|l|`),e.orderBy)){yield`|o|`;let t=Object.keys(e.orderBy);for(let n=0;n<t.length;n++){let r=t[n];yield r,yield e.orderBy[r]}}}static*getInsertKey(e,t){yield*e,t&&(t.fields&&t.fields.length>0&&(yield`|f|`,yield*t.fields),typeof t.ttl==`number`&&(yield`|t|`),t.ifNotExists&&(yield`|e|`))}static*getUpdateKey(e,t,n){yield*Cache._yieldKeyAndAllQs(e,t),n&&(n.fields&&n.fields.length>0&&(yield`|f|`,yield*n.fields),typeof n.ttl==`number`&&(yield`|t|`),n.ifExists&&(yield`|e|`),n.when&&(yield*Cache._yieldKeyAndOperators(Object.keys(n.when),n.when)))}static*getRemoveKey(e,t,n){yield*Cache._yieldKeyAndOperators(e,t),n&&(n.fields&&n.fields.length>0&&(yield`|f|`,yield*n.fields),n.ifExists&&(yield`|e|`),n.deleteOnlyColumns&&(yield`|dc|`),n.when&&(yield*Cache._yieldKeyAndOperators(Object.keys(n.when),n.when)))}static*_yieldKeyAndOperators(e,t){for(let n=0;n<e.length;n++){let r=e[n];yield r,yield*Cache._yieldOperators(t[r])}}static*_yieldOperators(e){e!=null&&e instanceof t&&(yield e.key,e.hasChildValues&&(yield*Cache._yieldOperators(e.value[0]),yield`|/|`,yield*Cache._yieldOperators(e.value[1])))}static*_yieldKeyAndAllQs(n,r){for(let i=0;i<n.length;i++){let a=n[i];yield a;let o=r[a];o!=null&&(o instanceof t?yield*Cache._yieldOperators(o):o instanceof e&&(yield o.sign,yield o.inverted))}}};export{n as default};
@@ -1 +1 @@
1
- import e from"../errors.js";import t from"../utils.js";var n=class{static getPropertiesInfo(e,t,n,r){let i=e;return t&&t.fields&&t.fields.length>0&&(i=t.fields),i.map(e=>({propertyName:e,columnName:r.getColumnName(e),value:n[e],fromModel:r.getFromModelFn(e)}))}static adaptOrderBy(n,r){return!n||!n.orderBy?t.emptyArray:Object.keys(n.orderBy).map(t=>{let i=n.orderBy[t],a=typeof i==`string`?i.toUpperCase():i;if(a!==`ASC`&&a!==`DESC`)throw new e.ArgumentError(`Order must be either "ASC" or "DESC", obtained: `+i);return[r.getColumnName(t),a]})}static adaptOptions(e,t){let n={prepare:!0,executionProfile:void 0,timestamp:void 0,isIdempotent:t};return typeof e==`string`?n.executionProfile=e:e!=null&&(n.executionProfile=e.executionProfile,n.timestamp=e.timestamp,e.isIdempotent!==void 0&&(n.isIdempotent=e.isIdempotent)),n}static adaptAllOptions(e,t){let n={prepare:!0,executionProfile:void 0,fetchSize:void 0,pageState:void 0,timestamp:void 0,isIdempotent:void 0};return typeof e==`string`?n.executionProfile=e:e!=null&&(n.executionProfile=e.executionProfile,n.fetchSize=e.fetchSize,n.pageState=e.pageState,n.timestamp=e.timestamp,n.isIdempotent=e.isIdempotent),t&&(n.isIdempotent=!0),n}static adaptBatchOptions(e,t,n){let r={prepare:!0,executionProfile:void 0,timestamp:void 0,logged:void 0,isIdempotent:t,counter:n};return typeof e==`string`?r.executionProfile=e:e!=null&&(r.executionProfile=e.executionProfile,r.timestamp=e.timestamp,r.logged=e.logged!==!1,e.isIdempotent!==void 0&&(r.isIdempotent=e.isIdempotent)),r}};export{n as default};
1
+ import e from"../errors.js";import t from"../utils.js";var DocInfoAdapter=class{static getPropertiesInfo(e,t,n,r){let i=e;return t&&t.fields&&t.fields.length>0&&(i=t.fields),i.map(e=>({propertyName:e,columnName:r.getColumnName(e),value:n[e],fromModel:r.getFromModelFn(e)}))}static adaptOrderBy(n,r){return!n||!n.orderBy?t.emptyArray:Object.keys(n.orderBy).map(t=>{let i=n.orderBy[t],a=typeof i==`string`?i.toUpperCase():i;if(a!==`ASC`&&a!==`DESC`)throw new e.ArgumentError(`Order must be either "ASC" or "DESC", obtained: `+i);return[r.getColumnName(t),a]})}static adaptOptions(e,t){let n={prepare:!0,executionProfile:void 0,timestamp:void 0,isIdempotent:t};return typeof e==`string`?n.executionProfile=e:e!=null&&(n.executionProfile=e.executionProfile,n.timestamp=e.timestamp,e.isIdempotent!==void 0&&(n.isIdempotent=e.isIdempotent)),n}static adaptAllOptions(e,t){let n={prepare:!0,executionProfile:void 0,fetchSize:void 0,pageState:void 0,timestamp:void 0,isIdempotent:void 0};return typeof e==`string`?n.executionProfile=e:e!=null&&(n.executionProfile=e.executionProfile,n.fetchSize=e.fetchSize,n.pageState=e.pageState,n.timestamp=e.timestamp,n.isIdempotent=e.isIdempotent),t&&(n.isIdempotent=!0),n}static adaptBatchOptions(e,t,n){let r={prepare:!0,executionProfile:void 0,timestamp:void 0,logged:void 0,isIdempotent:t,counter:n};return typeof e==`string`?r.executionProfile=e:e!=null&&(r.executionProfile=e.executionProfile,r.timestamp=e.timestamp,r.logged=e.logged!==!1,e.isIdempotent!==void 0&&(r.isIdempotent=e.isIdempotent)),r}};export{DocInfoAdapter as default};
@@ -1 +1 @@
1
- import e from"../errors.js";import{ModelBatchItem as t}from"./model-batch-item.js";import n from"./model-mapper.js";import r from"./result-mapper.js";import i from"./result.js";import a from"./doc-info-adapter.js";import o from"./mapping-handler.js";import s from"./model-mapping-info.js";var c=class{constructor(e,t){if(!e)throw Error(`client must be defined`);this.client=e,this._modelMappingInfos=s.parse(t,e.keyspace),this._modelMappers=new Map}forModel(e){let t=this._modelMappers.get(e);if(t===void 0){let r=this._modelMappingInfos.get(e);if(r===void 0){if(!this.client.keyspace)throw Error(`No mapping information found for model '${e}'. Mapper is unable to create default mappings without setting the keyspace`);r=s.createDefault(e,this.client.keyspace),this.client.log(`info`,`Mapping information for model '${e}' not found, creating default mapping. Keyspace: ${r.keyspace}; Table: ${r.tables[0].name}.`)}else this.client.log(`info`,`Creating model mapper for '${e}' using mapping information. Keyspace: ${r.keyspace}; Table${r.tables.length>1?`s`:``}: ${r.tables.map(e=>e.name)}.`);t=new n(e,new o(this.client,r)),this._modelMappers.set(e,t)}return t}batch(n,o){if(!Array.isArray(n)||!(n.length>0))return Promise.reject(new e.ArgumentError(`First parameter items should be an Array with 1 or more ModelBatchItem instances`));let s=[],c=!0,l;return Promise.all(n.map(e=>e instanceof t?e.pushQueries(s).then(e=>{c&&=e.isIdempotent,l=e.isCounter}):Promise.reject(Error(`Batch items must be instances of ModelBatchItem, use modelMapper.batching object to create each item`)))).then(()=>this.client.batch(s,a.adaptBatchOptions(o,c,l))).then(e=>new i(e,n[0].getMappingInfo(),r.getMutationAdapter(e)))}};export{c as default};
1
+ import e from"../errors.js";import{ModelBatchItem as t}from"./model-batch-item.js";import n from"./model-mapper.js";import r from"./result-mapper.js";import i from"./result.js";import a from"./doc-info-adapter.js";import o from"./mapping-handler.js";import s from"./model-mapping-info.js";var Mapper=class{constructor(e,t){if(!e)throw Error(`client must be defined`);this.client=e,this._modelMappingInfos=s.parse(t,e.keyspace),this._modelMappers=new Map}forModel(e){let t=this._modelMappers.get(e);if(t===void 0){let r=this._modelMappingInfos.get(e);if(r===void 0){if(!this.client.keyspace)throw Error(`No mapping information found for model '${e}'. Mapper is unable to create default mappings without setting the keyspace`);r=s.createDefault(e,this.client.keyspace),this.client.log(`info`,`Mapping information for model '${e}' not found, creating default mapping. Keyspace: ${r.keyspace}; Table: ${r.tables[0].name}.`)}else this.client.log(`info`,`Creating model mapper for '${e}' using mapping information. Keyspace: ${r.keyspace}; Table${r.tables.length>1?`s`:``}: ${r.tables.map(e=>e.name)}.`);t=new n(e,new o(this.client,r)),this._modelMappers.set(e,t)}return t}batch(n,o){if(!Array.isArray(n)||!(n.length>0))return Promise.reject(new e.ArgumentError(`First parameter items should be an Array with 1 or more ModelBatchItem instances`));let s=[],c=!0,l;return Promise.all(n.map(e=>e instanceof t?e.pushQueries(s).then(e=>{c&&=e.isIdempotent,l=e.isCounter}):Promise.reject(Error(`Batch items must be instances of ModelBatchItem, use modelMapper.batching object to create each item`)))).then(()=>this.client.batch(s,a.adaptBatchOptions(o,c,l))).then(e=>new i(e,n[0].getMappingInfo(),r.getMutationAdapter(e)))}};export{Mapper as default};
@@ -1 +1 @@
1
- import e from"../utils.js";import t from"./tree.js";import n from"./cache.js";import r from"./query-generator.js";import i from"./result-mapper.js";import a from"./result.js";import o from"./object-selector.js";import s from"./doc-info-adapter.js";var c=class{constructor(e,n){this._client=e,this._cache={select:new t().on(`add`,e=>this._validateCacheLength(e)),selectAll:new t().on(`add`,e=>this._validateCacheLength(e)),insert:new t().on(`add`,e=>this._validateCacheLength(e)),update:new t().on(`add`,e=>this._validateCacheLength(e)),remove:new t().on(`add`,e=>this._validateCacheLength(e)),customQueries:new Map},this.info=n}getSelectExecutor(t,i,a){let c=Object.keys(t);if(c.length===0)return Promise.reject(Error(`Expected object with keys`));let l=n.getSelectKey(c,t,i),u=this._cache.select.getOrCreate(l,()=>({executor:null,resultAdapter:null}));if(u.executor!==null)return Promise.resolve(u.executor);let d=s.getPropertiesInfo(c,null,t,this.info),f=s.getPropertiesInfo(e.emptyArray,i,t,this.info),p=s.adaptOrderBy(i,this.info),m=i&&i.limit;return this._client.connect().then(()=>o.getForSelect(this._client,this.info,a,d,f,p)).then(e=>{let t=r.getSelect(e,this.info.keyspace,d,f,p,m),n=r.selectParamsGetter(d,m),i=this;return u.executor=function(e,r,a){return i._executeSelect(t,n,e,r,a,u)},u.executor})}getSelectAllExecutor(t){let i=n.getSelectAllKey(t),a=this._cache.selectAll.getOrCreate(i,()=>({executor:null,resultAdapter:null}));if(a.executor!==null)return a.executor;let c=s.getPropertiesInfo(e.emptyArray,t,e.emptyObject,this.info),l=s.adaptOrderBy(t,this.info),u=t&&t.limit,d=o.getForSelectAll(this.info),f=r.getSelect(d,this.info.keyspace,e.emptyArray,c,l,u),p=r.selectParamsGetter(e.emptyArray,u),m=this;return a.executor=function(e,t){return m._executeSelect(f,p,null,e,t,a)},a.executor}_executeSelect(e,t,n,r,o,c){let l=s.adaptAllOptions(o,!0);return this._client.execute(e,t(n,r,this.info),l).then(e=>(c.resultAdapter===null&&(c.resultAdapter=i.getSelectAdapter(this.info,e)),new a(e,this.info,c.resultAdapter)))}getInsertExecutor(e,t){let r=Object.keys(e);if(r.length===0)return Promise.reject(Error(`Expected object with keys`));let i=n.getInsertKey(r,t),a=this._cache.insert.getOrCreate(i,()=>({executor:null}));return a.executor===null?this.createInsertQueries(r,e,t).then(e=>e.length===1?this._setSingleExecutor(a,e[0]):this._setBatchExecutor(a,e)):Promise.resolve(a.executor)}createInsertQueries(e,t,n){let i=s.getPropertiesInfo(e,n,t,this.info),a=n&&n.ifNotExists;return this._client.connect().then(()=>o.getForInsert(this._client,this.info,i)).then(e=>{if(e.length>1&&a)throw Error(`Batch with ifNotExists conditions cannot span multiple tables`);return e.map(e=>r.getInsert(e,this.info.keyspace,i,n,a))})}getUpdateExecutor(e,t){let r=Object.keys(e);if(r.length===0)return Promise.reject(Error(`Expected object with keys`));let i=n.getUpdateKey(r,e,t),a=this._cache.update.getOrCreate(i,()=>({executor:null}));return a.executor===null?this.createUpdateQueries(r,e,t).then(e=>e.length===1?this._setSingleExecutor(a,e[0]):this._setBatchExecutor(a,e)):Promise.resolve(a.executor)}createUpdateQueries(t,n,i){let a=s.getPropertiesInfo(t,i,n,this.info),c=i&&i.ifExists,l=i&&i.when?s.getPropertiesInfo(Object.keys(i.when),null,i.when,this.info):e.emptyArray;if(l.length>0&&c)throw Error(`Both when and ifExists conditions can not be applied to the same statement`);return this._client.connect().then(()=>o.getForUpdate(this._client,this.info,a,l)).then(e=>{if(e.length>1&&(l.length>0||c))throw Error(`Batch with when or ifExists conditions cannot span multiple tables`);return e.map(e=>r.getUpdate(e,this.info.keyspace,a,i,l,c))})}getDeleteExecutor(e,t){let r=Object.keys(e);if(r.length===0)return Promise.reject(Error(`Expected object with keys`));let i=n.getRemoveKey(r,e,t),a=this._cache.remove.getOrCreate(i,()=>({executor:null}));return a.executor===null?this.createDeleteQueries(r,e,t).then(e=>e.length===1?this._setSingleExecutor(a,e[0]):this._setBatchExecutor(a,e)):Promise.resolve(a.executor)}createDeleteQueries(t,n,i){let a=s.getPropertiesInfo(t,i,n,this.info),c=i&&i.ifExists,l=i&&i.when?s.getPropertiesInfo(Object.keys(i.when),null,i.when,this.info):e.emptyArray;if(l.length>0&&c)throw Error(`Both when and ifExists conditions can not be applied to the same statement`);return this._client.connect().then(()=>o.getForDelete(this._client,this.info,a,l)).then(e=>{if(e.length>1&&(l.length>0||c))throw Error(`Batch with when or ifExists conditions cannot span multiple tables`);return e.map(e=>r.getDelete(e,this.info.keyspace,a,i,l,c))})}getExecutorFromQuery(e,t,n){let r=this,o=n?s.adaptAllOptions(n):null;return function(n,c){let l=o||s.adaptAllOptions(c);return r._client.execute(e,t(n),l).then(t=>{let n=r._cache.customQueries.get(e);if(n===void 0){let a=i.getCustomQueryAdapter(r.info,t);n=a.fn,a.canCache&&(r._cache.customQueries.set(e,n),r._cache.customQueries.size===100&&r._client.log(`warning`,`Custom queries cache reached 100 items, this could be caused by hard-coding parameter values inside the query, which should be avoided`))}return new a(t,r.info,n)})}}_setSingleExecutor(e,t){let n=this;return e.executor=function(e,r,o){let c=s.adaptOptions(o,t.isIdempotent);return n._client.execute(t.query,t.paramsGetter(e,r,n.info),c).then(e=>new a(e,n.info,i.getMutationAdapter(e)))},e.executor}_setBatchExecutor(e,t){let n=this,r=t.reduce((e,t)=>e&&t.isIdempotent,!0);return e.executor=function(e,o,c){let l=t.map(t=>({query:t.query,params:t.paramsGetter(e,o,n.info)})),u=s.adaptOptions(c,r);return n._client.batch(l,u).then(e=>new a(e,n.info,i.getMutationAdapter(e)))},e.executor}_validateCacheLength(e){e===100&&this._client.log(`warning`,`ModelMapper cache reached 100 items, this could be caused by building the object to map in different ways (with different shapes) each time. Use the same or few object structures for a model and represent unset values with undefined or types.unset`)}};export{c as default};
1
+ import e from"../utils.js";import t from"./tree.js";import n from"./cache.js";import r from"./query-generator.js";import i from"./result-mapper.js";import a from"./result.js";import o from"./object-selector.js";import s from"./doc-info-adapter.js";var MappingHandler=class{constructor(e,n){this._client=e,this._cache={select:new t().on(`add`,e=>this._validateCacheLength(e)),selectAll:new t().on(`add`,e=>this._validateCacheLength(e)),insert:new t().on(`add`,e=>this._validateCacheLength(e)),update:new t().on(`add`,e=>this._validateCacheLength(e)),remove:new t().on(`add`,e=>this._validateCacheLength(e)),customQueries:new Map},this.info=n}getSelectExecutor(t,i,a){let c=Object.keys(t);if(c.length===0)return Promise.reject(Error(`Expected object with keys`));let l=n.getSelectKey(c,t,i),u=this._cache.select.getOrCreate(l,()=>({executor:null,resultAdapter:null}));if(u.executor!==null)return Promise.resolve(u.executor);let d=s.getPropertiesInfo(c,null,t,this.info),f=s.getPropertiesInfo(e.emptyArray,i,t,this.info),p=s.adaptOrderBy(i,this.info),m=i&&i.limit;return this._client.connect().then(()=>o.getForSelect(this._client,this.info,a,d,f,p)).then(e=>{let t=r.getSelect(e,this.info.keyspace,d,f,p,m),n=r.selectParamsGetter(d,m),i=this;return u.executor=function(e,r,a){return i._executeSelect(t,n,e,r,a,u)},u.executor})}getSelectAllExecutor(t){let i=n.getSelectAllKey(t),a=this._cache.selectAll.getOrCreate(i,()=>({executor:null,resultAdapter:null}));if(a.executor!==null)return a.executor;let c=s.getPropertiesInfo(e.emptyArray,t,e.emptyObject,this.info),l=s.adaptOrderBy(t,this.info),u=t&&t.limit,d=o.getForSelectAll(this.info),f=r.getSelect(d,this.info.keyspace,e.emptyArray,c,l,u),p=r.selectParamsGetter(e.emptyArray,u),m=this;return a.executor=function(e,t){return m._executeSelect(f,p,null,e,t,a)},a.executor}_executeSelect(e,t,n,r,o,c){let l=s.adaptAllOptions(o,!0);return this._client.execute(e,t(n,r,this.info),l).then(e=>(c.resultAdapter===null&&(c.resultAdapter=i.getSelectAdapter(this.info,e)),new a(e,this.info,c.resultAdapter)))}getInsertExecutor(e,t){let r=Object.keys(e);if(r.length===0)return Promise.reject(Error(`Expected object with keys`));let i=n.getInsertKey(r,t),a=this._cache.insert.getOrCreate(i,()=>({executor:null}));return a.executor===null?this.createInsertQueries(r,e,t).then(e=>e.length===1?this._setSingleExecutor(a,e[0]):this._setBatchExecutor(a,e)):Promise.resolve(a.executor)}createInsertQueries(e,t,n){let i=s.getPropertiesInfo(e,n,t,this.info),a=n&&n.ifNotExists;return this._client.connect().then(()=>o.getForInsert(this._client,this.info,i)).then(e=>{if(e.length>1&&a)throw Error(`Batch with ifNotExists conditions cannot span multiple tables`);return e.map(e=>r.getInsert(e,this.info.keyspace,i,n,a))})}getUpdateExecutor(e,t){let r=Object.keys(e);if(r.length===0)return Promise.reject(Error(`Expected object with keys`));let i=n.getUpdateKey(r,e,t),a=this._cache.update.getOrCreate(i,()=>({executor:null}));return a.executor===null?this.createUpdateQueries(r,e,t).then(e=>e.length===1?this._setSingleExecutor(a,e[0]):this._setBatchExecutor(a,e)):Promise.resolve(a.executor)}createUpdateQueries(t,n,i){let a=s.getPropertiesInfo(t,i,n,this.info),c=i&&i.ifExists,l=i&&i.when?s.getPropertiesInfo(Object.keys(i.when),null,i.when,this.info):e.emptyArray;if(l.length>0&&c)throw Error(`Both when and ifExists conditions can not be applied to the same statement`);return this._client.connect().then(()=>o.getForUpdate(this._client,this.info,a,l)).then(e=>{if(e.length>1&&(l.length>0||c))throw Error(`Batch with when or ifExists conditions cannot span multiple tables`);return e.map(e=>r.getUpdate(e,this.info.keyspace,a,i,l,c))})}getDeleteExecutor(e,t){let r=Object.keys(e);if(r.length===0)return Promise.reject(Error(`Expected object with keys`));let i=n.getRemoveKey(r,e,t),a=this._cache.remove.getOrCreate(i,()=>({executor:null}));return a.executor===null?this.createDeleteQueries(r,e,t).then(e=>e.length===1?this._setSingleExecutor(a,e[0]):this._setBatchExecutor(a,e)):Promise.resolve(a.executor)}createDeleteQueries(t,n,i){let a=s.getPropertiesInfo(t,i,n,this.info),c=i&&i.ifExists,l=i&&i.when?s.getPropertiesInfo(Object.keys(i.when),null,i.when,this.info):e.emptyArray;if(l.length>0&&c)throw Error(`Both when and ifExists conditions can not be applied to the same statement`);return this._client.connect().then(()=>o.getForDelete(this._client,this.info,a,l)).then(e=>{if(e.length>1&&(l.length>0||c))throw Error(`Batch with when or ifExists conditions cannot span multiple tables`);return e.map(e=>r.getDelete(e,this.info.keyspace,a,i,l,c))})}getExecutorFromQuery(e,t,n){let r=this,o=n?s.adaptAllOptions(n):null;return function(n,c){let l=o||s.adaptAllOptions(c);return r._client.execute(e,t(n),l).then(t=>{let n=r._cache.customQueries.get(e);if(n===void 0){let a=i.getCustomQueryAdapter(r.info,t);n=a.fn,a.canCache&&(r._cache.customQueries.set(e,n),r._cache.customQueries.size===100&&r._client.log(`warning`,`Custom queries cache reached 100 items, this could be caused by hard-coding parameter values inside the query, which should be avoided`))}return new a(t,r.info,n)})}}_setSingleExecutor(e,t){let n=this;return e.executor=function(e,r,o){let c=s.adaptOptions(o,t.isIdempotent);return n._client.execute(t.query,t.paramsGetter(e,r,n.info),c).then(e=>new a(e,n.info,i.getMutationAdapter(e)))},e.executor}_setBatchExecutor(e,t){let n=this,r=t.reduce((e,t)=>e&&t.isIdempotent,!0);return e.executor=function(e,o,c){let l=t.map(t=>({query:t.query,params:t.paramsGetter(e,o,n.info)})),u=s.adaptOptions(c,r);return n._client.batch(l,u).then(e=>new a(e,n.info,i.getMutationAdapter(e)))},e.executor}_validateCacheLength(e){e===100&&this._client.log(`warning`,`ModelMapper cache reached 100 items, this could be caused by building the object to map in different ways (with different shapes) each time. Use the same or few object structures for a model and represent unset values with undefined or types.unset`)}};export{MappingHandler as default};
@@ -1 +1 @@
1
- import e from"./cache.js";var t=class{constructor(e,t,n,r){this.doc=e,this.docInfo=t,this.handler=n,this.cache=r}getQueries(){let e=Object.keys(this.doc),t=this.cache.getOrCreate(this.getCacheKey(e),()=>({queries:null}));return t.queries===null&&(t.queries=this.createQueries(e)),t.queries}getCacheKey(e){throw Error(`getCacheKey must be implemented`)}createQueries(e){throw Error(`getCacheKey must be implemented`)}pushQueries(e){let t=!0,n;return this.getQueries().then(r=>(r.forEach(r=>{t&&=r.isIdempotent,n=r.isCounter,e.push({query:r.query,params:r.paramsGetter(this.doc,this.docInfo,this.getMappingInfo())})}),{isIdempotent:t,isCounter:n}))}getMappingInfo(){return this.handler.info}},n=class extends t{constructor(e,t,n,r){super(e,t,n,r)}getCacheKey(t){return e.getInsertKey(t,this.docInfo)}createQueries(e){return this.handler.createInsertQueries(e,this.doc,this.docInfo)}},r=class extends t{constructor(e,t,n,r){super(e,t,n,r)}getCacheKey(t){return e.getUpdateKey(t,this.doc,this.docInfo)}createQueries(e){return this.handler.createUpdateQueries(e,this.doc,this.docInfo)}},i=class extends t{constructor(e,t,n,r){super(e,t,n,r)}getCacheKey(t){return e.getRemoveKey(t,this.doc,this.docInfo)}createQueries(e){return this.handler.createDeleteQueries(e,this.doc,this.docInfo)}};export{n as InsertModelBatchItem,t as ModelBatchItem,i as RemoveModelBatchItem,r as UpdateModelBatchItem};
1
+ import e from"./cache.js";var ModelBatchItem=class{constructor(e,t,n,r){this.doc=e,this.docInfo=t,this.handler=n,this.cache=r}getQueries(){let e=Object.keys(this.doc),t=this.cache.getOrCreate(this.getCacheKey(e),()=>({queries:null}));return t.queries===null&&(t.queries=this.createQueries(e)),t.queries}getCacheKey(e){throw Error(`getCacheKey must be implemented`)}createQueries(e){throw Error(`getCacheKey must be implemented`)}pushQueries(e){let t=!0,n;return this.getQueries().then(r=>(r.forEach(r=>{t&&=r.isIdempotent,n=r.isCounter,e.push({query:r.query,params:r.paramsGetter(this.doc,this.docInfo,this.getMappingInfo())})}),{isIdempotent:t,isCounter:n}))}getMappingInfo(){return this.handler.info}},InsertModelBatchItem=class extends ModelBatchItem{constructor(e,t,n,r){super(e,t,n,r)}getCacheKey(t){return e.getInsertKey(t,this.docInfo)}createQueries(e){return this.handler.createInsertQueries(e,this.doc,this.docInfo)}},UpdateModelBatchItem=class extends ModelBatchItem{constructor(e,t,n,r){super(e,t,n,r)}getCacheKey(t){return e.getUpdateKey(t,this.doc,this.docInfo)}createQueries(e){return this.handler.createUpdateQueries(e,this.doc,this.docInfo)}},RemoveModelBatchItem=class extends ModelBatchItem{constructor(e,t,n,r){super(e,t,n,r)}getCacheKey(t){return e.getRemoveKey(t,this.doc,this.docInfo)}createQueries(e){return this.handler.createDeleteQueries(e,this.doc,this.docInfo)}};export{InsertModelBatchItem,ModelBatchItem,RemoveModelBatchItem,UpdateModelBatchItem};
@@ -1 +1 @@
1
- import e from"./tree.js";import{InsertModelBatchItem as t,RemoveModelBatchItem as n,UpdateModelBatchItem as r}from"./model-batch-item.js";var i=class{constructor(t){this._handler=t,this._cache={insert:new e,update:new e,remove:new e}}insert(e,n){return new t(e,n,this._handler,this._cache.insert)}update(e,t){return new r(e,t,this._handler,this._cache.update)}remove(e,t){return new n(e,t,this._handler,this._cache.update)}};export{i as default};
1
+ import e from"./tree.js";import{InsertModelBatchItem as t,RemoveModelBatchItem as n,UpdateModelBatchItem as r}from"./model-batch-item.js";var ModelBatchMapper=class{constructor(t){this._handler=t,this._cache={insert:new e,update:new e,remove:new e}}insert(e,n){return new t(e,n,this._handler,this._cache.insert)}update(e,t){return new r(e,t,this._handler,this._cache.update)}remove(e,t){return new n(e,t,this._handler,this._cache.update)}};export{ModelBatchMapper as default};
@@ -1 +1 @@
1
- import e from"./model-batch-mapper.js";var t=class{constructor(t,n){this.name=t,this._handler=n,this.batching=new e(this._handler)}get(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getSelectExecutor(e,t,!0).then(r=>r(e,t,n)).then(e=>e.first())}find(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getSelectExecutor(e,t,!1).then(r=>r(e,t,n))}findAll(e,t){return t===void 0&&typeof e==`string`&&(t=e,e=null),this._handler.getSelectAllExecutor(e)(e,t)}insert(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getInsertExecutor(e,t).then(r=>r(e,t,n))}update(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getUpdateExecutor(e,t).then(r=>r(e,t,n))}remove(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getDeleteExecutor(e,t).then(r=>r(e,t,n))}mapWithQuery(e,t,n){return this._handler.getExecutorFromQuery(e,t,n)}};export{t as default};
1
+ import e from"./model-batch-mapper.js";var ModelMapper=class{constructor(t,n){this.name=t,this._handler=n,this.batching=new e(this._handler)}get(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getSelectExecutor(e,t,!0).then(r=>r(e,t,n)).then(e=>e.first())}find(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getSelectExecutor(e,t,!1).then(r=>r(e,t,n))}findAll(e,t){return t===void 0&&typeof e==`string`&&(t=e,e=null),this._handler.getSelectAllExecutor(e)(e,t)}insert(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getInsertExecutor(e,t).then(r=>r(e,t,n))}update(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getUpdateExecutor(e,t).then(r=>r(e,t,n))}remove(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getDeleteExecutor(e,t).then(r=>r(e,t,n))}mapWithQuery(e,t,n){return this._handler.getExecutorFromQuery(e,t,n)}};export{ModelMapper as default};
@@ -1 +1 @@
1
- import{DefaultTableMappings as e,TableMappings as t}from"./table-mappings.js";var n=class n{constructor(e,t,n,r){this.keyspace=e,this.tables=t,this._mappings=n,this._columns=r,this._documentProperties=new Map;for(let e of r.values())this._documentProperties.set(e.propertyName,e)}getColumnName(e){let t=this._documentProperties.get(e);return t===void 0?this._mappings.getColumnName(e):t.columnName}getPropertyName(e){let t=this._columns.get(e);return t===void 0?this._mappings.getPropertyName(e):t.propertyName}getFromModelFn(e){let t=this._documentProperties.get(e);return t===void 0?null:t.fromModel}getToModelFn(e){let t=this._columns.get(e);return t===void 0?null:t.toModel}newInstance(){return this._mappings.newObjectInstance()}static parse(e,t){let r=new Map;return!e||!e.models||Object.keys(e.models).forEach(i=>{let a=e.models[i];r.set(i,n._create(i,t,a))}),r}static _create(i,a,o){if(!a&&(!o||!o.keyspace))throw Error(`You should specify the keyspace of the model in the MappingOptions when the Client is not using a keyspace`);if(!o)return n.createDefault(i,a);let s;if(s=o.tables&&o.tables.length>0?o.tables.map(e=>{let t={name:null,isView:!1};if(typeof e==`string`?t.name=e:e&&(t.name=e.name,t.isView=!!e.isView),!t.name)throw Error(`Table name not specified for model '${i}'`);return t}):[{name:i,isView:!1}],o.mappings&&!(o.mappings instanceof t))throw Error(`mappings should be an instance of TableMappings`);let c=new Map;return o.columns!==null&&typeof o.columns==`object`&&Object.keys(o.columns).forEach(e=>{c.set(e,r.parse(e,o.columns[e]))}),new n(o.keyspace||a,s,o.mappings||new e,c)}static createDefault(t,r){return new n(r,[{name:t,isView:!1}],new e,new Map)}},r=class e{constructor(e,t,n,r){if(this.columnName=e,this.propertyName=t,n&&typeof n!=`function`)throw TypeError(`toModel type for property '${t}' should be a function (obtained ${typeof n})`);if(r&&typeof r!=`function`)throw TypeError(`fromModel type for property '${t}' should be a function (obtained ${typeof r})`);this.toModel=n,this.fromModel=r}static parse(t,n){return n?typeof n==`string`?new e(t,n):new e(t,n.name||t,n.toModel,n.fromModel):new e(t,t)}};export{n as default};
1
+ import{DefaultTableMappings as e,TableMappings as t}from"./table-mappings.js";var n=class ModelMappingInfo{constructor(e,t,n,r){this.keyspace=e,this.tables=t,this._mappings=n,this._columns=r,this._documentProperties=new Map;for(let e of r.values())this._documentProperties.set(e.propertyName,e)}getColumnName(e){let t=this._documentProperties.get(e);return t===void 0?this._mappings.getColumnName(e):t.columnName}getPropertyName(e){let t=this._columns.get(e);return t===void 0?this._mappings.getPropertyName(e):t.propertyName}getFromModelFn(e){let t=this._documentProperties.get(e);return t===void 0?null:t.fromModel}getToModelFn(e){let t=this._columns.get(e);return t===void 0?null:t.toModel}newInstance(){return this._mappings.newObjectInstance()}static parse(e,t){let n=new Map;return!e||!e.models||Object.keys(e.models).forEach(r=>{let i=e.models[r];n.set(r,ModelMappingInfo._create(r,t,i))}),n}static _create(n,i,a){if(!i&&(!a||!a.keyspace))throw Error(`You should specify the keyspace of the model in the MappingOptions when the Client is not using a keyspace`);if(!a)return ModelMappingInfo.createDefault(n,i);let o;if(o=a.tables&&a.tables.length>0?a.tables.map(e=>{let t={name:null,isView:!1};if(typeof e==`string`?t.name=e:e&&(t.name=e.name,t.isView=!!e.isView),!t.name)throw Error(`Table name not specified for model '${n}'`);return t}):[{name:n,isView:!1}],a.mappings&&!(a.mappings instanceof t))throw Error(`mappings should be an instance of TableMappings`);let s=new Map;return a.columns!==null&&typeof a.columns==`object`&&Object.keys(a.columns).forEach(e=>{s.set(e,r.parse(e,a.columns[e]))}),new ModelMappingInfo(a.keyspace||i,o,a.mappings||new e,s)}static createDefault(t,n){return new ModelMappingInfo(n,[{name:t,isView:!1}],new e,new Map)}},r=class ModelColumnInfo{constructor(e,t,n,r){if(this.columnName=e,this.propertyName=t,n&&typeof n!=`function`)throw TypeError(`toModel type for property '${t}' should be a function (obtained ${typeof n})`);if(r&&typeof r!=`function`)throw TypeError(`fromModel type for property '${t}' should be a function (obtained ${typeof r})`);this.toModel=n,this.fromModel=r}static parse(e,t){return t?typeof t==`string`?new ModelColumnInfo(e,t):new ModelColumnInfo(e,t.name||e,t.toModel,t.fromModel):new ModelColumnInfo(e,e)}};export{n as default};
@@ -1 +1 @@
1
- const e={all:1,none:0,some:-1};var t=class{static getForSelect(t,i,a,o,s,c){return Promise.all(i.tables.map(e=>e.isView?t.metadata.getMaterializedView(i.keyspace,e.name):t.metadata.getTable(i.keyspace,e.name))).then(t=>{for(let l=0;l<t.length;l++){let u=t[l];if(u===null)throw Error(`Table "${i.tables[l].name}" could not be retrieved`);if(r(u.partitionKeys,o)===e.all&&!(a&&r(u.clusteringKeys,o)!==e.all)&&!(o.length>u.partitionKeys.length&&!o.reduce((e,t)=>e&&(n(u.partitionKeys,e=>e.name===t.columnName)||n(u.clusteringKeys,e=>e.name===t.columnName)),!0))&&s.reduce((e,t)=>e&&u.columnsByName[t.columnName]!==void 0,!0)&&c.reduce((e,t,n)=>{if(!e)return!1;let r=u.clusteringKeys[n];return r&&r.name===t[0]},!0))return u.name}let l=`No table matches the filter (${a?`all PKs have to be specified`:`PKs`}): [${o.map(e=>e.columnName)}]`;throw s.length>0&&(l+=`; fields: [${s.map(e=>e.columnName)}]`),c.length>0&&(l+=`; orderBy: [${c.map(e=>e[0])}]`),Error(l)})}static getForSelectAll(e){return e.tables[0].name}static getForInsert(t,n,i){return Promise.all(n.tables.filter(e=>!e.isView).map(e=>t.metadata.getTable(n.keyspace,e.name))).then(t=>{let o=t.filter((t,o)=>{if(t===null)throw Error(`Table "${n.tables[o].name}" could not be retrieved`);if(r(t.partitionKeys,i)!==e.all)return!1;let s=r(t.clusteringKeys,i);if(s===e.all)return!0;if(s===e.some)return!1;let c=a(t);return i.length===t.partitionKeys.length+c&&c>0});if(o.length===0)throw Error(`No table matches (all PKs have to be specified) fields: [${i.map(e=>e.columnName)}]`);return o})}static getForUpdate(t,n,a,o){return Promise.all(n.tables.filter(e=>!e.isView).map(e=>t.metadata.getTable(n.keyspace,e.name))).then(t=>{let s=t.filter((t,s)=>{if(t===null)throw Error(`Table "${n.tables[s].name}" could not be retrieved`);if(r(t.partitionKeys,a)!==e.all)return!1;let c=r(t.clusteringKeys,a);if(c===e.some||c===e.none&&!i(t))return!1;let l=a.reduce((e,n)=>e+(t.columnsByName[n.columnName]===void 0?0:1),0);return l<=t.partitionKeys.length+t.clusteringKeys.length&&(!i(t)||l<=t.partitionKeys.length)?!1:o.reduce((e,n)=>e&&t.columnsByName[n.columnName]!==void 0,!0)});if(s.length===0){let e=`No table matches (all PKs and columns to set have to be specified) fields: [${a.map(e=>e.columnName)}]`;throw o.length>0&&(e+=`; condition: [${o.map(e=>e.columnName)}]`),Error(e)}return s})}static getForDelete(e,t,n,r){return Promise.all(t.tables.filter(e=>!e.isView).map(n=>e.metadata.getTable(t.keyspace,n.name))).then(e=>{let i=e.filter((e,i)=>{if(e===null)throw Error(`Table "${t.tables[i].name}" could not be retrieved`);let a=e.partitionKeys.concat(e.clusteringKeys).map(e=>e.name),o=n.map(e=>e.columnName);for(let e=0;e<a.length;e++)if(o.indexOf(a[e])===-1)return!1;return r.reduce((t,n)=>t&&e.columnsByName[n.columnName]!==void 0,!0)});if(i.length===0){let e=`No table matches (all PKs have to be specified) fields: [${n.map(e=>e.columnName)}]`;throw r.length>0&&(e+=`; condition: [${r.map(e=>e.columnName)}]`),Error(e)}return i})}};function n(e,t){return e.filter(t).length>0}function r(t,r){if(t.length===0)return e.all;let i=r.reduce((e,r)=>e+ +!!n(t,e=>r.columnName===e.name),0);return i===0?e.none:i===t.length?e.all:e.some}function i(e){return a(e)>0}function a(e){return e.columns.reduce((e,t)=>e+ +!!t.isStatic,0)}export{t as default};
1
+ const e={all:1,none:0,some:-1};var ObjectSelector=class{static getForSelect(t,n,r,i,a,o){return Promise.all(n.tables.map(e=>e.isView?t.metadata.getMaterializedView(n.keyspace,e.name):t.metadata.getTable(n.keyspace,e.name))).then(t=>{for(let s=0;s<t.length;s++){let c=t[s];if(c===null)throw Error(`Table "${n.tables[s].name}" could not be retrieved`);if(keysAreIncluded(c.partitionKeys,i)===e.all&&!(r&&keysAreIncluded(c.clusteringKeys,i)!==e.all)&&!(i.length>c.partitionKeys.length&&!i.reduce((e,t)=>e&&(contains(c.partitionKeys,e=>e.name===t.columnName)||contains(c.clusteringKeys,e=>e.name===t.columnName)),!0))&&a.reduce((e,t)=>e&&c.columnsByName[t.columnName]!==void 0,!0)&&o.reduce((e,t,n)=>{if(!e)return!1;let r=c.clusteringKeys[n];return r&&r.name===t[0]},!0))return c.name}let s=`No table matches the filter (${r?`all PKs have to be specified`:`PKs`}): [${i.map(e=>e.columnName)}]`;throw a.length>0&&(s+=`; fields: [${a.map(e=>e.columnName)}]`),o.length>0&&(s+=`; orderBy: [${o.map(e=>e[0])}]`),Error(s)})}static getForSelectAll(e){return e.tables[0].name}static getForInsert(t,n,r){return Promise.all(n.tables.filter(e=>!e.isView).map(e=>t.metadata.getTable(n.keyspace,e.name))).then(t=>{let i=t.filter((t,i)=>{if(t===null)throw Error(`Table "${n.tables[i].name}" could not be retrieved`);if(keysAreIncluded(t.partitionKeys,r)!==e.all)return!1;let a=keysAreIncluded(t.clusteringKeys,r);if(a===e.all)return!0;if(a===e.some)return!1;let o=staticColumnCount(t);return r.length===t.partitionKeys.length+o&&o>0});if(i.length===0)throw Error(`No table matches (all PKs have to be specified) fields: [${r.map(e=>e.columnName)}]`);return i})}static getForUpdate(t,n,r,i){return Promise.all(n.tables.filter(e=>!e.isView).map(e=>t.metadata.getTable(n.keyspace,e.name))).then(t=>{let a=t.filter((t,a)=>{if(t===null)throw Error(`Table "${n.tables[a].name}" could not be retrieved`);if(keysAreIncluded(t.partitionKeys,r)!==e.all)return!1;let o=keysAreIncluded(t.clusteringKeys,r);if(o===e.some||o===e.none&&!hasStaticColumn(t))return!1;let s=r.reduce((e,n)=>e+(t.columnsByName[n.columnName]===void 0?0:1),0);return s<=t.partitionKeys.length+t.clusteringKeys.length&&(!hasStaticColumn(t)||s<=t.partitionKeys.length)?!1:i.reduce((e,n)=>e&&t.columnsByName[n.columnName]!==void 0,!0)});if(a.length===0){let e=`No table matches (all PKs and columns to set have to be specified) fields: [${r.map(e=>e.columnName)}]`;throw i.length>0&&(e+=`; condition: [${i.map(e=>e.columnName)}]`),Error(e)}return a})}static getForDelete(e,t,n,r){return Promise.all(t.tables.filter(e=>!e.isView).map(n=>e.metadata.getTable(t.keyspace,n.name))).then(e=>{let i=e.filter((e,i)=>{if(e===null)throw Error(`Table "${t.tables[i].name}" could not be retrieved`);let a=e.partitionKeys.concat(e.clusteringKeys).map(e=>e.name),o=n.map(e=>e.columnName);for(let e=0;e<a.length;e++)if(o.indexOf(a[e])===-1)return!1;return r.reduce((t,n)=>t&&e.columnsByName[n.columnName]!==void 0,!0)});if(i.length===0){let e=`No table matches (all PKs have to be specified) fields: [${n.map(e=>e.columnName)}]`;throw r.length>0&&(e+=`; condition: [${r.map(e=>e.columnName)}]`),Error(e)}return i})}};function contains(e,t){return e.filter(t).length>0}function keysAreIncluded(t,n){if(t.length===0)return e.all;let r=n.reduce((e,n)=>e+ +!!contains(t,e=>n.columnName===e.name),0);return r===0?e.none:r===t.length?e.all:e.some}function hasStaticColumn(e){return staticColumnCount(e)>0}function staticColumnCount(e){return e.columns.reduce((e,t)=>e+ +!!t.isStatic,0)}export{ObjectSelector as default};
@@ -1 +1 @@
1
- import e from"../errors.js";var t=class{constructor(e,t,n,r){this.key=e,this.value=t,this.hasChildValues=n,this.isInOperator=r}},n=class{constructor(e,t,n){this.sign=e,this.value=t,this.inverted=!!n}};const r={in_:function(n){if(!Array.isArray(n))throw new e.ArgumentError(`IN operator supports only Array values`);return new t(`IN`,n,!1,!0)},gt:function(e){return new t(`>`,e)},gte:function(e){return new t(`>=`,e)},lt:function(e){return new t(`<`,e)},lte:function(e){return new t(`<=`,e)},notEq:function(e){return new t(`!=`,e)},and:function(e,n){return new t(`AND`,[e,n],!0)},incr:function(e){return new n(`+`,e)},decr:function(e){return new n(`-`,e)},append:function(e){return new n(`+`,e)},prepend:function(e){return new n(`+`,e,!0)},remove:function(e){return new n(`-`,e)}};export{n as QueryAssignment,t as QueryOperator,r as q};
1
+ import e from"../errors.js";var QueryOperator=class{constructor(e,t,n,r){this.key=e,this.value=t,this.hasChildValues=n,this.isInOperator=r}},QueryAssignment=class{constructor(e,t,n){this.sign=e,this.value=t,this.inverted=!!n}};const t={in_:function(t){if(!Array.isArray(t))throw new e.ArgumentError(`IN operator supports only Array values`);return new QueryOperator(`IN`,t,!1,!0)},gt:function(e){return new QueryOperator(`>`,e)},gte:function(e){return new QueryOperator(`>=`,e)},lt:function(e){return new QueryOperator(`<`,e)},lte:function(e){return new QueryOperator(`<=`,e)},notEq:function(e){return new QueryOperator(`!=`,e)},and:function(e,t){return new QueryOperator(`AND`,[e,t],!0)},incr:function(e){return new QueryAssignment(`+`,e)},decr:function(e){return new QueryAssignment(`-`,e)},append:function(e){return new QueryAssignment(`+`,e)},prepend:function(e){return new QueryAssignment(`+`,e,!0)},remove:function(e){return new QueryAssignment(`-`,e)}};export{QueryAssignment,QueryOperator,t as q};
@@ -1,9 +1,9 @@
1
- import e from"../types/index.js";import{QueryAssignment as t,QueryOperator as n}from"./q.js";import r from"vm";const i=e.dataTypes,a=`gen-param-getter`;var o=class e{static getSelect(t,n,r,i,a,o){let s=`SELECT `;return s+=i.length>0?i.map(e=>`"${e.columnName}"`).join(`, `):`*`,s+=` FROM ${n}.${t}`,r.length>0&&(s+=` WHERE `,s+=e._getConditionWithOperators(r)),a.length>0&&(s+=` ORDER BY `,s+=a.map(e=>`"${e[0]}" ${e[1]}`).join(`, `)),typeof o==`number`&&(s+=` LIMIT ?`),s}static selectParamsGetter(t,n){let i=`(function getParametersSelect(doc, docInfo, mappingInfo) {
2
- `;return i+=` return [`,i+=e._valueGetterExpression(t),typeof n==`number`&&(t.length>0&&(i+=`, `),i+=`docInfo['limit']`),i+=`];
3
- })`,new r.Script(i,{filename:a}).runInThisContext()}static getInsert(t,n,r,i,a){let o=i&&i.ttl,s=r.filter(e=>t.columnsByName[e.columnName]!==void 0);return{query:e._getInsertQuery(t.name,n,s,a,o),paramsGetter:e._insertParamsGetter(s,i),isIdempotent:!a}}static _getInsertQuery(e,t,n,r,i){let a=`INSERT INTO ${t}.${e} (`;return a+=n.map(e=>`"${e.columnName}"`).join(`, `),a+=`) VALUES (`,a+=n.map(()=>`?`).join(`, `),a+=`)`,r===!0&&(a+=` IF NOT EXISTS`),typeof i==`number`&&(a+=` USING TTL ?`),a}static _insertParamsGetter(t,n){let i=`(function getParametersInsert(doc, docInfo, mappingInfo) {
4
- `;return i+=` return [`,i+=e._valueGetterExpression(t),n&&typeof n.ttl==`number`&&(i+=`, docInfo['ttl']`),i+=`];
5
- })`,new r.Script(i,{filename:a}).runInThisContext()}static getUpdate(n,r,a,o,s,c){let l=o&&o.ttl,u=new Set(n.partitionKeys.concat(n.clusteringKeys).map(e=>e.name)),d=!0,f=!1,p=a.filter(e=>{let r=n.columnsByName[e.columnName];return r===void 0?!1:(r.type.code===i.list&&e.value instanceof t?d=!1:r.type.code===i.counter&&(d=!1,f=!0),!0)});return{query:e._getUpdateQuery(n.name,r,u,p,s,c,l),isIdempotent:d&&s.length===0&&!c,paramsGetter:e._updateParamsGetter(u,p,s,l),isCounter:f}}static _getUpdateQuery(n,r,i,a,o,s,c){let l=`UPDATE ${r}.${n} `;return typeof c==`number`&&(l+=`USING TTL ? `),l+=`SET `,l+=a.filter(e=>!i.has(e.columnName)).map(e=>e.value instanceof t?e.value.inverted?`"${e.columnName}" = ? ${e.value.sign} "${e.columnName}"`:`"${e.columnName}" = "${e.columnName}" ${e.value.sign} ?`:`"${e.columnName}" = ?`).join(`, `),l+=` WHERE `,l+=a.filter(e=>i.has(e.columnName)).map(e=>`"${e.columnName}" = ?`).join(` AND `),s===!0?l+=` IF EXISTS`:o.length>0&&(l+=` IF `+e._getConditionWithOperators(o)),l}static _updateParamsGetter(t,n,i,o){let s=`(function getParametersUpdate(doc, docInfo, mappingInfo) {
6
- `;return s+=` return [`,typeof o==`number`&&(s+=`docInfo['ttl'], `),s+=e._assignmentGetterExpression(n.filter(e=>!t.has(e.columnName))),s+=`, `,s+=e._valueGetterExpression(n.filter(e=>t.has(e.columnName))),i.length>0&&(s+=`, `+e._valueGetterExpression(i,`docInfo.when`)),s+=`];
7
- })`,new r.Script(s,{filename:a}).runInThisContext()}static getDelete(t,n,r,i,a,o){let s=i&&i.deleteOnlyColumns,c=new Set(t.partitionKeys.concat(t.clusteringKeys).map(e=>e.name)),l=r.filter(e=>t.columnsByName[e.columnName]!==void 0);return{query:e._getDeleteQuery(t.name,n,c,l,a,o,s),paramsGetter:e._deleteParamsGetter(c,l,a),isIdempotent:a.length===0&&!o}}static _getDeleteQuery(t,n,r,i,a,o,s){let c=`DELETE`;if(s){let e=i.filter(e=>!r.has(e.columnName)).map(e=>`"${e.columnName}"`).join(`, `);e!==``&&(c+=` `+e)}return c+=` FROM ${n}.${t} WHERE `,c+=i.filter(e=>r.has(e.columnName)).map(e=>`"${e.columnName}" = ?`).join(` AND `),o===!0?c+=` IF EXISTS`:a.length>0&&(c+=` IF `+e._getConditionWithOperators(a)),c}static _deleteParamsGetter(t,n,i){let o=`(function getParametersDelete(doc, docInfo, mappingInfo) {
8
- `;return o+=` return [`,o+=e._valueGetterExpression(n.filter(e=>t.has(e.columnName))),i.length>0&&(o+=`, `+e._valueGetterExpression(i,`docInfo.when`)),o+=`];
9
- })`,new r.Script(o,{filename:a}).runInThisContext()}static _valueGetterExpression(t,n){return n||=`doc`,t.map(t=>e._valueGetterSingle(`${n}['${t.propertyName}']`,t.propertyName,t.value,t.fromModel)).join(`, `)}static _valueGetterSingle(t,r,i,a){let o=t;if(i instanceof n){if(i.hasChildValues)return`${e._valueGetterSingle(`${t}.value[0]`,r,i.value[0],a)}, ${e._valueGetterSingle(`${t}.value[1]`,r,i.value[1],a)}`;if(o=`${t}.value`,i.isInOperator&&a)return`${o}.map(v => ${e._getMappingFunctionCall(r,`v`)})`}return a?e._getMappingFunctionCall(r,o):o}static _assignmentGetterExpression(n,r){return r||=`doc`,n.map(n=>{let i=`${r}['${n.propertyName}']${n.value instanceof t?`.value`:``}`;return n.fromModel?e._getMappingFunctionCall(n.propertyName,i):i}).join(`, `)}static _getConditionWithOperators(t){return t.map(t=>e._getSingleCondition(t.columnName,t.value)).join(` AND `)}static _getMappingFunctionCall(e,t){return`mappingInfo.getFromModelFn('${e}')(${t})`}static _getSingleCondition(t,r){return r instanceof n?r.hasChildValues?`${e._getSingleCondition(t,r.value[0])} ${r.key} ${e._getSingleCondition(t,r.value[1])}`:`"${t}" ${r.key} ?`:`"${t}" = ?`}};export{o as default};
1
+ import e from"../types/index.js";import{QueryAssignment as t,QueryOperator as n}from"./q.js";import r from"vm";const i=e.dataTypes,a=`gen-param-getter`;var o=class QueryGenerator{static getSelect(e,t,n,r,i,a){let o=`SELECT `;return o+=r.length>0?r.map(e=>`"${e.columnName}"`).join(`, `):`*`,o+=` FROM ${t}.${e}`,n.length>0&&(o+=` WHERE `,o+=QueryGenerator._getConditionWithOperators(n)),i.length>0&&(o+=` ORDER BY `,o+=i.map(e=>`"${e[0]}" ${e[1]}`).join(`, `)),typeof a==`number`&&(o+=` LIMIT ?`),o}static selectParamsGetter(e,t){let n=`(function getParametersSelect(doc, docInfo, mappingInfo) {
2
+ `;return n+=` return [`,n+=QueryGenerator._valueGetterExpression(e),typeof t==`number`&&(e.length>0&&(n+=`, `),n+=`docInfo['limit']`),n+=`];
3
+ })`,new r.Script(n,{filename:a}).runInThisContext()}static getInsert(e,t,n,r,i){let a=r&&r.ttl,o=n.filter(t=>e.columnsByName[t.columnName]!==void 0);return{query:QueryGenerator._getInsertQuery(e.name,t,o,i,a),paramsGetter:QueryGenerator._insertParamsGetter(o,r),isIdempotent:!i}}static _getInsertQuery(e,t,n,r,i){let a=`INSERT INTO ${t}.${e} (`;return a+=n.map(e=>`"${e.columnName}"`).join(`, `),a+=`) VALUES (`,a+=n.map(()=>`?`).join(`, `),a+=`)`,r===!0&&(a+=` IF NOT EXISTS`),typeof i==`number`&&(a+=` USING TTL ?`),a}static _insertParamsGetter(e,t){let n=`(function getParametersInsert(doc, docInfo, mappingInfo) {
4
+ `;return n+=` return [`,n+=QueryGenerator._valueGetterExpression(e),t&&typeof t.ttl==`number`&&(n+=`, docInfo['ttl']`),n+=`];
5
+ })`,new r.Script(n,{filename:a}).runInThisContext()}static getUpdate(e,n,r,a,o,s){let c=a&&a.ttl,l=new Set(e.partitionKeys.concat(e.clusteringKeys).map(e=>e.name)),u=!0,d=!1,f=r.filter(n=>{let r=e.columnsByName[n.columnName];return r===void 0?!1:(r.type.code===i.list&&n.value instanceof t?u=!1:r.type.code===i.counter&&(u=!1,d=!0),!0)});return{query:QueryGenerator._getUpdateQuery(e.name,n,l,f,o,s,c),isIdempotent:u&&o.length===0&&!s,paramsGetter:QueryGenerator._updateParamsGetter(l,f,o,c),isCounter:d}}static _getUpdateQuery(e,n,r,i,a,o,s){let c=`UPDATE ${n}.${e} `;return typeof s==`number`&&(c+=`USING TTL ? `),c+=`SET `,c+=i.filter(e=>!r.has(e.columnName)).map(e=>e.value instanceof t?e.value.inverted?`"${e.columnName}" = ? ${e.value.sign} "${e.columnName}"`:`"${e.columnName}" = "${e.columnName}" ${e.value.sign} ?`:`"${e.columnName}" = ?`).join(`, `),c+=` WHERE `,c+=i.filter(e=>r.has(e.columnName)).map(e=>`"${e.columnName}" = ?`).join(` AND `),o===!0?c+=` IF EXISTS`:a.length>0&&(c+=` IF `+QueryGenerator._getConditionWithOperators(a)),c}static _updateParamsGetter(e,t,n,i){let o=`(function getParametersUpdate(doc, docInfo, mappingInfo) {
6
+ `;return o+=` return [`,typeof i==`number`&&(o+=`docInfo['ttl'], `),o+=QueryGenerator._assignmentGetterExpression(t.filter(t=>!e.has(t.columnName))),o+=`, `,o+=QueryGenerator._valueGetterExpression(t.filter(t=>e.has(t.columnName))),n.length>0&&(o+=`, `+QueryGenerator._valueGetterExpression(n,`docInfo.when`)),o+=`];
7
+ })`,new r.Script(o,{filename:a}).runInThisContext()}static getDelete(e,t,n,r,i,a){let o=r&&r.deleteOnlyColumns,s=new Set(e.partitionKeys.concat(e.clusteringKeys).map(e=>e.name)),c=n.filter(t=>e.columnsByName[t.columnName]!==void 0);return{query:QueryGenerator._getDeleteQuery(e.name,t,s,c,i,a,o),paramsGetter:QueryGenerator._deleteParamsGetter(s,c,i),isIdempotent:i.length===0&&!a}}static _getDeleteQuery(e,t,n,r,i,a,o){let s=`DELETE`;if(o){let e=r.filter(e=>!n.has(e.columnName)).map(e=>`"${e.columnName}"`).join(`, `);e!==``&&(s+=` `+e)}return s+=` FROM ${t}.${e} WHERE `,s+=r.filter(e=>n.has(e.columnName)).map(e=>`"${e.columnName}" = ?`).join(` AND `),a===!0?s+=` IF EXISTS`:i.length>0&&(s+=` IF `+QueryGenerator._getConditionWithOperators(i)),s}static _deleteParamsGetter(e,t,n){let i=`(function getParametersDelete(doc, docInfo, mappingInfo) {
8
+ `;return i+=` return [`,i+=QueryGenerator._valueGetterExpression(t.filter(t=>e.has(t.columnName))),n.length>0&&(i+=`, `+QueryGenerator._valueGetterExpression(n,`docInfo.when`)),i+=`];
9
+ })`,new r.Script(i,{filename:a}).runInThisContext()}static _valueGetterExpression(e,t){return t||=`doc`,e.map(e=>QueryGenerator._valueGetterSingle(`${t}['${e.propertyName}']`,e.propertyName,e.value,e.fromModel)).join(`, `)}static _valueGetterSingle(e,t,r,i){let a=e;if(r instanceof n){if(r.hasChildValues)return`${QueryGenerator._valueGetterSingle(`${e}.value[0]`,t,r.value[0],i)}, ${QueryGenerator._valueGetterSingle(`${e}.value[1]`,t,r.value[1],i)}`;if(a=`${e}.value`,r.isInOperator&&i)return`${a}.map(v => ${QueryGenerator._getMappingFunctionCall(t,`v`)})`}return i?QueryGenerator._getMappingFunctionCall(t,a):a}static _assignmentGetterExpression(e,n){return n||=`doc`,e.map(e=>{let r=`${n}['${e.propertyName}']${e.value instanceof t?`.value`:``}`;return e.fromModel?QueryGenerator._getMappingFunctionCall(e.propertyName,r):r}).join(`, `)}static _getConditionWithOperators(e){return e.map(e=>QueryGenerator._getSingleCondition(e.columnName,e.value)).join(` AND `)}static _getMappingFunctionCall(e,t){return`mappingInfo.getFromModelFn('${e}')(${t})`}static _getSingleCondition(e,t){return t instanceof n?t.hasChildValues?`${QueryGenerator._getSingleCondition(e,t.value[0])} ${t.key} ${QueryGenerator._getSingleCondition(e,t.value[1])}`:`"${e}" ${t.key} ?`:`"${e}" = ?`}};export{o as default};
@@ -1,4 +1,4 @@
1
- import e from"../utils.js";import t from"../types/index.js";import n from"vm";var r=class r{static getSelectAdapter(e,t){let r=t.columns;if(!r)throw Error(`Expected ROWS result obtained VOID`);let i=`(function rowAdapter(row, info) {
1
+ import e from"../utils.js";import t from"../types/index.js";import n from"vm";var r=class ResultMapper{static getSelectAdapter(e,t){let r=t.columns;if(!r)throw Error(`Expected ROWS result obtained VOID`);let i=`(function rowAdapter(row, info) {
2
2
  const item = info.newInstance();
3
3
  `;for(let t of r)i+=` item['${e.getPropertyName(t.name)}'] = `,e.getToModelFn(t.name)?i+=`info.getToModelFn('${t.name}')(row['${t.name}']);\n`:i+=`row['${t.name}'];\n`;return i+=` return item;
4
- })`,new n.Script(i,{filename:`gen-result-mapper`}).runInThisContext()}static getMutationAdapter(n){return n.columns===null||n.columns.length===1&&n.columns[0].name===`[applied]`&&n.columns[0].type.code===t.dataTypes.boolean?e.noop:r._getConditionalRowAdapter(n)}static _getConditionalRowAdapter(e){return function(t,n){let r=n.newInstance();for(let i=1;i<e.columns.length;i++){let a=e.columns[i];r[n.getPropertyName(a.name)]=t[a.name]}return r}}static getCustomQueryAdapter(n,i){return i.columns===null||i.columns.length===0?{canCache:!0,fn:e.noop}:i.columns[0].name===`[applied]`&&i.columns[0].type.code===t.dataTypes.boolean?{canCache:!1,fn:r._getConditionalRowAdapter(i)}:{canCache:!0,fn:r.getSelectAdapter(n,i)}}};export{r as default};
4
+ })`,new n.Script(i,{filename:`gen-result-mapper`}).runInThisContext()}static getMutationAdapter(n){return n.columns===null||n.columns.length===1&&n.columns[0].name===`[applied]`&&n.columns[0].type.code===t.dataTypes.boolean?e.noop:ResultMapper._getConditionalRowAdapter(n)}static _getConditionalRowAdapter(e){return function(t,n){let r=n.newInstance();for(let i=1;i<e.columns.length;i++){let a=e.columns[i];r[n.getPropertyName(a.name)]=t[a.name]}return r}}static getCustomQueryAdapter(n,r){return r.columns===null||r.columns.length===0?{canCache:!0,fn:e.noop}:r.columns[0].name===`[applied]`&&r.columns[0].type.code===t.dataTypes.boolean?{canCache:!1,fn:ResultMapper._getConditionalRowAdapter(r)}:{canCache:!0,fn:ResultMapper.getSelectAdapter(n,r)}}};export{r as default};
@@ -1 +1 @@
1
- import e from"../utils.js";import t from"util";const n=t.inspect.custom||`inspect`;var r=class{constructor(e,t,n){this._rs=e,this._info=t,this._rowAdapter=n,this._isEmptyLwt=e.columns!==null&&e.columns.length===1&&this._rs.rowLength===1&&e.columns[0].name===`[applied]`,this.length=this._isEmptyLwt?0:e.rowLength||0,this.pageState=e.pageState}wasApplied(){return this._rs.wasApplied()}first(){return!this._rs.rowLength||this._isEmptyLwt?null:this._rowAdapter(this._rs.rows[0],this._info)}*[Symbol.iterator](){if(!this._isEmptyLwt)for(let e=0;e<this._rs.rows.length;e++)yield this._rowAdapter(this._rs.rows[e],this._info)}toArray(){return this._isEmptyLwt||!this._rs.rows?e.emptyArray:this._rs.rows.map(e=>this._rowAdapter(e,this._info))}forEach(e,t){let n=0;t||=this;for(let r of this)e.call(t,r,n++)}[n](){return this.toArray()}};export{r as default};
1
+ import e from"../utils.js";import t from"util";const n=t.inspect.custom||`inspect`;var Result=class{constructor(e,t,n){this._rs=e,this._info=t,this._rowAdapter=n,this._isEmptyLwt=e.columns!==null&&e.columns.length===1&&this._rs.rowLength===1&&e.columns[0].name===`[applied]`,this.length=this._isEmptyLwt?0:e.rowLength||0,this.pageState=e.pageState}wasApplied(){return this._rs.wasApplied()}first(){return!this._rs.rowLength||this._isEmptyLwt?null:this._rowAdapter(this._rs.rows[0],this._info)}*[Symbol.iterator](){if(!this._isEmptyLwt)for(let e=0;e<this._rs.rows.length;e++)yield this._rowAdapter(this._rs.rows[e],this._info)}toArray(){return this._isEmptyLwt||!this._rs.rows?e.emptyArray:this._rs.rows.map(e=>this._rowAdapter(e,this._info))}forEach(e,t){let n=0;t||=this;for(let r of this)e.call(t,r,n++)}[n](){return this.toArray()}};export{Result as default};
@@ -1 +1 @@
1
- var e=class{newObjectInstance(){return{}}getColumnName(e){return e}getPropertyName(e){return e}},t=class extends e{constructor(){super()}getColumnName(e){return e.replace(/[a-z][A-Z]/g,(e,t)=>e.charAt(0)+`_`+e.charAt(1)).toLowerCase()}getPropertyName(e){return e.replace(/_[a-z]/g,(e,t)=>t===0?e:e.substr(1).toUpperCase())}},n=class extends e{constructor(){super()}getColumnName(e){return super.getColumnName(e)}getPropertyName(e){return super.getPropertyName(e)}newObjectInstance(){return super.newObjectInstance()}};export{n as DefaultTableMappings,e as TableMappings,t as UnderscoreCqlToCamelCaseMappings};
1
+ var TableMappings=class{newObjectInstance(){return{}}getColumnName(e){return e}getPropertyName(e){return e}},UnderscoreCqlToCamelCaseMappings=class extends TableMappings{constructor(){super()}getColumnName(e){return e.replace(/[a-z][A-Z]/g,(e,t)=>e.charAt(0)+`_`+e.charAt(1)).toLowerCase()}getPropertyName(e){return e.replace(/_[a-z]/g,(e,t)=>t===0?e:e.substr(1).toUpperCase())}},DefaultTableMappings=class extends TableMappings{constructor(){super()}getColumnName(e){return super.getColumnName(e)}getPropertyName(e){return super.getPropertyName(e)}newObjectInstance(){return super.newObjectInstance()}};export{DefaultTableMappings,TableMappings,UnderscoreCqlToCamelCaseMappings};
@@ -1 +1 @@
1
- import e from"events";var t=class extends e{constructor(e,t,n){super(),this.key=e,this.value=t,this.edges=n||[]}},n=class extends t{constructor(){super([],null),this.length=0}getOrCreate(e,n){typeof e.next!=`function`&&(e=e[Symbol.iterator]());let i=this,a=!1,o=e.next();for(;;){let t;for(let r=1;r<i.key.length;r++){if(o.done||i.key[r]!==o.value){t=this._createBranch(i,r,o.done,n);break}o=e.next()}if(o.done){a=!0;break}if(t!==void 0)break;let r=i.edges,s;for(let t=0;t<r.length;t++){let n=r[t];if(n.key[0]===o.value){s=n,o=e.next();break}}if(s===void 0)break;i=s}if(!a){let a=n();return i.edges.push(new t(r(o.value,e),a)),this._onItemAdded(),a}return i.value===null&&i.edges.length>0&&(i.value=n()),i.value}_createBranch(e,n,r,i){let a=new t(e.key.slice(n),e.value,e.edges);return e.key=e.key.slice(0,n),e.edges=[a],r?(e.value=i(),this._onItemAdded()):e.value=null,a}_onItemAdded(){this.length++,this.emit(`add`,this.length)}};function r(e,t){let n=[e],r=t.next();for(;!r.done;)n.push(r.value),r=t.next();return n}export{n as default};
1
+ import e from"events";var Node=class extends e{constructor(e,t,n){super(),this.key=e,this.value=t,this.edges=n||[]}},Tree=class extends Node{constructor(){super([],null),this.length=0}getOrCreate(e,t){typeof e.next!=`function`&&(e=e[Symbol.iterator]());let n=this,r=!1,i=e.next();for(;;){let a;for(let r=1;r<n.key.length;r++){if(i.done||n.key[r]!==i.value){a=this._createBranch(n,r,i.done,t);break}i=e.next()}if(i.done){r=!0;break}if(a!==void 0)break;let o=n.edges,s;for(let t=0;t<o.length;t++){let n=o[t];if(n.key[0]===i.value){s=n,i=e.next();break}}if(s===void 0)break;n=s}if(!r){let r=t();return n.edges.push(new Node(iteratorToArray(i.value,e),r)),this._onItemAdded(),r}return n.value===null&&n.edges.length>0&&(n.value=t()),n.value}_createBranch(e,t,n,r){let i=new Node(e.key.slice(t),e.value,e.edges);return e.key=e.key.slice(0,t),e.edges=[i],n?(e.value=r(),this._onItemAdded()):e.value=null,i}_onItemAdded(){this.length++,this.emit(`add`,this.length)}};function iteratorToArray(e,t){let n=[e],r=t.next();for(;!r.done;)n.push(r.value),r=t.next();return n}export{Tree as default};
@@ -1 +1 @@
1
- function e(){this.name=null,this.keyspaceName=null,this.signature=null,this.argumentTypes=null,this.stateFunction=null,this.stateType=null,this.finalFunction=null,this.initConditionRaw=null,this.initCondition=null,this.returnType=null,this.deterministic=null}export{e as default};
1
+ function Aggregate(){this.name=null,this.keyspaceName=null,this.signature=null,this.argumentTypes=null,this.stateFunction=null,this.stateType=null,this.finalFunction=null,this.initConditionRaw=null,this.initCondition=null,this.returnType=null,this.deterministic=null}export{Aggregate as default};
@@ -1 +1 @@
1
- import e from"../errors.js";import t from"util";var n=class n{constructor(e,t,n){this._hosts=e,this._openConnections=t,this._inFlightQueries=n}getConnectedHosts(){return this._hosts}getOpenConnections(t){if(!t)throw new e.ArgumentError(`Host is not defined`);return this._openConnections[t.address]||0}getInFlightQueries(t){if(!t)throw new e.ArgumentError(`Host is not defined`);return this._inFlightQueries[t.address]||0}toString(){return t.format(`{"hosts": %j, "openConnections": %j, "inFlightQueries": %j}`,this._hosts.map(function(e){return e.address}),this._openConnections,this._inFlightQueries)}static from(e){let t={},r={},i=[];return e.hosts.forEach(e=>{e.pool.connections.length!==0&&(i.push(e),t[e.address]=e.pool.connections.length,r[e.address]=e.getInFlight())}),new n(i,t,r)}};export{n as default};
1
+ import e from"../errors.js";import t from"util";var n=class ClientState{constructor(e,t,n){this._hosts=e,this._openConnections=t,this._inFlightQueries=n}getConnectedHosts(){return this._hosts}getOpenConnections(t){if(!t)throw new e.ArgumentError(`Host is not defined`);return this._openConnections[t.address]||0}getInFlightQueries(t){if(!t)throw new e.ArgumentError(`Host is not defined`);return this._inFlightQueries[t.address]||0}toString(){return t.format(`{"hosts": %j, "openConnections": %j, "inFlightQueries": %j}`,this._hosts.map(function(e){return e.address}),this._openConnections,this._inFlightQueries)}static from(e){let t={},n={},r=[];return e.hosts.forEach(e=>{e.pool.connections.length!==0&&(r.push(e),t[e.address]=e.pool.connections.length,n[e.address]=e.getInFlight())}),new ClientState(r,t,n)}};export{n as default};
@@ -1 +1 @@
1
- import e from"util";import t from"events";function n(e){t.EventEmitter.call(this),this.setMaxListeners(0),Object.defineProperty(this,`loading`,{value:!1,enumerable:!1,writable:!0}),Object.defineProperty(this,`loaded`,{value:!1,enumerable:!1,writable:!0}),this.name=e,this.bloomFilterFalsePositiveChance=0,this.caching=null,this.comment=null,this.gcGraceSeconds=0,this.compactionClass=null,this.compactionOptions=null,this.compression=null,this.localReadRepairChance=0,this.readRepairChance=0,this.extensions=null,this.crcCheckChance=null,this.populateCacheOnFlush=!1,this.defaultTtl=0,this.speculativeRetry=`NONE`,this.minIndexInterval=128,this.maxIndexInterval=2048,this.columns=null,this.columnsByName=null,this.partitionKeys=[],this.clusteringKeys=[],this.clusteringOrder=[],this.nodesync=null}e.inherits(n,t.EventEmitter);export{n as default};
1
+ import e from"util";import t from"events";function DataCollection(e){t.EventEmitter.call(this),this.setMaxListeners(0),Object.defineProperty(this,`loading`,{value:!1,enumerable:!1,writable:!0}),Object.defineProperty(this,`loaded`,{value:!1,enumerable:!1,writable:!0}),this.name=e,this.bloomFilterFalsePositiveChance=0,this.caching=null,this.comment=null,this.gcGraceSeconds=0,this.compactionClass=null,this.compactionOptions=null,this.compression=null,this.localReadRepairChance=0,this.readRepairChance=0,this.extensions=null,this.crcCheckChance=null,this.populateCacheOnFlush=!1,this.defaultTtl=0,this.speculativeRetry=`NONE`,this.minIndexInterval=128,this.maxIndexInterval=2048,this.columns=null,this.columnsByName=null,this.partitionKeys=[],this.clusteringKeys=[],this.clusteringOrder=[],this.nodesync=null}e.inherits(DataCollection,t.EventEmitter);export{DataCollection as default};
@@ -1 +1 @@
1
- import e from"../promise-utils.js";import t from"../utils.js";import n from"util";const r=1e3;var i=class{constructor(e,t){this._delay=e,this._logger=t,this._queue=null,this._timeout=null}eventReceived(t,i){return new Promise((a,o)=>{t.callback=e.getCallback(a,o),this._queue=this._queue||{callbacks:[],keyspaces:{}};let s=i?0:this._delay;if(t.all&&(this._queue.mainEvent=t),this._queue.callbacks.length===r&&this._logger(`warn`,n.format(`Event debouncer queue exceeded %d events`,r)),this._queue.callbacks.push(t.callback),this._queue.mainEvent)return this._slideDelay(s);let c=this._queue.keyspaces[t.keyspace];c||=this._queue.keyspaces[t.keyspace]={events:[]},t.cqlObject===void 0&&(c.mainEvent=t),c.events.push(t),this._slideDelay(s)})}_slideDelay(e){let t=this;function n(){let e=t._queue;t._queue=null,t._timeout=null,a(e)}if(e===0)return this._timeout&&clearTimeout(this._timeout),n();let r=this._timeout;this._timeout=setTimeout(n,e),r&&clearTimeout(r)}shutdown(){this._queue&&(this._queue.callbacks.forEach(function(e){e()}),this._queue=null,clearTimeout(this._timeout),this._timeout=null)}};function a(n){if(n.mainEvent)return e.toCallback(n.mainEvent.handler(),e=>{for(let t=0;t<n.callbacks.length;t++)n.callbacks[t](e)});t.each(Object.keys(n.keyspaces),function(t,r){let i=n.keyspaces[t];if(i.mainEvent)return e.toCallback(i.mainEvent.handler(),function(e){for(let t=0;t<i.events.length;t++)i.events[t].callback(e);r()});i.events.forEach(e=>{e.handler(),e.callback()}),r()})}export{i as default};
1
+ import e from"../promise-utils.js";import t from"../utils.js";import n from"util";const r=1e3;var EventDebouncer=class{constructor(e,t){this._delay=e,this._logger=t,this._queue=null,this._timeout=null}eventReceived(t,i){return new Promise((a,o)=>{t.callback=e.getCallback(a,o),this._queue=this._queue||{callbacks:[],keyspaces:{}};let s=i?0:this._delay;if(t.all&&(this._queue.mainEvent=t),this._queue.callbacks.length===r&&this._logger(`warn`,n.format(`Event debouncer queue exceeded %d events`,r)),this._queue.callbacks.push(t.callback),this._queue.mainEvent)return this._slideDelay(s);let c=this._queue.keyspaces[t.keyspace];c||=this._queue.keyspaces[t.keyspace]={events:[]},t.cqlObject===void 0&&(c.mainEvent=t),c.events.push(t),this._slideDelay(s)})}_slideDelay(e){let t=this;function process(){let e=t._queue;t._queue=null,t._timeout=null,processQueue(e)}if(e===0)return this._timeout&&clearTimeout(this._timeout),process();let n=this._timeout;this._timeout=setTimeout(process,e),n&&clearTimeout(n)}shutdown(){this._queue&&(this._queue.callbacks.forEach(function(e){e()}),this._queue=null,clearTimeout(this._timeout),this._timeout=null)}};function processQueue(n){if(n.mainEvent)return e.toCallback(n.mainEvent.handler(),e=>{for(let t=0;t<n.callbacks.length;t++)n.callbacks[t](e)});t.each(Object.keys(n.keyspaces),function(t,r){let i=n.keyspaces[t];if(i.mainEvent)return e.toCallback(i.mainEvent.handler(),function(e){for(let t=0;t<i.events.length;t++)i.events[t].callback(e);r()});i.events.forEach(e=>{e.handler(),e.callback()}),r()})}export{EventDebouncer as default};
@@ -1 +1 @@
1
- import e from"../errors.js";import t from"../promise-utils.js";import n from"../utils.js";import r from"../types/index.js";import{ExecutionOptions as i}from"../execution-options.js";import a from"../requests.js";import{TokenRange as o}from"../token.js";import s from"../tokenizer.js";import c from"./schema-parser.js";import l from"util";import u from"events";var d=class{constructor(t,r){if(!t)throw new e.ArgumentError(`Options are not defined`);Object.defineProperty(this,`options`,{value:t,enumerable:!1,writable:!1}),Object.defineProperty(this,`controlConnection`,{value:r,enumerable:!1,writable:!1}),this.keyspaces={},this.initialized=!1,this._isDbaas=!1,this._schemaParser=c.getByVersion(t,r,this.getUdt.bind(this)),this.log=n.log,this._preparedQueries=new f(t.maxPrepared,(...e)=>this.log(...e))}setCassandraVersion(e){this._schemaParser=c.getByVersion(this.options,this.controlConnection,this.getUdt.bind(this),e,this._schemaParser)}isDbaas(){return this._isDbaas}setProductTypeAsDbaas(){this._isDbaas=!0}setPartitioner(e){return/RandomPartitioner$/.test(e)?this.tokenizer=new s.RandomTokenizer:/ByteOrderedPartitioner$/.test(e)?this.tokenizer=new s.ByteOrderedTokenizer:this.tokenizer=new s.Murmur3Tokenizer}buildTokens(e){if(!this.tokenizer)return this.log(`error`,`Tokenizer could not be determined`);let t=[],r={},i=e.values(),a=this.tokenizer.stringify,s={};i.forEach(e=>{if(!e.tokens)return;e.tokens.forEach(i=>{let o=this.tokenizer.parse(i);n.insertSorted(t,o,(e,t)=>e.compare(t)),r[a(o)]=e});let i=s[e.datacenter];i||=s[e.datacenter]={hostLength:0,racks:new n.HashSet},i.hostLength++,i.racks.add(e.rack)}),this.primaryReplicas=r,this.ring=t;let c=new Set;if(this.ring.length===1){let e=this.tokenizer.minToken();c.add(new o(e,e,this.tokenizer))}else for(let e=0;e<this.ring.length;e++){let t=this.ring[e],n=this.ring[(e+1)%this.ring.length];c.add(new o(t,n,this.tokenizer))}this.tokenRanges=c,this.ringTokensAsStrings=Array(t.length);for(let e=0;e<t.length;e++)this.ringTokensAsStrings[e]=a(t[e]);this.datacenters=s}refreshKeyspace(e,n){return t.optionalCallback(this._refreshKeyspace(e),n)}async _refreshKeyspace(e){if(!this.initialized)throw this._uninitializedError();this.log(`info`,l.format(`Retrieving keyspace %s metadata`,e));try{let t=await this._schemaParser.getKeyspace(e);return t?(this.keyspaces[t.name]=t,t):(delete this.keyspaces[e],null)}catch(e){throw this.log(`error`,`There was an error while trying to retrieve keyspace information`,e),e}}refreshKeyspaces(e,n){if((typeof e==`function`||e===void 0)&&(n=e,e=!0),!this.initialized){let e=this._uninitializedError();return n?n(e):Promise.reject(e)}return t.optionalCallback(this.refreshKeyspacesInternal(e),n)}async refreshKeyspacesInternal(e){this.log(`info`,`Retrieving keyspaces metadata`);try{return this.keyspaces=await this._schemaParser.getKeyspaces(e),this.keyspaces}catch(e){throw this.log(`error`,`There was an error while trying to retrieve keyspaces information`,e),e}}_getKeyspaceReplicas(e){return e.replicas||=e.tokenToReplica(this.tokenizer,this.ringTokensAsStrings,this.primaryReplicas,this.datacenters),e.replicas}getReplicas(e,t){if(!this.ring)return null;Buffer.isBuffer(t)&&(t=this.tokenizer.hash(t)),t instanceof o&&(t=t.end);let r;if(e&&(r=this.keyspaces[e],!r))return null;let i=n.binarySearch(this.ring,t,(e,t)=>e.compare(t));i<0&&(i=~i),i>=this.ring.length&&(i%=this.ring.length);let a=this.ringTokensAsStrings[i];return e?this._getKeyspaceReplicas(r)[a]:[this.primaryReplicas[a]]}getTokenRanges(){return this.tokenRanges}getTokenRangesForHost(e,t){if(!this.ring)return null;let n;if(e&&(n=this.keyspaces[e],!n))return null;if(this.ring.length===1)return this.getTokenRanges();let r=this._getKeyspaceReplicas(n),i=new Set;return this.tokenRanges.forEach(e=>{r[this.tokenizer.stringify(e.end)].indexOf(t)!==-1&&i.add(e)}),i}newToken(e){if(!this.tokenizer)throw Error(`Partitioner not established. This should only happen if metadata was disabled or you have not connected yet.`);return Array.isArray(e)?this.tokenizer.hash(Buffer.concat(e)):typeof e==`string`?this.tokenizer.parse(e):this.tokenizer.hash(e)}newTokenRange(e,t){if(!this.tokenizer)throw Error(`Partitioner not established. This should only happen if metadata was disabled or you have not connected yet.`);return new o(e,t,this.tokenizer)}getPreparedInfo(e,t){return this._preparedQueries.getOrAdd(e,t)}clearPrepared(){this._preparedQueries.clear()}getPreparedById(e){return this._preparedQueries.getById(e)}setPreparedById(e){return this._preparedQueries.setById(e)}getAllPrepared(){return this._preparedQueries.getAll()}_uninitializedError(){return Error(`Metadata has not been initialized. This could only happen if you have not connected yet.`)}getUdt(e,n,r){return t.optionalCallback(this._getUdt(e,n),r)}async _getUdt(e,t){if(!this.initialized)throw this._uninitializedError();let n;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return null;n=t.udts}return await this._schemaParser.getUdt(e,t,n)}getTable(e,n,r){return t.optionalCallback(this._getTable(e,n),r)}async _getTable(e,t){if(!this.initialized)throw this._uninitializedError();let n,r;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return null;n=t.tables,r=t.virtual}return await this._schemaParser.getTable(e,t,n,r)}getFunctions(e,n,r){return t.optionalCallback(this._getFunctionsWrapper(e,n),r)}async _getFunctionsWrapper(t,n){if(!t||!n)throw new e.ArgumentError(`You must provide the keyspace name and cql function name to retrieve the metadata`);let r=await this._getFunctions(t,n,!1);return Array.from(r.values())}getFunction(e,n,r,i){return t.optionalCallback(this._getSingleFunction(e,n,r,!1),i)}getAggregates(e,n,r){return t.optionalCallback(this._getAggregates(e,n),r)}async _getAggregates(t,n){if(!t||!n)throw new e.ArgumentError(`You must provide the keyspace name and cql aggregate name to retrieve the metadata`);let r=await this._getFunctions(t,n,!0);return Array.from(r.values())}getAggregate(e,n,r,i){return t.optionalCallback(this._getSingleFunction(e,n,r,!0),i)}getMaterializedView(e,n,r){return t.optionalCallback(this._getMaterializedView(e,n),r)}async _getMaterializedView(e,t){if(!this.initialized)throw this._uninitializedError();let n;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return null;n=t.views}return await this._schemaParser.getMaterializedView(e,t,n)}async _getFunctions(e,t,n){if(!this.initialized)throw this._uninitializedError();let r;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return new Map;r=n?t.aggregates:t.functions}return await this._schemaParser.getFunctions(e,t,n,r)}async _getSingleFunction(t,n,i,a){if(!t||!n)throw new e.ArgumentError(`You must provide the keyspace name and cql function name to retrieve the metadata`);if(!Array.isArray(i))throw new e.ArgumentError(`Signature must be an array of types`);return i=i.map(e=>typeof e==`string`?e:r.getDataTypeNameByCode(e)),(await this._getFunctions(t,n,a)).get(i.join(`,`))||null}getTrace(e,n,r){return!r&&typeof n==`function`&&(r=n,n=null),t.optionalCallback(this._getTrace(e,n),r)}async _getTrace(e,n){if(!this.initialized)throw this._uninitializedError();let r,o=0,s=i.empty();s.getConsistency=()=>n;let c=new a.QueryRequest(l.format(`SELECT * FROM system_traces.sessions WHERE session_id=%s`,e),null,s),u=new a.QueryRequest(l.format(`SELECT * FROM system_traces.events WHERE session_id=%s`,e),null,s);for(;!r&&o++<5;){let e=(await this.controlConnection.query(c)).rows[0];if(!e||typeof e.duration!=`number`){await t.delay(400);continue}r={requestType:e.request,coordinator:e.coordinator,parameters:e.parameters,startedAt:e.started_at,duration:e.duration,clientAddress:e.client,events:null};let n=await this.controlConnection.query(u);r.events=n.rows.map(e=>({id:e.event_id,activity:e.activity,source:e.source,elapsed:e.source_elapsed,thread:e.thread}))}if(!r)throw Error(`Trace ${e.toString()} could not fully retrieved after 5 attempts`);return r}checkSchemaAgreement(e){return t.optionalCallback(this._checkSchemaAgreement(),e)}async _checkSchemaAgreement(){let e=this.controlConnection.connection;if(!e)return!1;try{return await this.compareSchemaVersions(e)}catch{return!1}}async adaptUserHints(e,t){if(!Array.isArray(t))return;let n=[];for(let i=0;i<t.length;i++){let a=t[i];if(typeof a!=`string`)continue;let o=r.dataTypes.getByName(a);this._checkUdtTypes(n,o,e),t[i]=o}for(let e of n){let t=await this.getUdt(e.info.keyspace,e.info.name);if(!t)throw TypeError(`User defined type not found: `+e.info.keyspace+`.`+e.info.name);e.info=t}}_checkUdtTypes(e,t,n){if(t.code===r.dataTypes.udt){let r=t.info.split(`.`);if(t.info={keyspace:r[0],name:r[1]},!t.info.name){if(!n)throw TypeError(`No keyspace specified for udt: `+r.join(`.`));t.info.name=t.info.keyspace,t.info.keyspace=n}e.push(t);return}if(t.info){if(t.code===r.dataTypes.list||t.code===r.dataTypes.set)return this._checkUdtTypes(e,t.info,n);t.code===r.dataTypes.map&&(this._checkUdtTypes(e,t.info[0],n),this._checkUdtTypes(e,t.info[1],n))}}async compareSchemaVersions(e){let t=new Set,n=await e.send(new a.QueryRequest(`SELECT schema_version FROM system.local`),null);n&&n.rows&&n.rows.length===1&&t.add(n.rows[0].schema_version.toString());let r=await e.send(new a.QueryRequest(`SELECT schema_version FROM system.peers`),null);if(r&&r.rows)for(let e of r.rows){let n=e.schema_version;n&&t.add(n.toString())}return t.size===1}},f=class{constructor(e,t){this.length=0,this._maxPrepared=e,this._mapByKey=new Map,this._mapById=new Map,this._logger=t}_getKey(e,t){return(e||``)+t}getOrAdd(e,t){let n=this._getKey(e,t),r=this._mapByKey.get(n);return r||(this._validateOverflow(),r=new u.EventEmitter,r.setMaxListeners(0),r.query=t,r.keyspace=e,this._mapByKey.set(n,r),this.length++,r)}_validateOverflow(){if(this.length<this._maxPrepared)return;let e=[];this._logger(`warning`,`Prepared statements exceeded maximum. This could be caused by preparing queries that contain parameters`);let t=this.length-this._maxPrepared+1;for(let[n,r]of this._mapByKey)if(r.queryId&&e.push([n,r])>=t)break;for(let[t,n]of e)this._mapByKey.delete(t),this._mapById.delete(n.queryId.toString(`hex`)),this.length--}setById(e){this._mapById.set(e.queryId.toString(`hex`),e)}getById(e){return this._mapById.get(e.toString(`hex`))}clear(){this._mapByKey=new Map,this._mapById=new Map,this.length=0}getAll(){return Array.from(this._mapByKey.values()).filter(e=>!!e.queryId)}};export{d as default};
1
+ import e from"../errors.js";import t from"../promise-utils.js";import n from"../utils.js";import r from"../types/index.js";import{ExecutionOptions as i}from"../execution-options.js";import a from"../requests.js";import{TokenRange as o}from"../token.js";import s from"../tokenizer.js";import c from"./schema-parser.js";import l from"util";import u from"events";var Metadata=class{constructor(t,r){if(!t)throw new e.ArgumentError(`Options are not defined`);Object.defineProperty(this,`options`,{value:t,enumerable:!1,writable:!1}),Object.defineProperty(this,`controlConnection`,{value:r,enumerable:!1,writable:!1}),this.keyspaces={},this.initialized=!1,this._isDbaas=!1,this._schemaParser=c.getByVersion(t,r,this.getUdt.bind(this)),this.log=n.log,this._preparedQueries=new PreparedQueries(t.maxPrepared,(...e)=>this.log(...e))}setCassandraVersion(e){this._schemaParser=c.getByVersion(this.options,this.controlConnection,this.getUdt.bind(this),e,this._schemaParser)}isDbaas(){return this._isDbaas}setProductTypeAsDbaas(){this._isDbaas=!0}setPartitioner(e){return/RandomPartitioner$/.test(e)?this.tokenizer=new s.RandomTokenizer:/ByteOrderedPartitioner$/.test(e)?this.tokenizer=new s.ByteOrderedTokenizer:this.tokenizer=new s.Murmur3Tokenizer}buildTokens(e){if(!this.tokenizer)return this.log(`error`,`Tokenizer could not be determined`);let t=[],r={},i=e.values(),a=this.tokenizer.stringify,s={};i.forEach(e=>{if(!e.tokens)return;e.tokens.forEach(i=>{let o=this.tokenizer.parse(i);n.insertSorted(t,o,(e,t)=>e.compare(t)),r[a(o)]=e});let i=s[e.datacenter];i||=s[e.datacenter]={hostLength:0,racks:new n.HashSet},i.hostLength++,i.racks.add(e.rack)}),this.primaryReplicas=r,this.ring=t;let c=new Set;if(this.ring.length===1){let e=this.tokenizer.minToken();c.add(new o(e,e,this.tokenizer))}else for(let e=0;e<this.ring.length;e++){let t=this.ring[e],n=this.ring[(e+1)%this.ring.length];c.add(new o(t,n,this.tokenizer))}this.tokenRanges=c,this.ringTokensAsStrings=Array(t.length);for(let e=0;e<t.length;e++)this.ringTokensAsStrings[e]=a(t[e]);this.datacenters=s}refreshKeyspace(e,n){return t.optionalCallback(this._refreshKeyspace(e),n)}async _refreshKeyspace(e){if(!this.initialized)throw this._uninitializedError();this.log(`info`,l.format(`Retrieving keyspace %s metadata`,e));try{let t=await this._schemaParser.getKeyspace(e);return t?(this.keyspaces[t.name]=t,t):(delete this.keyspaces[e],null)}catch(e){throw this.log(`error`,`There was an error while trying to retrieve keyspace information`,e),e}}refreshKeyspaces(e,n){if((typeof e==`function`||e===void 0)&&(n=e,e=!0),!this.initialized){let e=this._uninitializedError();return n?n(e):Promise.reject(e)}return t.optionalCallback(this.refreshKeyspacesInternal(e),n)}async refreshKeyspacesInternal(e){this.log(`info`,`Retrieving keyspaces metadata`);try{return this.keyspaces=await this._schemaParser.getKeyspaces(e),this.keyspaces}catch(e){throw this.log(`error`,`There was an error while trying to retrieve keyspaces information`,e),e}}_getKeyspaceReplicas(e){return e.replicas||=e.tokenToReplica(this.tokenizer,this.ringTokensAsStrings,this.primaryReplicas,this.datacenters),e.replicas}getReplicas(e,t){if(!this.ring)return null;Buffer.isBuffer(t)&&(t=this.tokenizer.hash(t)),t instanceof o&&(t=t.end);let r;if(e&&(r=this.keyspaces[e],!r))return null;let i=n.binarySearch(this.ring,t,(e,t)=>e.compare(t));i<0&&(i=~i),i>=this.ring.length&&(i%=this.ring.length);let a=this.ringTokensAsStrings[i];return e?this._getKeyspaceReplicas(r)[a]:[this.primaryReplicas[a]]}getTokenRanges(){return this.tokenRanges}getTokenRangesForHost(e,t){if(!this.ring)return null;let n;if(e&&(n=this.keyspaces[e],!n))return null;if(this.ring.length===1)return this.getTokenRanges();let r=this._getKeyspaceReplicas(n),i=new Set;return this.tokenRanges.forEach(e=>{r[this.tokenizer.stringify(e.end)].indexOf(t)!==-1&&i.add(e)}),i}newToken(e){if(!this.tokenizer)throw Error(`Partitioner not established. This should only happen if metadata was disabled or you have not connected yet.`);return Array.isArray(e)?this.tokenizer.hash(Buffer.concat(e)):typeof e==`string`?this.tokenizer.parse(e):this.tokenizer.hash(e)}newTokenRange(e,t){if(!this.tokenizer)throw Error(`Partitioner not established. This should only happen if metadata was disabled or you have not connected yet.`);return new o(e,t,this.tokenizer)}getPreparedInfo(e,t){return this._preparedQueries.getOrAdd(e,t)}clearPrepared(){this._preparedQueries.clear()}getPreparedById(e){return this._preparedQueries.getById(e)}setPreparedById(e){return this._preparedQueries.setById(e)}getAllPrepared(){return this._preparedQueries.getAll()}_uninitializedError(){return Error(`Metadata has not been initialized. This could only happen if you have not connected yet.`)}getUdt(e,n,r){return t.optionalCallback(this._getUdt(e,n),r)}async _getUdt(e,t){if(!this.initialized)throw this._uninitializedError();let n;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return null;n=t.udts}return await this._schemaParser.getUdt(e,t,n)}getTable(e,n,r){return t.optionalCallback(this._getTable(e,n),r)}async _getTable(e,t){if(!this.initialized)throw this._uninitializedError();let n,r;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return null;n=t.tables,r=t.virtual}return await this._schemaParser.getTable(e,t,n,r)}getFunctions(e,n,r){return t.optionalCallback(this._getFunctionsWrapper(e,n),r)}async _getFunctionsWrapper(t,n){if(!t||!n)throw new e.ArgumentError(`You must provide the keyspace name and cql function name to retrieve the metadata`);let r=await this._getFunctions(t,n,!1);return Array.from(r.values())}getFunction(e,n,r,i){return t.optionalCallback(this._getSingleFunction(e,n,r,!1),i)}getAggregates(e,n,r){return t.optionalCallback(this._getAggregates(e,n),r)}async _getAggregates(t,n){if(!t||!n)throw new e.ArgumentError(`You must provide the keyspace name and cql aggregate name to retrieve the metadata`);let r=await this._getFunctions(t,n,!0);return Array.from(r.values())}getAggregate(e,n,r,i){return t.optionalCallback(this._getSingleFunction(e,n,r,!0),i)}getMaterializedView(e,n,r){return t.optionalCallback(this._getMaterializedView(e,n),r)}async _getMaterializedView(e,t){if(!this.initialized)throw this._uninitializedError();let n;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return null;n=t.views}return await this._schemaParser.getMaterializedView(e,t,n)}async _getFunctions(e,t,n){if(!this.initialized)throw this._uninitializedError();let r;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return new Map;r=n?t.aggregates:t.functions}return await this._schemaParser.getFunctions(e,t,n,r)}async _getSingleFunction(t,n,i,a){if(!t||!n)throw new e.ArgumentError(`You must provide the keyspace name and cql function name to retrieve the metadata`);if(!Array.isArray(i))throw new e.ArgumentError(`Signature must be an array of types`);return i=i.map(e=>typeof e==`string`?e:r.getDataTypeNameByCode(e)),(await this._getFunctions(t,n,a)).get(i.join(`,`))||null}getTrace(e,n,r){return!r&&typeof n==`function`&&(r=n,n=null),t.optionalCallback(this._getTrace(e,n),r)}async _getTrace(e,n){if(!this.initialized)throw this._uninitializedError();let r,o=0,s=i.empty();s.getConsistency=()=>n;let c=new a.QueryRequest(l.format(`SELECT * FROM system_traces.sessions WHERE session_id=%s`,e),null,s),u=new a.QueryRequest(l.format(`SELECT * FROM system_traces.events WHERE session_id=%s`,e),null,s);for(;!r&&o++<5;){let e=(await this.controlConnection.query(c)).rows[0];if(!e||typeof e.duration!=`number`){await t.delay(400);continue}r={requestType:e.request,coordinator:e.coordinator,parameters:e.parameters,startedAt:e.started_at,duration:e.duration,clientAddress:e.client,events:null};let n=await this.controlConnection.query(u);r.events=n.rows.map(e=>({id:e.event_id,activity:e.activity,source:e.source,elapsed:e.source_elapsed,thread:e.thread}))}if(!r)throw Error(`Trace ${e.toString()} could not fully retrieved after 5 attempts`);return r}checkSchemaAgreement(e){return t.optionalCallback(this._checkSchemaAgreement(),e)}async _checkSchemaAgreement(){let e=this.controlConnection.connection;if(!e)return!1;try{return await this.compareSchemaVersions(e)}catch{return!1}}async adaptUserHints(e,t){if(!Array.isArray(t))return;let n=[];for(let i=0;i<t.length;i++){let a=t[i];if(typeof a!=`string`)continue;let o=r.dataTypes.getByName(a);this._checkUdtTypes(n,o,e),t[i]=o}for(let e of n){let t=await this.getUdt(e.info.keyspace,e.info.name);if(!t)throw TypeError(`User defined type not found: `+e.info.keyspace+`.`+e.info.name);e.info=t}}_checkUdtTypes(e,t,n){if(t.code===r.dataTypes.udt){let r=t.info.split(`.`);if(t.info={keyspace:r[0],name:r[1]},!t.info.name){if(!n)throw TypeError(`No keyspace specified for udt: `+r.join(`.`));t.info.name=t.info.keyspace,t.info.keyspace=n}e.push(t);return}if(t.info){if(t.code===r.dataTypes.list||t.code===r.dataTypes.set)return this._checkUdtTypes(e,t.info,n);t.code===r.dataTypes.map&&(this._checkUdtTypes(e,t.info[0],n),this._checkUdtTypes(e,t.info[1],n))}}async compareSchemaVersions(e){let t=new Set,n=await e.send(new a.QueryRequest(`SELECT schema_version FROM system.local`),null);n&&n.rows&&n.rows.length===1&&t.add(n.rows[0].schema_version.toString());let r=await e.send(new a.QueryRequest(`SELECT schema_version FROM system.peers`),null);if(r&&r.rows)for(let e of r.rows){let n=e.schema_version;n&&t.add(n.toString())}return t.size===1}},PreparedQueries=class{constructor(e,t){this.length=0,this._maxPrepared=e,this._mapByKey=new Map,this._mapById=new Map,this._logger=t}_getKey(e,t){return(e||``)+t}getOrAdd(e,t){let n=this._getKey(e,t),r=this._mapByKey.get(n);return r||(this._validateOverflow(),r=new u.EventEmitter,r.setMaxListeners(0),r.query=t,r.keyspace=e,this._mapByKey.set(n,r),this.length++,r)}_validateOverflow(){if(this.length<this._maxPrepared)return;let e=[];this._logger(`warning`,`Prepared statements exceeded maximum. This could be caused by preparing queries that contain parameters`);let t=this.length-this._maxPrepared+1;for(let[n,r]of this._mapByKey)if(r.queryId&&e.push([n,r])>=t)break;for(let[t,n]of e)this._mapByKey.delete(t),this._mapById.delete(n.queryId.toString(`hex`)),this.length--}setById(e){this._mapById.set(e.queryId.toString(`hex`),e)}getById(e){return this._mapById.get(e.toString(`hex`))}clear(){this._mapByKey=new Map,this._mapById=new Map,this.length=0}getAll(){return Array.from(this._mapByKey.values()).filter(e=>!!e.queryId)}};export{Metadata as default};
@@ -1 +1 @@
1
- import e from"./data-collection.js";import t from"util";function n(t){e.call(this,t),this.tableName=null,this.whereClause=null,this.includeAllColumns=!1}t.inherits(n,e);export{n as default};
1
+ import e from"./data-collection.js";import t from"util";function MaterializedView(t){e.call(this,t),this.tableName=null,this.whereClause=null,this.includeAllColumns=!1}t.inherits(MaterializedView,e);export{MaterializedView as default};
@@ -1 +1 @@
1
- function e(){this.name=null,this.keyspaceName=null,this.signature=null,this.argumentNames=null,this.argumentTypes=null,this.body=null,this.calledOnNullInput=null,this.language=null,this.returnType=null,this.deterministic=null,this.monotonic=null,this.monotonicOn=null}export{e as default};
1
+ function SchemaFunction(){this.name=null,this.keyspaceName=null,this.signature=null,this.argumentNames=null,this.argumentTypes=null,this.body=null,this.calledOnNullInput=null,this.language=null,this.returnType=null,this.deterministic=null,this.monotonic=null,this.monotonicOn=null}export{SchemaFunction as default};
@@ -1 +1 @@
1
- import e from"../utils.js";import t from"../types/index.js";import n from"util";const r={custom:0,keys:1,composites:2};function i(e,t,n,r){this.name=e,this.target=t,this.kind=typeof n==`string`?a(n):n,this.options=r}i.prototype.isCompositesKind=function(){return this.kind===r.composites},i.prototype.isKeysKind=function(){return this.kind===r.keys},i.prototype.isCustomKind=function(){return this.kind===r.custom},i.fromRows=function(t){return!t||t.length===0?e.emptyArray:t.map(function(e){let t=e.options;return new i(e.index_name,t.target,a(e.kind),t)})},i.fromColumnRows=function(e,r){let o=[];for(let s=0;s<e.length;s++){let c=e[s],l=c.index_name;if(!l)continue;let u=r[c.column_name],d,f=JSON.parse(c.index_options);d=f!==null&&f.index_keys!==void 0?n.format(`keys(%s)`,u.name):f!==null&&f.index_keys_and_values!==void 0?n.format(`entries(%s)`,u.name):u.type.options.frozen&&(u.type.code===t.dataTypes.map||u.type.code===t.dataTypes.list||u.type.code===t.dataTypes.set)?n.format(`full(%s)`,u.name):u.name,o.push(new i(l,d,a(c.index_type),f))}return o};function a(e){return e?r[e.toLowerCase()]:r.custom}export{i as default};
1
+ import e from"../utils.js";import t from"../types/index.js";import n from"util";const r={custom:0,keys:1,composites:2};function Index(e,t,n,r){this.name=e,this.target=t,this.kind=typeof n==`string`?getKindByName(n):n,this.options=r}Index.prototype.isCompositesKind=function(){return this.kind===r.composites},Index.prototype.isKeysKind=function(){return this.kind===r.keys},Index.prototype.isCustomKind=function(){return this.kind===r.custom},Index.fromRows=function(t){return!t||t.length===0?e.emptyArray:t.map(function(e){let t=e.options;return new Index(e.index_name,t.target,getKindByName(e.kind),t)})},Index.fromColumnRows=function(e,r){let i=[];for(let a=0;a<e.length;a++){let o=e[a],s=o.index_name;if(!s)continue;let c=r[o.column_name],l,u=JSON.parse(o.index_options);l=u!==null&&u.index_keys!==void 0?n.format(`keys(%s)`,c.name):u!==null&&u.index_keys_and_values!==void 0?n.format(`entries(%s)`,c.name):c.type.options.frozen&&(c.type.code===t.dataTypes.map||c.type.code===t.dataTypes.list||c.type.code===t.dataTypes.set)?n.format(`full(%s)`,c.name):c.name,i.push(new Index(s,l,getKindByName(o.index_type),u))}return i};function getKindByName(e){return e?r[e.toLowerCase()]:r.custom}export{Index as default};