/
analyze.c
1776 lines (1703 loc) · 54.9 KB
/
analyze.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
/*
* Copyright 2010-2017, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* This file contains code associated with the ANALYZE command.
*
* The ANALYZE command gather statistics about the content of tables
* and indices. These statistics are made available to the query planner
* to help it make better decisions about how to perform queries.
*
* The following system tables are or have been supported:
*
* CREATE TABLE _sql_stat1(tbl, idx, stat);
* CREATE TABLE _sql_stat4(tbl, idx, nEq, nLt, nDLt, sample);
*
* For most applications, _sql_stat1 provides all the statistics required
* for the query planner to make good choices.
*
* Format of _sql_stat1:
*
* There is normally one row per index, with the index identified by the
* name in the idx column. The tbl column is the name of the table to
* which the index belongs. In each such row, the stat column will be
* a string consisting of a list of integers. The first integer in this
* list is the number of rows in the index. (This is the same as the
* number of rows in the table.) The second integer is the
* average number of rows in the index that have the same value in
* the first column of the index. The third integer is the average
* number of rows in the index that have the same value for the first two
* columns. The N-th integer (for N>1) is the average number of rows in
* the index which have the same value for the first N-1 columns. For
* a K-column index, there will be K+1 integers in the stat column. If
* the index is unique, then the last integer will be 1.
*
* The list of integers in the stat column can optionally be followed
* by the keyword "unordered". The "unordered" keyword, if it is present,
* must be separated from the last integer by a single space. If the
* "unordered" keyword is present, then the query planner assumes that
* the index is unordered and will not use the index for a range query.
*
* If the _sql_stat1.idx column is NULL, then the _sql_stat1.stat
* column contains a single integer which is the (estimated) number of
* rows in the table identified by _sql_stat1.tbl.
*
* Format for _sql_stat4:
*
* The _sql_stat4 table contains histogram data
* to aid the query planner in choosing good indices based on the values
* that indexed columns are compared against in the WHERE clauses of
* queries.
*
* The _sql_stat4 table contains multiple entries for each index.
* The idx column names the index and the tbl column is the table of the
* index. If the idx and tbl columns are the same, then the sample is
* of the INTEGER PRIMARY KEY. The sample column is a blob which is the
* binary encoding of a key from the index. The nEq column is a
* list of integers. The first integer is the approximate number
* of entries in the index whose left-most column exactly matches
* the left-most column of the sample. The second integer in nEq
* is the approximate number of entries in the index where the
* first two columns match the first two columns of the sample.
* And so forth. nLt is another list of integers that show the approximate
* number of entries that are strictly less than the sample. The first
* integer in nLt contains the number of entries in the index where the
* left-most column is less than the left-most column of the sample.
* The K-th integer in the nLt entry is the number of index entries
* where the first K columns are less than the first K columns of the
* sample. The nDLt column is like nLt except that it contains the
* number of distinct entries in the index that are less than the
* sample.
*
* There can be an arbitrary number of _sql_stat4 entries per index.
* The ANALYZE command will typically generate _sql_stat4 tables
* that contain between 10 and 40 samples which are distributed across
* the key space, though not uniformly, and which include samples with
* large nEq values.
*
*/
#include "box/box.h"
#include "box/index.h"
#include "box/key_def.h"
#include "box/schema.h"
#include "third_party/qsort_arg.h"
#include "sqlInt.h"
#include "tarantoolInt.h"
#include "vdbeInt.h"
/**
* This routine generates code that opens the sql_stat1/4 tables.
* If the sql_statN tables do not previously exist, they are
* created.
*
* @param parse Parsing context.
* @param table_name Delete records of this table if specified.
*/
static void
vdbe_emit_stat_space_open(struct Parse *parse, const char *table_name)
{
const char *stat_names[] = {"_sql_stat1", "_sql_stat4"};
struct Vdbe *v = sqlGetVdbe(parse);
assert(v != NULL);
assert(sqlVdbeDb(v) == parse->db);
for (uint i = 0; i < lengthof(stat_names); ++i) {
const char *space_name = stat_names[i];
if (table_name != NULL) {
vdbe_emit_stat_space_clear(parse, space_name, NULL,
table_name);
} else {
struct space *stat_space = space_by_name(stat_names[i]);
assert(stat_space != NULL);
sqlVdbeAddOp1(v, OP_Clear, stat_space->def->id);
}
}
}
/*
* Recommended number of samples for _sql_stat4
*/
#ifndef SQL_STAT4_SAMPLES
#define SQL_STAT4_SAMPLES 24
#endif
/*
* Three SQL functions - stat_init(), stat_push(), and stat_get() -
* share an instance of the following structure to hold their state
* information.
*/
typedef struct Stat4Accum Stat4Accum;
typedef struct Stat4Sample Stat4Sample;
struct Stat4Sample {
tRowcnt *anEq; /* _sql_stat4.nEq */
tRowcnt *anDLt; /* _sql_stat4.nDLt */
tRowcnt *anLt; /* _sql_stat4.nLt */
u8 *aKey; /* Table key */
u32 nKey; /* Sizeof aKey[] */
u8 isPSample; /* True if a periodic sample */
int iCol; /* If !isPSample, the reason for inclusion */
u32 iHash; /* Tiebreaker hash */
};
struct Stat4Accum {
tRowcnt nRow; /* Number of rows in the entire table */
tRowcnt nPSample; /* How often to do a periodic sample */
int nCol; /* Number of columns in index + pk */
int nKeyCol; /* Number of index columns w/o the pk */
int mxSample; /* Maximum number of samples to accumulate */
Stat4Sample current; /* Current row as a Stat4Sample */
u32 iPrn; /* Pseudo-random number used for sampling */
Stat4Sample *aBest; /* Array of nCol best samples */
int iMin; /* Index in a[] of entry with minimum score */
int nSample; /* Current number of samples */
int iGet; /* Index of current sample accessed by stat_get() */
Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
sql *db; /* Database connection, for malloc() */
};
/* Reclaim memory used by a Stat4Sample
*/
static void
sampleClear(sql * db, Stat4Sample * p)
{
assert(db != 0);
if (p->nKey) {
sqlDbFree(db, p->aKey);
p->nKey = 0;
}
}
/* Initialize the BLOB value of a sample key.
*/
static void
sampleSetKey(sql * db, Stat4Sample * p, int n, const u8 * pData)
{
assert(db != 0);
if (p->nKey)
sqlDbFree(db, p->aKey);
p->aKey = sqlDbMallocRawNN(db, n);
if (p->aKey) {
p->nKey = n;
memcpy(p->aKey, pData, n);
} else {
p->nKey = 0;
}
}
/*
* Copy the contents of object (*pFrom) into (*pTo).
*/
static void
sampleCopy(Stat4Accum * p, Stat4Sample * pTo, Stat4Sample * pFrom)
{
pTo->isPSample = pFrom->isPSample;
pTo->iCol = pFrom->iCol;
pTo->iHash = pFrom->iHash;
memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt) * (p->nCol+1));
memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt) * (p->nCol+1));
memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt) * (p->nCol+1));
sampleSetKey(p->db, pTo, pFrom->nKey, pFrom->aKey);
}
/*
* Reclaim all memory of a Stat4Accum structure.
*/
static void
stat4Destructor(void *pOld)
{
Stat4Accum *p = (Stat4Accum *) pOld;
int i;
for (i = 0; i < p->nCol; i++)
sampleClear(p->db, p->aBest + i);
for (i = 0; i < p->mxSample; i++)
sampleClear(p->db, p->a + i);
sampleClear(p->db, &p->current);
sqlDbFree(p->db, p);
}
/*
* Implementation of the stat_init(N,K,C) SQL function. The three parameters
* are:
* N: The number of columns in the index including the pk (note 1)
* K: The number of columns in the index excluding the pk.
* C: The number of rows in the index (note 2)
*
* Note 1: In the special case of the covering index, N is the number of
* PRIMARY KEY columns, not the total number of columns in the table.
*
* Note 2: C is only used for STAT4.
*
* N=K+P where P is the number of columns in the
* PRIMARY KEY of the table. The covering index as N==K as a special case.
*
* This routine allocates the Stat4Accum object in heap memory. The return
* value is a pointer to the Stat4Accum object. The datatype of the
* return value is BLOB, but it is really just a pointer to the Stat4Accum
* object.
*/
static void
statInit(sql_context * context, int argc, sql_value ** argv)
{
Stat4Accum *p;
int nCol; /* Number of columns in index being sampled */
int nKeyCol; /* Number of key columns */
int nColUp; /* nCol rounded up for alignment */
int n; /* Bytes of space to allocate */
sql *db; /* Database connection */
int mxSample = SQL_STAT4_SAMPLES;
/* Decode the three function arguments */
UNUSED_PARAMETER(argc);
nCol = sql_value_int(argv[0]);
assert(nCol > 0);
/* Tarantool: we use an additional artificial column for the reason
* that Tarantool's indexes don't contain PK columns after key columns.
* Hence, in order to correctly gather statistics when dealing with
* identical rows, we have to use this artificial column.
*/
nColUp = sizeof(tRowcnt) < 8 ? (nCol + 2) & ~1 : nCol + 1;
nKeyCol = sql_value_int(argv[1]);
assert(nKeyCol <= nCol);
assert(nKeyCol > 0);
/* Allocate the space required for the Stat4Accum object */
n = sizeof(*p)
+ sizeof(tRowcnt) * nColUp /* Stat4Accum.anEq */
+ sizeof(tRowcnt) * nColUp /* Stat4Accum.anDLt */
+ sizeof(tRowcnt) * nColUp /* Stat4Accum.anLt */
+ sizeof(Stat4Sample) * (nCol + 1 + mxSample) /* Stat4Accum.aBest[], a[] */
+ sizeof(tRowcnt) * 3 * nColUp * (nCol + 1 + mxSample);
db = sql_context_db_handle(context);
p = sqlDbMallocZero(db, n);
if (p == 0) {
context->is_aborted = true;
return;
}
p->db = db;
p->nRow = 0;
p->nCol = nCol;
p->nKeyCol = nKeyCol;
p->current.anDLt = (tRowcnt *) & p[1];
p->current.anEq = &p->current.anDLt[nColUp];
{
u8 *pSpace; /* Allocated space not yet assigned */
int i; /* Used to iterate through p->aSample[] */
p->iGet = -1;
p->mxSample = mxSample;
p->nPSample =
(tRowcnt) (sql_value_int64(argv[2]) /
(mxSample / 3 + 1) + 1);
p->current.anLt = &p->current.anEq[nColUp];
p->iPrn =
0x689e962d * (u32) nCol ^ 0xd0944565 *
(u32) sql_value_int(argv[2]);
/* Set up the Stat4Accum.a[] and aBest[] arrays */
p->a = (struct Stat4Sample *)&p->current.anLt[nColUp];
p->aBest = &p->a[mxSample];
pSpace = (u8 *) (&p->a[mxSample + nCol + 1]);
for (i = 0; i < (mxSample + nCol + 1); i++) {
p->a[i].anEq = (tRowcnt *) pSpace;
pSpace += (sizeof(tRowcnt) * nColUp);
p->a[i].anLt = (tRowcnt *) pSpace;
pSpace += (sizeof(tRowcnt) * nColUp);
p->a[i].anDLt = (tRowcnt *) pSpace;
pSpace += (sizeof(tRowcnt) * nColUp);
}
assert((pSpace - (u8 *) p) == n);
for (i = 0; i < nCol + 1; i++) {
p->aBest[i].iCol = i;
}
}
/* Return a pointer to the allocated object to the caller. Note that
* only the pointer (the 2nd parameter) matters. The size of the object
* (given by the 3rd parameter) is never used and can be any positive
* value.
*/
sql_result_blob(context, p, sizeof(*p), stat4Destructor);
}
static const FuncDef statInitFuncdef = {
3, /* nArg */
0, /* funcFlags */
0, /* pUserData */
0, /* pNext */
statInit, /* xSFunc */
0, /* xFinalize */
"stat_init", /* zName */
{0},
0, false
};
/*
* pNew and pOld are both candidate non-periodic samples selected for
* the same column (pNew->iCol==pOld->iCol). Ignoring this column and
* considering only any trailing columns and the sample hash value, this
* function returns true if sample pNew is to be preferred over pOld.
* In other words, if we assume that the cardinalities of the selected
* column for pNew and pOld are equal, is pNew to be preferred over pOld.
*
* This function assumes that for each argument sample, the contents of
* the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
*/
static int
sampleIsBetterPost(Stat4Accum * pAccum, Stat4Sample * pNew, Stat4Sample * pOld)
{
int nCol = pAccum->nCol;
int i;
assert(pNew->iCol == pOld->iCol);
for (i = pNew->iCol + 1; i < nCol + 1; i++) {
if (pNew->anEq[i] > pOld->anEq[i])
return 1;
if (pNew->anEq[i] < pOld->anEq[i])
return 0;
}
if (pNew->iHash > pOld->iHash)
return 1;
return 0;
}
/*
* Return true if pNew is to be preferred over pOld.
*
* This function assumes that for each argument sample, the contents of
* the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
*/
static int
sampleIsBetter(Stat4Accum * pAccum, Stat4Sample * pNew, Stat4Sample * pOld)
{
tRowcnt nEqNew = pNew->anEq[pNew->iCol];
tRowcnt nEqOld = pOld->anEq[pOld->iCol];
assert(pOld->isPSample == 0 && pNew->isPSample == 0);
if ((nEqNew > nEqOld))
return 1;
if (nEqNew == nEqOld) {
if (pNew->iCol < pOld->iCol)
return 1;
return (pNew->iCol == pOld->iCol
&& sampleIsBetterPost(pAccum, pNew, pOld));
}
return 0;
}
/*
* Copy the contents of sample *pNew into the p->a[] array. If necessary,
* remove the least desirable sample from p->a[] to make room.
*/
static void
sampleInsert(Stat4Accum * p, Stat4Sample * pNew, int nEqZero)
{
Stat4Sample *pSample = 0;
int i;
if (pNew->isPSample == 0) {
Stat4Sample *pUpgrade = 0;
assert(pNew->anEq[pNew->iCol] > 0);
/* This sample is being added because the prefix that ends in column
* iCol occurs many times in the table. However, if we have already
* added a sample that shares this prefix, there is no need to add
* this one. Instead, upgrade the priority of the highest priority
* existing sample that shares this prefix.
*/
for (i = p->nSample - 1; i >= 0; i--) {
Stat4Sample *pOld = &p->a[i];
if (pOld->anEq[pNew->iCol] == 0) {
if (pOld->isPSample)
return;
assert(pOld->iCol > pNew->iCol);
assert(sampleIsBetter(p, pNew, pOld));
if (pUpgrade == 0
|| sampleIsBetter(p, pOld, pUpgrade)) {
pUpgrade = pOld;
}
}
}
if (pUpgrade) {
pUpgrade->iCol = pNew->iCol;
pUpgrade->anEq[pUpgrade->iCol] =
pNew->anEq[pUpgrade->iCol];
goto find_new_min;
}
}
/* If necessary, remove sample iMin to make room for the new sample. */
if (p->nSample >= p->mxSample) {
Stat4Sample *pMin = &p->a[p->iMin];
tRowcnt *anEq = pMin->anEq;
tRowcnt *anLt = pMin->anLt;
tRowcnt *anDLt = pMin->anDLt;
sampleClear(p->db, pMin);
memmove(pMin, &pMin[1],
sizeof(p->a[0]) * (p->nSample - p->iMin - 1));
pSample = &p->a[p->nSample - 1];
pSample->nKey = 0;
pSample->anEq = anEq;
pSample->anDLt = anDLt;
pSample->anLt = anLt;
p->nSample = p->mxSample - 1;
}
assert(p->nSample==0 || pNew->anLt[p->nCol] > p->a[p->nSample-1].anLt[p->nCol]);
/* Insert the new sample */
pSample = &p->a[p->nSample];
sampleCopy(p, pSample, pNew);
p->nSample++;
/* Zero the first nEqZero entries in the anEq[] array. */
memset(pSample->anEq, 0, sizeof(tRowcnt) * nEqZero);
find_new_min:
if (p->nSample >= p->mxSample) {
int iMin = -1;
for (i = 0; i < p->mxSample; i++) {
if (p->a[i].isPSample)
continue;
if (iMin < 0
|| sampleIsBetter(p, &p->a[iMin], &p->a[i])) {
iMin = i;
}
}
assert(iMin >= 0);
p->iMin = iMin;
}
}
/*
* Field iChng of the index being scanned has changed. So at this point
* p->current contains a sample that reflects the previous row of the
* index. The value of anEq[iChng] and subsequent anEq[] elements are
* correct at this point.
*/
static void
samplePushPrevious(Stat4Accum * p, int iChng)
{
int i;
/* Check if any samples from the aBest[] array should be pushed
* into samples array at this point.
*/
for (i = (p->nCol - 1); i >= iChng; i--) {
Stat4Sample *pBest = &p->aBest[i];
pBest->anEq[i] = p->current.anEq[i];
if (p->nSample < p->mxSample
|| sampleIsBetter(p, pBest, &p->a[p->iMin])) {
sampleInsert(p, pBest, i);
}
}
/* Update the anEq[] fields of any samples already collected. */
for (i = p->nSample - 1; i >= 0; i--) {
int j;
for (j = iChng; j < p->nCol + 1; j++) {
if (p->a[i].anEq[j] == 0)
p->a[i].anEq[j] = p->current.anEq[j];
}
}
}
/*
* Implementation of the stat_push SQL function: stat_push(P,C,R)
* Arguments:
*
* P Pointer to the Stat4Accum object created by stat_init()
* C Index of left-most column to differ from previous row
* R Key record for the current row
*
* This SQL function always returns NULL. It's purpose it to accumulate
* statistical data and/or samples in the Stat4Accum object about the
* index being analyzed. The stat_get() SQL function will later be used to
* extract relevant information for constructing the sql_statN tables.
*
* The R parameter is only used for STAT4
*/
static void
statPush(sql_context * context, int argc, sql_value ** argv)
{
int i;
/* The three function arguments */
Stat4Accum *p = (Stat4Accum *) sql_value_blob(argv[0]);
int iChng = sql_value_int(argv[1]);
UNUSED_PARAMETER(argc);
UNUSED_PARAMETER(context);
assert(p->nCol > 0);
/* iChng == p->nCol means that the current and previous rows are identical */
assert(iChng <= p->nCol);
if (p->nRow == 0) {
/* This is the first call to this function. Do initialization. */
for (i = 0; i < p->nCol + 1; i++)
p->current.anEq[i] = 1;
} else {
/* Second and subsequent calls get processed here */
samplePushPrevious(p, iChng);
/* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
* to the current row of the index.
*/
for (i = 0; i < iChng; i++) {
p->current.anEq[i]++;
}
for (i = iChng; i < p->nCol + 1; i++) {
p->current.anDLt[i]++;
p->current.anLt[i] += p->current.anEq[i];
p->current.anEq[i] = 1;
}
}
p->nRow++;
sampleSetKey(p->db, &p->current, sql_value_bytes(argv[2]),
sql_value_blob(argv[2]));
p->current.iHash = p->iPrn = p->iPrn * 1103515245 + 12345;
{
tRowcnt nLt = p->current.anLt[p->nCol];
/* Check if this is to be a periodic sample. If so, add it. */
if ((nLt / p->nPSample) != (nLt + 1) / p->nPSample) {
p->current.isPSample = 1;
p->current.iCol = 0;
sampleInsert(p, &p->current, p->nCol);
p->current.isPSample = 0;
}
/* Update the aBest[] array. */
for (i = 0; i < p->nCol; i++) {
p->current.iCol = i;
if (i >= iChng
|| sampleIsBetterPost(p, &p->current,
&p->aBest[i])) {
sampleCopy(p, &p->aBest[i], &p->current);
}
}
}
}
static const FuncDef statPushFuncdef = {
3, /* nArg */
0, /* funcFlags */
0, /* pUserData */
0, /* pNext */
statPush, /* xSFunc */
0, /* xFinalize */
"stat_push", /* zName */
{0},
0, false
};
#define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
#define STAT_GET_KEY 1 /* "key" column of stat4 entry */
#define STAT_GET_NEQ 2 /* "neq" column of stat4 entry */
#define STAT_GET_NLT 3 /* "nlt" column of stat4 entry */
#define STAT_GET_NDLT 4 /* "ndlt" column of stat4 entry */
/*
* Implementation of the stat_get(P,J) SQL function. This routine is
* used to query statistical information that has been gathered into
* the Stat4Accum object by prior calls to stat_push(). The P parameter
* has type BLOB but it is really just a pointer to the Stat4Accum object.
* The content to returned is determined by the parameter J
* which is one of the STAT_GET_xxxx values defined above.
*/
static void
statGet(sql_context * context, int argc, sql_value ** argv)
{
Stat4Accum *p = (Stat4Accum *) sql_value_blob(argv[0]);
/* STAT4 have a parameter on this routine. */
int eCall = sql_value_int(argv[1]);
assert(argc == 2);
assert(eCall == STAT_GET_STAT1 || eCall == STAT_GET_NEQ
|| eCall == STAT_GET_KEY || eCall == STAT_GET_NLT
|| eCall == STAT_GET_NDLT);
if (eCall == STAT_GET_STAT1) {
/* Return the value to store in the "stat" column of the _sql_stat1
* table for this index.
*
* The value is a string composed of a list of integers describing
* the index. The first integer in the list is the total number of
* entries in the index. There is one additional integer in the list
* for each indexed column. This additional integer is an estimate of
* the number of rows matched by a stabbing query on the index using
* a key with the corresponding number of fields. In other words,
* if the index is on columns (a,b) and the _sql_stat1 value is
* "100 10 2", then sql estimates that:
*
* * the index contains 100 rows,
* * "WHERE a=?" matches 10 rows, and
* * "WHERE a=? AND b=?" matches 2 rows.
*
* If D is the count of distinct values and K is the total number of
* rows, then each estimate is computed as:
*
* I = (K+D-1)/D
*/
char *z;
int i;
char *zRet = sqlMallocZero((p->nKeyCol + 1) * 25);
if (zRet == 0) {
context->is_aborted = true;
return;
}
sql_snprintf(24, zRet, "%llu", (u64) p->nRow);
z = zRet + sqlStrlen30(zRet);
for (i = 0; i < p->nKeyCol; i++) {
u64 nDistinct = p->current.anDLt[i] + 1;
u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
sql_snprintf(24, z, " %llu", iVal);
z += sqlStrlen30(z);
assert(p->current.anEq[i]);
}
assert(z[0] == '\0' && z > zRet);
sql_result_text(context, zRet, -1, sql_free);
} else if (eCall == STAT_GET_KEY) {
if (p->iGet < 0) {
samplePushPrevious(p, 0);
p->iGet = 0;
}
if (p->iGet < p->nSample) {
Stat4Sample *pS = p->a + p->iGet;
sql_result_blob(context, pS->aKey, pS->nKey,
SQL_TRANSIENT);
}
} else {
tRowcnt *aCnt = 0;
assert(p->iGet < p->nSample);
switch (eCall) {
case STAT_GET_NEQ:
aCnt = p->a[p->iGet].anEq;
break;
case STAT_GET_NLT:
aCnt = p->a[p->iGet].anLt;
break;
default:{
aCnt = p->a[p->iGet].anDLt;
p->iGet++;
break;
}
}
char *zRet = sqlMallocZero(p->nCol * 25);
if (zRet == 0) {
context->is_aborted = true;
} else {
int i;
char *z = zRet;
for (i = 0; i < p->nCol; i++) {
sql_snprintf(24, z, "%llu ", (u64) aCnt[i]);
z += sqlStrlen30(z);
}
assert(z[0] == '\0' && z > zRet);
z[-1] = '\0';
sql_result_text(context, zRet, -1, sql_free);
}
}
#ifndef SQL_DEBUG
UNUSED_PARAMETER(argc);
#endif
}
static const FuncDef statGetFuncdef = {
2, /* nArg */
0, /* funcFlags */
0, /* pUserData */
0, /* pNext */
statGet, /* xSFunc */
0, /* xFinalize */
"stat_get", /* zName */
{0},
0, false
};
static void
callStatGet(Vdbe * v, int regStat4, int iParam, int regOut)
{
assert(regOut != regStat4 && regOut != regStat4 + 1);
sqlVdbeAddOp2(v, OP_Integer, iParam, regStat4 + 1);
sqlVdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
(char *)&statGetFuncdef, P4_FUNCDEF);
sqlVdbeChangeP5(v, 2);
}
/**
* Generate code to do an analysis of all indices associated with
* a single table.
*
* @param parse Current parsing context.
* @param space Space to be analyzed.
*/
static void
vdbe_emit_analyze_space(struct Parse *parse, struct space *space)
{
assert(space != NULL);
struct space *stat1 = space_by_name("_sql_stat1");
assert(stat1 != NULL);
struct space *stat4 = space_by_name("_sql_stat4");
assert(stat4 != NULL);
/* Register to hold Stat4Accum object. */
int stat4_reg = ++parse->nMem;
/* Index of changed index field. */
int chng_reg = ++parse->nMem;
/* Key argument passed to stat_push(). */
int key_reg = ++parse->nMem;
/* Temporary use register. */
int tmp_reg = ++parse->nMem;
/* Register containing table name. */
int tab_name_reg = ++parse->nMem;
/* Register containing index name. */
int idx_name_reg = ++parse->nMem;
/* Value for the stat column of _sql_stat1. */
int stat1_reg = ++parse->nMem;
/* MUST BE LAST (see below). */
int prev_reg = ++parse->nMem;
/* Do not gather statistics on system tables. */
if (space_is_system(space))
return;
/*
* Open a read-only cursor on the table. Also allocate
* a cursor number to use for scanning indexes.
*/
int tab_cursor = parse->nTab;
parse->nTab += 2;
assert(space->index_count != 0);
struct Vdbe *v = sqlGetVdbe(parse);
assert(v != NULL);
const char *tab_name = space_name(space);
sqlVdbeAddOp4(v, OP_IteratorOpen, tab_cursor, 0, 0, (void *) space,
P4_SPACEPTR);
sqlVdbeLoadString(v, tab_name_reg, space->def->name);
for (uint32_t j = 0; j < space->index_count; ++j) {
struct index *idx = space->index[j];
const char *idx_name;
/*
* Primary indexes feature automatically generated
* names. Thus, for the sake of clarity, use
* instead more familiar table name.
*/
if (idx->def->iid == 0)
idx_name = tab_name;
else
idx_name = idx->def->name;
int part_count = idx->def->key_def->part_count;
/* Populate the register containing the index name. */
sqlVdbeLoadString(v, idx_name_reg, idx_name);
VdbeComment((v, "Analysis for %s.%s", tab_name, idx_name));
/*
* Pseudo-code for loop that calls stat_push():
*
* Rewind csr
* if eof(csr) goto end_of_scan;
* chng_reg = 0
* goto chng_addr_0;
*
* next_row:
* chng_reg = 0
* if( idx(0) != prev_reg(0) ) goto chng_addr_0
* chng_reg = 1
* if( idx(1) != prev_reg(1) ) goto chng_addr_1
* ...
* chng_reg = N
* goto chng_addr_N
*
* chng_addr_0:
* prev_reg(0) = idx(0)
* chng_addr_1:
* prev_reg(1) = idx(1)
* ...
*
* distinct_addr:
* key_reg = idx(key)
* stat_push(P, chng_reg, key_reg)
* Next csr
* if !eof(csr) goto next_row;
*
* end_of_scan:
*/
/*
* Make sure there are enough memory cells
* allocated to accommodate the prev_reg array
* and a trailing key (the key slot is required
* when building a record to insert into
* the sample column of the _sql_stat4 table).
*/
parse->nMem = MAX(parse->nMem, prev_reg + part_count);
/* Open a cursor on the index being analyzed. */
int idx_cursor;
if (j != 0) {
idx_cursor = parse->nTab - 1;
sqlVdbeAddOp4(v, OP_IteratorOpen, idx_cursor,
idx->def->iid, 0,
(void *) space, P4_SPACEPTR);
VdbeComment((v, "%s", idx->def->name));
} else {
/* We have already opened cursor on PK. */
idx_cursor = tab_cursor;
}
/*
* Invoke the stat_init() function.
* The arguments are:
* (1) The number of columns in the index
* (including the number of PK columns);
* (2) The number of columns in the key
* without the pk;
* (3) the number of rows in the index;
* FIXME: for Tarantool first and second args
* are the same.
*
* The third argument is only used for STAT4
*/
sqlVdbeAddOp2(v, OP_Count, idx_cursor, stat4_reg + 3);
sqlVdbeAddOp2(v, OP_Integer, part_count, stat4_reg + 1);
sqlVdbeAddOp2(v, OP_Integer, part_count, stat4_reg + 2);
sqlVdbeAddOp4(v, OP_Function0, 0, stat4_reg + 1, stat4_reg,
(char *)&statInitFuncdef, P4_FUNCDEF);
sqlVdbeChangeP5(v, 3);
/*
* Implementation of the following:
*
* Rewind csr
* if eof(csr) goto end_of_scan;
* chng_reg = 0
* goto next_push_0;
*/
int rewind_addr = sqlVdbeAddOp1(v, OP_Rewind, idx_cursor);
sqlVdbeAddOp2(v, OP_Integer, 0, chng_reg);
int distinct_addr = sqlVdbeMakeLabel(v);
/* Array of jump instruction addresses. */
int *jump_addrs = region_alloc(&parse->region,
sizeof(int) * part_count);
if (jump_addrs == NULL) {
diag_set(OutOfMemory, sizeof(int) * part_count,
"region", "jump_addrs");
parse->is_aborted = true;
return;
}
/*
* next_row:
* chng_reg = 0
* if( idx(0) != prev_reg(0) ) goto chng_addr_0
* chng_reg = 1
* if( idx(1) != prev_reg(1) ) goto chng_addr_1
* ...
* chng_reg = N
* goto distinct_addr
*/
sqlVdbeAddOp0(v, OP_Goto);
int next_row_addr = sqlVdbeCurrentAddr(v);
if (part_count == 1 && idx->def->opts.is_unique) {
/*
* For a single-column UNIQUE index, once
* we have found a non-NULL row, we know
* that all the rest will be distinct, so
* skip subsequent distinctness tests.
*/
sqlVdbeAddOp2(v, OP_NotNull, prev_reg,
distinct_addr);
}
struct key_part *part = idx->def->key_def->parts;
for (int i = 0; i < part_count; ++i, ++part) {
struct coll *coll = part->coll;
sqlVdbeAddOp2(v, OP_Integer, i, chng_reg);
sqlVdbeAddOp3(v, OP_Column, idx_cursor,
part->fieldno, tmp_reg);
jump_addrs[i] = sqlVdbeAddOp4(v, OP_Ne, tmp_reg, 0,
prev_reg + i,
(char *)coll,
P4_COLLSEQ);
sqlVdbeChangeP5(v, SQL_NULLEQ);
}
sqlVdbeAddOp2(v, OP_Integer, part_count, chng_reg);
sqlVdbeGoto(v, distinct_addr);
/*
* chng_addr_0:
* prev_reg(0) = idx(0)
* chng_addr_1:
* prev_reg(1) = idx(1)
* ...
*/
sqlVdbeJumpHere(v, next_row_addr - 1);
part = idx->def->key_def->parts;
for (int i = 0; i < part_count; ++i, ++part) {
sqlVdbeJumpHere(v, jump_addrs[i]);
sqlVdbeAddOp3(v, OP_Column, idx_cursor,
part->fieldno, prev_reg + i);
}
sqlVdbeResolveLabel(v, distinct_addr);
/*
* chng_addr_N:
* key_reg = idx(key)
* stat_push(P, chng_reg, key_reg)
* Next csr
* if !eof(csr) goto next_row;
*/
assert(key_reg == (stat4_reg + 2));
struct index *pk = space_index(space, 0);
int pk_part_count = pk->def->key_def->part_count;
/* Allocate memory for array. */
parse->nMem = MAX(parse->nMem,
prev_reg + part_count + pk_part_count);
int stat_key_reg = prev_reg + part_count;
for (int i = 0; i < pk_part_count; i++) {
uint32_t k = pk->def->key_def->parts[i].fieldno;
assert(k < space->def->field_count);
sqlVdbeAddOp3(v, OP_Column, idx_cursor, k,
stat_key_reg + i);
VdbeComment((v, "%s", space->def->fields[k].name));
}
sqlVdbeAddOp3(v, OP_MakeRecord, stat_key_reg,
pk_part_count, key_reg);
assert(chng_reg == (stat4_reg + 1));
sqlVdbeAddOp4(v, OP_Function0, 1, stat4_reg, tmp_reg,
(char *)&statPushFuncdef, P4_FUNCDEF);
sqlVdbeChangeP5(v, 3);
sqlVdbeAddOp2(v, OP_Next, idx_cursor, next_row_addr);
/* Add the entry to the stat1 table. */
callStatGet(v, stat4_reg, STAT_GET_STAT1, stat1_reg);
enum field_type types[4] = { FIELD_TYPE_STRING,
FIELD_TYPE_STRING,
FIELD_TYPE_STRING,
field_type_MAX };
sqlVdbeAddOp4(v, OP_MakeRecord, tab_name_reg, 4, tmp_reg,
(char *)types, sizeof(types));