-
Notifications
You must be signed in to change notification settings - Fork 2
/
AccessMongoDBAndMySQL.js
1536 lines (1324 loc) · 67.2 KB
/
AccessMongoDBAndMySQL.js
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* @License Starts
*
* Copyright © 2015 - present. MongoExpUser
*
* License: MIT - See: https://github.com/MongoExpUser/Shale-Reservoir-DNN-and-Drilling-Rare-Events-Graph/blob/master/README.md
*
* @License Ends
*
*
* ...Ecotert's AccessMongoDBAndMySQL.js (released as open-source under MIT License) implements:
*
* A) AccessMongoDBAndMySQL() class to:
* i) connect to and carry out CRUD operations & simple queries on MongoDB & MySQL (both regular SQL & NoSQL/Document Store)
* ii) upload/download files
*
* using:
*
* (1) MongoDB native driver - https://www.npmjs.com/package/mongodb
* (2) Mongoose ORM - https://www.npmjs.com/package/mongoose
* (3) MySQL Node.js driver - https://www.npmjs.com/package/mysql
* (4) MySQL Connector/Node.js - https://www.npmjs.com/package/@mysql/xdevapi
* (5) Node.js file system & stream modules and MongoDB GridFS
*
* B) TestAccessMongoDBAndMySQL() class: to test AccessMongoDBAndMySQL() class
*
*/
class AccessMongoDBAndMySQL
{
constructor()
{
return null;
}
static getMongoDBCollectionNames(collectionsList)
{
const namesList = [];
for(let index in collectionsList)
{
for(let key in collectionsList[index])
{
if(key === "name")
{
namesList.push(collectionsList[index]["name"]);
}
}
}
return namesList;
}
static getMySQLDocumentStoreCollectionNames(collectionsList)
{
const namesList = [];
for(let index = 0; index < collectionsList.length; index++)
{
namesList.push(collectionsList[index].inspect().collection)
}
return namesList;
}
static collectionExist(collectionNamesList, collectionName)
{
for(let index in collectionNamesList)
{
if(collectionNamesList[index] === collectionName)
{
return true;
}
}
return false;
}
static convertMapToObject(inputMap)
{
const outputObject = {};
inputMap.forEach(function(value, key)
{
outputObject[key] = value;
});
return outputObject;
}
static validDocument(keys, values)
{
return (keys !== null) && (keys !== undefined) && (values !== null) &&
(values !== undefined) && (keys.length === values.length);
}
static reservoirdataPipelineForAnalytics(nthLimit=undefined, reservoirZone=undefined, option=undefined)
{
let sqlQuery = "";
if(nthLimit === null || nthLimit === undefined)
{
//default nthLimit to 5, if not given or undefined as argument
nthLimit = 5;
}
switch(option)
{
// 1. nth top-most prolific very-sandy SPECIFIED "reservoirZone"
case ("prolificReservoirZones"):
sqlQuery = "" +
"SELECT rsp.Reservoir_ID, rsp.Cum_prod_mm_bbls, rsp.Prod_Rate_m_bopd, rsp.Days " +
"FROM ReservoirProduction rsp " +
"INNER JOIN Reservoir rs ON rsp.Reservoir_ID=rs.Reservoir_ID " +
"WHERE rs.Reservoir_Zone=" + "'" + reservoirZone + "'" + " AND rs.Avg_GR_api<30 " +
"ORDER BY rsp.Cum_prod_mm_bbls " +
"LIMIT " + String(nthLimit) + ";";
break;
// 2. nth top-most thick SPECIFIED "reservoirZone", with Reservoir_ID, Cum_prod and Days
case ("thickestReservoirZones"):
sqlQuery = "" +
"SELECT rs.Reservoir_Zone, rso.Net_pay_ft, rs.Reservoir_ID, rsp.Cum_prod_mm_bbls, rsp.Days " +
"FROM Reservoir rs " +
"INNER JOIN ReservoirSTOOIP rso ON rs.Reservoir_ID=rso.Reservoir_ID " +
"INNER JOIN ReservoirProduction rsp ON rs.Reservoir_ID=rsp.Reservoir_ID " +
"ORDER BY rsp.Cum_prod_mm_bbls " +
"LIMIT " + String(nthLimit) + ";";
break;
// 3. all Reservoir_Zone(s), with Reservoir_ID, Top_TVD_ft, STOOIP_mm_bbls, Net_pay_ft, Cum_prod and Days
case ("allReservoirZonesAndVolumeIndicators"):
sqlQuery = "" +
"SELECT rs.Reservoir_Zone, rs.Reservoir_ID, rs.Top_TVD_ft, rso.STOOIP_mm_bbls, rso.Net_pay_ft, rsp.Cum_prod_mm_bbls, rsp.Days " +
"FROM Reservoir rs " +
"INNER JOIN ReservoirSTOOIP rso ON rs.Reservoir_ID=rso.Reservoir_ID " +
"INNER JOIN ReservoirProduction rsp ON rs.Reservoir_ID=rsp.Reservoir_ID " +
"ORDER BY rsp.Days;";
break;
// 4. all properties ON all TABLES (Reservoir, ReservoirSTOOIP & ReservoirProduction)
case ("all"):
sqlQuery = "" +
"SELECT * " +
"FROM Reservoir rs " +
"INNER JOIN ReservoirSTOOIP rso ON rs.Reservoir_ID=rso.Reservoir_ID " +
"INNER JOIN ReservoirProduction rsp ON rs.Reservoir_ID=rsp.Reservoir_ID;";
break;
// 5. default
default:
//do nothing: ...add more data pipelines as deem necessary
break;
}
return sqlQuery;
}
static reservoirTableSchema()
{
//define schema variable and bracket, with correct spaces & commas
let schema = "";
let closeBracket = ")";
let openBracket = "(";
let closeIndexBracket = "), "
//define input keys
let inputKeys = AccessMongoDBAndMySQL.reservoirDocumentsKeys();
//define data types, with correct spaces and commas
const doubleDataType = " DOUBLE, ";
const textDataType = " TEXT, ";
const intDataType = " INT, ";
const indexStatement = "INDEX ";
//add "ROWID" primary key as auto increment (primary key is like automatically assigned "_id" in MongoDB)
schema = " (ROWID INT AUTO_INCREMENT PRIMARY KEY, ";
//then concatenate all keys, data types, spaces and commas
for(let index = 0; index < inputKeys.length; index++)
{
if(index === 0)
{
//this is Reservoir_ID: foreign key designate to other TABLES -> must be INDEXED
schema = schema + inputKeys[index] + intDataType + indexStatement + openBracket + inputKeys[index] + closeIndexBracket;
}
else if(index === 1)
{
schema = schema + inputKeys[index] + textDataType;
}
else if(index > 1)
{
schema = schema + inputKeys[index] + doubleDataType;
}
}
//add check constraints on GR and Deep resistvity data
let check_constraints = "CHECK (0>=Avg_GR_api<=150), CHECK (0>=Avg_Deep_Resis_ohm_m<=2000)";
//finally concatenate all, including check_constraints, & closeBracket to get the "tableSchema"
const tableSchema = schema + check_constraints + closeBracket;
return tableSchema;
}
static reservoirTableKeys()
{
//define key variable, opening brackets, closing brackets and seperators, with correct spaces & commas
let keys = "";
let seperator = ", ";
let openBracket = " (";
let closeBracket = ")";
//define input keys
let inputKeys = AccessMongoDBAndMySQL.reservoirDocumentsKeys();
//then concatenate opening bracket, all keys, spaces, commas and close bracket
keys = keys + openBracket;
for(let index = 0; index < inputKeys.length; index++)
{
if(index < (inputKeys.length-1))
{
keys = keys + inputKeys[index] + seperator;
}
else
{
keys = keys + inputKeys[index];
}
}
keys = keys + closeBracket;
return keys;
}
static reservoirTableValuesOne()
{
//values below map directly, sequentially, to keys in reservoirDocumentsKeys()
return [1200, 'Upper-Yoho', 540.89, 25.23, 3445.90, 3001.35];
}
static reservoirTableValuesTwo()
{
//values below map directly, sequentially, to keys in reservoirDocumentsKeys()
return [1400, 'Middle-Salabe', 345.61, 20.11, 8000.00, 7609.62];
}
static reservoirDocumentsKeys()
{
return ["Reservoir_ID", "Reservoir_Zone", "Avg_Deep_Resis_ohm_m", "Avg_GR_api", "Top_MD_ft", "Top_TVD_ft"];
}
static reservoirSTOOIPTableSchema()
{
//define schema variable and bracket, with correct spaces & commas
let schema = "";
let closeBracket = ")";
let openBracket = "(";
let closeIndexBracket = "), ";
//define input keys
let inputKeys = AccessMongoDBAndMySQL.reservoirSTOOIPDocumentsKeys();
//define data types, with correct spaces and commas
const doubleDataType = " DOUBLE, ";
const intDataType = " INT, ";
const indexStatement = "INDEX ";
//add "ROWID" primary key as auto increment (primary key is like automatically assigned "_id" in MongoDB)
schema = " (ROWID INT AUTO_INCREMENT PRIMARY KEY, ";
//then concatenate all keys, data types, spaces and commas
for(let index = 0; index < inputKeys.length; index++)
{
if(index === 0)
{
//this is Reservoir_ID: foreign key designate to other TABLES -> must be INDEXED
schema = schema + inputKeys[index] + intDataType + indexStatement + openBracket + inputKeys[index] + closeIndexBracket;
}
else
{
schema = schema + inputKeys[index] + doubleDataType;
}
}
//add foreign key constraint for Reservoir_ID
let foreign_key_constraint = "FOREIGN KEY (Reservoir_ID) REFERENCES Reservoir(Reservoir_ID)";
//finally concatenate all, including foreign_key_constraint and closeBracket to get the "tableSchema"
const tableSchema = schema + foreign_key_constraint + closeBracket;
return tableSchema;
}
static reservoirSTOOIPTableKeys()
{
//define key variable, opening brackets, closing brackets and seperators, with correct spaces & commas
let keys = "";
let seperator = ", ";
let openBracket = " ("
let closeBracket = ")";
//define input keys
let inputKeys = AccessMongoDBAndMySQL.reservoirSTOOIPDocumentsKeys();
//then concatenate opening bracket, all keys, spaces, commas and close bracket
keys = keys + openBracket;
for(let index = 0; index < inputKeys.length; index++)
{
if(index < (inputKeys.length-1))
{
keys = keys + inputKeys[index] + seperator;
}
else
{
keys = keys + inputKeys[index];
}
}
keys = keys + closeBracket;
return keys;
}
static reservoirSTOOIPTableValuesOne()
{
//values below map directly, sequentially, to keys in reservoirSTOOIPDocumentsKeys()
//note: STOOIP_bbls = 7758 * Area_acres * Net_pay_ft * Porosity_frac * Oil_sat_frac * (1/Bo) * (1/10E+6)
return [1200, 103.15, 0.2645, 0.8378, 100, 600, 997.89, 1.0000];
}
static reservoirSTOOIPTableValuesTwo()
{
//values below map directly, sequentially, to keys in reservoirSTOOIPDocumentsKeys()
//note: STOOIP_bbls = 7758 * Area_acres * Net_pay_ft * Porosity_frac * Oil_sat_frac * (1/Bo) * (1/10E+6)
return [1400, 81.19, 0.2237, 0.7301, 89, 720, 1200, 1.0001];
}
static reservoirSTOOIPDocumentsKeys()
{
return ["Reservoir_ID", "STOOIP_mm_bbls", "Porosity_frac", "Oil_sat_frac", "Net_pay_ft", "Area_acres", "Perm_mD", "Bo_factor"];
}
static reservoirProductionTableSchema()
{
//define schema variable and bracket, with correct spaces & commas
let schema = "";
let closeBracket = ")";
let openBracket = "(";
let closeIndexBracket = "), "
//define input keys
let inputKeys = AccessMongoDBAndMySQL.reservoirProductionDocumentsKeys();
//define data types, with correct spaces and commas
const doubleDataType = " DOUBLE, ";
const intDataType = " INT, ";
const indexStatement = "INDEX ";
//add "ROWID" primary key as auto increment (primary key is like automatically assigned "_id" in MongoDB)
schema = " (ROWID INT AUTO_INCREMENT PRIMARY KEY, ";
//then concatenate all keys, data types, spaces and commas
for(let index = 0; index < inputKeys.length; index++)
{
if(index === 0)
{
//this is Reservoir_ID: foreign key designate to other TABLES -> must be INDEXED
schema = schema + inputKeys[index] + intDataType + indexStatement + openBracket + inputKeys[index] + closeIndexBracket;
}
else
{
schema = schema + inputKeys[index] + doubleDataType;
}
}
//add foreign key constraint for Reservoir_ID
let foreign_key_constraint = "FOREIGN KEY (Reservoir_ID) REFERENCES Reservoir(Reservoir_ID)";
//finally concatenate all, including foreign_key_constraint and closeBracket to get the "tableSchema"
const tableSchema = schema + foreign_key_constraint + closeBracket;
return tableSchema;
}
static reservoirProductionTableKeys()
{
//define key variable, opening brackets, closing brackets and seperators, with correct spaces & commas
let keys = "";
let seperator = ", ";
let openBracket = " ("
let closeBracket = ")";
//define input keys
let inputKeys = AccessMongoDBAndMySQL.reservoirProductionDocumentsKeys();
//then concatenate opening bracket, all keys, spaces, commas and close bracket
keys = keys + openBracket;
for(let index = 0; index < inputKeys.length; index++)
{
if(index < (inputKeys.length-1))
{
keys = keys + inputKeys[index] + seperator;
}
else
{
keys = keys + inputKeys[index];
}
}
keys = keys + closeBracket;
return keys;
}
static reservoirProductionTableValuesOne()
{
//values below map directly, sequentially, to keys in reservoirProductionDocumentsKeys()
return [1200, 0.3671, 1.0211, 365.0];
}
static reservoirProductionTableValuesTwo()
{
//values below map directly, sequentially, to keys in reservoirProductionDocumentsKeys()
return [1400, 1.0206, 0.7656, 1460.0];
}
static reservoirProductionDocumentsKeys()
{
return ["Reservoir_ID", "Cum_prod_mm_bbls", "Prod_Rate_m_bopd", "Days"];
}
static drillingEventTableSchema()
{
//define schema variable and bracket, with correct spaces & commas
let schema = "";
let closeBracket = ")";
//define input keys
let inputKeys = AccessMongoDBAndMySQL.drillingEventDocumentKeys();
//define data types, with correct spaces and commas
const doubleDataType = " DOUBLE, ";
const textDataType = " TEXT, ";
const booleanDataType = " BOOLEAN, ";
const datatimeDataType = " DATETIME, ";
//add "ROWID" primary key as auto increment (primary key is like automatically assigned "_id" in MongoDB)
schema = " (ROWID INT AUTO_INCREMENT PRIMARY KEY, ";
//then concatenate all keys, data types, spaces and commas
for(let index = 0; index < inputKeys.length; index++)
{
if(index < 6)
{
schema = schema + inputKeys[index] + doubleDataType;
}
else if(index === 6)
{
schema = schema + inputKeys[index] + textDataType;
}
else if(index > 6 && index < 20)
{
schema = schema + inputKeys[index] + doubleDataType;
}
else if(index >= 20 && index < 23)
{
schema = schema + inputKeys[index] + booleanDataType;
}
else if(index === 23)
{
schema = schema + inputKeys[index] + datatimeDataType;
}
}
//add check constraints on some LWD data
let constraints = "CHECK (0>=GR_api<=150), CHECK (0>=DEEP_RESISTIVITY_ohm_m<= 2000)";
//finally concatenate all, including constraints and closeBracket to get the "tableSchema"
const tableSchema = schema + constraints + closeBracket;
return tableSchema;
}
static drillingEventTableKeys()
{
//define key variable, opening brackets, closing brackets and seperators, with correct spaces & commas
let keys = "";
let seperator = ", ";
let openBracket = " ("
let closeBracket = ")";
//define input keys
let inputKeys = AccessMongoDBAndMySQL.drillingEventDocumentKeys();
//then concatenate opening bracket, all keys, spaces, commas and close bracket
keys = keys + openBracket;
for(let index = 0; index < inputKeys.length; index++)
{
if(index < (inputKeys.length-1))
{
keys = keys + inputKeys[index] + seperator;
}
else
{
keys = keys + inputKeys[index];
}
}
keys = keys + closeBracket;
return keys;
}
static drillingEventTableValues()
{
//values below map directly, sequentially, to keys in drillingEventTableKeys()
return AccessMongoDBAndMySQL.drillingEventDocumentValues();
}
static drillingEventDocumentKeys()
{
return [
//data from regular drilling operation (drillstring-related)
"ROP_fph",
"RPM_rpm",
"SPP_psi",
"DWOB_lb",
"SWOB_lb",
"TQR_Ibft",
"BHA_TYPE_no_unit",
//data from regular drilling operation (mud-related)
"MUD_WEIGHT_sg",
"MUD_PLASTIC_VISC_cp",
"MUD_YIELD_POINT_lb_per_100ft_sq",
"MUD_FLOW_RATE_gpm",
//data (measured or calculated) from downhole MWD/LWD tool measurements
"TVD_ft",
"MD_ft",
"INC_deg",
"AZIM_deg",
"Dogleg_deg_per_100ft",
"CALIPER_HOLE_SIZE_inches",
"GR_api",
"DEEP_RESISTIVITY_ohm_m",
"SHOCK_g",
//event data from MWD/LWD tool measurements and other sources
"IS_VIBRATION_boolean_0_or_1",
"IS_KICK_boolean_0_or_1",
"IS_STUCKPIPE_boolean_0_or_1",
//time data
"TIME_ymd_hms"
]
}
static drillingEventDocumentValues()
{
//values below map directly, sequentially, to keys in drillingEventDocumentKeys()
return [ //data from regular drilling operation (drillstring-related)
35, 65, 235, 20000, 10000, 800, 'slick',
//data from regular drilling operation (mud-related)
1.18, 18.01, 16, 98.14,
//data (measured or calculated) from downhole MWD/LWD tool measurements
8000, 12000, 67.2, 110.5, 1.1, 6, 20, 303.3, 26,
//event data from MWD/LWD tool measurements and other sources
0, 0, 0,
//time data
new Date()
];
}
static drillingEventDocumentKeyValuePairs(keys, values)
{
const keyValuePairsMap = new Map();
const validKeyValuePairs = AccessMongoDBAndMySQL.validDocument(keys, values);
if(validKeyValuePairs === true)
{
for(let index = 0; index < keys.length; index++)
{
keyValuePairsMap.set(keys[index], values[index]);
}
}
//add constraints on some LWD data
// 1. GR_api constraint => 0>=GR_api<=150
if(keyValuePairsMap.get(keys[17]) < 0 || keyValuePairsMap.get(keys[17]) > 150)
{
keyValuePairsMap.set(keys[17], NaN);
}
// 2. DEEP_RESISTIVITY_ohm_m constraint => 0>=DEEP_RESISTIVITY_ohm_m<= 2000
if(keyValuePairsMap.get(keys[18]) < 0 || keyValuePairsMap.get(keys[18]) > 2000)
{
keyValuePairsMap.set(keys[18], NaN);
}
return keyValuePairsMap;
}
static drillingEventDocumentKeyValuePairsBinned(keys, values)
{
/*
note:
1) returns key-value pairs (for drilling event document) classified/binned into suitable categories
2) data in this document are used for drilling rear event/anomaly detection analytics with AIML algorithms
3) data are denormlized with embedded documents as sub-documents (i.e. classified/binned)
*/
const keyValuePairsMap = new Map();
const validKeyValuePairs = AccessMongoDBAndMySQL.validDocument(keys, values);
if(validKeyValuePairs === true)
{
let keyValue = {};
for(let index = 0; index < keys.length; index++)
{
if(index < 7)
{
keyValue[keys[index]] = values[index];
if(index === 6)
{
keyValuePairsMap.set("drillStringData", keyValue);
keyValue = {}; //reset to empty for next loop logic
}
}
else if(index >= 7 && index < 11)
{
keyValue[keys[index]] = values[index];
if(index === 10)
{
keyValuePairsMap.set("drillingMudData", keyValue);
keyValue = {};
}
}
else if(index >= 11 && index < 20)
{
keyValue[keys[index]] = values[index];
if(index === 19)
{
keyValuePairsMap.set("mwdLwdData", keyValue);
keyValue = {};
}
}
else if(index >= 20 && index < 23)
{
keyValue[keys[index]] = values[index];
if(index === 22)
{
keyValuePairsMap.set("eventData", keyValue);
keyValue = {};
}
}
else if(index === 23)
{
keyValue[keys[index]] = values[index];
if(index === 23)
{
keyValuePairsMap.set("time", keyValue);
keyValue = {};
}
}
}
}
return keyValuePairsMap;
}
static shaleReservoirDocumentKeys()
{
return { "reservoir_characteristics": "reservoir_characteristics",
"completion_details_per_pad": "completion_details_per_pad",
"production_details_per_pad": "production_details_per_pad"
};
}
static shaleReservoirDocumentValues()
{
return {
//1. reservoir_characteristics
reservoir_characteristics: {
reservoir_type: "dolomite_shale",
fluid_type: "oil",
fluid_species_mol_fraction: { HO: 0.0800, LO: 0.9090, CH4: 0.0090, CO2: 0.0010, others_traces: 0.0010 },
oil_api: 38.1,
maturity_level_Ro: 0.72,
init_oil_sat_frac: 0.82,
porosity_frac: 0.04,
thickness_ft: 86.2,
toc_frac: 0.056,
perm_nD: 5.1,
tvd_pressure_proxy_ft: 8900.3,
avg_calcite_frac: 0.017
},
//2. completion_details_per_pad
completion_details_per_pad: {
avg_number_of_stages_per_well: 20,
avg_perf_inverval_per_well_ft: 5200,
avg_proppant_loading_per_well_lbs: 9000.1,
avg_pumped_fluid_vol_per_well_mm_bbls: 4.2,
avg_well_direc_relative_to_max_prin_stress_deg_deg: 78.0, // also called: // also called: avg_fracture_directional_disparity_deg
number_of_wells: 5
},
// 3. production_details_per_pad
production_details_per_pad: {
ip_mboe_per_day_30day_avg: 1.12,
ip_mboe_per_day_12hrs_avg: 1.50,
cum_prod_boe_mm_bbls: { months_06: 0.342, months_18: 0.560, months_36: 0.637}
}
}
}
static shaleReservoirDocumentKeyValuePairsBinned(keys, values)
{
/*
note:
1) returns key-value pairs (for shale reservoir document) classified/binned into suitable categories
2) data in this document are used for shale reservoir analytics with AIML algorithms
3) data are denormlized with embedded documents as sub-documents (i.e. classified/binned)
*/
const keyValuePairsMap = new Map();
const validKeyValuePairs = AccessMongoDBAndMySQL.validDocument(keys, values);
if(validKeyValuePairs === true)
{
keyValuePairsMap.set(keys.reservoir_characteristics, values.reservoir_characteristics);
keyValuePairsMap.set(keys.completion_details_per_pad, values.completion_details_per_pad);
keyValuePairsMap.set(keys.production_details_per_pad, values.production_details_per_pad);
}
return keyValuePairsMap;
}
static createUserDocument(userName, email, password, productOrServiceSubscription, assetName)
{
const EconomicCrypto = require('./EconomicCrypto.js').EconomicCrypto;
const uuidV4 = require('uuid/v4');
const economicCrypto = new EconomicCrypto();
const hashAlgorithmPasd = 'bcrypt';
const hashAlgorithmBlockchain = 'whirlpool';
const pasd = economicCrypto.isHashConsensus([password], hashAlgorithmPasd);
const initDate = new Date();
const verificationCode = uuidV4();
const initConfirmation = false;
const initBlockChain = economicCrypto.isHashConsensus([uuidV4()], hashAlgorithmBlockchain);
const blockchain = [initBlockChain[0], initBlockChain[1], initBlockChain[2]];
const maxLoginAttempts = 10;
const lockTime = 1*60*60*1000; // 1 hour
const newUserMap = new Map(); // user document
newUserMap.set("username", userName);
newUserMap.set("email", email);
newUserMap.set("subscription", productOrServiceSubscription);
newUserMap.set("pasd", {"current": pasd, "lastFive": [pasd, pasd, pasd, pasd, pasd]});
newUserMap.set("assetname", assetName);
newUserMap.set("timeManagement", {"createdOn": initDate, "modifiedOn": initDate, "lastLogin": initDate, "lastLogOut": initDate});
newUserMap.set("accountStatus", {"verificationCode": verificationCode, "isAccountVerified": initConfirmation, "isAccountInUse": initConfirmation});
newUserMap.set("accountBalance", {"balanceDays": 0, "balanceDollars": 0, "initDays": 0});;
newUserMap.set("loginStatus", {"loginAttempts": 0, "maxLoginAttempts": maxLoginAttempts, "lockUntil": lockTime});
newUserMap.set("blockchain", blockchain);
//initialise files storage on the Document Stores (Distribued Ledgers) as Buffer -> note: limit on each file size is 16MB
//arbitrary initialise Buffer values will be over-written once actual files are uploaded to the Distributed Ledgers
newUserMap.set("distributedLedgersFiles", { "location": Buffer.from("lo"),
"reservoirVolumetrics": Buffer.from("resv"),
"petrophysical": Buffer.from("pp"),
"geoscience": Buffer.from("geo"),
"drilling": Buffer.from("drlg"),
"production": Buffer.from("prod")
});
return newUserMap;
}
mongoDBConnectionOptions(sslCertOptions, enableSSL)
{
if(enableSSL === true)
{
return {useNewUrlParser: true, useUnifiedTopology: true, readPreference: 'primaryPreferred',
maxStalenessSeconds: 90, poolSize: 200, ssl: true, sslValidate: true,
sslCA: sslCertOptions.ca, sslKey: sslCertOptions.key, sslCert: sslCertOptions.cert
};
}
else
{
return {useNewUrlParser: true, useUnifiedTopology: true, readPreference: 'primaryPreferred',
maxStalenessSeconds: 90, poolSize: 200, ssl: false, sslValidate: false
};
}
}
mySQLConnectionOptions(sslCertOptions, enableSSL, connectionOptions)
{
if(enableSSL === true)
{
return {host: connectionOptions.host, port: connectionOptions.port, user: connectionOptions.user,
password: connectionOptions.password, database: connectionOptions.database, debug: connectionOptions.debug,
timezone: 'Z', supportBigNumbers: true, ssl:{ca: sslCertOptions.ca, key: sslCertOptions.key, cert: sslCertOptions.cert},
pooling: { enabled: true, maxSize: 200 }
};
}
else
{
return {host: connectionOptions.host, port: connectionOptions.port, user: connectionOptions.user,
password: connectionOptions.password, database: connectionOptions.database, debug: connectionOptions.debug,
timezone: 'Z', supportBigNumbers: true, ssl: enableSSL, pooling: { enabled: true, maxSize: 200 }
};
}
}
AccessMongoDB(dbUserName, dbUserPassword, dbDomainURL, dbName, collectionName, confirmDatabase, sslCertOptions,
createCollection=false, dropCollection=false, enableSSL=false, collectionDisplayOption=undefined)
{
//connect with "MongoDB Node.js Native Driver". See - https://www.npmjs.com/package/mongodb
const mongodb = require('mongodb');
const fs = require('fs');
const util = require('util');
const uri = String('mongodb://' + dbUserName + ':' + dbUserPassword + '@' + dbDomainURL + '/' + dbName);
const mda = new AccessMongoDBAndMySQL();
const mongodbOptions = mda.mongoDBConnectionOptions(sslCertOptions, enableSSL);
mongodb.MongoClient.connect(uri, mongodbOptions, function(connectionError, client)
{
// 0.connect (authenticate) to database with mongoDB native driver (client)
if(connectionError)
{
console.log(connectionError);
console.log("Connection error: MongoDB-server is down or refusing connection.");
return;
}
console.log();
console.log("Now connected to MongoDB Server on:", dbDomainURL);
console.log();
const db = client.db(dbName);
if(confirmDatabase === true && dbName !== null)
{
//1...... confirm collection(s) exit(s) within database
db.listCollections().toArray(function(confirmCollectionError, existingCollections)
{
if(confirmCollectionError)
{
console.log("confirm Collection Error: ", confirmCollectionError);
return;
}
const collectionNamesList = AccessMongoDBAndMySQL.getMongoDBCollectionNames(existingCollections)
if(existingCollections.length > 0)
{
console.log("Total number of COLLECTION(S) within", dbName, "database:", existingCollections.length);
console.log();
console.log("It is confirmed that the COLLECTION(S) below exist(s) within", dbName, "database:");
console.log(collectionNamesList);
console.log();
}
if(createCollection === true)
{
//2...... create collection (TABLE equivalent in MySQL), if desired
//note: "strict: true" ensures unique collectionName: this is like "CREATE TABLE IF NOT EXISTS tableName" in MySQL
//2a. create document
db.createCollection(collectionName, {strict: true}, function(createCollectionError, createdCollection)
{
if(createCollectionError && createCollectionError.name === "MongoError")
{
console.log("Error: Existing COLLLECTION Error or other Error(s)");
console.log()
}
if(createdCollection)
{
console.log(collectionName, " COLLECTION successfully created!");
console.log();
}
//2b. count document(s)
//use aggregate pipeline stage to obtain number of existing document in the collection
const pipeline = [ { $group: { _id: null, numberOfDocuments: { $sum: 1 } } }, { $project: { _id: 0 } } ];
db.collection(collectionName).aggregate(pipeline).toArray(function(numberOfDocumentsError, documentPipeline)
{
if(numberOfDocumentsError)
{
console.log("Document Counts Error: ", numberOfDocumentsError);
return;
}
var documentsCount = undefined;
if(documentPipeline[0] === undefined)
{
documentsCount = 0;
}
else
{
documentsCount = documentPipeline[0].numberOfDocuments;
}
console.log("Total number of documents in the ", collectionName, "Collection is: ", documentsCount);
console.log()
//3...... insert/add document and its fields (key-value pairs) into collection
// .......this is equivalent to ROW & COLUMN-VALUES in regular MySQL
// 3a. defined documents and its fields (key-value pairs)
const keys = AccessMongoDBAndMySQL.drillingEventDocumentKeys();
const values = AccessMongoDBAndMySQL.drillingEventDocumentValues();
const documentObjectMap = AccessMongoDBAndMySQL.drillingEventDocumentKeyValuePairsBinned(keys, values);
const documentObject = AccessMongoDBAndMySQL.convertMapToObject(documentObjectMap);
//3b. insert
db.collection(collectionName).insertOne(documentObject, function(insertDocumentError, insertedObject)
{
if(insertDocumentError)
{
console.log("Insert Document Error: ", insertDocumentError);
return;
}
console.log("Document with id (", documentObject._id, ") and its fields (key-value pairs), is inserted into " + String(collectionName) + " COLLECTION successfully!");
console.log();
//4...... show documents and its fields (i.e. key-value pairs) in the collection
// note a: if "collectionDisplayOption" is null or undefined or unspecified, all documents & their
// fields (key-value pairs) in the COLLECTION will be displayed based on MongoDB default ordering
// note b: empty {} documentNames signifies all document names in the collection
if(collectionDisplayOption === "all" || collectionDisplayOption === null || collectionDisplayOption === undefined)
{
//option a: show all documents & their key-value pairs in the COLLECTION (sorted by dateTime in ascending order)
var sortByKeys = {_id: 1};
var specifiedKeys = {};
var documentNames = {};
}
else if(collectionDisplayOption === "wellTrajectory")
{
//option b: show all documents & fields (key-value pairs), based on specified key, in the COLLECTION (sorted by _id in ascending order)
//note: specified keys (except _id and TIME_ymd_hms) are related to "well trajectory"
var sortByKeys = {_id: 1};
var specifiedKeys = {_id: 1, MD_ft: 1, TVD_ft: 1, INC_deg: 1, AZIM_deg: 1, Dogleg_deg_per_100ft: 1, TIME_ymd_hms: 1};
var documentNames = {};
}
db.collection(collectionName).find(documentNames, {projection: specifiedKeys}).sort(sortByKeys).toArray(function(showCollectionError, foundCollection)
{
if(showCollectionError)
{
console.log("Show Collection Error: ", showCollectionError);
return;
}
console.log("Some or all documents and their fields (key-value pairs) in " + String(collectionName) + " COLLECTION are shown below!");
console.log(util.inspect(foundCollection, { showHidden: true, colors: true, depth: 4 }));
console.log();
//5...... drop/delete collection, if desired
if(dropCollection === true)
{
db.collection(collectionName).drop(function(dropCollectionError, droppedCollectionConfirmation)
{
if(dropCollectionError)
{
console.log("Drop/Delete Collection Error: ", dropCollectionError);
return;
}
console.log(String(collectionName) + " Collection is successfully dropped/deleted!");
console.log("Dropped?: ", droppedCollectionConfirmation);
console.log();
});
}
//6. create index on specified field(s) key, if collection is not dropped & documentsCount === 1
else if(dropCollection !== true && documentsCount === 1)
{
const indexedFields = {"mwdLwdData.TVD_ft": 1, "mwdLwdData.Dogleg_deg_per_100ft": 1};
db.collection(collectionName).createIndex(indexedFields, function(indexedFieldError, indexedConfirmation)
{
if(indexedFieldError)
{
console.log("Indexed Field Error: ", indexedFieldError);
return;