| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384 |
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
4x
4x
4x
4x
4x
54x
54x
54x
54x
54x
54x
54x
54x
54x
52x
52x
52x
52x
5x
5x
5x
5x
3x
5x
5x
5x
5x
1x
4x
4x
4x
4x
4x
5x
5x
5x
5x
2x
5x
5x
5x
5x
1x
4x
4x
4x
4x
13x
13x
13x
4x
4x
4x
9x
9x
4x
9x
9x
9x
9x
1x
8x
8x
8x
2x
2x
2x
2x
1x
2x
2x
2x
2x
2x
2x
12x
2x
2x
4x
4x
4x
4x
2x
4x
4x
4x
4x
4x
8x
8x
8x
8x
24x
6x
6x
8x
4x
8x
8x
14x
14x
14x
8x
8x
6x
6x
6x
6x
3x
6x
6x
6x
6x
6x
6x
4x
6x
6x
10x
10x
10x
10x
5x
5x
5x
5x
5x
5x
5x
5x
5x
5x
5x
7x
7x
7x
7x
1x
1x
1x
6x
8x
6x
1x
| /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const DataService = require('composer-runtime').DataService;
const Logger = require('composer-common').Logger;
const pouchCollate = require('pouchdb-collate');
const PouchDB = require('pouchdb-core');
const PouchDBDataCollection = require('./pouchdbdatacollection');
const PouchDBUtils = require('./pouchdbutils');
const LOG = Logger.getLog('PouchDBDataService');
// Install the PouchDB plugins. The order of the adapters is important!
PouchDB.plugin(require('pouchdb-find'));
// This is the object type used to form composite keys for the collection of collections.
const collectionObjectType = '$syscollections';
/**
* Base class representing the data service provided by a {@link Container}.
* @protected
*/
class PouchDBDataService extends DataService {
/**
* Register the specified PouchDB plugin with PouchDB.
* @param {*} plugin The PouchDB plugin to register.
*/
static registerPouchDBPlugin (plugin) {
// No logging here as this is called during static initialization
// at startup, and we don't want to try and load the logger yet.
PouchDB.plugin(plugin);
}
/**
* Create a new instance of PouchDB.
* @param {string} name The name of the PouchDB database.
* @param {Object} [options] Optional options for PouchDB.
* @return {PouchDB} The new instance of PouchDB.
*/
static createPouchDB (name, options) {
const method = 'createPouchDB';
LOG.entry(method, name, options);
let result = new PouchDB(name, options);
LOG.exit(method, result);
return result;
}
/**
* Constructor.
* @param {string} [uuid] The UUID of the container.
* @param {boolean} [autocommit] Should this data service auto commit?
* @param {Object} [options] Optional options for PouchDB.
* @param {Object} [additionalConnectorOptions] Additional connector specific options for this transaction.
*/
constructor (uuid, autocommit, options, additionalConnectorOptions = {}) {
super();
const method = 'constructor';
LOG.entry(method, uuid, autocommit, options, additionalConnectorOptions);
this.uuid = uuid;
this.db = PouchDBDataService.createPouchDB('Composer', options);
this.autocommit = !!autocommit;
this.pendingActions = [];
this.additionalConnectorOptions = additionalConnectorOptions;
LOG.exit(method);
}
/**
* Destroy the database.
* @return {Promise} A promise that will be resolved when destroyed, or
* rejected with an error.
*/
destroy () {
const method = 'destroy';
LOG.entry(method);
return this.db.destroy()
.then(() => {
LOG.exit(method);
});
}
/**
* Create a collection with the specified ID.
* @param {string} id The ID of the collection.
* @param {force} [force] force creation, don't check for existence first.
* @return {Promise} A promise that will be resolved with a {@link DataCollection}
* when complete, or rejected with an error.
*/
createCollection (id, force) {
const method = 'createCollection';
LOG.entry(method, id, force);
let compositeKey = [collectionObjectType];
if (this.uuid) {
compositeKey.unshift(this.uuid);
}
compositeKey.push(id);
const key = pouchCollate.toIndexableString(compositeKey);
return PouchDBUtils.getDocument(this.db, key)
.then((doc) => {
if (doc && !force) {
throw new Error(`Failed to add collection with ID '${id}' as the collection already exists`);
}
return this.handleAction(() => {
return PouchDBUtils.putDocument(this.db, key, {});
});
})
.then(() => {
let result = new PouchDBDataCollection(this, this.db, id, this.uuid);
LOG.exit(method, result);
return result;
});
}
/**
* Delete a collection with the specified ID.
* @param {string} id The ID of the collection.
* @return {Promise} A promise that will be resolved when complete, or rejected
* with an error.
*/
deleteCollection (id) {
const method = 'deleteCollection';
LOG.entry(method, id);
let compositeKey = [collectionObjectType];
if (this.uuid) {
compositeKey.unshift(this.uuid);
}
compositeKey.push(id);
const key = pouchCollate.toIndexableString(compositeKey);
return PouchDBUtils.getDocument(this.db, key)
.then((doc) => {
if (!doc) {
throw new Error(`Collection with ID '${id}' does not exist`);
}
return this.handleAction(() => {
return this.clearCollection(id)
.then(() => {
return PouchDBUtils.removeDocument(this.db, key);
});
});
})
.then(() => {
LOG.exit(method);
});
}
/**
* Get the collection with the specified ID.
* @param {string} id The ID of the collection.
* @param {Boolean} bypass bypass existence check
* @return {Promise} A promise that will be resolved with a {@link DataCollection}
* when complete, or rejected with an error.
*/
async getCollection(id, bypass) {
const method = 'getCollection';
LOG.entry(method, id);
if (bypass) {
let result = new PouchDBDataCollection(this, this.db, id, this.uuid);
LOG.exit(method, result);
return result;
} else {
let compositeKey = [collectionObjectType];
if(this.uuid) {
compositeKey.unshift(this.uuid);
}
compositeKey.push(id);
const key = pouchCollate.toIndexableString(compositeKey);
let doc = await PouchDBUtils.getDocument(this.db, key);
if (!doc) {
throw new Error(`Collection with ID '${id}' does not exist`);
}
let result = new PouchDBDataCollection(this, this.db, id, this.uuid);
LOG.exit(method, result);
return result;
}
}
/**
* Remove all the data
* @return {Promise} A promise that will be resolved when complete, or rejected
* with an error.
*/
removeAllData () {
const method = 'removeAllData';
LOG.entry(method);
let compositeKey = [];
if (this.uuid) {
compositeKey.unshift(this.uuid);
}
const startKey = pouchCollate.toIndexableString(compositeKey);
const endCompositeKey = compositeKey;
endCompositeKey.push('\uffff');
const endKey = pouchCollate.toIndexableString(endCompositeKey);
return this.db.allDocs({include_docs : true, startkey : startKey, endkey : endKey, inclusive_end : false})
.then((response) => {
const docs = response.rows.map((row) => {
return {
_id : row.id,
_rev : row.value.rev,
_deleted : true
};
});
return this.db.bulkDocs(docs);
})
.then(() => {
LOG.exit(method);
});
}
/**
* Determine whether the collection with the specified ID exists.
* @param {string} id The ID of the collection.
* @return {Promise} A promise that will be resolved with a boolean
* indicating whether the collection exists.
*/
existsCollection (id) {
const method = 'existsCollection';
LOG.entry(method, id);
let compositeKey = [collectionObjectType];
if (this.uuid) {
compositeKey.unshift(this.uuid);
}
compositeKey.push(id);
const key = pouchCollate.toIndexableString(compositeKey);
return PouchDBUtils.getDocument(this.db, key)
.then((doc) => {
LOG.exit(method, !!doc);
return !!doc;
});
}
/**
* Execute a query across all objects stored in all collections, using a query
* string that is dependent on the current Blockchain platform.
* @param {string} queryString The query string for the current Blockchain platform.
* @return {Promise} A promise that will be resolved with an array of objects
* when complete, or rejected with an error.
*/
executeQuery (queryString) {
const method = 'executeQuery';
LOG.entry(method, queryString);
const query = JSON.parse(queryString);
// PouchDB doesn't deal with $class in the same way that CouchDB does, so
// we need to adapt the selector slightly.
['$class', '$registryType', '$registryId'].forEach((prop) => {
if (query.selector[`\\${prop}`]) {
query.selector[prop] = query.selector[`\\${prop}`];
delete query.selector[`\\${prop}`];
}
});
if (this.uuid) {
query.selector.$networkId = this.uuid;
}
return this.db.find(query)
.then((response) => {
const docs = response.docs.map((doc) => {
delete doc._id;
delete doc._rev;
return doc;
});
LOG.exit(method, docs);
return docs;
});
}
/**
* Remove all objects from the specified collection.
* @param {string} id The ID of the collection.
* @return {Promise} A promise that will be resolved when complete, or rejected
* with an error.
*/
clearCollection (id) {
const method = 'clearCollection';
LOG.entry(method, id);
let compositeKey = [id];
if (this.uuid) {
compositeKey.unshift(this.uuid);
}
const startKey = pouchCollate.toIndexableString(compositeKey);
const endCompositeKey = compositeKey;
endCompositeKey.push('\uffff');
const endKey = pouchCollate.toIndexableString(endCompositeKey);
return this.db.allDocs({startkey : startKey, endkey : endKey, inclusive_end : false})
.then((response) => {
const docs = response.rows.map((row) => {
return {
_id : row.id,
_rev : row.value.rev,
_deleted : true
};
});
return this.db.bulkDocs(docs);
})
.then(() => {
LOG.exit(method);
});
}
/**
* Handle an action against this data service. If auto commit is enabled, then
* the action will be instantly executed. Otherwise it will be queued until the
* transaction is prepared.
* @param {Function} actionFunction The function implementing the acyion.
* @return {Promise} A promise that will be resolved when complete, or rejected
* with an error.
*/
handleAction (actionFunction) {
const method = 'handleAction';
LOG.entry(method, actionFunction);
return Promise.resolve()
.then(() => {
if (this.autocommit) {
LOG.debug(method, 'Autocommit enabled, executing action');
LOG.exit(method);
return actionFunction();
} else {
LOG.debug(method, 'Autocommit disabled, queueing action');
this.pendingActions.push(actionFunction);
LOG.exit(method);
}
});
}
/**
* Called at the start of a transaction.
* @param {boolean} readOnly Is the transaction read-only?
*/
async transactionStart (readOnly) {
const method = 'transactionStart';
LOG.entry(method, readOnly);
await super.transactionStart(readOnly);
this.pendingActions = [];
LOG.exit(method);
}
/**
* Called when a transaction is preparing to commit.
*/
async transactionPrepare () {
const method = 'transactionPrepare';
LOG.entry(method);
await super.transactionPrepare();
if (this.additionalConnectorOptions.commit === false) {
LOG.debug('commit specified as false');
LOG.exit(method);
return;
}
for (const pendingAction of this.pendingActions) {
await pendingAction();
}
LOG.exit(method);
}
}
module.exports = PouchDBDataService;
|