-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbquery.c
2305 lines (2091 loc) · 68.7 KB
/
dbquery.c
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
/*
* $Id: $
* $Version: $
*
* Copyright (c) Priit Järv 2010,2011,2013,2014
*
* This file is part of WhiteDB
*
* WhiteDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WhiteDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with WhiteDB. If not, see <http://www.gnu.org/licenses/>.
*
*/
/** @file dbquery.c
* WhiteDB query engine.
*/
/* ====== Includes =============== */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ====== Private headers and defs ======== */
#ifdef __cplusplus
extern "C" {
#endif
#include "dballoc.h"
#include "dbquery.h"
#include "dbcompare.h"
#include "dbmpool.h"
#include "dbschema.h"
#include "dbhash.h"
/* T-tree based scoring */
#define TTREE_SCORE_EQUAL 5
#define TTREE_SCORE_BOUND 2
#define TTREE_SCORE_NULL -1 /** penalty for null values, which
* are likely to be abundant */
#define TTREE_SCORE_MASK 5 /** matching field in template */
/* Query flags for internal use */
#define QUERY_FLAGS_PREFETCH 0x1000
#define QUERY_RESULTSET_PAGESIZE 63 /* mpool is aligned, so we can align
* the result pages too by selecting an
* appropriate size */
/* Emulate array index when doing a scan of key-value pairs
* in a JSON query.
* If this is not desirable, commenting this out makes
* scans somewhat faster.
*/
#define JSON_SCAN_UNWRAP_ARRAY
struct __query_result_page {
gint rows[QUERY_RESULTSET_PAGESIZE];
struct __query_result_page *next;
};
typedef struct __query_result_page query_result_page;
typedef struct {
query_result_page *page; /** current page of results */
gint pidx; /** current index on page (reading) */
} query_result_cursor;
typedef struct {
void *mpool; /** storage for row offsets */
query_result_page *first_page; /** first page of results, for rewinding */
query_result_cursor wcursor; /** read cursor */
query_result_cursor rcursor; /** write cursor */
gint res_count; /** number of rows in results */
} query_result_set;
/* ======= Private protos ================ */
static gint most_restricting_column(void *db,
wg_query_arg *arglist, gint argc, gint *index_id);
static gint check_arglist(void *db, void *rec, wg_query_arg *arglist,
gint argc);
static gint prepare_params(void *db, void *matchrec, gint reclen,
wg_query_arg *arglist, gint argc,
wg_query_arg **farglist, gint *fargc);
static gint find_ttree_bounds(void *db, gint index_id, gint col,
gint start_bound, gint end_bound, gint start_inclusive, gint end_inclusive,
gint *curr_offset, gint *curr_slot, gint *end_offset, gint *end_slot);
static wg_query *internal_build_query(void *db, void *matchrec, gint reclen,
wg_query_arg *arglist, gint argc, gint flags, wg_uint rowlimit);
static query_result_set *create_resultset(void *db);
static void free_resultset(void *db, query_result_set *set);
static void rewind_resultset(void *db, query_result_set *set);
static gint append_resultset(void *db, query_result_set *set, gint offset);
static gint fetch_resultset(void *db, query_result_set *set);
static query_result_set *intersect_resultset(void *db,
query_result_set *seta, query_result_set *setb);
static gint check_and_merge_by_kv(void *db, void *rec,
wg_json_query_arg *arg, query_result_set *next_set);
static gint check_and_merge_by_key(void *db, void *rec,
wg_json_query_arg *arg, query_result_set *next_set);
static gint check_and_merge_recursively(void *db, void *rec,
wg_json_query_arg *arg, query_result_set *next_set, int depth);
static gint prepare_json_arglist(void *db, wg_json_query_arg *arglist,
wg_json_query_arg **sorted_arglist, gint argc,
gint *index_id, gint *vindex_id, gint *kindex_id);
static gint encode_query_param_unistr(void *db, char *data, gint type,
char *extdata, int length);
static gint show_query_error(void* db, char* errmsg);
/*static gint show_query_error_nr(void* db, char* errmsg, gint nr);*/
/* ====== Functions ============== */
/** Find most restricting column from query argument list
* This is probably a reasonable approach to optimize queries
* based on T-tree indexes, but might be difficult to combine
* with hash indexes.
* XXX: currently only considers the existence of T-tree
* index and nothing else.
*/
static gint most_restricting_column(void *db,
wg_query_arg *arglist, gint argc, gint *index_id) {
struct column_score {
gint column;
int score;
int index_id;
};
struct column_score *sc;
int i, j, mrc_score = -1;
gint mrc = -1;
db_memsegment_header* dbh = dbmemsegh(db);
sc = (struct column_score *) malloc(argc * sizeof(struct column_score));
if(!sc) {
show_query_error(db, "Failed to allocate memory");
return -1;
}
/* Scan through the arguments and calculate accumulated score
* for each column. */
for(i=0; i<argc; i++) {
/* As a side effect, we're initializing the score array
* in the same loop */
sc[i].column = -1;
sc[i].score = 0;
sc[i].index_id = 0;
/* Locate the slot for the column */
for(j=0; j<argc; j++) {
if(sc[j].column == -1) {
sc[j].column = arglist[i].column;
break;
}
if(sc[j].column == arglist[i].column) break;
}
/* Apply our primitive scoring */
switch(arglist[i].cond) {
case WG_COND_EQUAL:
sc[j].score += TTREE_SCORE_EQUAL;
if(arglist[i].value == 0) /* NULL values get a small penalty */
sc[j].score += TTREE_SCORE_NULL;
break;
case WG_COND_LESSTHAN:
case WG_COND_GREATER:
case WG_COND_LTEQUAL:
case WG_COND_GTEQUAL:
/* these all qualify as a bound. So two bounds
* appearing in the argument list on the same column
* score higher than one bound. */
sc[j].score += TTREE_SCORE_BOUND;
break;
default:
/* Note that we consider WG_COND_NOT_EQUAL near useless */
break;
}
}
/* Now loop over the scores to find the best. */
for(i=0; i<argc; i++) {
if(sc[i].column == -1) break;
/* Find the index on the column. The score is modified by the
* estimated quality of the index (0 if no index found).
*/
if(sc[i].column <= MAX_INDEXED_FIELDNR) {
gint *ilist = &dbh->index_control_area_header.index_table[sc[i].column];
while(*ilist) {
gcell *ilistelem = (gcell *) offsettoptr(db, *ilist);
if(ilistelem->car) {
wg_index_header *hdr = \
(wg_index_header *) offsettoptr(db, ilistelem->car);
if(hdr->type == WG_INDEX_TYPE_TTREE) {
#ifdef USE_INDEX_TEMPLATE
/* If index templates are available, we can increase the
* score of the index if the template has any columns matching
* the query parameters. On the other hand, in case of a
* mismatch the index is unusable and has to be skipped.
* The indexes are sorted in the order of fixed columns in
* the template, so if there is a match, the search is
* complete (remaining index are likely to be worse)
*/
if(hdr->template_offset) {
wg_index_template *tmpl = \
(wg_index_template *) offsettoptr(db, hdr->template_offset);
void *matchrec = offsettoptr(db, tmpl->offset_matchrec);
gint reclen = wg_get_record_len(db, matchrec);
for(j=0; j<reclen; j++) {
gint enc = wg_get_field(db, matchrec, j);
if(wg_get_encoded_type(db, enc) != WG_VARTYPE) {
/* defined column in matchrec. The score is increased
* if arglist has a WG_COND_EQUAL column with the same
* value. In any other case the index is not usable.
*/
int match = 0, k;
for(k=0; k<argc; k++) {
if(arglist[k].column == j) {
if(arglist[k].cond == WG_COND_EQUAL &&\
WG_COMPARE(db, enc, arglist[k].value) == WG_EQUAL) {
match = 1;
}
else
goto nextindex;
}
}
if(match) {
sc[i].score += TTREE_SCORE_MASK;
if(!enc)
sc[i].score += TTREE_SCORE_NULL;
}
else
goto nextindex;
}
}
}
#endif
sc[i].index_id = ilistelem->car;
break;
}
}
#ifdef USE_INDEX_TEMPLATE
nextindex:
#endif
ilist = &ilistelem->cdr;
}
}
if(!sc[i].index_id)
sc[i].score = 0; /* no index, score reset */
if(sc[i].score > mrc_score) {
mrc_score = sc[i].score;
mrc = sc[i].column;
*index_id = sc[i].index_id;
}
}
/* TODO: does the best score have no index? In that case,
* try to locate an index that would restrict at least
* some columns.
*/
free(sc);
return mrc;
}
/** Check a record against list of conditions
* returns 1 if the record matches
* returns 0 if the record fails at least one condition
*/
static gint check_arglist(void *db, void *rec, wg_query_arg *arglist,
gint argc) {
int i, reclen;
reclen = wg_get_record_len(db, rec);
for(i=0; i<argc; i++) {
gint encoded;
if(arglist[i].column < reclen)
encoded = wg_get_field(db, rec, arglist[i].column);
else
return 0; /* XXX: should shorter records always fail?
* other possiblities here: compare to WG_ILLEGAL
* or WG_NULLTYPE. Current idea is based on SQL
* concept of comparisons to NULL always failing.
*/
switch(arglist[i].cond) {
case WG_COND_EQUAL:
if(WG_COMPARE(db, encoded, arglist[i].value) != WG_EQUAL)
return 0;
break;
case WG_COND_LESSTHAN:
if(WG_COMPARE(db, encoded, arglist[i].value) != WG_LESSTHAN)
return 0;
break;
case WG_COND_GREATER:
if(WG_COMPARE(db, encoded, arglist[i].value) != WG_GREATER)
return 0;
break;
case WG_COND_LTEQUAL:
if(WG_COMPARE(db, encoded, arglist[i].value) == WG_GREATER)
return 0;
break;
case WG_COND_GTEQUAL:
if(WG_COMPARE(db, encoded, arglist[i].value) == WG_LESSTHAN)
return 0;
break;
case WG_COND_NOT_EQUAL:
if(WG_COMPARE(db, encoded, arglist[i].value) == WG_EQUAL)
return 0;
break;
default:
break;
}
}
return 1;
}
/** Prepare query parameters
*
* - Validates matchrec and arglist
* - Converts external pointers to locally allocated data
* - Builds an unified argument list
*
* Returns 0 on success, non-0 on error.
*
* If the function was successful, *farglist will be set to point
* to a newly allocated unified argument list and *fargc will be set
* to indicate the size of *farglist.
*
* If there was an error, *farglist and *fargc may be in
* an undetermined state.
*/
static gint prepare_params(void *db, void *matchrec, gint reclen,
wg_query_arg *arglist, gint argc,
wg_query_arg **farglist, gint *fargc) {
int i;
if(matchrec) {
/* Get the correct length of matchrec data area and the pointer
* to the beginning of the data. If matchrec is a plain array in
* local memory (indicated by NON-zero reclen) we will skip this step.
*/
if(!reclen) {
reclen = wg_get_record_len(db, matchrec);
matchrec = wg_get_record_dataarray(db, matchrec);
}
#ifdef CHECK
if(!reclen) {
show_query_error(db, "Zero-length match record argument");
return -1;
}
#endif
}
#ifdef CHECK
if(arglist && !argc) {
show_query_error(db, "Zero-length argument list");
return -1;
}
if(!arglist && argc) {
show_query_error(db, "Invalid argument list (NULL)");
return -1;
}
#endif
/* Determine total number of query parameters (number of arguments
* in arglist and non-wildcard fields of matchrec).
*/
*fargc = argc;
if(matchrec) {
for(i=0; i<reclen; i++) {
if(wg_get_encoded_type(db, ((gint *) matchrec)[i]) != WG_VARTYPE)
(*fargc)++;
}
}
if(*fargc) {
wg_query_arg *tmp = NULL;
/* The simplest way to treat matchrec is to convert it to
* arglist. While doing this, we will create a local copy of the
* argument list, which has the side effect of allowing the caller
* to free the original arglist after wg_make_query() returns. The
* local copy will be attached to the query object and needs to
* survive beyond that.
*/
tmp = (wg_query_arg *) malloc(*fargc * sizeof(wg_query_arg));
if(!tmp) {
show_query_error(db, "Failed to allocate memory");
return -2;
}
/* Copy the arglist contents */
for(i=0; i<argc; i++) {
tmp[i].column = arglist[i].column;
tmp[i].cond = arglist[i].cond;
tmp[i].value = arglist[i].value;
}
/* Append the matchrec data */
if(matchrec) {
int j;
for(i=0, j=argc; i<reclen; i++) {
if(wg_get_encoded_type(db, ((gint *) matchrec)[i]) != WG_VARTYPE) {
tmp[j].column = i;
tmp[j].cond = WG_COND_EQUAL;
tmp[j++].value = ((gint *) matchrec)[i];
}
}
}
*farglist = tmp;
}
else {
*farglist = NULL;
}
return 0;
}
/*
* Locate the node offset and slot for start and end bound
* in a T-tree index.
*
* return -1 on error
* return 0 on success
*/
static gint find_ttree_bounds(void *db, gint index_id, gint col,
gint start_bound, gint end_bound, gint start_inclusive, gint end_inclusive,
gint *curr_offset, gint *curr_slot, gint *end_offset, gint *end_slot)
{
/* hold the offsets temporarily */
gint co = *curr_offset;
gint cs = *curr_slot;
gint eo = *end_offset;
gint es = *end_slot;
wg_index_header *hdr = (wg_index_header *) offsettoptr(db, index_id);
struct wg_tnode *node;
if(start_bound==WG_ILLEGAL) {
/* Find leftmost node in index */
#ifdef TTREE_CHAINED_NODES
co = TTREE_MIN_NODE(hdr);
#else
/* LUB node search function has the useful property
* of returning the leftmost node when called directly
* on index root node */
co = wg_ttree_find_lub_node(db, TTREE_ROOT_NODE(hdr));
#endif
cs = 0; /* leftmost slot */
} else {
gint boundtype;
if(start_inclusive) {
/* In case of inclusive range, we get the leftmost
* node for the given value and the first slot that
* is equal or greater than the given value.
*/
co = wg_search_ttree_leftmost(db,
TTREE_ROOT_NODE(hdr), start_bound, &boundtype, NULL);
if(boundtype == REALLY_BOUNDING_NODE) {
cs = wg_search_tnode_first(db, co, start_bound, col);
if(cs == -1) {
show_query_error(db, "Starting index node was bad");
return -1;
}
} else if(boundtype == DEAD_END_RIGHT_NOT_BOUNDING) {
/* No exact match, but the next node should be in
* range. */
node = (struct wg_tnode *) offsettoptr(db, co);
co = TNODE_SUCCESSOR(db, node);
cs = 0;
} else if(boundtype == DEAD_END_LEFT_NOT_BOUNDING) {
/* Simplest case, values that are in range start
* with this node. */
cs = 0;
}
} else {
/* For non-inclusive, we need the rightmost node and
* the last slot+1. The latter may overflow into next node.
*/
co = wg_search_ttree_rightmost(db,
TTREE_ROOT_NODE(hdr), start_bound, &boundtype, NULL);
if(boundtype == REALLY_BOUNDING_NODE) {
cs = wg_search_tnode_last(db, co, start_bound, col);
if(cs == -1) {
show_query_error(db, "Starting index node was bad");
return -1;
}
cs++;
node = (struct wg_tnode *) offsettoptr(db, co);
if(node->number_of_elements <= cs) {
/* Crossed node boundary */
co = TNODE_SUCCESSOR(db, node);
cs = 0;
}
} else if(boundtype == DEAD_END_RIGHT_NOT_BOUNDING) {
/* Since exact value was not found, this case is exactly
* the same as with the inclusive range. */
node = (struct wg_tnode *) offsettoptr(db, co);
co = TNODE_SUCCESSOR(db, node);
cs = 0;
} else if(boundtype == DEAD_END_LEFT_NOT_BOUNDING) {
/* No exact value in tree, same as inclusive range */
cs = 0;
}
}
}
/* Finding of the end of the range is more or less opposite
* of finding the beginning. */
if(end_bound==WG_ILLEGAL) {
/* Rightmost node in index */
#ifdef TTREE_CHAINED_NODES
eo = TTREE_MAX_NODE(hdr);
#else
/* GLB search on root node returns the rightmost node in tree */
eo = wg_ttree_find_glb_node(db, TTREE_ROOT_NODE(hdr));
#endif
if(eo) {
node = (struct wg_tnode *) offsettoptr(db, eo);
es = node->number_of_elements - 1; /* rightmost slot */
}
} else {
gint boundtype;
if(end_inclusive) {
/* Find the rightmost node with a given value and the
* righmost slot that is equal or smaller than that value
*/
eo = wg_search_ttree_rightmost(db,
TTREE_ROOT_NODE(hdr), end_bound, &boundtype, NULL);
if(boundtype == REALLY_BOUNDING_NODE) {
es = wg_search_tnode_last(db, eo, end_bound, col);
if(es == -1) {
show_query_error(db, "Ending index node was bad");
return -1;
}
} else if(boundtype == DEAD_END_RIGHT_NOT_BOUNDING) {
/* Last node containing values in range. */
node = (struct wg_tnode *) offsettoptr(db, eo);
es = node->number_of_elements - 1;
} else if(boundtype == DEAD_END_LEFT_NOT_BOUNDING) {
/* Previous node should be in range. */
node = (struct wg_tnode *) offsettoptr(db, eo);
eo = TNODE_PREDECESSOR(db, node);
if(eo) {
node = (struct wg_tnode *) offsettoptr(db, eo);
es = node->number_of_elements - 1; /* rightmost */
}
}
} else {
/* For non-inclusive, we need the leftmost node and
* the first slot-1.
*/
eo = wg_search_ttree_leftmost(db,
TTREE_ROOT_NODE(hdr), end_bound, &boundtype, NULL);
if(boundtype == REALLY_BOUNDING_NODE) {
es = wg_search_tnode_first(db, eo,
end_bound, col);
if(es == -1) {
show_query_error(db, "Ending index node was bad");
return -1;
}
es--;
if(es < 0) {
/* Crossed node boundary */
node = (struct wg_tnode *) offsettoptr(db, eo);
eo = TNODE_PREDECESSOR(db, node);
if(eo) {
node = (struct wg_tnode *) offsettoptr(db, eo);
es = node->number_of_elements - 1;
}
}
} else if(boundtype == DEAD_END_RIGHT_NOT_BOUNDING) {
/* No exact value in tree, same as inclusive range */
node = (struct wg_tnode *) offsettoptr(db, eo);
es = node->number_of_elements - 1;
} else if(boundtype == DEAD_END_LEFT_NOT_BOUNDING) {
/* No exact value in tree, same as inclusive range */
node = (struct wg_tnode *) offsettoptr(db, eo);
eo = TNODE_PREDECESSOR(db, node);
if(eo) {
node = (struct wg_tnode *) offsettoptr(db, eo);
es = node->number_of_elements - 1; /* rightmost slot */
}
}
}
}
/* Now detect the cases where the above bound search
* has produced a result with an empty range.
*/
if(co) {
/* Value could be bounded inside a node, but actually
* not present. Note that we require the end_slot to be
* >= curr_slot, this implies that query->direction == 1.
*/
if(eo == co && es < cs) {
co = 0; /* query will return no rows */
eo = 0;
} else if(!eo) {
/* If one offset is 0 the other should be forced to 0, so that
* if we want to switch direction we won't run into any surprises.
*/
co = 0;
} else {
/* Another case we have to watch out for is when we have a
* range that fits in the space between two nodes. In that case
* the end offset will end up directly left of the start offset.
*/
node = (struct wg_tnode *) offsettoptr(db, co);
if(eo == TNODE_PREDECESSOR(db, node)) {
co = 0; /* no rows */
eo = 0;
}
}
} else {
eo = 0; /* again, if one offset is 0,
* the other should be, too */
}
*curr_offset = co;
*curr_slot = cs;
*end_offset = eo;
*end_slot = es;
return 0;
}
/** Create a query object.
*
* matchrec - array of encoded integers. Can be a pointer to a database record
* or a user-allocated array. If reclen is 0, it is treated as a native
* database record. If reclen is non-zero, reclen number of gint-sized
* words is read, starting from the pointer.
*
* Fields of type WG_VARTYPE in matchrec are treated as wildcards. Other
* types, including NULL, are used as "equals" conditions.
*
* arglist - array of wg_query_arg objects. The size is must be given
* by argc.
*
* flags - type of query requested and other parameters
*
* rowlimit - maximum number of rows fetched. Only has an effect if
* QUERY_FLAGS_PREFETCH is set.
*
* returns NULL if constructing the query fails. Otherwise returns a pointer
* to a wg_query object.
*/
static wg_query *internal_build_query(void *db, void *matchrec, gint reclen,
wg_query_arg *arglist, gint argc, gint flags, wg_uint rowlimit) {
wg_query *query;
wg_query_arg *full_arglist;
gint fargc = 0;
gint col, index_id = -1;
int i;
#ifdef CHECK
if (!dbcheck(db)) {
/* XXX: currently show_query_error would work too */
#ifdef WG_NO_ERRPRINT
#else
fprintf(stderr, "Invalid database pointer in wg_make_query.\n");
#endif
return NULL;
}
#endif
/* Check and prepare the parameters. If there was an error,
* prepare_params() does it's own cleanup so we can (and should)
* return immediately.
*/
if(prepare_params(db, matchrec, reclen, arglist, argc,
&full_arglist, &fargc)) {
return NULL;
}
query = (wg_query *) malloc(sizeof(wg_query));
if(!query) {
show_query_error(db, "Failed to allocate memory");
if(full_arglist) free(full_arglist);
return NULL;
}
if(fargc) {
/* Find the best (hopefully) index to base the query on.
* Then initialise the query object to the first row in the
* query result set.
* XXX: only considering T-tree indexes now. */
col = most_restricting_column(db, full_arglist, fargc, &index_id);
}
else {
/* Create a "full scan" query with no arguments. */
index_id = -1;
full_arglist = NULL; /* redundant/paranoia */
}
if(index_id > 0) {
int start_inclusive = 0, end_inclusive = 0;
gint start_bound = WG_ILLEGAL; /* encoded values */
gint end_bound = WG_ILLEGAL;
query->qtype = WG_QTYPE_TTREE;
query->column = col;
query->curr_offset = 0;
query->curr_slot = -1;
query->end_offset = 0;
query->end_slot = -1;
query->direction = 1;
/* Determine the bounds for the given column/index.
*
* Examples of using rightmost and leftmost bounds in T-tree queries:
* val = 5 ==>
* find leftmost (A) and rightmost (B) nodes that contain value 5.
* Follow nodes sequentially from A until B is reached.
* val > 1 & val < 7 ==>
* find rightmost node with value 1 (A). Find leftmost node with
* value 7 (B). Find the rightmost value in A that still equals 1.
* The value immediately to the right is the beginning of the result
* set and the value immediately to the left of the first occurrence
* of 7 in B is the end of the result set.
* val > 1 & val <= 7 ==>
* A is the same as above. Find rightmost node with value 7 (B). The
* beginning of the result set is the same as above, the end is the
* last slot in B with value 7.
* val <= 1 ==>
* find rightmost node with value 1. Find the last (rightmost) slot
* containing 1. The result set begins with that value, scan left
* until the end of chain is reached.
*/
for(i=0; i<fargc; i++) {
if(full_arglist[i].column != col) continue;
switch(full_arglist[i].cond) {
case WG_COND_EQUAL:
/* Set bounds as if we had val >= 1 & val <= 1 */
if(start_bound==WG_ILLEGAL ||\
WG_COMPARE(db, start_bound, full_arglist[i].value)==WG_LESSTHAN) {
start_bound = full_arglist[i].value;
start_inclusive = 1;
}
if(end_bound==WG_ILLEGAL ||\
WG_COMPARE(db, end_bound, full_arglist[i].value)==WG_GREATER) {
end_bound = full_arglist[i].value;
end_inclusive = 1;
}
break;
case WG_COND_LESSTHAN:
/* No earlier right bound or new end bound is a smaller
* value (reducing the result set). The result set is also
* possibly reduced if the value is equal, because this
* condition is non-inclusive. */
if(end_bound==WG_ILLEGAL ||\
WG_COMPARE(db, end_bound, full_arglist[i].value)!=WG_LESSTHAN) {
end_bound = full_arglist[i].value;
end_inclusive = 0;
}
break;
case WG_COND_GREATER:
/* No earlier left bound or new left bound is >= of old value */
if(start_bound==WG_ILLEGAL ||\
WG_COMPARE(db, start_bound, full_arglist[i].value)!=WG_GREATER) {
start_bound = full_arglist[i].value;
start_inclusive = 0;
}
break;
case WG_COND_LTEQUAL:
/* Similar to "less than", but inclusive */
if(end_bound==WG_ILLEGAL ||\
WG_COMPARE(db, end_bound, full_arglist[i].value)==WG_GREATER) {
end_bound = full_arglist[i].value;
end_inclusive = 1;
}
break;
case WG_COND_GTEQUAL:
/* Similar to "greater", but inclusive */
if(start_bound==WG_ILLEGAL ||\
WG_COMPARE(db, start_bound, full_arglist[i].value)==WG_LESSTHAN) {
start_bound = full_arglist[i].value;
start_inclusive = 1;
}
break;
case WG_COND_NOT_EQUAL:
/* Force use of full argument list to check each row in the result
* set since we have a condition we cannot satisfy using
* a continuous range of T-tree values alone
*/
query->column = -1;
break;
default:
show_query_error(db, "Invalid condition (ignoring)");
break;
}
}
/* Simple sanity check. Is start_bound greater than end_bound? */
if(start_bound!=WG_ILLEGAL && end_bound!=WG_ILLEGAL &&\
WG_COMPARE(db, start_bound, end_bound) == WG_GREATER) {
/* return empty query */
query->argc = 0;
query->arglist = NULL;
free(full_arglist);
return query;
}
/* Now find the bounding nodes for the query */
if(find_ttree_bounds(db, index_id, col,
start_bound, end_bound, start_inclusive, end_inclusive,
&query->curr_offset, &query->curr_slot, &query->end_offset,
&query->end_slot)) {
free(query);
free(full_arglist);
return NULL;
}
/* XXX: here we can reverse the direction and switch the start and
* end nodes/slots, if "descending" sort order is needed.
*/
} else {
/* Nothing better than full scan available */
void *rec;
query->qtype = WG_QTYPE_SCAN;
query->column = -1; /* no special column, entire argument list
* should be checked for each row */
rec = wg_get_first_record(db);
if(rec)
query->curr_record = ptrtooffset(db, rec);
else
query->curr_record = 0;
}
/* Now attach the argument list to the query. If the query is based
* on a column index, we will create a slimmer copy that does not contain
* the conditions already satisfied by the index bounds.
*/
if(query->column == -1) {
query->arglist = full_arglist;
query->argc = fargc;
}
else {
int cnt = 0;
for(i=0; i<fargc; i++) {
if(full_arglist[i].column != query->column)
cnt++;
}
/* The argument list is reduced, but still contains columns */
if(cnt) {
int j;
query->arglist = (wg_query_arg *) malloc(cnt * sizeof(wg_query_arg));
if(!query->arglist) {
show_query_error(db, "Failed to allocate memory");
free(query);
free(full_arglist);
return NULL;
}
for(i=0, j=0; i<fargc; i++) {
if(full_arglist[i].column != query->column) {
query->arglist[j].column = full_arglist[i].column;
query->arglist[j].cond = full_arglist[i].cond;
query->arglist[j++].value = full_arglist[i].value;
}
}
} else
query->arglist = NULL;
query->argc = cnt;
free(full_arglist); /* Now we have a reduced argument list, free
* the original one */
}
/* Now handle any post-processing required.
*/
if(flags & QUERY_FLAGS_PREFETCH) {
query_result_page **prevnext;
query_result_page *currpage;
void *rec;
query->curr_page = NULL; /* initialize as empty */
query->curr_pidx = 0;
query->res_count = 0;
/* XXX: could move this inside the loop (speeds up empty
* query, slows down other queries) */
query->mpool = wg_create_mpool(db, sizeof(query_result_page));
if(!query->mpool) {
show_query_error(db, "Failed to allocate result memory pool");
wg_free_query(db, query);
return NULL;
}
i = QUERY_RESULTSET_PAGESIZE;
prevnext = (query_result_page **) &(query->curr_page);
while((rec = wg_fetch(db, query))) {
if(i >= QUERY_RESULTSET_PAGESIZE) {
currpage = (query_result_page *) \
wg_alloc_mpool(db, query->mpool, sizeof(query_result_page));
if(!currpage) {
show_query_error(db, "Failed to allocate a resultset row");
wg_free_query(db, query);
return NULL;
}
memset(currpage->rows, 0, sizeof(gint) * QUERY_RESULTSET_PAGESIZE);
*prevnext = currpage;
prevnext = &(currpage->next);
currpage->next = NULL;
i = 0;
}
currpage->rows[i++] = ptrtooffset(db, rec);
query->res_count++;
if(rowlimit && query->res_count >= rowlimit)
break;
}
/* Finally, convert the query type. */
query->qtype = WG_QTYPE_PREFETCH;
}
return query;
}
/** Create a query object and pre-fetch all data rows.
*
* Allocates enough space to hold all row offsets, fetches them and stores
* them in an array. Isolation is not guaranteed in any way, shape or form,
* but can be implemented on top by the user.
*
* returns NULL if constructing the query fails. Otherwise returns a pointer
* to a wg_query object.
*/
wg_query *wg_make_query(void *db, void *matchrec, gint reclen,
wg_query_arg *arglist, gint argc) {
return internal_build_query(db,
matchrec, reclen, arglist, argc, QUERY_FLAGS_PREFETCH, 0);
}
/** Create a query object and pre-fetch rowlimit number of rows.
*
* returns NULL if constructing the query fails. Otherwise returns a pointer
* to a wg_query object.
*/
wg_query *wg_make_query_rc(void *db, void *matchrec, gint reclen,
wg_query_arg *arglist, gint argc, wg_uint rowlimit) {
return internal_build_query(db,
matchrec, reclen, arglist, argc, QUERY_FLAGS_PREFETCH, rowlimit);
}
/** Return next record from the query object
* returns NULL if no more records
*/
void *wg_fetch(void *db, wg_query *query) {
void *rec;
#ifdef CHECK
if (!dbcheck(db)) {
/* XXX: currently show_query_error would work too */
#ifdef WG_NO_ERRPRINT
#else
fprintf(stderr, "Invalid database pointer in wg_fetch.\n");
#endif
return NULL;
}
if(!query) {
show_query_error(db, "Invalid query object");
return NULL;
}
#endif
if(query->qtype == WG_QTYPE_SCAN) {
for(;;) {
void *next;
if(!query->curr_record) {
/* Query exhausted */
return NULL;
}