starting on View
[rrq/rrqmisc.git] / vector / View.c
1 #include <stdlib.h>
2 #include <View.h>
3 #include <HashVector.h>
4 #include <QueryCallbacks.h>
5 #include <Query.h>
6 #include <stringitem.h>
7
8 /**
9  * A View is a "virtual relation" that captures the differences at
10  * successive evaluations in the binding sequences offered by a query.
11  */
12 typedef struct {
13     struct QueryCallbacks *def;
14     /**
15      * This is the source query to be a view of.
16      */
17     Query *source;
18     /**
19      * This is the size of the names tuple.
20      */
21     int arity;
22     /**
23      * This is the binding names to track.
24      */
25     Tuple *names;
26     /**
27      * This is the collection of bindings for the tracked names being
28      * gained at the latest evaluation.
29      */
30     HashVector gained;
31     /**
32      * This is the collection of bindings for the tracked names being
33      * last at the latest evaluation.
34      */
35     HashVector lost;
36 } View;
37
38 static Tuple *View_type_Tuple(HashVector *hv) {
39     Tuple *t = Tuple_calloc( hv->fill );
40     VectorIndex index = 0;
41     for ( ; index < hv->table.size; index++ ) {
42         t->elements[ index ] = &stringitem;
43     }
44     return t;
45 }
46
47 static QueryCallbacks View_def = {
48     .reclaim = 0,
49     .next = 0,
50     .variables = 0
51 };
52
53 Query *View_create(Query *q) {
54     View *vq = (View*) malloc( sizeof( View ) );
55     HashVector hv = (HashVector) {
56         .table = (Vector) {
57             .variant = Nibble_index_levels, .size = 16, .entries = 0
58         },
59         .fill = 0, .holes = 0, .type = &stringitem
60     };
61     q->def->variables( q, &hv ); // Obtain query variables
62     
63     TupleSchema *ts = TupleSchema_create( hv.fill, View_type_Tuple( &hv ) );
64     (*vq) = (View) {
65         .def = &View_def,
66         .source = q,
67         .arity = 0,
68         .gained = (HashVector) {
69             .table = (Vector) {
70                 .variant = Nibble_index_levels,
71                 .size = 16,
72                 .entries = 0
73             },
74             .fill = 0, .holes = 0, .type = (ItemKeyFun*) ts
75         },
76         .lost = (HashVector) {
77             .table = (Vector) {
78                 .variant = Nibble_index_levels,
79                 .size = 16,
80                 .entries = 0
81             },
82             .fill = 0, .holes = 0, .type = (ItemKeyFun*) ts
83         }
84     };
85     return (Query*) vq;
86 }