@routier/pouchdb-plugin 0.0.1-alpha.1

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.
@@ -0,0 +1,930 @@
1
+ import PouchDB from 'pouchdb';
2
+ import { PouchDbTranslator } from './PouchDbTranslator';
3
+ import { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';
4
+ import { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';
5
+ import { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, EntityUpdateInfo, IDbPlugin, IQuery } from '@routier/core/plugins';
6
+ import { CallbackResult, PluginEventCallbackPartialResult, PluginEventCallbackResult, PluginEventResult, Result } from '@routier/core/results';
7
+ import { assertIsNotNull } from '@routier/core/assertions';
8
+ import { combineExpressions, ComparatorExpression, Expression, getProperties } from '@routier/core/expressions';
9
+ import { BulkPersistChanges, BulkPersistResult, SchemaCollection, UnknownRecord } from '@routier/core';
10
+
11
+ const queue = new SyncronousQueue();
12
+ const INDEX_NAME = "routier_pdb_indexes"
13
+ const cache: Record<string, unknown> = {};
14
+
15
+ type PouchDBPluginOptions = PouchDB.Configuration.DatabaseConfiguration & {
16
+ queryType?: "default" | "memory-optimized" | "experimental";
17
+ sync?: PouchDB.Replication.SyncOptions & {
18
+ remoteDb: string;
19
+ onChange?: (schemas: SchemaCollection, change: PouchDB.Replication.SyncResult<{}>) => void;
20
+ onError?: (error: any) => void;
21
+ onComplete?: (info: PouchDB.Replication.SyncResult<{}>) => void;
22
+ onPaused?: (info: PouchDB.Replication.SyncResult<{}>) => void;
23
+ onActive?: (info: PouchDB.Replication.SyncResult<{}>) => void;
24
+ onDenied?: (info: PouchDB.Replication.SyncResult<{}>) => void;
25
+ auth?: {
26
+ username: string;
27
+ password: string;
28
+ };
29
+ headers?: { [key: string]: string };
30
+ };
31
+ }
32
+
33
+ export type PouchDbDesignDoc = {
34
+ _id: string;
35
+ language?: string;
36
+ views?: {
37
+ [viewName: string]: {
38
+ map: string | Function;
39
+ reduce?: string | Function;
40
+ };
41
+ };
42
+ filters?: {
43
+ [filterName: string]: string | Function;
44
+ };
45
+ validate_doc_update?: string | Function;
46
+ options?: Record<string, any>;
47
+ [key: string]: any; // allow other CouchDB features
48
+ }
49
+
50
+ type MatchingIndex = {
51
+ viewName: string,
52
+ properties: {
53
+ property: PropertyInfo<any>,
54
+ value: unknown
55
+ }[]
56
+ }
57
+
58
+ export class PouchDbPlugin implements IDbPlugin {
59
+
60
+ private readonly _name: string;
61
+ private readonly _options?: PouchDBPluginOptions;
62
+
63
+ constructor(name: string, options?: PouchDBPluginOptions) {
64
+ this._name = name;
65
+ this._options = options;
66
+ }
67
+
68
+ private _tryStartSync(schemas: SchemaCollection) {
69
+ if (this._options?.sync != null) {
70
+
71
+ if (cache["sync"] == null) {
72
+ cache["sync"] = {}; // placeholder
73
+ const localDb = new PouchDB(this._name);
74
+ const remoteDb = new PouchDB(this._options.sync.remoteDb);
75
+
76
+ // Set up sync
77
+ const sync = localDb.sync(remoteDb, {
78
+ ...this._options.sync
79
+ });
80
+
81
+ sync.on('change', (change) => this._options.sync.onChange(schemas, change));
82
+
83
+ cache["sync"] = sync;
84
+ }
85
+ }
86
+ }
87
+
88
+ private _identityBulkOperations(identitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {
89
+
90
+ if (changes.aggregate.size === 0) {
91
+ done(Result.success())
92
+ return;
93
+ }
94
+
95
+ // Link each entity to a schema id below so we can easily look up the schema id for an entity
96
+ const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];
97
+ const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];
98
+ const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];
99
+
100
+ for (const [schemaId, schemaChanges] of changes) {
101
+
102
+ if (identitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {
103
+ continue;
104
+ }
105
+
106
+ updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));
107
+ adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));
108
+ removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));
109
+ }
110
+
111
+ // Do adds separate. Updates/Removes already have an id that we can reference
112
+ // Default can do the same as updates/removes below since it has an id
113
+ // Check again now to see if we have any identity schema changes
114
+ if (updates.length === 0 && removes.length === 0 && adds.length === 0) {
115
+ done(Result.success())
116
+ return;
117
+ }
118
+
119
+ this._doWork((db, d) => {
120
+ try {
121
+
122
+ const updatedDocuments = [...updates].map(w => w.change.entity);
123
+ const errors: any[] = [];
124
+
125
+ db.bulkDocs([...removes.map(w => ({ _id: w.entity._id, _rev: w.entity._rev, _deleted: true })), ...updatedDocuments], null, (error, response) => {
126
+
127
+ if (error) {
128
+ d(Result.error(error));
129
+ return;
130
+ }
131
+
132
+ for (let i = 0, length = response.length; i < length; i++) {
133
+ const doc = response[i];
134
+
135
+ if ("error" in doc && doc.error === true) {
136
+ errors.push(doc); // send back the entire error
137
+ continue;
138
+ }
139
+
140
+ if ("id" in doc && "ok" in doc) {
141
+ const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);
142
+
143
+ if (updatesIndex !== -1) {
144
+ // Optimistically assume that the update worked as expected
145
+ const update = updates[updatesIndex];
146
+
147
+ const changesResult = result.get(update.schemaId);
148
+
149
+ // Set the new rev
150
+ (update.change.entity as UnknownRecord)._rev = doc.rev;
151
+
152
+ changesResult.updates.push(update.change.entity);
153
+ continue;
154
+ }
155
+
156
+ const removesIndex = removes.findIndex(x => x.entity._id === doc.id);
157
+
158
+ if (removesIndex !== -1) {
159
+
160
+ const remove = removes[removesIndex];
161
+
162
+ const changesResult = result.get(remove.schemaId);
163
+
164
+ changesResult.removes.push(remove.entity);
165
+ }
166
+ }
167
+ }
168
+
169
+ if (errors.length > 0) {
170
+ d(Result.error(errors));
171
+ return;
172
+ }
173
+
174
+ const pipeline = new WorkPipeline();
175
+
176
+ for (let i = 0, length = identitySchemaIds.length; i < length; i++) {
177
+ const schemaId = identitySchemaIds[i];
178
+ pipeline.pipe((d) => {
179
+ const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);
180
+ const schemaResult = result.get(schemaId);
181
+
182
+ assertIsNotNull(schemaResult);
183
+ assertIsNotNull(schemaAdds);
184
+
185
+ db.bulkDocs([...schemaAdds], null, (error, response) => {
186
+
187
+ if (error) {
188
+ d(Result.error(error));
189
+ return;
190
+ }
191
+
192
+ const ids = response.map(x => x.id);
193
+
194
+ for (let i = 0, length = response.length; i < length; i++) {
195
+
196
+ const doc = response[i];
197
+
198
+ if ("error" in doc) {
199
+
200
+ const reason = doc.reason ?? doc.error;
201
+
202
+ d(Result.error(reason));
203
+ return;
204
+ }
205
+
206
+ if ("id" in doc && "ok" in doc) {
207
+ ids.push(doc.id);
208
+ } else {
209
+ d(Result.error(doc.error));
210
+ return;
211
+ }
212
+ }
213
+
214
+ this._bulkGetAdditions(ids, (bulkGetResponse) => {
215
+
216
+ if (bulkGetResponse.ok !== Result.SUCCESS) {
217
+ d(Result.error(bulkGetResponse));
218
+ return;
219
+ }
220
+
221
+ for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {
222
+ const docs = bulkGetResponse.data.results[i].docs;
223
+
224
+ if (docs.length === 1) {
225
+ const doc = docs[0];
226
+
227
+ if ("ok" in doc) {
228
+ schemaResult.adds.push(doc.ok as any);
229
+ }
230
+ }
231
+ }
232
+
233
+ d(Result.success());
234
+ });
235
+ });
236
+
237
+ });
238
+ }
239
+
240
+ pipeline.filter((r) => {
241
+ if (r.ok !== Result.SUCCESS) {
242
+ d(r);
243
+ return;
244
+ }
245
+
246
+ d(Result.success());
247
+ });
248
+ });
249
+ } catch (e) {
250
+ d(Result.error(e));
251
+ }
252
+ }, done);
253
+ }
254
+
255
+ private _defaultBulkOperations(nonIdentitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {
256
+
257
+ if (changes.aggregate.size === 0) {
258
+ done(Result.success())
259
+ return;
260
+ }
261
+
262
+ // Link each entity to a schema id below so we can easily look up the schema id for an entity
263
+ const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];
264
+ const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];
265
+ const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];
266
+
267
+ for (const [schemaId, schemaChanges] of changes) {
268
+
269
+ if (nonIdentitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {
270
+ continue;
271
+ }
272
+
273
+ updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));
274
+ adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));
275
+ removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));
276
+ }
277
+
278
+ if (updates.length === 0 && removes.length === 0 && adds.length === 0) {
279
+ done(Result.success())
280
+ return;
281
+ }
282
+
283
+ this._doWork((db, d) => {
284
+ try {
285
+
286
+ db.bulkDocs([
287
+ ...removes.map(x => ({ _id: x.entity._id, _rev: x.entity._rev, _deleted: true })),
288
+ ...updates.map(x => x.change.entity)
289
+ ], null, (error, response) => {
290
+
291
+ if (error != null) {
292
+ d(Result.error(error));
293
+ return;
294
+ }
295
+
296
+ for (let i = 0, length = response.length; i < length; i++) {
297
+ const doc = response[i];
298
+
299
+ if ("error" in doc) {
300
+
301
+ const reason = doc.reason ?? doc.error;
302
+
303
+ d(Result.error(reason));
304
+ return;
305
+ }
306
+
307
+ const removesIndex = removes.findIndex(x => x.entity._id === doc.id);
308
+
309
+ if (removesIndex !== -1) {
310
+ const { schemaId } = removes[removesIndex]
311
+ const schemaResult = result.get(schemaId);
312
+
313
+ assertIsNotNull(schemaResult);
314
+
315
+ schemaResult.removes.push(doc as any);
316
+ continue;
317
+ }
318
+
319
+ const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);
320
+
321
+ if (updatesIndex !== -1) {
322
+ // Optimistically assume that the update worked as expected
323
+ const update = updates[updatesIndex];
324
+
325
+ const changesResult = result.get(update.schemaId);
326
+
327
+ // Set the new rev
328
+ (update.change.entity as UnknownRecord)._rev = doc.rev;
329
+
330
+ changesResult.updates.push(update.change.entity);
331
+ continue;
332
+ }
333
+
334
+ d(Result.error(new Error("Cannot classify resulting doc")));
335
+ return;
336
+ }
337
+
338
+ const pipeline = new WorkPipeline();
339
+
340
+ for (let i = 0, length = nonIdentitySchemaIds.length; i < length; i++) {
341
+ const schemaId = nonIdentitySchemaIds[i];
342
+ pipeline.pipe((d) => {
343
+ const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);
344
+ const schemaResult = result.get(schemaId);
345
+
346
+ assertIsNotNull(schemaResult);
347
+ assertIsNotNull(schemaAdds);
348
+
349
+ db.bulkDocs([...schemaAdds], null, (error, response) => {
350
+
351
+ if (error) {
352
+ d(Result.error(error));
353
+ return;
354
+ }
355
+
356
+ const ids = response.map(x => x.id);
357
+
358
+ for (let i = 0, length = response.length; i < length; i++) {
359
+
360
+ const doc = response[i];
361
+
362
+ if ("error" in doc) {
363
+
364
+ const reason = doc.reason ?? doc.error;
365
+
366
+ d(Result.error(reason));
367
+ return;
368
+ }
369
+
370
+ if ("id" in doc && "ok" in doc) {
371
+ ids.push(doc.id);
372
+ } else {
373
+ d(Result.error(doc.error));
374
+ return;
375
+ }
376
+ }
377
+
378
+ this._bulkGetAdditions(ids, (bulkGetResponse) => {
379
+
380
+ if (bulkGetResponse.ok !== Result.SUCCESS) {
381
+ d(Result.error(bulkGetResponse));
382
+ return;
383
+ }
384
+
385
+ for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {
386
+ const docs = bulkGetResponse.data.results[i].docs;
387
+
388
+ if (docs.length === 1) {
389
+ const doc = docs[0];
390
+
391
+ if ("ok" in doc) {
392
+ schemaResult.adds.push(doc.ok as any);
393
+ }
394
+ }
395
+ }
396
+
397
+ d(Result.success());
398
+ });
399
+ });
400
+
401
+ });
402
+ }
403
+
404
+ pipeline.filter((r) => {
405
+ if (r.ok !== Result.SUCCESS) {
406
+ d(r);
407
+ return;
408
+ }
409
+
410
+ d(Result.success());
411
+ });
412
+ });
413
+ } catch (e) {
414
+ d(Result.error(e));
415
+ }
416
+ }, done);
417
+ }
418
+
419
+ private _prepareProperties(...properties: PropertyInfo<any>[]) {
420
+
421
+ properties.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));
422
+ const paths = properties.map(w => w.getAssignmentPath({ parent: "doc" }));
423
+ const viewName = `by_${paths.join("_")}`;
424
+
425
+ return {
426
+ properties,
427
+ paths,
428
+ viewName
429
+ }
430
+ }
431
+
432
+ private resolveIndexes<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<PouchDbDesignDoc | null>) {
433
+
434
+ const indexes = event.operation.schema.getIndexes();
435
+
436
+ if (indexes.length === 0) {
437
+ done(Result.success(null));
438
+ return;
439
+ }
440
+
441
+ if (cache["indexes"]) {
442
+ done(Result.success(cache["indexes"] as PouchDbDesignDoc));
443
+ return; // Already built
444
+ }
445
+
446
+ const ddoc: PouchDbDesignDoc = {
447
+ _id: `_design/${INDEX_NAME}`,
448
+ views: {}
449
+ }
450
+
451
+ for (let i = 0, length = indexes.length; i < length; i++) {
452
+ const index = indexes[i];
453
+ const { viewName, paths } = this._prepareProperties(...index.properties);
454
+
455
+ if (index.properties.length === 1) {
456
+ const property = index.properties[0];
457
+ const path = property.getAssignmentPath({ parent: "doc" });
458
+ ddoc.views[viewName] = {
459
+ map: `function(doc) {
460
+ if (${path}) {
461
+ emit(${path});
462
+ }
463
+ }`
464
+ }
465
+ continue;
466
+ }
467
+
468
+ ddoc.views[viewName] = {
469
+ map: `function(doc) {
470
+ if (${paths.join(" && ")}) {
471
+ emit([${paths.join(",")}]);
472
+ }
473
+ }`
474
+ }
475
+ }
476
+
477
+ this._doWork((db, d) => {
478
+ // change this out in the future? or make a new index, this does not return the rev which makes us need to call get again below
479
+ db.allDocs({
480
+ startkey: '_design/',
481
+ endkey: '_design0',
482
+ include_docs: true
483
+ }).then(response => {
484
+
485
+ // if we have no indexes, let's create it
486
+ if (response.rows.length === 0) {
487
+ db.put(ddoc as any, {}, (e) => {
488
+ if (e) {
489
+ d(Result.error(e));
490
+ return;
491
+ }
492
+
493
+ cache["indexes"] = ddoc;
494
+
495
+ d(Result.success(ddoc));
496
+ });
497
+ return;
498
+ }
499
+
500
+ const matchingIndex = response.rows.find(x => x.id === `_design/${INDEX_NAME}`);
501
+
502
+ // make sure we have the correct index created
503
+ if (matchingIndex == null) {
504
+ db.put(ddoc as any, {}, (e) => {
505
+ if (e) {
506
+ d(Result.error(e));
507
+ return;
508
+ }
509
+
510
+ cache["indexes"] = ddoc;
511
+
512
+ d(Result.success(ddoc));
513
+ });
514
+ return;
515
+ }
516
+
517
+ assertIsNotNull(ddoc.views);
518
+ assertIsNotNull(matchingIndex.doc);
519
+
520
+ const views = Object.keys(ddoc.views)
521
+
522
+ // make sure all of the views are in the document, if not update it
523
+ if (views.some(x => (matchingIndex.doc as any).views[x] == null)) {
524
+
525
+ // need to get the rev
526
+ db.get(ddoc._id, {}, (e, result) => {
527
+
528
+ if (e != null) {
529
+ d(Result.error(e));
530
+ return;
531
+ }
532
+
533
+ (result as any).views = ddoc.views
534
+
535
+ db.put(result as any, {}, (e) => {
536
+
537
+ if (e) {
538
+ d(Result.error(e));
539
+ return;
540
+ }
541
+
542
+ cache["indexes"] = ddoc;
543
+
544
+ d(Result.success(ddoc));
545
+ });
546
+ })
547
+ return;
548
+ }
549
+
550
+ d(Result.success(ddoc));
551
+ }).catch(e => {
552
+ d(Result.error(e));
553
+ });
554
+ }, done)
555
+ }
556
+
557
+ // id should be a string here because this is only run on identity inserts
558
+ private _bulkGetAdditions<TEntity extends {}>(ids: string[], done: CallbackResult<PouchDB.Core.BulkGetResponse<TEntity>>) {
559
+
560
+ if (ids.length === 0) {
561
+ done(Result.success({ results: [] }));
562
+ return;
563
+ }
564
+
565
+ this._doWork((db, d) => {
566
+ db.bulkGet<TEntity>({
567
+ docs: ids.map(w => ({ id: w as string }))
568
+ }, (error, response) => {
569
+
570
+ if (error) {
571
+ d(Result.error(error));
572
+ return
573
+ }
574
+
575
+ d(Result.success(response));
576
+ });
577
+ }, done);
578
+ }
579
+
580
+ private _validateSchemas(event: DbPluginBulkPersistEvent) {
581
+ for (const [, schema] of event.schemas) {
582
+ if (schema.idProperties.length > 1) {
583
+ throw new Error("PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key")
584
+ }
585
+ }
586
+ }
587
+
588
+ private _bulkPersist(
589
+ event: DbPluginBulkPersistEvent,
590
+ done: PluginEventCallbackPartialResult<BulkPersistResult>) {
591
+
592
+ this._validateSchemas(event);
593
+ this._tryStartSync(event.schemas);
594
+
595
+ const result = event.operation.toResult();
596
+ const identitySchemaIds: SchemaId[] = [];
597
+ const defaultSchemaIds: SchemaId[] = [];
598
+
599
+ for (const [schemaId, schema] of event.schemas) {
600
+
601
+ if (schema.hasIdentityKeys) {
602
+ identitySchemaIds.push(schemaId);
603
+ continue;
604
+ }
605
+
606
+ defaultSchemaIds.push(schemaId);
607
+ }
608
+
609
+ this._identityBulkOperations(identitySchemaIds, event.operation, result, (identityResult) => {
610
+
611
+ if (identityResult.ok !== Result.SUCCESS) {
612
+ done(PluginEventResult.error(event.id, identityResult.error))
613
+ return;
614
+ }
615
+
616
+ this._defaultBulkOperations(defaultSchemaIds, event.operation, result, (defaultResult) => {
617
+
618
+ if (defaultResult.ok !== Result.SUCCESS) {
619
+ done(PluginEventResult.error(event.id, defaultResult.error))
620
+ return;
621
+ }
622
+
623
+ done(PluginEventResult.success(event.id, result))
624
+ });
625
+
626
+ });
627
+ }
628
+
629
+ private _doWork<TResult, TEntity>(work: (db: PouchDB.Database<TEntity>, done: CallbackResult<TResult>) => void, done: CallbackResult<TResult>, shouldClose: boolean = false) {
630
+ const { sync, queryType, ...rest } = this._options ?? {};
631
+ const db = new PouchDB<TEntity>(this._name, rest);
632
+
633
+ work(db, (result) => {
634
+
635
+ if (shouldClose) {
636
+ db.close(() => done(result));
637
+ }
638
+
639
+ done(result);
640
+ })
641
+ }
642
+
643
+ destroy(_event: DbPluginEvent, done: (error?: any) => void): void {
644
+ // this needs to be queued too
645
+ this._doWork((w, d) => {
646
+ w.destroy(null, (e) => {
647
+ if (e) {
648
+ d(Result.error(e))
649
+ return;
650
+ }
651
+
652
+ d(Result.success());
653
+ });
654
+ }, done, false);
655
+ }
656
+
657
+
658
+ bulkPersist(
659
+ event: DbPluginBulkPersistEvent,
660
+ done: PluginEventCallbackPartialResult<BulkPersistResult>) {
661
+
662
+ const unitOfWork: SyncronousUnitOfWork = (d) => this._bulkPersist(event, (r) => {
663
+ d();
664
+ done(r)
665
+ })
666
+
667
+ queue.enqueue(unitOfWork.bind(this));
668
+ }
669
+
670
+ query<TRoot extends {}, TShape extends any = TRoot>(event: DbPluginQueryEvent<TRoot, TShape>, done: PluginEventCallbackResult<TShape>): void {
671
+
672
+ this._tryStartSync(event.schemas);
673
+
674
+ const unitOfWork: SyncronousUnitOfWork = (d) => this._query<TRoot, TShape>(event, (r) => {
675
+ d();
676
+ done(r)
677
+ })
678
+
679
+ queue.enqueue(unitOfWork.bind(this));
680
+ }
681
+
682
+ protected onGetIndex<TEntity extends {}, TShape extends unknown = TEntity>(_: IQuery<TEntity, TShape>, __: PouchDB.Find.FindRequest<unknown>, done: (result: null | string | [string, string]) => void) {
683
+ done(null);
684
+ }
685
+
686
+ extractEqualityValueForProperty(expression: Expression, prop: PropertyInfo<any>): any | undefined {
687
+ // Recursively search for a comparator expression that matches the property
688
+ if (expression.type === "comparator" && (expression as ComparatorExpression).comparator === "equals") {
689
+ // Check left side is property, right side is value
690
+ if (expression.left && expression.left.type === "property" && (expression.left as any).property.name === prop.name && expression.right && expression.right.type === "value") {
691
+ return (expression.right as any).value;
692
+ }
693
+ // Or right side is property, left side is value
694
+ if (expression.right && expression.right.type === "property" && (expression.right as any).property.name === prop.name && expression.left && expression.left.type === "value") {
695
+ return (expression.left as any).value;
696
+ }
697
+ }
698
+ // Recursively check left and right
699
+ if (expression.left) {
700
+ const left = this.extractEqualityValueForProperty(expression.left, prop);
701
+ if (left !== undefined) return left;
702
+ }
703
+ if (expression.right) {
704
+ const right = this.extractEqualityValueForProperty(expression.right, prop);
705
+ if (right !== undefined) return right;
706
+ }
707
+ return undefined;
708
+ }
709
+
710
+ private _findMatchingIndex(ddoc: PouchDbDesignDoc, expression: Expression): MatchingIndex {
711
+ const queryProperties = getProperties(expression);
712
+
713
+ const { viewName } = this._prepareProperties(...queryProperties);
714
+
715
+ if (ddoc.views == null) {
716
+ return null;
717
+ }
718
+
719
+ const index = ddoc.views[viewName];
720
+
721
+ if (index == null) {
722
+ return null;
723
+ }
724
+
725
+ const properties: MatchingIndex["properties"] = [];
726
+
727
+ for (const property of queryProperties) {
728
+ const value = this.extractEqualityValueForProperty(expression, property);
729
+
730
+ if (value === undefined) {
731
+ return null
732
+ }
733
+
734
+ properties.push({
735
+ property,
736
+ value
737
+ });
738
+ }
739
+
740
+ return {
741
+ viewName,
742
+ properties
743
+ };
744
+ }
745
+
746
+ private _queryIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, matchingIndex: MatchingIndex, done: CallbackResult<TShape>) {
747
+ const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);
748
+ this._doWork((w, d) => {
749
+
750
+ const options: PouchDB.Query.Options<any, any> = {
751
+ include_docs: true,
752
+ };
753
+
754
+ const values = matchingIndex.properties.map(x => x.value);
755
+
756
+ if (values.some(x => x == null) == false) {
757
+
758
+ if (values.length === 1) {
759
+ options.key = values[0];
760
+ } else {
761
+ options.keys = values;
762
+ }
763
+ }
764
+
765
+ w.query(`${INDEX_NAME}/${matchingIndex.viewName}`, options, (error, response) => {
766
+
767
+ if (error != null) {
768
+ d(Result.error(error));
769
+ return;
770
+ }
771
+
772
+ const translated = translator.translate(response.rows.map(w => w.doc));
773
+ d(Result.success(translated));
774
+ });
775
+ }, done);
776
+ }
777
+
778
+ private _queryNoIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<TShape>) {
779
+ const filters = event.operation.options.get("filter")
780
+ if (filters.length === 0) {
781
+ this._queryWithNoFilters(event, done);
782
+ return;
783
+ }
784
+
785
+ this._queryWithFilters(event, done);
786
+ }
787
+
788
+ private _queryWithNoFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<TShape>) {
789
+ const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);
790
+ this._doWork((w, d) => {
791
+ w.allDocs({
792
+ include_docs: true
793
+ }).then(response => {
794
+ const data = response.rows.map(w => w.doc);
795
+ const translated = translator.translate(data);
796
+ d(Result.success(translated));
797
+ }).catch(error => {
798
+ d(Result.error(error));
799
+ });
800
+ }, done);
801
+ }
802
+
803
+ private _queryWithFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<TShape>) {
804
+ const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);
805
+ this._doWork((w, d) => {
806
+
807
+ if (this._name.startsWith("http")) {
808
+ // Cannot query remote databases using translator.matches, fallback to alldocs
809
+ // Does not throw, will fail on the remote server
810
+ w.allDocs({
811
+ include_docs: true
812
+ }).then(response => {
813
+ const data = response.rows.map(w => w.doc);
814
+ const translated = translator.translate(data);
815
+ d(Result.success(translated));
816
+ }).catch(error => {
817
+ d(Result.error(error));
818
+ });
819
+ return;
820
+ }
821
+
822
+ w.query<{}, any>((doc, emit) => {
823
+ if (typeof doc === "object" && "_id" in doc && translator.matches(doc)) {
824
+ emit(doc._id, doc);
825
+ }
826
+ }, (error, response) => {
827
+
828
+ if (error != null) {
829
+ d(Result.error(error));
830
+ return;
831
+ }
832
+
833
+ const data = response.rows.map(w => w.value);
834
+ const translated = translator.translate(data);
835
+ d(Result.success(translated));
836
+ });
837
+
838
+ }, done);
839
+ }
840
+
841
+ private _query<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: PluginEventCallbackResult<TShape>): void {
842
+ this.resolveIndexes(event, (r) => {
843
+ if (r.ok !== Result.SUCCESS) {
844
+ done(PluginEventResult.error(event.id, r.error))
845
+ return;
846
+ }
847
+
848
+ const ddoc = r.data;
849
+
850
+ if (ddoc == null) {
851
+ this._queryNoIndex(event, done);
852
+ return;
853
+ }
854
+
855
+ const mapMatchingIndex = this.findMatchingIndexForMap(ddoc, event);
856
+
857
+ if (mapMatchingIndex != null) {
858
+ this._queryIndex(event, mapMatchingIndex, done);
859
+ return;
860
+ }
861
+
862
+ const expression = this._getExpressionFromQuery(event);
863
+
864
+ if (Expression.isEmpty(expression)) {
865
+ this._queryNoIndex(event, done);
866
+ return;
867
+ }
868
+
869
+ const matchingIndex = this._findMatchingIndex(ddoc, expression);
870
+
871
+ if (matchingIndex == null) {
872
+ this._queryNoIndex(event, done);
873
+ return;
874
+ }
875
+
876
+ this._queryIndex(event, matchingIndex, done);
877
+ });
878
+ }
879
+
880
+ private _getExpressionFromQuery<TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>) {
881
+ const filters = event.operation.options.get("filter");
882
+
883
+ const databaseFilters = filters.filter(x => x.option.target === "database");
884
+
885
+ if (databaseFilters.length === 0) {
886
+ return Expression.EMPTY;
887
+ }
888
+
889
+ const expressions = databaseFilters.map(x => x.option.value.expression);
890
+
891
+ return combineExpressions(...expressions);
892
+ }
893
+
894
+ private findMatchingIndexForMap<TEntity extends {}, TShape>(ddoc: PouchDbDesignDoc, event: DbPluginQueryEvent<TEntity, TShape>): MatchingIndex | null {
895
+ const map = event.operation.options.getLast("map");
896
+ const filters = event.operation.options.get("filter");
897
+
898
+ // we only want to look at the index if there are no filters
899
+ if (filters.length > 0) {
900
+ return null;
901
+ }
902
+
903
+ if (map == null || map.target !== "database") {
904
+ return null;
905
+ }
906
+
907
+ if (map.value.fields.length !== 1 || map.value.fields[0].property == null) {
908
+ return null;
909
+ }
910
+
911
+ const property = map.value.fields[0].property;
912
+
913
+ const { viewName } = this._prepareProperties(property);
914
+
915
+ if (ddoc.views == null) {
916
+ return null;
917
+ }
918
+
919
+ const index = ddoc.views[viewName];
920
+
921
+ if (index == null) {
922
+ return null;
923
+ }
924
+
925
+ return {
926
+ viewName,
927
+ properties: [{ property, value: null }]
928
+ }
929
+ }
930
+ }