| 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404 |
1
8
8
8
8
8
8
8
1081
1081
1081
8
8
8
8
8
8
8
8
8
8
8
2840
246
246
246
2594
18
18
18
18
2840
42
42
2840
60
2840
264
2840
8
595
595
264
595
139
139
139
595
595
595
595
595
595
595
595
595
163
17
595
595
8
1475
1475
1475
8
1475
1475
317
1475
2049
617
1475
8
317
317
317
317
8
567
567
567
567
154
151
151
154
567
8
595
595
595
595
9
586
586
586
586
586
586
586
1124
586
35
551
532
532
530
547
532
233
532
19
538
586
586
586
586
586
587
593
593
562
593
593
589
483
150
150
150
483
483
106
54
54
52
1
1
589
586
586
586
8
7
7
7
3
3
4
2
2
7
3
7
2
7
5
7
7
7
7
7
7
31
31
5
5
2
31
24
20
20
10
10
10
10
20
20
10
10
31
31
14
31
31
7
8
8
173
173
173
173
8
610
8
76
76
8
2
8
8
15
15
4
11
9
2
2
15
15
15
15
2
15
8
9
8
4
8
4
8
2
8
2
2
2
2
2
2
2
8
2148
2148
2148
2148
8
1067
1067
1067
519
1067
8
137
137
130
137
137
4
2
6
2
4
2
133
137
130
7
2
5
5
137
8
2
8
5
8
6
6
8
8
8
8
8
8
282
282
282
282
282
8
2
2
8
24
1
23
24
8
15
15
15
13
2
2
2
1
1
3
3
13
2
15
15
8
10
10
10
9
1
10
10
8
240
240
240
236
240
240
233
233
31
93
31
62
202
202
202
287
2
202
202
233
7
240
240
240
240
8
2
8
2
8
8
2
2
8
8
11
11
2
2
2
2
2
2
9
9
11
11
8
93
83
83
10
10
10
10
10
10
10
10
8
10
8
688
688
688
688
688
688
688
688
8
8
2
2
8
2
2
8
2
2
8
8
8
4
4
8
739
739
8
8
271
8
1067
1066
1067
1067
8
23
23
8
1088
1088
1088
8
8
1
8
1066
1066
1066
8
21
21
21
8
8
29
29
28
29
45
29
8
378
232
378
378
378
378
8
244
244
244
244
244
326
244
8
243
8
237
237
234
3
237
8
17
8
2
8
8
8
8
8
8
8
8
1066
8
1
8
8
8
8
3
8
8
8
20
8
8
8
8
429
8
8
1
1
| /**
* **The Graph** respresents the cypher-query-api of the neo4j database
* You can perform basic actions and queries directly on the graph
* ###[Query Structure](http://docs.neo4j.org/refcard/2.0/)
* Read Query Structure:
* [START]
* [MATCH]
* [WHERE]
* [WITH [ORDER BY] [SKIP] [LIMIT]]
* RETURN [ORDER BY] [SKIP] [LIMIT]
*
* Write-Only Query Structure:
* (CREATE [UNIQUE] | MERGE)*
* [SET|DELETE|FOREACH]*
* [RETURN [ORDER BY] [SKIP] [LIMIT]]
*
* Read-Write Query Structure:
* [START]
* [MATCH]
* [WHERE]
* [WITH [ORDER BY] [SKIP] [LIMIT]]
* [CREATE [UNIQUE]|MERGE]*
* [SET|DELETE|FOREACH]*
* [RETURN [ORDER BY] [SKIP] [LIMIT]]
*
* @todo: maybe check of valid query structure?!
*/
/**
* Initialize the Graph object with a neo4jrestful client
*
* @param {object} neo4jrestful object
* @return {object} Graph object
*/
var __initGraph__ = function(neo4jrestful) {
// Requirements (for browser and nodejs):
// * neo4jmapper helpers
// * underscorejs
Iif (typeof window === 'object') {
var helpers = window.Neo4jMapper.helpers;
var _ = window._;
var CypherQuery = window.Neo4jMapper.CypherQuery;
var ConditionalParameters = window.Neo4jMapper.ConditionalParameters;
} else {
var helpers = require('./helpers');
var _ = require('underscore');
var CypherQuery = require('./cypherquery');
var ConditionalParameters = require('./conditionalparameters')
}
// Ensure that we have a Neo4jRestful client we can work with
Iif ((typeof neo4jrestful !== 'undefined') && (helpers.constructorNameOfFunction(neo4jrestful) !== 'Neo4jRestful'))
throw Error('You have to use an Neo4jRestful object as argument')
/**
* Constructor of Graph
* @constructor
* @param {string} url
*/
var Graph = function Graph(url) {
Iif (url) {
this.neo4jrestful = new neo4jrestful.constructor(url);
}
this.resetQuery();
return this;
}
Graph.prototype.neo4jrestful = neo4jrestful;
Graph.prototype._query_history_ = null;
// see graph.resetQuery() for initialization
Graph.prototype.cypher = null;
Graph.prototype._queryString_ = ''; // stores a query string temporarily
Graph.prototype._loadOnResult_ = 'node|relationship|path';
Graph.prototype._resortResults_ = true; // see in graph.query() -> _increaseDone()
Graph.prototype._nativeResults_ = false; // it's not implemented, all results are processed so far
Graph.prototype.info = null; // contains the info response of the neo4j database
Graph.prototype._response_ = null; // contains the last response object
Graph.prototype._columns_ = null; // contains `columns` of { columns: [ … ], data: [ … ] }
/**
* The following argument combinations are accepted:
* * query, parameters, cb
* * parameters, cb
* * query, cb
* * cb
*
* Example:
*
* `Graph.new().exec('START n=node({id}) RETURN n;', { id: 123 }, cb);`
*
*
* @param {string|object|function} [query]
* @param {object|function} [parameters]
* @param {Function} cb (optional, but needed to trigger query execution finally)
*/
Graph.prototype.exec = function(query, parameters, cb) {
if (typeof query === 'function') {
cb = query;
query = undefined;
parameters = undefined;
} else if (typeof parameters === 'function') {
cb = parameters;
Eif (typeof query === 'object') {
parameters = query;
query = undefined;
}
}
if (typeof query === 'object') {
// query may be parameters
parameters = query;
query = undefined;
}
if ((typeof parameters === 'object') && (parameters !== null)) {
this.addParameters(parameters);
}
if (typeof cb === 'function') {
// args: queryString, parameters (are added above), cb, options (no options are used here)
this.query(query, {}, cb, {});
}
return this;
}
/**
* Executes a (cypher)-query-string directly in neo4j
*
* Example:
*
* `Graph.query('START n=node(123) RETURN n;', cb);`
*
* @param {string} cypherQuery
* @param {object} [parameters]
* @param {Function} cb
* @param {object} [options] will be passed to `neo4jrestful.query`
*/
Graph.prototype.query = function(cypherQuery, parameters, cb, options) {
var self = this;
if (typeof cypherQuery !== 'string') {
cypherQuery = this.toCypherQuery();
}
if (typeof parameters === 'function') {
cb = parameters;
options = {};
parameters = {};
}
Iif ((typeof options !== 'object')&&(options !== null)) {
options = {};
}
Iif (!parameters)
parameters = {};
Iif (Object.keys(parameters).length > 0) {
this.addParameters(parameters);
}
options.params = (typeof this.cypher.useParameters === 'boolean') ? this.parameters() : {};
options.context = self;
// we expect a cb in most cases and perfom the query immediately
Eif (typeof cb === 'function') {
this.neo4jrestful.query(cypherQuery, options, function(err, res, debug) {
self._processResult(err, res, debug, options, function(err, res, debug) {
// Is used by Node on performing an "update" via a cypher query
// The result length is 1, so we remove the array
if ((res)&&(res.length===1)&&(options.cypher)) {
if ((options.cypher.limit === 1) || (options.cypher._update_) || (typeof res[0] !== 'object')) {
res = res[0];
}
}
cb(err, res, debug);
});
});
} else {
// otherwise we store the query string and expect it will be executed with `.exec(cb)` or `.stream(cb)`
this._queryString_ = cypherQuery;
}
return this;
}
/**
* Returns the number of column wich contains the labels
* @private
* @param {array} columns
* @return {number} of column
*/
Graph.prototype.__indexOfLabelColumn = function(columns) {
var labelColumns = this.__indexOfLabelColumns(columns);
var keys = Object.keys(labelColumns);
return (keys.length === 1) ? keys[0] : -1;
}
/**
* Returns the numbers of column wich contain labels
* @private
* @param {array} columns
* @return {array} indexes
*/
Graph.prototype.__indexOfLabelColumns = function(columns) {
var labelColumns = {};
if (typeof columns === 'undefined')
columns = this._columns_;
for (var i=0; i < columns.length; i++) {
if (/^labels\([a-zA-Z]+\)$/.test(columns[i]))
labelColumns[i] = columns[i];
}
return labelColumns;
}
/**
* Removes label column from array
* @private
* @param {array} array
* @param {number} columnIndexOfLabel
* @return {array} without label column
*/
Graph.prototype.__removeLabelColumnFromArray = function(array, columnIndexOfLabel) {
Eif (typeof columnIndexOfLabel !== 'number')
columnIndexOfLabel = this.__indexOfLabelColumn();
array.splice(columnIndexOfLabel, 1);
return array;
}
/**
* Removes label column from results
* @private
* @param {array} result
* @return {array} without label column
*/
Graph.prototype.__sortOutLabelColumn = function(result) {
var nodeLabels = [];
var nodeLabelsColumn = this.__indexOfLabelColumn(result.columns);
var self = this;
if (nodeLabelsColumn >= 0) {
// we have a 'labels(n)' column
for (var i=0; i < result.data.length; i++) {
nodeLabels.push(result.data[i][nodeLabelsColumn]);
result.data[i] = self.__removeLabelColumnFromArray(result.data[i], nodeLabelsColumn);
}
this._columns_ = self.__removeLabelColumnFromArray(this._columns_, nodeLabelsColumn);
}
return nodeLabels;
}
/**
* Processes results array, i.e.
* * sort out data result
* * detect objects and instantiate them
* * applies labels from result set on node object(s)
* @param {object} err
* @param {object} result
* @param {object} debug
* @param {object} options
* @param {Function} cb
*/
Graph.prototype._processResult = function(err, result, debug, options, cb) {
var self = options.context;
self._response_ = self.neo4jrestful._response_;
self._columns_ = self.neo4jrestful._columns_;
if (err)
return cb(err, result, debug);
var loadNode = /node/i.test(self._loadOnResult_);
var loadRelationship = /relation/i.test(self._loadOnResult_);
var loadPath = /path/i.test(self._loadOnResult_);
var todo = 0;
var iterationDone = false;
// if we have the native mode, return results instantly at this point
// TODO: to be implemented
Iif (self._nativeResults_)
// we turned off all loading hooks and no sorting -> so lets return the native result
return cb(err, result, debug);
// increase the number of done jobs
// resort the results if options is activated
// and finally invoke the cb if we are done
var __oneMoreJobDone = function() {
if ((todo === 0)&&(iterationDone)) {
if (result.data.length === 0) {
// empty result
return cb(err, null, debug);
}
// if is set to true, sort result:
// * return only the data (columns are attached to graph._columns_)
// * remove array if we only have one column
// e.g. { columns: [ 'count' ], data: [ { 1 } ] } -> 1
if (self._resortResults_) {
var cleanResult = result.data;
// remove array, if we have only one column
if (self._columns_.length === 1) {
for (var row=0; row < cleanResult.length; row++) {
cleanResult[row] = cleanResult[row][0];
}
}
if ((self.cypher.limit === 1) && (cleanResult.length === 1)) {
// if we have a limit of 1 we can only get data[0] or null
cleanResult = (cleanResult.length === 1) ? cleanResult[0] : null;
}
cb(err, cleanResult, debug);
} else {
cb(err, result, debug);
}
} else {
todo--;
}
}
Iif ((!result.data)&&(result.length === 1)) {
return cb(err, result[0], debug);
}
// check for node labels column (is attached by query builder)
// copy to a new array and remove column from result to the results cleaner
var nodeLabelsColumn = this.__indexOfLabelColumn(result.columns);
var nodeLabels = (this._resortResults_) ? this.__sortOutLabelColumn(result) : null;
var recommendConstructor = options.recommendConstructor;
for (var row=0; row < result.data.length; row++) {
for (var column=0; column < result.data[row].length; column++) {
var data = result.data[row][column];
// try to create an instance if we have an object here
if ((typeof data === 'object') && (data !== null))
self.neo4jrestful.createObjectFromResponseData(result.data[row][column], recommendConstructor);
// result.data[row][column] = object;
var object = result.data[row][column];
if (object) {
if ((object.classification === 'Node') && (loadNode)) {
if (nodeLabelsColumn >= 0) {
// if we have labels(n) column
var labels = nodeLabels.shift()
object = self.neo4jrestful.Node.instantiateNodeAsModel(object, labels, options.recommendConstructor);
object.__skip_loading_labels__ = true;
}
todo++;
object.load(__oneMoreJobDone);
}
else if ((object.classification === 'Relationship') && (loadRelationship)) {
todo++;
object.load(__oneMoreJobDone);
}
else if ((object.classification === 'Path') && (loadPath)) {
todo++;
object.load(__oneMoreJobDone);
}
result.data[row][column] = object;
}
}
}
iterationDone = true;
__oneMoreJobDone();
return this;
}
/**
* Stream a cypher query
* @param {string} [cypherQuery]
* @param {object} [parameters]
* @param {Function} cb
* @param {object} [options]
*/
Graph.prototype.stream = function(cypherQuery, parameters, cb, options) {
var self = this;
var Node = Graph.Node;
// check arguments for callback
if (typeof cypherQuery === 'function') {
cb = cypherQuery;
cypherQuery = undefined;
} else if (typeof parameters === 'function') {
cb = parameters;
parameters = undefined;
}
if (typeof cypherQuery !== 'string') {
cypherQuery = this.toCypherQuery();
}
if (parameters) {
this.addParameters(parameters);
}
if (!options) {
options = {};
}
// get and set option values
var recommendConstructor = (options) ? options.recommendConstructor || Node : Node;
options.params = (typeof this.cypher.useParameters === 'boolean') ? this.parameters() : {};
parameters = this.parameters();
var i = 0; // counter is used to prevent changing _columns_ more than once
var indexOfLabelColumn = null;
this.neo4jrestful.stream(cypherQuery, options, function(data, response, debug) {
// neo4jrestful already created an object, but not with a recommend constructor
self._columns_ = response._columns_;
if ((self._resortResults_)&&(i === 0)) {
indexOfLabelColumn = self.__indexOfLabelColumn(self._columns_);
if (indexOfLabelColumn >= 0) {
// remove [ 'n', 'labels(n)' ] labels(n) column
self._columns_ = self.__removeLabelColumnFromArray(self._columns_, indexOfLabelColumn);
}
}
if ((data) && (typeof data === 'object')) {
if (data.constructor === Array) {
var labels = null;
if ((self._resortResults_) && (indexOfLabelColumn >= 0)) {
labels = data[indexOfLabelColumn];
data = self.__removeLabelColumnFromArray(data, indexOfLabelColumn);
Eif (data.length === 1)
data = data[0];
}
for (var column = 0; column < data.length; column++) {
if ((data[column]) && (data[column]._response_)) {
data[column] = self.neo4jrestful.createObjectFromResponseData(data[column]._response_, recommendConstructor);
data[column] = self.neo4jrestful.Node.instantiateNodeAsModel(data[column], labels);
}
}
}
}
self._response_ = response;
if ((data) && (data._response_)) {
data = self.neo4jrestful.createObjectFromResponseData(data._response_, recommendConstructor);
// data = self.neo4jrestful.Node.instantiateNodeAsModel(data, labels);
}
i++;
return cb(data, self, debug);
});
return this;
}
/**
* Shortcut for `graph.stream`
* @see Graph.prototype.stream
*/
Graph.prototype.each = Graph.prototype.stream;
/**
* Set cypher parameters (and removes previous ones if exists)
* @param {object} parameters
*/
Graph.prototype.setParameters = function(parameters) {
Iif ((typeof parameters !== 'object') || (parameters === null))
throw Error('parameter(s) as argument must be an object, e.g. { key: "value" }')
Iif (this.cypher.useParameters === null)
this.cypher.useParameters = true;
this.cypher.parameters = parameters;
return this;
}
/**
* Get cypher parameters
* @return {object} parameters
*/
Graph.prototype.parameters = function() {
return this.cypher.parameters || {};
}
/**
* Add cypher Parameters
* @param {object} parameters
*/
Graph.prototype.addParameters = function(parameters) {
this.cypher.addParameters(parameters);
return this;
}
/**
* Add cypher Parameter
* @param {object} parameter
*/
Graph.prototype.addParameter = function(parameter) {
return this.addParameters(parameter);
}
/**
* Deletes *all* nodes and *all* relationships
* @param {Function} cb
*/
Graph.prototype.wipeDatabase = function(cb) {
var query = "START n=node(*) MATCH n-[r?]-() DELETE n, r;";
return this.query(query, cb);
}
/**
* Counts all objects of a specific type
* @param {String} (all|node|relationship|[nr]:Movie)
* @param {Function} cb
*/
Graph.prototype.countAllOfType = function(type, cb) {
var query = '';
if (/^n(ode)*$/i.test(type))
query = "START n=node(*) RETURN count(n);"
else if (/^r(elationship)*$/i.test(type))
query = "START r=relationship(*) RETURN count(r);";
else Iif (/^[nr]\:.+/.test(type))
// count labels
query = "MATCH "+type+" RETURN "+type[0]+";";
else
query = "START n=node(*) OPTIONAL MATCH n-[r]-() RETURN count(n), count(r);";
return Graph.query(query, function(err,data){
Eif ((data)&&(data.data)) {
var count = data.data[0][0];
if (typeof data.data[0][1] !== 'undefined')
count += data.data[0][1];
return cb(err, count);
}
cb(err,data);
});
}
/**
* Counts all relationships
* @param {Function} cb
*/
Graph.prototype.countRelationships = function(cb) {
return this.countAllOfType('relationship', cb);
}
/**
* Alias for countRelationships()
* @see Graph.countRelationships()
* @param {Function} cb
*/
Graph.prototype.countRelations = function(cb) {
return this.countRelationships(cb);
}
/**
* Counts all nodes
* @param {Function} cb
*/
Graph.prototype.countNodes = function(cb) {
return this.countAllOfType('node', cb);
}
/**
* Counts all relationships and nodes
* @param {Function} cb
*/
Graph.prototype.countAll = function(cb) {
return this.countAllOfType('all', cb);
}
/**
* Queries information of the database and stores it on `this.info`
* @param {Function} cb
*/
Graph.prototype.about = function(cb) {
var self = this;
Iif (this.info)
return cb(null,info);
else
return this.neo4jrestful.get('/'+this.neo4jrestful.urlOptions.endpoint, function(err, info){
Eif (info) {
self.info = info
}
Eif (typeof cb === 'function')
cb(err,info);
});
}
/**
* Resets the query history
*/
Graph.prototype.resetQuery = function() {
this._query_history_ = [];
this._queryString_ = '';
this.cypher = new CypherQuery();
return this;
}
/**
* Startpoint to begin query chaining
*
* Example:
* `Graph.start().where( …`
*
* @param {string} start
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.start = function(start, parameters, cb) {
this.resetQuery();
Iif (typeof start === 'function') {
cb = start;
start = null;
}
if (start)
this._query_history_.push({ START: start });
return this.exec(parameters, cb);
}
/**
* `MATCH …`
* @param {object|string|array} match
* @param {object} [parameters]
* @param {Function} [cb]
* @param {object} [options]
*/
Graph.prototype.match = function(match, parameters, cb, options) {
var self = this;
if (typeof options !== 'object')
options = {};
var matchString = '';
if (typeof match === 'object') {
if (match.length) {
match.forEach(function(item){
if (typeof item === 'object') {
matchString += self._addObjectLiteralForStatement(item);
} else {
matchString += String(item);
}
});
} else {
matchString = self._addObjectLiteralForStatement(match);
}
} else {
matchString = match;
}
// do we have "ON MATCH", "OPTIONAL MATCH" or "MATCH" ?
if (!options.switch)
this._query_history_.push({ MATCH: matchString });
else if (options.switch === 'ON MATCH')
this._query_history_.push({ ON_MATCH: matchString });
else Eif (options.switch === 'OPTIONAL MATCH')
this._query_history_.push({ OPTIONAL_MATCH: matchString });
return this.exec(parameters, cb);
}
/**
* `ON MATCH …`
* @param {string|object|array} onMatch
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.onMatch = function(onMatch, parameters, cb) {
return this.match(onMatch, parameters, cb, { switch: 'ON MATCH' });
}
/**
* `OPTIONAL MATCH …`
* @param {string|object|array} onMatch
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.optionalMatch = function(optionalMatch, parameters, cb) {
return this.match(optionalMatch, parameters, cb, { switch: 'OPTIONAL MATCH' });
}
/**
* `WITH …`
* @param {string} withStatement
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.with = function(withStatement, parameters, cb) {
this._query_history_.push({ WITH: withStatement });
return this.exec(parameters, cb);
}
/**
* `SKIP …`
* @param {number} skip
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.skip = function(skip, parameters, cb) {
skip = parseInt(skip);
Iif (skip === NaN)
throw Error('SKIP must be an integer');
this._query_history_.push({ SKIP: skip });
return this.exec(parameters, cb);
}
/**
* `LIMIT …`
* @param {number} limit
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.limit = function(limit, parameters, cb) {
limit = parseInt(limit);
Iif (limit === NaN)
throw Error('LIMIT must be an integer');
this._query_history_.push({ LIMIT: limit });
this.cypher.limit = limit; // TODO: implement: if limit 1 only return { r } or null instead if [ { r } ]
return this.exec(parameters, cb);
}
/**
* `MERGE …`
* @param {string} merge
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.merge = function(merge, parameters, cb) {
// TODO: values to parameter
this._query_history_.push({ MERGE: merge });
return this.exec(parameters, cb);
}
/**
* Pure string as statement segment
* @param {string} statement
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.custom = function(statement, parameters, cb) {
if ((typeof statement === 'object') && (typeof statement.toQuery === 'function')) {
this._query_history_.push(statement.toQuery().toString());
} else {
this._query_history_.push(statement);
}
return this.exec(parameters, cb);
}
/**
* `SET …`
* @param {string|object} set
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.set = function(set, parameters, cb) {
var setString = '';
var data = null;
if ((typeof set === 'object')&&(set !== null)) {
if (set.constructor !== Array) {
data = set;
set = [];
if (this.cypher.useParameters) {
set = this._addKeyValuesToParameters(data, ' = ');
} else {
for (var key in data) {
var value = data[key];
set.push(helpers.escapeProperty(key)+' = '+helpers.valueToStringForCypherQuery(value, "'"));
}
}
}
setString += set.join(', ');
} else {
setString += set;
}
this._query_history_.push({ SET: setString });
return this.exec(parameters, cb);
}
/**
* `SET n = …`, sets explicit to a set of values
*
* Example:
* `{ n: { name: 'Steve' } }`
* ~> SET n = { `name`: 'Steve' }
*
* @param {object} setWith value set
* @param {[type]} parameters
* @param {Function} cb
*/
Graph.prototype.setWith = function(setWith, parameters, cb) {
var setString = '';
setString += Object.keys(setWith)[0]+' = ';
if (this.cypher.useParameters) {
setString += this._addObjectLiteralToParameters(setWith[Object.keys(setWith)[0]]);
} else {
setString += helpers.serializeObjectForCypher(setWith[Object.keys(setWith)[0]]);
}
this._query_history_.push({ SET: setString });
return this.exec(parameters, cb);
}
/**
* `CREATE …`
* @param {string|object} create
* @param {object} [parameters]
* @param {Function} [cb]
* @param {[type]} [options]
*/
Graph.prototype.create = function(create, parameters, cb, options) {
var self = this;
var creates = [];
if (typeof options !== 'object')
options = {};
options = _.defaults(options, {
action: 'CREATE'
});
if (typeof create === 'object') {
creates.push('( ');
if (create.length) {
create.forEach(function(item){
if (typeof item === 'object') {
creates.push(self._addObjectLiteralForStatement(item));
} else {
creates.push(String(item));
}
});
} else {
// we have a object literal
var parts = [];
for (var part in create) {
for (var attr in create[part]) {
// on create, only add values beside `null` and `undefined`, otherwise neo4j will throw an exception
if ((create[part][attr] === undefined)||(create[part][attr] === null)) {
delete create[part][attr];
}
}
parts.push(part + ' ' + self._addObjectLiteralForStatement(create[part]));
}
creates.push(parts.join(', '));
}
creates.push(' )');
} else {
creates = [ create ];
}
var statementSegment = {};
// { CREATE: creates.join(' ') } for instance
statementSegment[options.action] = creates.join(' ');
this._query_history_.push(statementSegment);
return this.exec(parameters, cb);
}
/**
* `ON CREATE …`
* @see Graph.prototype.create
*/
Graph.prototype.onCreate = function(onCreate, parameters, cb) {
return this.create(onCreate, parameters, cb, { action: 'ON_CREATE' });
}
/**
* `CREATE UNIQUE …`
* @see Graph.prototype.create
*/
Graph.prototype.createUnique = function(createUnique, parameters, cb) {
return this.create(createUnique, parameters, cb, { action: 'CREATE_UNIQUE' });
}
/**
* `CREATE INDEX ON …`
* @see Graph.prototype.create
*/
Graph.prototype.createIndexOn = function(createIndexOn, parameters, cb) {
return this.create(createIndexOn, parameters, cb, { action: 'CREATE_INDEX_ON' });
}
/**
* `CASE … END`
* @param {string} caseStatement
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.case = function(caseStatement, parameters, cb) {
this._query_history_.push({ CASE: caseStatement.replace(/END\s*$/i,'') + ' END ' });
return this.exec(parameters, cb);
}
/**
* `DROP INDEX ON …`
* @param {string} dropIndexOn
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.dropIndexOn = function(dropIndexOn, parameters, cb) {
this._query_history_.push({ DROP_INDEX_ON: dropIndexOn });
return this.exec(parameters, cb);
}
/**
* `ORDER BY …`
* @param {string|object} property
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.orderBy = function(property, parameters, cb) {
var direction = ''
, s = '';
if (typeof property === 'object') {
var key = Object.keys(property)[0];
cb = direction;
direction = property[key];
property = key;
direction = ( (typeof direction === 'string') && ((/^(ASC|DESC)$/).test(direction)) ) ? direction : 'ASC';
s = property+' '+direction;
} else Eif (typeof property === 'string') {
s = property;
}
this._query_history_.push({ ORDER_BY: s });
return this.exec(parameters, cb);
}
/**
* `WHERE …`
*
* Examples:
* Graph.start('n=node(1)').where({ $OR : [ { 'n.name?': 'Steve' }, { 'n.name?': 'Jobs' } ] })
* Graph.start('n=node(1)').where("n.name? = {name1} OR n.name? = {name2}", { name1: 'Steve', name2: 'Jobs' })
*
* @param {object|string} where
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.where = function(where, parameters, cb) {
if (typeof where === 'string') {
this._query_history_.push({ WHERE: where });
return this.exec(parameters, cb);
}
Iif (this.cypher.useParameters === null)
this.cypher.useParameters = true;
Eif (!_.isArray(where))
where = [ where ];
var options = { valuesToParameters: this.cypher.useParameters, parametersStartCountAt: Object.keys(this.cypher.parameters || {}).length };
var condition = new ConditionalParameters(where, options);
var whereCondition = condition.toString().replace(/^\(\s(.+)\)$/, '$1');
this._query_history_.push({ WHERE: whereCondition });
if (this.cypher.useParameters)
this.addParameters(condition.parameters);
return this.exec(parameters, cb);
}
/**
* `RETURN …`
* @param {String} returnStatement
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.return = function(returnStatement, parameters, cb, distinct) {
var parts = [];
Eif (returnStatement) {
Iif (returnStatement.constructor === Array)
parts = returnStatement;
Iif ((typeof returnStatement === 'Object') && (Object.keys(returnStatement).length > 0))
Object.keys(returnStatement).forEach(function(key) {
parts.push(key+' AS ' + returnStatement[key]);
});
}
Iif (parts.length > 0)
returnStatement = parts.join(', ');
Iif (distinct === true)
this._query_history_.push({ RETURN_DISTINCT: returnStatement });
else
this._query_history_.push({ RETURN: returnStatement });
return this.exec(parameters, cb);
}
/**
* `RETURN DISTINCT …`
* @param {[type]} returnStatement
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.returnDistinct = function(returnStatement, parameters, cb) {
return this.return(returnStatement, parameters, cb, true);
}
/**
* `DELETE …`
* @param {string} deleteStatement
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.delete = function(deleteStatement, parameters, cb) {
this._query_history_.push({ DELETE: deleteStatement });
return this.exec(parameters, cb);
}
/**
* `REMOVE …`
* @param {string} remove
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.remove = function(remove, parameters, cb) {
this._query_history_.push({ REMOVE: remove });
return this.exec(parameters, cb);
}
/**
* `FOR EACH …`
* @param {[type]} foreach
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.foreach = function(foreach, parameters, cb) {
this._query_history_.push({ FOREACH: foreach });
return this.exec(parameters, cb);
}
/**
* `UNION …`
* @param {[type]} union
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.union = function(union, parameters, cb) {
this._query_history_.push({ UNION: union });
return this.exec(parameters, cb);
}
/**
* `USING …`
* @param {[type]} using
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.using = function(using, parameters, cb) {
this._query_history_.push({ USING: using });
return this.exec(parameters, cb);
}
/**
* Cypher-compatible-comment
* @param {string} comment
* @param {object} [parameters]
* @param {Function} [cb]
*/
Graph.prototype.comment = function(comment, parameters, cb) {
this.custom(' /* '+comment.replace(/^\s*\/\*\s*/,'').replace(/\s*\*\/\s*$/,'')+' */ ');
return this.exec(parameters, cb);
}
/**
* Returns cypher query object
* @return {object} Cypher query object
*/
Graph.prototype.toQuery = function() {
this.cypher.statements = this._query_history_;
return this.cypher;
}
/**
* Return query as String
* @return {string} query
*/
Graph.prototype.toQueryString = function() {
return this.toQuery().toString();
}
/**
* @see Graph.prototype.toQueryString
*/
Graph.prototype.toCypherQuery = function() {
return this.toQuery().toCypher();
}
/**
* Enables loading for specific types
* Define type(s) simply in a string
*
* Examples:
* 'node|relationship|path' or '*' to enable load for all types
* 'node|relationship' to enable for node + relationships
* '' to disable for all (you can also use `disableLoading()` instead)
*
* @param {string} classifications
*/
Graph.prototype.enableLoading = function(classifications) {
if (classifications === '*')
classifications = 'node|relationship|path';
this._loadOnResult_ = classifications;
return this;
}
/**
* Disables loading on results (speeds up queries but less convenient)
*/
Graph.prototype.disableLoading = function() {
this._loadOnResult_ = '';
return this;
}
/**
* Sort Results
* By default we get results like:
* `{ columns: [ 'node' ], data: [ [ { nodeObject#1 } ], … [ { nodeObject#n} ]] }`
* To keep it more handy, we return just the data
* and (if we have only 1 column) instead of [ {node} ] -> {node}
* If you want to have access to the columns anyway, you can get them on `graph._columns_`
*
* @param {boolean} trueOrFalse
*/
Graph.prototype.sortResult = function(trueOrFalse) {
Iif (typeof trueOrFalse === 'undefined')
trueOrFalse = true;
this._resortResults_ = trueOrFalse;
return this;
}
/**
* Enables sorting of result
*/
Graph.prototype.enableSorting = function() {
return this.sortResult(true);
}
/**
* Disbales sorting of result
*/
Graph.prototype.disableSorting = function() {
return this.sortResult(false);
}
/**
* Enables processing of result
*/
Graph.prototype.enableProcessing = function() {
this.sortResult(true);
this.enableLoading('*');
return this;
}
/**
* Disbales processing of result
*/
Graph.prototype.disableProcessing = function() {
this.sortResult(false);
this.disableLoading();
return this;
}
/**
* Will be called for logging, can be overriddin with a custom function
*/
Graph.prototype.log = function(){ /* > /dev/null */ };
/**
* Expect s.th. like [ value, value2 ] or [ { key1: value }, { key2: value } ]
* @private
* @param {object|array} parameters
* @return {object} parameters
*/
Graph.prototype._addParametersToCypher = function(parameters) {
Eif ( (typeof parameters === 'object') && (parameters) && (parameters.constructor === Array) ) {
if (!this.cypher.hasParameters())
this.cypher.parameters = {};
for (var i=0; i < parameters.length; i++) {
this._addParameterToCypher(parameters[i]);
}
} else {
throw Error('You need to pass parameters as array');
}
return this.cypher.parameters;
}
/**
* Expect s.th. like 'value' or { parameterkey: 'value' }
* @private
* @param {string|object} parameter
* @return {object} parameters
*/
Graph.prototype._addParameterToCypher = function(parameter) {
if (!this.cypher.hasParameters())
this.cypher.parameters = {};
Iif ((typeof parameter === 'object')&&(parameter !== null)) {
_.extend(this.cypher.parameters, parameter);
} else {
// we name the parameter with `_value#_`
var count = Object.keys(this.cypher.parameters).length;
// values with `undefined` will be replaced with `null` because neo4j doesn't process `undefined`
this.cypher.parameters['_value'+count+'_'] = (typeof parameter === 'undefined') ? null : parameter;
// return the placeholder
return '{_value'+count+'_}';
}
return this.cypher.parameters;
}
/**
* Add key value to parameters
* @private
* @param {object} key/value object literal
* @param {string} [assignOperator], can be ' = ' or ' : ' for instance
* @return {array} values
*/
Graph.prototype._addKeyValuesToParameters = function(o, assignOperator) {
o = helpers.flattenObject(o);
var values = [];
var identifierDelimiter = '`';
Iif (typeof assignOperator !== 'string')
assignOperator = ' = ';
for (var attr in o) {
values.push(helpers.escapeProperty(attr, identifierDelimiter) + assignOperator + this._addParameterToCypher(o[attr]));
}
return values;
}
/**
* Add object literal to parameters
* @private
* @param {object} objectLiteral
* @return {string} map, e.g. `{ n.`name`: '…', …, n.`phone`: '…' }`
*/
Graph.prototype._addObjectLiteralToParameters = function(objectLiteral) {
return '{ '+this._addKeyValuesToParameters(objectLiteral, ' : ').join(', ')+' }';
}
/**
* Adds object literal to query.
* If parameters are used (default), values will be added to parameters and replaced with `{_value%n_}`
* @private
* @param {object} o
* @return {string} serialized object literal
*/
Graph.prototype._addObjectLiteralForStatement = function(o) {
var s = '';
if (this.cypher.useParameters)
s = this._addObjectLiteralToParameters(o);
else
s = helpers.serializeObjectForCypher(o);
return s;
}
/**
* # Static methods
* are aliases to methods on instanced Graph()
*/
/**
* @see Graph.prototype.query
*/
Graph.query = function(cypher, parameters, cb, options) {
return Graph.disableProcessing().query(cypher, parameters, cb, options);
}
/**
* @see Graph.prototype.stream
*/
Graph.stream = function(cypher, parameters, cb, options) {
return new Graph.disableProcessing().stream(cypher, parameters, cb, options);
}
/**
* @see Graph.prototype.wipeDatabase
*/
Graph.wipeDatabase = function(cb) {
return new Graph().wipeDatabase(cb);
}
/**
* @see Graph.prototype.countAllOfType
*/
Graph.countAllOfType = function(type, cb) {
return new Graph().countAllOfType(type, cb);
}
/**
* @see Graph.prototype.countRelationships
*/
Graph.countRelationships = function(cb) {
return new Graph().countRelationships(cb);
}
/**
* @see Graph.prototype.countRelations
*/
Graph.countRelations = function(cb) {
return new Graph().countRelationships(cb);
}
/**
* @see Graph.prototype.countNodes
*/
Graph.countNodes = function(cb) {
return new Graph().countNodes(cb);
}
/**
* @see Graph.prototype.countAll
*/
Graph.countAll = function(cb) {
return new Graph().countAll(cb);
}
/**
* @see Graph.prototype.about
*/
Graph.about = function(cb) {
return new Graph().about(cb);
}
/**
* @see Graph.prototype.start
*/
Graph.start = function(start, parameters, cb) {
return new Graph().enableProcessing().start(start, parameters, cb);
}
/**
* @see Graph.prototype.custom
*/
Graph.custom = function(statement, parameters, cb) {
return Graph.start().custom(statement, parameters, cb);
}
/**
* @see Graph.prototype.match
*/
Graph.match = function(statement, parameters, cb) {
return Graph.start().match(statement, parameters, cb);
}
/**
* @see Graph.prototype.where
*/
Graph.where = function(statement, parameters, cb) {
return Graph.start().where(statement, parameters, cb);
}
/**
* @see Graph.prototype.return
*/
Graph.return = function(statement, parameters, cb) {
return Graph.start().return(statement, parameters, cb);
}
/**
* @see Graph.prototype.create
*/
Graph.create = function(statement, parameters, cb) {
return Graph.start().create(statement, parameters, cb);
}
/**
* @see Graph.prototype.enableLoading
*/
Graph.enableLoading = function(classifications) {
return Graph.start().enableLoading(classifications);
}
/**
* @see Graph.prototype.disableLoading
*/
Graph.disableLoading = function() {
return Graph.start().disableLoading();
}
/**
* @see Graph.prototype.disableProcessing
*/
Graph.disableProcessing = function() {
return Graph.start().disableProcessing();
}
/**
* @see Graph.prototype.enableProcessing
*/
Graph.enableProcessing = function() {
return Graph.start().enableProcessing();
}
/**
* @see Graph.prototype.enableSorting
*/
Graph.enableSorting = function() {
return Graph.start().enableSorting();
}
/**
* @see Graph.prototype.disableSorting
*/
Graph.disableSorting = function() {
return Graph.start().disableSorting();
}
/**
* Returns a new neo4jrestful client
* Can be used for direct requests on neo4j for instance
* @return {object} neo4jrestful
*/
Graph.request = function() {
// creates a new neo4jrestful client
return neo4jrestful.singleton();
}
/**
* Instanciate a new Graph object, same as `new Graph()
* @see Graph
*/
Graph.new = function(url) {
return new Graph(url);
}
return neo4jrestful.Graph = Graph;
}
Eif (typeof window !== 'object') {
module.exports = exports = {
init: __initGraph__
};
} else {
window.Neo4jMapper.initGraph = __initGraph__;
}
|