UNPKG

11.1 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
8
9var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
10
11var _createClass2 = require('babel-runtime/helpers/createClass');
12
13var _createClass3 = _interopRequireDefault(_createClass2);
14
15var _streamObserver = require('./internal/stream-observer');
16
17var _streamObserver2 = _interopRequireDefault(_streamObserver);
18
19var _result = require('./result');
20
21var _result2 = _interopRequireDefault(_result);
22
23var _transaction = require('./transaction');
24
25var _transaction2 = _interopRequireDefault(_transaction);
26
27var _error = require('./error');
28
29var _util = require('./internal/util');
30
31var _connectionHolder = require('./internal/connection-holder');
32
33var _connectionHolder2 = _interopRequireDefault(_connectionHolder);
34
35var _driver = require('./driver');
36
37var _driver2 = _interopRequireDefault(_driver);
38
39var _transactionExecutor = require('./internal/transaction-executor');
40
41var _transactionExecutor2 = _interopRequireDefault(_transactionExecutor);
42
43var _bookmark = require('./internal/bookmark');
44
45var _bookmark2 = _interopRequireDefault(_bookmark);
46
47function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
48
49/**
50 * A Session instance is used for handling the connection and
51 * sending statements through the connection.
52 * @access public
53 */
54
55var Session = function () {
56
57 /**
58 * @constructor
59 * @param {string} mode the default access mode for this session.
60 * @param {ConnectionProvider} connectionProvider - the connection provider to acquire connections from.
61 * @param {Bookmark} bookmark - the initial bookmark for this session.
62 * @param {Object} [config={}] - this driver configuration.
63 */
64 function Session(mode, connectionProvider, bookmark, config) {
65 (0, _classCallCheck3.default)(this, Session);
66
67 this._mode = mode;
68 this._readConnectionHolder = new _connectionHolder2.default(_driver.READ, connectionProvider);
69 this._writeConnectionHolder = new _connectionHolder2.default(_driver.WRITE, connectionProvider);
70 this._open = true;
71 this._hasTx = false;
72 this._lastBookmark = bookmark;
73 this._transactionExecutor = _createTransactionExecutor(config);
74 }
75
76 /**
77 * Run Cypher statement
78 * Could be called with a statement object i.e.: {text: "MATCH ...", parameters: {param: 1}}
79 * or with the statement and parameters as separate arguments.
80 * @param {mixed} statement - Cypher statement to execute
81 * @param {Object} parameters - Map with parameters to use in statement
82 * @return {Result} - New Result
83 */
84
85
86 (0, _createClass3.default)(Session, [{
87 key: 'run',
88 value: function run(statement) {
89 var parameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
90
91 var _validateStatementAnd = (0, _util.validateStatementAndParameters)(statement, parameters),
92 query = _validateStatementAnd.query,
93 params = _validateStatementAnd.params;
94
95 return this._run(query, params, function (connection, streamObserver) {
96 return connection.run(query, params, streamObserver);
97 });
98 }
99 }, {
100 key: '_run',
101 value: function _run(statement, parameters, statementRunner) {
102 var streamObserver = new _streamObserver2.default(this._onRunFailure());
103 var connectionHolder = this._connectionHolderWithMode(this._mode);
104 if (!this._hasTx) {
105 connectionHolder.initializeConnection();
106 connectionHolder.getConnection(streamObserver).then(function (connection) {
107 statementRunner(connection, streamObserver);
108 connection.pullAll(streamObserver);
109 connection.sync();
110 }).catch(function (error) {
111 return streamObserver.onError(error);
112 });
113 } else {
114 streamObserver.onError((0, _error.newError)('Statements cannot be run directly on a ' + 'session with an open transaction; either run from within the ' + 'transaction or use a different session.'));
115 }
116 return new _result2.default(streamObserver, statement, parameters, function () {
117 return streamObserver.serverMetadata();
118 }, connectionHolder);
119 }
120
121 /**
122 * Begin a new transaction in this session. A session can have at most one transaction running at a time, if you
123 * want to run multiple concurrent transactions, you should use multiple concurrent sessions.
124 *
125 * While a transaction is open the session cannot be used to run statements outside the transaction.
126 *
127 * @param {string|string[]} [bookmarkOrBookmarks=null] - reference or references to some previous transactions.
128 * DEPRECATED: This parameter is deprecated in favour of {@link Driver#session} that accepts an initial bookmark.
129 * Session will ensure that all nested transactions are chained with bookmarks to guarantee causal consistency.
130 * @returns {Transaction} - New Transaction
131 */
132
133 }, {
134 key: 'beginTransaction',
135 value: function beginTransaction(bookmarkOrBookmarks) {
136 this._updateBookmark(new _bookmark2.default(bookmarkOrBookmarks));
137 return this._beginTransaction(this._mode);
138 }
139 }, {
140 key: '_beginTransaction',
141 value: function _beginTransaction(accessMode) {
142 var _this = this;
143
144 if (this._hasTx) {
145 throw (0, _error.newError)('You cannot begin a transaction on a session with an open transaction; ' + 'either run from within the transaction or use a different session.');
146 }
147
148 var mode = _driver2.default._validateSessionMode(accessMode);
149 var connectionHolder = this._connectionHolderWithMode(mode);
150 connectionHolder.initializeConnection();
151 this._hasTx = true;
152
153 return new _transaction2.default(connectionHolder, function () {
154 _this._hasTx = false;
155 }, this._onRunFailure(), this._lastBookmark, this._updateBookmark.bind(this));
156 }
157
158 /**
159 * Return the bookmark received following the last completed {@link Transaction}.
160 *
161 * @return {string|null} a reference to a previous transaction
162 */
163
164 }, {
165 key: 'lastBookmark',
166 value: function lastBookmark() {
167 return this._lastBookmark.maxBookmarkAsString();
168 }
169
170 /**
171 * Execute given unit of work in a {@link READ} transaction.
172 *
173 * Transaction will automatically be committed unless the given function throws or returns a rejected promise.
174 * Some failures of the given function or the commit itself will be retried with exponential backoff with initial
175 * delay of 1 second and maximum retry time of 30 seconds. Maximum retry time is configurable via driver config's
176 * <code>maxTransactionRetryTime</code> property in milliseconds.
177 *
178 * @param {function(tx: Transaction): Promise} transactionWork - callback that executes operations against
179 * a given {@link Transaction}.
180 * @return {Promise} resolved promise as returned by the given function or rejected promise when given
181 * function or commit fails.
182 */
183
184 }, {
185 key: 'readTransaction',
186 value: function readTransaction(transactionWork) {
187 return this._runTransaction(_driver.READ, transactionWork);
188 }
189
190 /**
191 * Execute given unit of work in a {@link WRITE} transaction.
192 *
193 * Transaction will automatically be committed unless the given function throws or returns a rejected promise.
194 * Some failures of the given function or the commit itself will be retried with exponential backoff with initial
195 * delay of 1 second and maximum retry time of 30 seconds. Maximum retry time is configurable via driver config's
196 * <code>maxTransactionRetryTime</code> property in milliseconds.
197 *
198 * @param {function(tx: Transaction): Promise} transactionWork - callback that executes operations against
199 * a given {@link Transaction}.
200 * @return {Promise} resolved promise as returned by the given function or rejected promise when given
201 * function or commit fails.
202 */
203
204 }, {
205 key: 'writeTransaction',
206 value: function writeTransaction(transactionWork) {
207 return this._runTransaction(_driver.WRITE, transactionWork);
208 }
209 }, {
210 key: '_runTransaction',
211 value: function _runTransaction(accessMode, transactionWork) {
212 var _this2 = this;
213
214 return this._transactionExecutor.execute(function () {
215 return _this2._beginTransaction(accessMode);
216 }, transactionWork);
217 }
218
219 /**
220 * Update value of the last bookmark.
221 * @param {Bookmark} newBookmark the new bookmark.
222 * @private
223 */
224
225 }, {
226 key: '_updateBookmark',
227 value: function _updateBookmark(newBookmark) {
228 if (newBookmark && !newBookmark.isEmpty()) {
229 this._lastBookmark = newBookmark;
230 }
231 }
232
233 /**
234 * Close this session.
235 * @param {function()} callback - Function to be called after the session has been closed
236 * @return
237 */
238
239 }, {
240 key: 'close',
241 value: function close() {
242 var _this3 = this;
243
244 var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {
245 return null;
246 };
247
248 if (this._open) {
249 this._open = false;
250 this._transactionExecutor.close();
251 this._readConnectionHolder.close().then(function () {
252 _this3._writeConnectionHolder.close().then(function () {
253 callback();
254 });
255 });
256 } else {
257 callback();
258 }
259 }
260
261 //Can be overridden to add error callback on RUN
262
263 }, {
264 key: '_onRunFailure',
265 value: function _onRunFailure() {
266 return function (err) {
267 return err;
268 };
269 }
270 }, {
271 key: '_connectionHolderWithMode',
272 value: function _connectionHolderWithMode(mode) {
273 if (mode === _driver.READ) {
274 return this._readConnectionHolder;
275 } else if (mode === _driver.WRITE) {
276 return this._writeConnectionHolder;
277 } else {
278 throw (0, _error.newError)('Unknown access mode: ' + mode);
279 }
280 }
281 }]);
282 return Session;
283}(); /**
284 * Copyright (c) 2002-2018 Neo4j Sweden AB [http://neo4j.com]
285 *
286 * This file is part of Neo4j.
287 *
288 * Licensed under the Apache License, Version 2.0 (the "License");
289 * you may not use this file except in compliance with the License.
290 * You may obtain a copy of the License at
291 *
292 * http://www.apache.org/licenses/LICENSE-2.0
293 *
294 * Unless required by applicable law or agreed to in writing, software
295 * distributed under the License is distributed on an "AS IS" BASIS,
296 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
297 * See the License for the specific language governing permissions and
298 * limitations under the License.
299 */
300
301
302function _createTransactionExecutor(config) {
303 var maxRetryTimeMs = config && config.maxTransactionRetryTime ? config.maxTransactionRetryTime : null;
304 return new _transactionExecutor2.default(maxRetryTimeMs);
305}
306
307exports.default = Session;
\No newline at end of file