-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathknit_memory.js
3278 lines (2635 loc) · 106 KB
/
knit_memory.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
//vendor/collection_functions ======================================================
CollectionFunctions = (function(){
var standardArrayFeatures = {
iterator:function(collection){
var position = 0
return {
next: function() {
var result = collection[position]
position += 1
return result
},
hasNext: function(){return position<collection.length}
}
},
nothing:function(){return null},
get:function(array, index){return array[index]},
equals:function(a,b){return a == b},
newCollection:function(){return []},
append:function(array, item){ array.push(item) },
isCollection:function(thing){ return typeof thing.length != "undefined" && typeof thing.push != "undefined" },
size:function(array){ return array.length },
sort:function(array){ return [].concat(array).sort() },
concat:function(){
var firstArray = arguments[0]
var otherArrays = []
for(var i=1; i<arguments.length; i++) {otherArrays[i-1] = arguments[i]}
return firstArray.concat.apply(firstArray, otherArrays)
}
}
var mainFunction = function(userFeatures) {
var factory = (function me(features, arrayFunctions, createAcrossCF) {
//============ SETUP ============
var featureRequirementBug = function(featureName){
throw new Error("BUG: a missing feature is required in order to perform this operation. " +
"The developer should have prevented this function from being exported.")
}
var featureNames = ["iterator", "nothing", "equals", "newCollection", "append",
"isCollection", "size", "concat", "comparator", "sort", "get"]
for (var i=0; i<featureNames.length; i++) {
var featureName = featureNames[i],
halt = featureRequirementBug
halt.unavailable = true
features[featureName] = features[featureName] || halt
}
function feature(featureName) {
return !features[featureName].unavailable
}
function getFeatureIfAvailable(featureName) {
var feature = features[featureName]
return feature.unavailable ? undefined : feature
}
var createAcrossCF = createAcrossCF==false ? false : true,
breaker = {},
functionsForExport = {}
//============ COLLECTION FUNCTIONS ============
var iteratorHolder = {iteratorFunction:features.iterator} //so we can wrap/override later
function iterator(collection) {
return iteratorHolder.iteratorFunction(collection)
}
if (feature("iterator"))
functionsForExport.iterator = iterator
var getOne = getFeatureIfAvailable("get") ||
function(collection, index) {
var itemAtIndex = features.nothing()
each(collection, function(item, i){
if (i == index) {
itemAtIndex = item
return breaker
}
})
return itemAtIndex
}
function get(collection, indexOrIndexes) {
if (typeof indexOrIndexes.length != "undefined") {
var indexes = indexOrIndexes
return arrayFunctions.map(indexes, function(index){return getOne(collection, index)})
} else {
var index = indexOrIndexes
return getOne(collection, index)
}
}
if (functionsForExport.iterator ||
feature("get"))
functionsForExport.get = get
function each(collection, callback) {
var count = 0
var iteratorInstance = iterator(collection)
while (iteratorInstance.hasNext()) {
var item=iteratorInstance.next(),
result = callback(item, count)
if (result === breaker) break
count += 1
}
}
if (functionsForExport.iterator)
functionsForExport.each = each
function detect(collection, matcher) {
var hit = features.nothing()
each(collection, function(item, i){
if (matcher(item, i)) {
hit = item
return breaker
}
})
return hit
}
if (functionsForExport.each &&
feature("nothing"))
functionsForExport.detect = detect
function select(collection, matcher) {
var newCollection = features.newCollection()
each(collection, function(item, i){
if (matcher(item, i)) features.append(newCollection, item)
})
return newCollection
}
if (functionsForExport.each &&
feature("newCollection") &&
feature("append"))
functionsForExport.select = select
function map(collection, transformer, newCollectionF, appenderF) {
newCollectionF = newCollectionF || function(){return []}
appenderF = appenderF || function(arr, item){arr.push(item)}
var newCollection = newCollectionF()
each(collection, function(item, i){
appenderF(newCollection, transformer(item, i))
})
return newCollection
}
if (functionsForExport.each &&
feature("newCollection") &&
feature("append"))
functionsForExport.map = map
function pluck(collection, property) {
return map(collection, function(item){
var value = item[property]
if (typeof value == "function") value = value.apply(item, [])
return value
})
}
if (functionsForExport.map)
functionsForExport.pluck = pluck
function toCollection(thing, iteratorF) {
iteratorF = iteratorF || arrayFunctions.iterator
var newCollection = features.newCollection(),
iteratorInstance = iteratorF(thing)
while (iteratorInstance.hasNext()) features.append(newCollection, iteratorInstance.next())
return newCollection
}
if (feature("newCollection") &&
feature("append"))
functionsForExport.toCollection = toCollection
function isSorted(collection) {
var sorted = true,
previousItem = null
each(collection, function(item, i){
if (i>=1 && features.comparator(previousItem, item) < 0) {
sorted = false
return breaker
}
previousItem = item
})
return sorted
}
if (functionsForExport.each &&
feature("comparator"))
functionsForExport.isSorted = isSorted
var sort = getFeatureIfAvailable("sort") ||
function(collection) {
var array = map(collection, function(item){return item})
array.sort(features.comparator())
var sortedCollection = map(array, function(item){return item}, features.newCollection, features.append)
return sortedCollection
}
if (feature("sort") ||
functionsForExport.map &&
feature("comparator"))
functionsForExport.sort = sort
//evaluator? word?
function sortBy(collection, evaluator) {
var array = map(collection, function(item){return item})
array.sort(function(a,b){
var aValue = evaluator(a),
bValue = evaluator(b)
return aValue==bValue ? 0 : (aValue>bValue ? 1 : -1)
})
var sortedCollection = map(array, function(item){return item}, features.newCollection, features.append)
return sortedCollection
}
if (functionsForExport.map)
functionsForExport.sortBy = sortBy
function indexOf(collection, findMe) {
var index = features.nothing()
detect(collection, function(item, i){
if (features.equals(item, findMe)) {
index = i
return true
}
})
return index
}
function indexesOf(collection, findCollection) { //anglo-saxon rules win every time in this library
return map(findCollection, function(item){return indexOf(collection, item)})
}
function include(collection, findMe) {
return indexOf(collection, findMe) != features.nothing()
}
if (functionsForExport.detect &&
feature("nothing") &&
feature("equals")) {
functionsForExport.indexOf = indexOf
functionsForExport.indexesOf = indexesOf
functionsForExport.include = include
}
function uniq(collection) {
var newCollection = features.newCollection()
each(collection, function(item){
if (!include(newCollection, item)) features.append(newCollection, item)
})
return newCollection
}
if (functionsForExport.each &&
functionsForExport.include &&
feature("newCollection") &&
feature("append"))
functionsForExport.uniq = uniq
function overlap(collectionA, collectionB, acceptor) {
var result = select(collectionA, function(itemA) {
return include(collectionB, itemA) == acceptor
})
result = uniq(result)
return result
}
function intersect(collectionA, collectionB) { return overlap(collectionA, collectionB, true) }
function differ(collectionA, collectionB) { return overlap(collectionA, collectionB, false) }
if (functionsForExport.select &&
functionsForExport.include &&
functionsForExport.uniq) {
functionsForExport.intersect = intersect
functionsForExport.differ = differ
}
function without(collection, dontWantThisItem) {
return select(collection, function(item) {
return !features.equals(item, dontWantThisItem)
})
}
if (functionsForExport.select &&
feature("equals"))
functionsForExport.without = without
function remove(collection, indexWeDontWant) {
var newCollection = features.newCollection()
each(collection, function(item,i) {
if (i!=indexWeDontWant) features.append(newCollection, item)
})
return newCollection
}
if (functionsForExport.each &&
feature("newCollection") &&
feature("append"))
functionsForExport.remove = remove
function flatten(collection) {
var newCollection = features.newCollection()
each(collection, function(item){
if (features.isCollection(item)) {
var itemFlattened = flatten(item)
each(itemFlattened, function(item) {
features.append(newCollection, item)
})
} else {
features.append(newCollection, item)
}
})
return newCollection
}
if (functionsForExport.each &&
feature("newCollection") &&
feature("isCollection") &&
feature("append"))
functionsForExport.flatten = flatten
var concat = getFeatureIfAvailable("concat") ||
function() {
var newCollection = features.newCollection()
arrayFunctions.each(arguments, function(collection){
each(collection, function(item){features.append(newCollection, item)})
})
return newCollection
}
if (feature("concat") ||
feature("newCollection") &&
feature("append"))
functionsForExport.all =
functionsForExport.clone =
functionsForExport.concat = concat
function repeat(collection, times) {
var repeated = features.newCollection()
for (var i=0; i<times; i++) repeated = concat(repeated, collection)
return repeated
}
if (functionsForExport.concat &&
feature("newCollection"))
functionsForExport.repeat = repeat
/*
Hey look my head is hurting too. But this is worth it, I think! (?)
We're expressing multi-collection capability through CF itself,
meaning you get multi-collection detect, map, etc for free. Yay!
*/
var acrossCF = arrayFunctions && createAcrossCF ?
me({iterator:function(collections){
var iteratorInstances = arrayFunctions.map(collections, function(collection){return iterator(collection)})
return {
next: function() {
return arrayFunctions.map(iteratorInstances, function(iterator){
return iterator.hasNext() ? iterator.next() : features.nothing()
}, features.newCollection, features.append)
},
hasNext: function(){
return arrayFunctions.detect(iteratorInstances, function(iterator){return iterator.hasNext()})
}
}
},
equals:function(collectionA, collectionB){return equals(collectionA, collectionB)},
nothing:features.nothing,
newCollection:features.newCollection,
append:features.append,
isCollection:undefined, //doesn't make sense when dealing with multiple collections
},
arrayFunctions,
false //to stop recursion
) :
function(){throw "across not supported in this context"}
function across() {
var collections = arguments
return acrossCF.makeObjectStyleFunctions(function(){return collections})
}
function zip() {
var lastArgument = arguments[arguments.length-1]
if (typeof lastArgument == "function") {
var collections = arrayFunctions.slice(arguments, [0,-2]),
callback = lastArgument
across.apply(null, collections).each(function(entryCollection, i){
callback.apply(null, arrayFunctions.map(entryCollection, function(item){return item}).concat([i]) )
})
} else {
var collections = arguments
return across.apply(null, collections).all()
}
}
if (createAcrossCF) { //can't do across across because we would all die
functionsForExport.across = across
functionsForExport.zip = zip
}
function equals(collectionA, collectionB) {
var acrossAB = across(collectionA, collectionB)
var foundNotEqual = acrossAB.detect(function(pairCollection){
var iter = features.iterator(pairCollection)
var a = iter.next()
var b = iter.next()
return !features.equals(a, b)
})
return !foundNotEqual
}
if (functionsForExport.detect &&
feature("iterator") &&
feature("equals") &&
feature("newCollection"))
functionsForExport.equals = equals
var size = getFeatureIfAvailable("size") ||
function(collection) {
var count = 0
each(collection, function() { count += 1 })
return count
}
function empty(collection) { return size(collection) == 0 }
if (feature("size") || functionsForExport.each) {
functionsForExport.size = size
functionsForExport.empty = empty
}
function slice(collection, a, b) {
function sliceStartPlusLength(collection, startPos, length) {
var newCollection = features.newCollection()
each(collection, function(item, i) {
if (i>=startPos) features.append(newCollection, item)
if (i==(startPos+length-1)) return breaker
})
return newCollection
}
function sliceRange(collection, range) {
var startPos = range[0],
endPos = range[1]
if (startPos>=0 && endPos>=0) {
return sliceStartPlusLength(collection, startPos, endPos-startPos+1)
} else {
var theSize = size(collection),
positiveStartPos = startPos<0 ? theSize + startPos : startPos,
positiveEndPos = endPos<0 ? theSize + endPos : endPos
return sliceRange(collection, [positiveStartPos, positiveEndPos])
}
}
if (typeof a.length != "undefined") {
var range = a
return sliceRange(collection, range)
} else {
var startPos = a,
length = b
return sliceStartPlusLength(collection, startPos, length)
}
}
if (functionsForExport.each &&
feature("newCollection") &&
feature("append"))
functionsForExport.slice = slice
function splice(mainCollection, spliceInCollection, insertAtIndex, overwriteLength) {
overwriteLength = overwriteLength || 0
return concat(slice(mainCollection, [0, insertAtIndex-1]),
spliceInCollection,
slice(mainCollection, [insertAtIndex + overwriteLength, -1]))
}
if (functionsForExport.concat &&
functionsForExport.slice)
functionsForExport.splice = splice
function inspect(collection) {
var strings = []
each(collection, function(item){
strings.push(typeof item.inspect == "function" ? item.inspect() : "" + item)
})
return strings.join(",")
}
if (functionsForExport.each) functionsForExport.inspect = inspect
//============ CONCLUSION ============
function specialCurry(func, collectionFunc) {
return function() {
var args = []
for(key in arguments){args[key] = arguments[key]}
args.unshift(collectionFunc.apply(this, []))
return func.apply(null, args)
}
}
function makeObjectStyleFunctions(collectionGetter) {
var curried = {}
for(k in functionsForExport){curried[k] = specialCurry(functionsForExport[k], collectionGetter)}
return curried
}
function layerOnCostTracking(functions) {
iteratorHolder._callsToNextSession = 0
iteratorHolder._callsToNextTotal = 0
var wrappedFunctions = {}
function makeCostResettingWrapper(inner) {
return function() {
iteratorHolder._callsToNextSession = 0
var args = arrayFunctions.map(arguments, function(arg){return arg}),
result = inner.apply(this, args)
return result
}
}
for (k in functions) wrappedFunctions[k] = makeCostResettingWrapper(functions[k])
var innerIteratorFunction = iteratorHolder.iteratorFunction
iteratorHolder.iteratorFunction = function(collection) {
var realIterator = innerIteratorFunction(collection)
var realNext = realIterator.next
realIterator.next = function() {
iteratorHolder._callsToNextSession += 1
iteratorHolder._callsToNextTotal += 1
return realNext()
}
return realIterator
}
wrappedFunctions.lastCost = function() { return iteratorHolder._callsToNextSession }
wrappedFunctions.totalCost = function() { return iteratorHolder._callsToNextTotal }
wrappedFunctions.resetTotalCost = function() { iteratorHolder._callsToNextTotal = 0 }
return wrappedFunctions
}
function makeExports(functions) {
return {
functions:functions,
decorate: function(target){for(k in functions){target[k] = functions[k]}},
makeObjectStyleFunctions: makeObjectStyleFunctions,
decorateObjectStyle: function(target, collectionGetter){
var curriedFunctions = makeObjectStyleFunctions(collectionGetter)
for(k in curriedFunctions){target[k] = curriedFunctions[k]}
}
}
}
var originalExports = makeExports(functionsForExport),
layeredStatsExports = makeExports(layerOnCostTracking(functionsForExport))
originalExports.withStatTracking = layeredStatsExports
return originalExports
}) //end factory
var arrayCF = factory.apply(null, [standardArrayFeatures])
var f = factory(userFeatures, arrayCF.functions)
f.appendFeatures = function(newFeatures) {
var combined = {}
for(var k in userFeatures) {combined[k] = userFeatures[k]}
for(var k in newFeatures) {combined[k] = newFeatures[k]}
return factory(combined, arrayCF.functions)
}
return f
}
var externalArrayCF = mainFunction.apply(null, [standardArrayFeatures]) //convenience
externalArrayCF.functions.toArray = externalArrayCF.functions.toCollection
externalArrayCF.withStatTracking.functions.toArray = externalArrayCF.withStatTracking.functions.toCollection
delete externalArrayCF.functions.toCollection
delete externalArrayCF.withStatTracking.functions.toCollection
mainFunction.Array = externalArrayCF
return mainFunction
})()
//knit/core ======================================================
//knit/namespace ======================================================
if (typeof global === 'undefined') throw new Error("Please define global. If you are in a browser, set global=window.")
global.knit = {
algebra: {predicate:{}},
mixin:{},
translation:{sql:{}},
engine:{ memory:{}, sqlite:{} },
attributeType:{}
}
//knit/core/util ======================================================
//internal utilities
knit._util = {
//see http://fitzgeraldnick.com/weblog/39/
quacksLike: function(object, signature) {
if (typeof signature === "undefined") throw("no signature provided")
if (object === undefined) return false
var k, ctor
for ( k in signature ) {
ctor = signature[k]
if ( ctor === Number ) {
if ( Object.prototype.toString.call(object[k]) !== "[object Number]" || isNaN(object[k]) ) {
return false
}
} else if ( ctor === String ) {
if ( Object.prototype.toString.call(object[k]) !== "[object String]" ) {
return false
}
} else if ( ctor === Boolean ) {
var value = object[k]
if (!(value === true || value === false)) return false
} else if ( ! (object[k] instanceof ctor) ) {
return false
}
}
return true
},
bind: function(f, objectThatShouldBeThis) {
return function() {
var args = knit._util.toArray(arguments)
return f.apply(objectThatShouldBeThis, args)
}
},
extend: function() {
//chicken and egg
var args = []
for (var i=0; i<arguments.length; i++) {
args.push(arguments[i])
}
var mergee = args.shift(),
toMerges = args
for (i=0; i<toMerges.length; i++) {
var toMerge = toMerges[i]
for(var k in toMerge) mergee[k] = toMerge[k]
}
return mergee
},
delegate: function(object, signature, delegateFunction) {
knit._util.each(knit._util.keys(signature), function(methodNameToDelegate) {
object[methodNameToDelegate] = function() {
var target = delegateFunction.apply(this, []),
targetFunction = target[methodNameToDelegate]
if (typeof targetFunction != "function") {
throw(methodNameToDelegate + " not an available function on delegate.")
}
return targetFunction.apply(target, arguments)
}
})
},
keys: function(obj) {
var keys = []
for (var k in obj) keys.push(k)
return keys
},
values: function(obj) {
var values = []
for (var k in obj) values.push(obj[k])
return values
},
isArray: function(thing){
return Object.prototype.toString.apply(thing) == "[object Array]"
},
deepEqual:function(a,b,equalsMethodName) {
function objectsEqual(objA, objB, equalsMethodName) {
for (var key in objA) if (!(key in objB) || !knit._util.deepEqual(objA[key], objB[key], equalsMethodName)) return false
return true
}
if (a===b) return true
if (typeof a != typeof b) return false
if ((a===null || b===null) && a!=b) return false
if (this.isArray(a) && this.isArray(b)) {
if (a.length != b.length) return false
var i = a.length
while (i--) { if ( ! knit._util.deepEqual(a[i], b[i], equalsMethodName)) return false } //hrm
} else {
if (a[equalsMethodName] && b[equalsMethodName]) {
if (!a[equalsMethodName](b)) return false
} else if (typeof a == "object" && typeof b == "object") {
if (!objectsEqual(a, b, equalsMethodName) || !objectsEqual(b, a, equalsMethodName)) return false //inefficient
} else {
if (a!=b) return false
}
}
return true
},
deepSame:function(a,b) { return knit._util.deepEqual(a,b, "isSame") },
deepSameThisVsOther:function(other) { return knit._util.deepSame(this, other) }
}
knit._util.extend(knit._util, CollectionFunctions.Array.functions)
//knit/core/signatures ======================================================
knit.signature = (function(){
var _ = knit._util
var inspectable = {inspect:Function},
like = {isSame:Function, isEquivalent:Function},
signatures = {}
signatures.attribute = _.extend(
{name:Function, type:Function, sourceRelation:Function},
like,
inspectable
)
signatures.nestedAttribute = _.extend(
{nestedRelation:Function},
signatures.attribute
)
signatures.relation = _.extend(
{attributes:Function, split:Function, merge:Function, newNestedAttribute:Function},
like,
inspectable
)
signatures.relationExpression = _.extend(
{defaultCompiler:Function, compile:Function},
signatures.relation
)
signatures.compiledRelation = _.extend(
{rows:Function, objects:Function, cost:Function},
signatures.relation
)
signatures.executionStrategy = _.extend(
{rowsAsync:Function, rowsSync:Function},
signatures.relation
)
signatures.join = _.extend(
{relationOne:Object, relationTwo:Object, predicate:Object},
signatures.relation
)
signatures.rawRelation = {attributes:Array, rows:Array}
return signatures
})()
//knit/core/reference ======================================================
knit.RelationReference = (function(){
var _ = knit._util,
C = function(relationName) {
this._relation = new knit.UnresolvedRelationReference(relationName)
},
p = C.prototype
p.resolve = function(bindings) {
if (this._relation.resolve) this._relation = this._relation.resolve(bindings)
return this
}
_.each(["id", "attr", "name"], function(methodNameToDelegate) {
p[methodNameToDelegate] = function() {
return this._relation[methodNameToDelegate].apply(this._relation, arguments)
}
})
_.delegate(p,
_.extend({}, knit.signature.compiledRelation, knit.signature.relationExpression),
function(){return this._relation})
p.isSame =
p.isEquivalent = function(other) {
return this._relation.isSame(other) || !!(other._relation && this._relation.isSame(other._relation))
}
return C
})()
knit.UnresolvedRelationReference = (function(){
var _ = knit._util,
_id = 0,
C = function(relationName) {
this._relationName = relationName
_id += 1
this._id = "unresolvedRelation_" + _id
},
p = C.prototype
p.id = function(bindings) { return this._id }
p.resolve = function(bindings) { return bindings[this._relationName] }
_.each(["attributes", "attr", "merge", "split", "newNestedAttribute"], function(methodNameToDelegate) {
p[methodNameToDelegate] = function() {
throw(methodNameToDelegate + " not available until after resolve (and refs are bound to real relations)")
}
})
p.isSame =
p.isEquivalent = function(other) {
return other.constructor == C &&
this._relationName == other._relationName
}
p.inspect = function(){return "*" + this._relationName }
return C
})()
knit.NullRelation = (function(){
var C = function() {},
p = C.prototype
p.resolve = function(bindings) { return this }
p.id = function() { return "nullRelation_id" }
p.attributes = function() { return new knit.Attributes([]) }
p.attr = function() { throw("Null Relation has no attributes") }
p.inspect = function() { return "nullRelation" }
p.merge =
p.split = function() { return this }
p.newNestedAttribute = function() { throw("It doesn't make sense for Null Relation to create attributes") }
p.isSame =
p.isEquivalent = function(other) { return this === other }
return new C()
})()
knit.AttributeReference = (function(){
var C = function(relationRef, attributeName) {
this._attribute = new knit.UnresolvedAttributeReference(relationRef, attributeName)
},
p = C.prototype
p.resolve = function(bindings) {
if (this._attribute.resolve) this._attribute = this._attribute.resolve(bindings)
return this
}
p.name = function() { return this._attribute.name() }
p.fullyQualifiedName = function() { return this._attribute.fullyQualifiedName() }
p.structuredName = function() { return this._attribute.structuredName() }
p.type = function() { return this._attribute.type() }
p.sourceRelation = function() { return this._attribute.sourceRelation() }
p.isSame =
p.isEquivalent = function(other) { return this._attribute.isSame(other) }
p.inspect = function(){return this._attribute.inspect()}
return C
})()
knit.UnresolvedAttributeReference = (function(){
var _ = knit._util,
C = function(relationRef, attributeName) {
this._relationRef = relationRef
this._attributeName = attributeName
},
p = C.prototype
p.resolve = function(bindings) {
return this._relationRef.resolve(bindings).attr(this._attributeName)
}
p.name = function() { return this._attributeName }
p.fullyQualifiedName = function() { return this._attributeName }
p.structuredName = function() { return this._attributeName }
p.type = function() { return null }
p.sourceRelation = function() { return this._relationRef }
p.isSame =
p.isEquivalent = function(other) {
return _.quacksLike(other, knit.signature.attribute) &&
this.sourceRelation().isSame(other.sourceRelation()) &&
this.name() == other.name()
}
p.inspect = function(){return "*" + this._attributeName}
return C
})()
knit.NestedAttributeReference = (function(){
var _ = knit._util,
C = function(attributeName, nestedAttributes) {
this._attribute = new knit.UnresolvedNestedAttributeReference(attributeName, nestedAttributes)
},
p = C.prototype
p.resolve = function(bindings) {
if (this._attribute.resolve) this._attribute = this._attribute.resolve(bindings)
return this
}
p.name = function() { return this._attribute.name() }
p.structuredName = function() { return this._attribute.structuredName() }
p.fullyQualifiedName = function() { return this._attribute.fullyQualifiedName() }
p.type = function() { return knit.attributeType.Nested }
p.setSourceRelation = function(sourceRelation) { return this._attribute.setSourceRelation(sourceRelation) }
p.sourceRelation = function() { return this._attribute.sourceRelation() }
p.nestedRelation = function() { return this._attribute.nestedRelation() }
p.isSame =
p.isEquivalent = function(other) {
return _.quacksLike(other, knit.signature.attribute) &&
this._attribute.isSame(other)
}
p.inspect = function(){return this._attribute.inspect()}
return C
})()
knit.UnresolvedNestedAttributeReference = (function(){
var _ = knit._util,
C = function(attributeName, nestedAttributes) {
this._attributeName = attributeName
this._nestedAttributes = nestedAttributes
this._sourceRelation = knit.NullRelation
},
p = C.prototype
p.resolve = function(bindings) {
_.each(this._nestedAttributes, function(nestedAttribute){nestedAttribute.resolve(bindings)})
return this.sourceRelation().newNestedAttribute(this._attributeName, this._nestedAttributes)
}
p.name = function() { return this._attributeName }
p.structuredName = function() { return this._attributeName }
p.fullyQualifiedName = function() { return this._attributeName }
p.type = function() { return knit.attributeType.Nested }
p.sourceRelation = function() { return this._sourceRelation }
p.setSourceRelation = function(sourceRelation) { this._sourceRelation = sourceRelation; return this }
p.nestedRelation = function() { throw("nestedRelation is not available until after resolve") }
p.isSame =
p.isEquivalent = function(other) {
return _.quacksLike(other, knit.signature.attribute) &&
this.sourceRelation().isSame(other.sourceRelation()) &&
this.name() == other.name()
}
p.inspect = function(){return "*" + this._attributeName}
return C
})()
knit.ReferenceEnvironment = (function(){
var _ = knit._util,
C = function() {
this._keyToRef = {}
this._internalBindings = {}
},
p = C.prototype
p.relation = function(relationName) {
var relationRef = this._keyToRef[relationName] = this._keyToRef[relationName] || new knit.RelationReference(relationName)
return relationRef
}
function regularAttr(relationNameDotAttributeName) {
var key = relationNameDotAttributeName,
parts = relationNameDotAttributeName.split("."),
relationRef = this.relation(parts[0]),
attributeName = parts[1],
attributeRef = this._keyToRef[key] = this._keyToRef[key] || new knit.AttributeReference(relationRef, attributeName)
return attributeRef
}
function nestedAttr(attributeName, nestedAttributeRefs) {
var key = attributeName,