/
dict0stats.cc
4724 lines (3907 loc) · 138 KB
/
dict0stats.cc
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 (c) 2009, 2019, Oracle and/or its affiliates. All Rights Reserved.
Copyright (c) 2015, 2023, MariaDB Corporation.
This program 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; version 2 of the License.
This program 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
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA
*****************************************************************************/
/**************************************************//**
@file dict/dict0stats.cc
Code used for calculating and manipulating table statistics.
Created Jan 06, 2010 Vasil Dimov
*******************************************************/
#include "dict0stats.h"
#include "dyn0buf.h"
#include "row0sel.h"
#include "trx0trx.h"
#include "lock0lock.h"
#include "pars0pars.h"
#include <mysql_com.h>
#include "log.h"
#include "btr0btr.h"
#include "que0que.h"
#include "scope.h"
#include "debug_sync.h"
#include <algorithm>
#include <map>
#include <vector>
#include <thread>
/* Sampling algorithm description @{
The algorithm is controlled by one number - N_SAMPLE_PAGES(index),
let it be A, which is the number of leaf pages to analyze for a given index
for each n-prefix (if the index is on 3 columns, then 3*A leaf pages will be
analyzed).
Let the total number of leaf pages in the table be T.
Level 0 - leaf pages, level H - root.
Definition: N-prefix-boring record is a record on a non-leaf page that equals
the next (to the right, cross page boundaries, skipping the supremum and
infimum) record on the same level when looking at the fist n-prefix columns.
The last (user) record on a level is not boring (it does not match the
non-existent user record to the right). We call the records boring because all
the records on the page below a boring record are equal to that boring record.
We avoid diving below boring records when searching for a leaf page to
estimate the number of distinct records because we know that such a leaf
page will have number of distinct records == 1.
For each n-prefix: start from the root level and full scan subsequent lower
levels until a level that contains at least A*10 distinct records is found.
Lets call this level LA.
As an optimization the search is canceled if it has reached level 1 (never
descend to the level 0 (leaf)) and also if the next level to be scanned
would contain more than A pages. The latter is because the user has asked
to analyze A leaf pages and it does not make sense to scan much more than
A non-leaf pages with the sole purpose of finding a good sample of A leaf
pages.
After finding the appropriate level LA with >A*10 distinct records (or less in
the exceptions described above), divide it into groups of equal records and
pick A such groups. Then pick the last record from each group. For example,
let the level be:
index: 0,1,2,3,4,5,6,7,8,9,10
record: 1,1,1,2,2,7,7,7,7,7,9
There are 4 groups of distinct records and if A=2 random ones are selected,
e.g. 1,1,1 and 7,7,7,7,7, then records with indexes 2 and 9 will be selected.
After selecting A records as described above, dive below them to find A leaf
pages and analyze them, finding the total number of distinct records. The
dive to the leaf level is performed by selecting a non-boring record from
each page and diving below it.
This way, a total of A leaf pages are analyzed for the given n-prefix.
Let the number of different key values found in each leaf page i be Pi (i=1..A).
Let N_DIFF_AVG_LEAF be (P1 + P2 + ... + PA) / A.
Let the number of different key values on level LA be N_DIFF_LA.
Let the total number of records on level LA be TOTAL_LA.
Let R be N_DIFF_LA / TOTAL_LA, we assume this ratio is the same on the
leaf level.
Let the number of leaf pages be N.
Then the total number of different key values on the leaf level is:
N * R * N_DIFF_AVG_LEAF.
See REF01 for the implementation.
The above describes how to calculate the cardinality of an index.
This algorithm is executed for each n-prefix of a multi-column index
where n=1..n_uniq.
@} */
/* names of the tables from the persistent statistics storage */
#define TABLE_STATS_NAME_PRINT "mysql.innodb_table_stats"
#define INDEX_STATS_NAME_PRINT "mysql.innodb_index_stats"
#ifdef UNIV_STATS_DEBUG
#define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
#else /* UNIV_STATS_DEBUG */
#define DEBUG_PRINTF(fmt, ...) /* noop */
#endif /* UNIV_STATS_DEBUG */
/* Gets the number of leaf pages to sample in persistent stats estimation */
#define N_SAMPLE_PAGES(index) \
static_cast<ib_uint64_t>( \
(index)->table->stats_sample_pages != 0 \
? (index)->table->stats_sample_pages \
: srv_stats_persistent_sample_pages)
/* number of distinct records on a given level that are required to stop
descending to lower levels and fetch N_SAMPLE_PAGES(index) records
from that level */
#define N_DIFF_REQUIRED(index) (N_SAMPLE_PAGES(index) * 10)
/* A dynamic array where we store the boundaries of each distinct group
of keys. For example if a btree level is:
index: 0,1,2,3,4,5,6,7,8,9,10,11,12
data: b,b,b,b,b,b,g,g,j,j,j, x, y
then we would store 5,7,10,11,12 in the array. */
typedef std::vector<ib_uint64_t, ut_allocator<ib_uint64_t> > boundaries_t;
/** Allocator type used for index_map_t. */
typedef ut_allocator<std::pair<const char* const, dict_index_t*> >
index_map_t_allocator;
/** Auxiliary map used for sorting indexes by name in dict_stats_save(). */
typedef std::map<const char*, dict_index_t*, ut_strcmp_functor,
index_map_t_allocator> index_map_t;
bool dict_table_t::is_stats_table() const
{
return !strcmp(name.m_name, TABLE_STATS_NAME) ||
!strcmp(name.m_name, INDEX_STATS_NAME);
}
bool trx_t::has_stats_table_lock() const
{
for (const lock_t *l : lock.table_locks)
if (l && l->un_member.tab_lock.table->is_stats_table())
return true;
return false;
}
/*********************************************************************//**
Checks whether an index should be ignored in stats manipulations:
* stats fetch
* stats recalc
* stats save
@return true if exists and all tables are ok */
UNIV_INLINE
bool
dict_stats_should_ignore_index(
/*===========================*/
const dict_index_t* index) /*!< in: index */
{
return !index->is_btree() || index->to_be_dropped || !index->is_committed();
}
/** expected column definition */
struct dict_col_meta_t
{
/** column name */
const char *name;
/** main type */
unsigned mtype;
/** prtype mask; all these bits have to be set in prtype */
unsigned prtype_mask;
/** column length in bytes */
unsigned len;
};
/** For checking whether a table exists and has a predefined schema */
struct dict_table_schema_t
{
/** table name */
span<const char> table_name;
/** table name in SQL */
const char *table_name_sql;
/** number of columns */
unsigned n_cols;
/** columns */
const dict_col_meta_t columns[8];
};
static const dict_table_schema_t table_stats_schema =
{
{C_STRING_WITH_LEN(TABLE_STATS_NAME)}, TABLE_STATS_NAME_PRINT, 6,
{
{"database_name", DATA_VARMYSQL, DATA_NOT_NULL, 192},
{"table_name", DATA_VARMYSQL, DATA_NOT_NULL, 597},
/*
Don't check the DATA_UNSIGNED flag in last_update.
It presents if the server is running in a pure MariaDB installation,
because MariaDB's Field_timestampf::flags has UNSIGNED_FLAG.
But DATA_UNSIGNED misses when the server starts on a MySQL-5.7 directory
(during a migration), because MySQL's Field_timestampf::flags does not
have UNSIGNED_FLAG.
This is fine not to check DATA_UNSIGNED, because Field_timestampf
in both MariaDB and MySQL support only non-negative time_t values.
*/
{"last_update", DATA_INT, DATA_NOT_NULL, 4},
{"n_rows", DATA_INT, DATA_NOT_NULL | DATA_UNSIGNED, 8},
{"clustered_index_size", DATA_INT, DATA_NOT_NULL | DATA_UNSIGNED, 8},
{"sum_of_other_index_sizes", DATA_INT, DATA_NOT_NULL | DATA_UNSIGNED, 8},
}
};
static const dict_table_schema_t index_stats_schema =
{
{C_STRING_WITH_LEN(INDEX_STATS_NAME)}, INDEX_STATS_NAME_PRINT, 8,
{
{"database_name", DATA_VARMYSQL, DATA_NOT_NULL, 192},
{"table_name", DATA_VARMYSQL, DATA_NOT_NULL, 597},
{"index_name", DATA_VARMYSQL, DATA_NOT_NULL, 192},
/*
Don't check the DATA_UNSIGNED flag in last_update.
See comments about last_update in table_stats_schema above.
*/
{"last_update", DATA_INT, DATA_NOT_NULL, 4},
{"stat_name", DATA_VARMYSQL, DATA_NOT_NULL, 64*3},
{"stat_value", DATA_INT, DATA_NOT_NULL | DATA_UNSIGNED, 8},
{"sample_size", DATA_INT, DATA_UNSIGNED, 8},
{"stat_description", DATA_VARMYSQL, DATA_NOT_NULL, 1024*3}
}
};
/** Construct the type's SQL name (e.g. BIGINT UNSIGNED)
@param mtype InnoDB main type
@param prtype InnoDB precise type
@param len length of the column
@param name the SQL name
@param name_sz size of the name buffer
@return number of bytes written (excluding the terminating NUL byte) */
static int dtype_sql_name(unsigned mtype, unsigned prtype, unsigned len,
char *name, size_t name_sz)
{
const char *Unsigned= "";
const char *Main= "UNKNOWN";
switch (mtype) {
case DATA_INT:
switch (len) {
case 1:
Main= "TINYINT";
break;
case 2:
Main= "SMALLINT";
break;
case 3:
Main= "MEDIUMINT";
break;
case 4:
Main= "INT";
break;
case 8:
Main= "BIGINT";
break;
}
append_unsigned:
if (prtype & DATA_UNSIGNED)
Unsigned= " UNSIGNED";
len= 0;
break;
case DATA_FLOAT:
Main= "FLOAT";
goto append_unsigned;
case DATA_DOUBLE:
Main= "DOUBLE";
goto append_unsigned;
case DATA_FIXBINARY:
Main= "BINARY";
break;
case DATA_CHAR:
case DATA_MYSQL:
Main= "CHAR";
break;
case DATA_VARCHAR:
case DATA_VARMYSQL:
Main= "VARCHAR";
break;
case DATA_BINARY:
Main= "VARBINARY";
break;
case DATA_GEOMETRY:
Main= "GEOMETRY";
len= 0;
break;
case DATA_BLOB:
switch (len) {
case 9:
Main= "TINYBLOB";
break;
case 10:
Main= "BLOB";
break;
case 11:
Main= "MEDIUMBLOB";
break;
case 12:
Main= "LONGBLOB";
break;
}
len= 0;
}
const char* Not_null= (prtype & DATA_NOT_NULL) ? " NOT NULL" : "";
if (len)
return snprintf(name, name_sz, "%s(%u)%s%s", Main, len, Unsigned,
Not_null);
else
return snprintf(name, name_sz, "%s%s%s", Main, Unsigned, Not_null);
}
static bool innodb_table_stats_not_found;
static bool innodb_index_stats_not_found;
static bool innodb_table_stats_not_found_reported;
static bool innodb_index_stats_not_found_reported;
/*********************************************************************//**
Checks whether a table exists and whether it has the given structure.
The table must have the same number of columns with the same names and
types. The order of the columns does not matter.
dict_table_schema_check() @{
@return DB_SUCCESS if the table exists and contains the necessary columns */
static
dberr_t
dict_table_schema_check(
/*====================*/
const dict_table_schema_t* req_schema, /*!< in: required table
schema */
char* errstr, /*!< out: human readable error
message if != DB_SUCCESS is
returned */
size_t errstr_sz) /*!< in: errstr size */
{
const dict_table_t* table= dict_sys.load_table(req_schema->table_name);
if (!table) {
if (opt_bootstrap)
return DB_TABLE_NOT_FOUND;
if (req_schema == &table_stats_schema) {
if (innodb_table_stats_not_found_reported) {
return DB_STATS_DO_NOT_EXIST;
}
innodb_table_stats_not_found = true;
innodb_table_stats_not_found_reported = true;
} else {
ut_ad(req_schema == &index_stats_schema);
if (innodb_index_stats_not_found_reported) {
return DB_STATS_DO_NOT_EXIST;
}
innodb_index_stats_not_found = true;
innodb_index_stats_not_found_reported = true;
}
snprintf(errstr, errstr_sz, "Table %s not found.",
req_schema->table_name_sql);
return DB_TABLE_NOT_FOUND;
}
if (!table->is_readable() && !table->space) {
/* missing tablespace */
snprintf(errstr, errstr_sz,
"Tablespace for table %s is missing.",
req_schema->table_name_sql);
return DB_TABLE_NOT_FOUND;
}
if (unsigned(table->n_def - DATA_N_SYS_COLS) != req_schema->n_cols) {
/* the table has a different number of columns than required */
snprintf(errstr, errstr_sz,
"%s has %d columns but should have %u.",
req_schema->table_name_sql,
table->n_def - DATA_N_SYS_COLS,
req_schema->n_cols);
return DB_ERROR;
}
/* For each column from req_schema->columns[] search
whether it is present in table->cols[].
The following algorithm is O(n_cols^2), but is optimized to
be O(n_cols) if the columns are in the same order in both arrays. */
for (unsigned i = 0; i < req_schema->n_cols; i++) {
ulint j = dict_table_has_column(
table, req_schema->columns[i].name, i);
if (j == table->n_def) {
snprintf(errstr, errstr_sz,
"required column %s"
" not found in table %s.",
req_schema->columns[i].name,
req_schema->table_name_sql);
return(DB_ERROR);
}
/* we found a column with the same name on j'th position,
compare column types and flags */
/* check length for exact match */
if (req_schema->columns[i].len != table->cols[j].len) {
sql_print_warning("InnoDB: Table %s has"
" length mismatch in the"
" column name %s."
" Please run mariadb-upgrade",
req_schema->table_name_sql,
req_schema->columns[i].name);
}
/*
check mtype for exact match.
This check is relaxed to allow use to use TIMESTAMP
(ie INT) for last_update instead of DATA_BINARY.
We have to test for both values as the innodb_table_stats
table may come from MySQL and have the old type.
*/
if (req_schema->columns[i].mtype != table->cols[j].mtype &&
!(req_schema->columns[i].mtype == DATA_INT &&
table->cols[j].mtype == DATA_FIXBINARY)) {
} else if ((~table->cols[j].prtype
& req_schema->columns[i].prtype_mask)) {
} else {
continue;
}
int s = snprintf(errstr, errstr_sz,
"Column %s in table %s is ",
req_schema->columns[i].name,
req_schema->table_name_sql);
if (s < 0 || static_cast<size_t>(s) >= errstr_sz) {
return DB_ERROR;
}
errstr += s;
errstr_sz -= s;
s = dtype_sql_name(table->cols[j].mtype, table->cols[j].prtype,
table->cols[j].len, errstr, errstr_sz);
if (s < 0 || static_cast<size_t>(s) + sizeof " but should be "
>= errstr_sz) {
return DB_ERROR;
}
errstr += s;
memcpy(errstr, " but should be ", sizeof " but should be ");
errstr += (sizeof " but should be ") - 1;
errstr_sz -= s + (sizeof " but should be ") - 1;
s = dtype_sql_name(req_schema->columns[i].mtype,
req_schema->columns[i].prtype_mask,
req_schema->columns[i].len,
errstr, errstr_sz);
return DB_ERROR;
}
if (size_t n_foreign = table->foreign_set.size()) {
snprintf(errstr, errstr_sz,
"Table %s has %zu foreign key(s) pointing"
" to other tables, but it must have 0.",
req_schema->table_name_sql, n_foreign);
return DB_ERROR;
}
if (size_t n_referenced = table->referenced_set.size()) {
snprintf(errstr, errstr_sz,
"There are %zu foreign key(s) pointing to %s, "
"but there must be 0.", n_referenced,
req_schema->table_name_sql);
return DB_ERROR;
}
return DB_SUCCESS;
}
/*********************************************************************//**
Checks whether the persistent statistics storage exists and that all
tables have the proper structure.
@return true if exists and all tables are ok */
static bool dict_stats_persistent_storage_check(bool dict_already_locked)
{
char errstr[512];
dberr_t ret;
if (!dict_already_locked) {
dict_sys.lock(SRW_LOCK_CALL);
}
ut_ad(dict_sys.locked());
/* first check table_stats */
ret = dict_table_schema_check(&table_stats_schema, errstr,
sizeof(errstr));
if (ret == DB_SUCCESS) {
/* if it is ok, then check index_stats */
ret = dict_table_schema_check(&index_stats_schema, errstr,
sizeof(errstr));
}
if (!dict_already_locked) {
dict_sys.unlock();
}
switch (ret) {
case DB_SUCCESS:
return true;
default:
if (!opt_bootstrap) {
ib::error() << errstr;
}
/* fall through */
case DB_STATS_DO_NOT_EXIST:
return false;
}
}
/** Executes a given SQL statement using the InnoDB internal SQL parser.
This function will free the pinfo object.
@param[in,out] pinfo pinfo to pass to que_eval_sql() must already
have any literals bound to it
@param[in] sql SQL string to execute
@param[in,out] trx transaction
@return DB_SUCCESS or error code */
static
dberr_t dict_stats_exec_sql(pars_info_t *pinfo, const char* sql, trx_t *trx)
{
ut_ad(dict_sys.locked());
if (!dict_stats_persistent_storage_check(true))
{
pars_info_free(pinfo);
return DB_STATS_DO_NOT_EXIST;
}
return que_eval_sql(pinfo, sql, trx);
}
/*********************************************************************//**
Duplicate a table object and its indexes.
This function creates a dummy dict_table_t object and initializes the
following table and index members:
dict_table_t::id (copied)
dict_table_t::heap (newly created)
dict_table_t::name (copied)
dict_table_t::corrupted (copied)
dict_table_t::indexes<> (newly created)
dict_table_t::magic_n
for each entry in dict_table_t::indexes, the following are initialized:
(indexes that have DICT_FTS set in index->type are skipped)
dict_index_t::id (copied)
dict_index_t::name (copied)
dict_index_t::table_name (points to the copied table name)
dict_index_t::table (points to the above semi-initialized object)
dict_index_t::type (copied)
dict_index_t::to_be_dropped (copied)
dict_index_t::online_status (copied)
dict_index_t::n_uniq (copied)
dict_index_t::fields[] (newly created, only first n_uniq, only fields[i].name)
dict_index_t::indexes<> (newly created)
dict_index_t::stat_n_diff_key_vals[] (only allocated, left uninitialized)
dict_index_t::stat_n_sample_sizes[] (only allocated, left uninitialized)
dict_index_t::stat_n_non_null_key_vals[] (only allocated, left uninitialized)
dict_index_t::magic_n
The returned object should be freed with dict_stats_table_clone_free()
when no longer needed.
@return incomplete table object */
static
dict_table_t*
dict_stats_table_clone_create(
/*==========================*/
const dict_table_t* table) /*!< in: table whose stats to copy */
{
size_t heap_size;
dict_index_t* index;
/* Estimate the size needed for the table and all of its indexes */
heap_size = 0;
heap_size += sizeof(dict_table_t);
heap_size += strlen(table->name.m_name) + 1;
for (index = dict_table_get_first_index(table);
index != NULL;
index = dict_table_get_next_index(index)) {
if (dict_stats_should_ignore_index(index)) {
continue;
}
ut_ad(!dict_index_is_ibuf(index));
ulint n_uniq = dict_index_get_n_unique(index);
heap_size += sizeof(dict_index_t);
heap_size += strlen(index->name) + 1;
heap_size += n_uniq * sizeof(index->fields[0]);
for (ulint i = 0; i < n_uniq; i++) {
heap_size += strlen(index->fields[i].name) + 1;
}
heap_size += n_uniq * sizeof(index->stat_n_diff_key_vals[0]);
heap_size += n_uniq * sizeof(index->stat_n_sample_sizes[0]);
heap_size += n_uniq * sizeof(index->stat_n_non_null_key_vals[0]);
}
/* Allocate the memory and copy the members */
mem_heap_t* heap;
heap = mem_heap_create(heap_size);
dict_table_t* t;
t = (dict_table_t*) mem_heap_zalloc(heap, sizeof(*t));
t->stats_mutex_init();
MEM_CHECK_DEFINED(&table->id, sizeof(table->id));
t->id = table->id;
t->heap = heap;
t->name.m_name = mem_heap_strdup(heap, table->name.m_name);
t->mdl_name.m_name = t->name.m_name;
t->corrupted = table->corrupted;
UT_LIST_INIT(t->indexes, &dict_index_t::indexes);
#ifdef BTR_CUR_HASH_ADAPT
UT_LIST_INIT(t->freed_indexes, &dict_index_t::indexes);
#endif /* BTR_CUR_HASH_ADAPT */
for (index = dict_table_get_first_index(table);
index != NULL;
index = dict_table_get_next_index(index)) {
if (dict_stats_should_ignore_index(index)) {
continue;
}
ut_ad(!dict_index_is_ibuf(index));
dict_index_t* idx;
idx = (dict_index_t*) mem_heap_zalloc(heap, sizeof(*idx));
MEM_CHECK_DEFINED(&index->id, sizeof(index->id));
idx->id = index->id;
idx->name = mem_heap_strdup(heap, index->name);
idx->table = t;
idx->type = index->type;
idx->to_be_dropped = 0;
idx->online_status = ONLINE_INDEX_COMPLETE;
idx->set_committed(true);
idx->n_uniq = index->n_uniq;
idx->fields = (dict_field_t*) mem_heap_zalloc(
heap, idx->n_uniq * sizeof(idx->fields[0]));
for (ulint i = 0; i < idx->n_uniq; i++) {
idx->fields[i].name = mem_heap_strdup(
heap, index->fields[i].name);
}
/* hook idx into t->indexes */
UT_LIST_ADD_LAST(t->indexes, idx);
idx->stat_n_diff_key_vals = (ib_uint64_t*) mem_heap_zalloc(
heap,
idx->n_uniq * sizeof(idx->stat_n_diff_key_vals[0]));
idx->stat_n_sample_sizes = (ib_uint64_t*) mem_heap_zalloc(
heap,
idx->n_uniq * sizeof(idx->stat_n_sample_sizes[0]));
idx->stat_n_non_null_key_vals = (ib_uint64_t*) mem_heap_zalloc(
heap,
idx->n_uniq * sizeof(idx->stat_n_non_null_key_vals[0]));
ut_d(idx->magic_n = DICT_INDEX_MAGIC_N);
idx->stat_defrag_n_page_split = 0;
idx->stat_defrag_n_pages_freed = 0;
}
ut_d(t->magic_n = DICT_TABLE_MAGIC_N);
return(t);
}
/*********************************************************************//**
Free the resources occupied by an object returned by
dict_stats_table_clone_create(). */
static
void
dict_stats_table_clone_free(
/*========================*/
dict_table_t* t) /*!< in: dummy table object to free */
{
t->stats_mutex_destroy();
mem_heap_free(t->heap);
}
/*********************************************************************//**
Write all zeros (or 1 where it makes sense) into an index
statistics members. The resulting stats correspond to an empty index. */
static
void
dict_stats_empty_index(
/*===================*/
dict_index_t* index, /*!< in/out: index */
bool empty_defrag_stats)
/*!< in: whether to empty defrag stats */
{
ut_ad(!(index->type & DICT_FTS));
ut_ad(!dict_index_is_ibuf(index));
ut_ad(index->table->stats_mutex_is_owner());
ulint n_uniq = index->n_uniq;
for (ulint i = 0; i < n_uniq; i++) {
index->stat_n_diff_key_vals[i] = 0;
index->stat_n_sample_sizes[i] = 1;
index->stat_n_non_null_key_vals[i] = 0;
}
index->stat_index_size = 1;
index->stat_n_leaf_pages = 1;
if (empty_defrag_stats) {
dict_stats_empty_defrag_stats(index);
dict_stats_empty_defrag_summary(index);
}
}
/*********************************************************************//**
Write all zeros (or 1 where it makes sense) into a table and its indexes'
statistics members. The resulting stats correspond to an empty table. */
static
void
dict_stats_empty_table(
/*===================*/
dict_table_t* table, /*!< in/out: table */
bool empty_defrag_stats)
/*!< in: whether to empty defrag stats */
{
/* Initialize table/index level stats is now protected by
table level lock_mutex.*/
table->stats_mutex_lock();
/* Zero the stats members */
table->stat_n_rows = 0;
table->stat_clustered_index_size = 1;
/* 1 page for each index, not counting the clustered */
table->stat_sum_of_other_index_sizes
= UT_LIST_GET_LEN(table->indexes) - 1;
table->stat_modified_counter = 0;
dict_index_t* index;
for (index = dict_table_get_first_index(table);
index != NULL;
index = dict_table_get_next_index(index)) {
if (index->type & DICT_FTS) {
continue;
}
ut_ad(!dict_index_is_ibuf(index));
dict_stats_empty_index(index, empty_defrag_stats);
}
table->stat_initialized = TRUE;
table->stats_mutex_unlock();
}
/*********************************************************************//**
Check whether index's stats are initialized (assert if they are not). */
static
void
dict_stats_assert_initialized_index(
/*================================*/
const dict_index_t* index) /*!< in: index */
{
MEM_CHECK_DEFINED(
index->stat_n_diff_key_vals,
index->n_uniq * sizeof(index->stat_n_diff_key_vals[0]));
MEM_CHECK_DEFINED(
index->stat_n_sample_sizes,
index->n_uniq * sizeof(index->stat_n_sample_sizes[0]));
MEM_CHECK_DEFINED(
index->stat_n_non_null_key_vals,
index->n_uniq * sizeof(index->stat_n_non_null_key_vals[0]));
MEM_CHECK_DEFINED(
&index->stat_index_size,
sizeof(index->stat_index_size));
MEM_CHECK_DEFINED(
&index->stat_n_leaf_pages,
sizeof(index->stat_n_leaf_pages));
}
/*********************************************************************//**
Check whether table's stats are initialized (assert if they are not). */
static
void
dict_stats_assert_initialized(
/*==========================*/
const dict_table_t* table) /*!< in: table */
{
ut_a(table->stat_initialized);
MEM_CHECK_DEFINED(&table->stats_last_recalc,
sizeof table->stats_last_recalc);
MEM_CHECK_DEFINED(&table->stat_persistent,
sizeof table->stat_persistent);
MEM_CHECK_DEFINED(&table->stats_auto_recalc,
sizeof table->stats_auto_recalc);
MEM_CHECK_DEFINED(&table->stats_sample_pages,
sizeof table->stats_sample_pages);
MEM_CHECK_DEFINED(&table->stat_n_rows,
sizeof table->stat_n_rows);
MEM_CHECK_DEFINED(&table->stat_clustered_index_size,
sizeof table->stat_clustered_index_size);
MEM_CHECK_DEFINED(&table->stat_sum_of_other_index_sizes,
sizeof table->stat_sum_of_other_index_sizes);
MEM_CHECK_DEFINED(&table->stat_modified_counter,
sizeof table->stat_modified_counter);
for (dict_index_t* index = dict_table_get_first_index(table);
index != NULL;
index = dict_table_get_next_index(index)) {
if (!dict_stats_should_ignore_index(index)) {
dict_stats_assert_initialized_index(index);
}
}
}
#define INDEX_EQ(i1, i2) \
((i1) != NULL \
&& (i2) != NULL \
&& (i1)->id == (i2)->id \
&& strcmp((i1)->name, (i2)->name) == 0)
/*********************************************************************//**
Copy table and index statistics from one table to another, including index
stats. Extra indexes in src are ignored and extra indexes in dst are
initialized to correspond to an empty index. */
static
void
dict_stats_copy(
/*============*/
dict_table_t* dst, /*!< in/out: destination table */
const dict_table_t* src, /*!< in: source table */
bool reset_ignored_indexes) /*!< in: if true, set ignored indexes
to have the same statistics as if
the table was empty */
{
ut_ad(src->stats_mutex_is_owner());
ut_ad(dst->stats_mutex_is_owner());
dst->stats_last_recalc = src->stats_last_recalc;
dst->stat_n_rows = src->stat_n_rows;
dst->stat_clustered_index_size = src->stat_clustered_index_size;
dst->stat_sum_of_other_index_sizes = src->stat_sum_of_other_index_sizes;
dst->stat_modified_counter = src->stat_modified_counter;
dict_index_t* dst_idx;
dict_index_t* src_idx;
for (dst_idx = dict_table_get_first_index(dst),
src_idx = dict_table_get_first_index(src);
dst_idx != NULL;
dst_idx = dict_table_get_next_index(dst_idx),
(src_idx != NULL
&& (src_idx = dict_table_get_next_index(src_idx)))) {
if (dict_stats_should_ignore_index(dst_idx)) {
if (reset_ignored_indexes) {
/* Reset index statistics for all ignored indexes,
unless they are FT indexes (these have no statistics)*/
if (dst_idx->type & DICT_FTS) {
continue;
}
dict_stats_empty_index(dst_idx, true);
} else {
continue;
}
}
ut_ad(!dict_index_is_ibuf(dst_idx));
if (!INDEX_EQ(src_idx, dst_idx)) {
for (src_idx = dict_table_get_first_index(src);
src_idx != NULL;
src_idx = dict_table_get_next_index(src_idx)) {
if (INDEX_EQ(src_idx, dst_idx)) {
break;
}
}
}
if (!INDEX_EQ(src_idx, dst_idx)) {
dict_stats_empty_index(dst_idx, true);
continue;
}
ulint n_copy_el;
if (dst_idx->n_uniq > src_idx->n_uniq) {
n_copy_el = src_idx->n_uniq;
/* Since src is smaller some elements in dst
will remain untouched by the following memmove(),
thus we init all of them here. */
dict_stats_empty_index(dst_idx, true);
} else {
n_copy_el = dst_idx->n_uniq;
}
memmove(dst_idx->stat_n_diff_key_vals,
src_idx->stat_n_diff_key_vals,
n_copy_el * sizeof(dst_idx->stat_n_diff_key_vals[0]));
memmove(dst_idx->stat_n_sample_sizes,
src_idx->stat_n_sample_sizes,
n_copy_el * sizeof(dst_idx->stat_n_sample_sizes[0]));
memmove(dst_idx->stat_n_non_null_key_vals,
src_idx->stat_n_non_null_key_vals,
n_copy_el * sizeof(dst_idx->stat_n_non_null_key_vals[0]));
dst_idx->stat_index_size = src_idx->stat_index_size;
dst_idx->stat_n_leaf_pages = src_idx->stat_n_leaf_pages;
dst_idx->stat_defrag_modified_counter =
src_idx->stat_defrag_modified_counter;
dst_idx->stat_defrag_n_pages_freed =
src_idx->stat_defrag_n_pages_freed;
dst_idx->stat_defrag_n_page_split =
src_idx->stat_defrag_n_page_split;
}
dst->stat_initialized = TRUE;
}
/** Duplicate the stats of a table and its indexes.
This function creates a dummy dict_table_t object and copies the input
table's stats into it. The returned table object is not in the dictionary
cache and cannot be accessed by any other threads. In addition to the
members copied in dict_stats_table_clone_create() this function initializes
the following:
dict_table_t::stat_initialized
dict_table_t::stat_persistent
dict_table_t::stat_n_rows
dict_table_t::stat_clustered_index_size
dict_table_t::stat_sum_of_other_index_sizes
dict_table_t::stat_modified_counter
dict_index_t::stat_n_diff_key_vals[]
dict_index_t::stat_n_sample_sizes[]
dict_index_t::stat_n_non_null_key_vals[]
dict_index_t::stat_index_size
dict_index_t::stat_n_leaf_pages
dict_index_t::stat_defrag_modified_counter
dict_index_t::stat_defrag_n_pages_freed
dict_index_t::stat_defrag_n_page_split
The returned object should be freed with dict_stats_snapshot_free()
when no longer needed.