forked from ossc-db/pg_dbms_stats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pg_dbms_stats.c
1776 lines (1569 loc) · 47.5 KB
/
pg_dbms_stats.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
/*
* pg_dbms_stats.c
*
* Copyright (c) 2009-2016, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
* Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*/
#include "postgres.h"
#include "access/transam.h"
#include "catalog/pg_statistic.h"
#include "catalog/pg_type.h"
#include "catalog/namespace.h"
#include "catalog/pg_authid.h"
#include "commands/trigger.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "optimizer/plancat.h"
#include "parser/parse_oper.h"
#include "storage/bufmgr.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/selfuncs.h"
#include "utils/syscache.h"
#include "miscadmin.h"
#if PG_VERSION_NUM >= 90200
#include "utils/rel.h"
#endif
#if PG_VERSION_NUM >= 90300
#include "access/htup_details.h"
#include "utils/catcache.h"
#endif
#include "pg_dbms_stats.h"
PG_MODULE_MAGIC;
/* Error levels used by pg_dbms_stats */
#define ELEVEL_DEBUG DEBUG3 /* log level for debug information */
#define ELEVEL_BADSTATS LOG /* log level for invalid statistics */
#define MAX_REL_CACHE 50 /* expected max # of rel stats entries */
/* Relation statistics cache entry */
typedef struct StatsRelationEntry
{
Oid relid; /* hash key must be at the head */
bool valid; /* T if the entry has valid stats */
BlockNumber relpages; /* # of pages as of last ANALYZE */
double reltuples; /* # of tuples as of last ANALYZE */
BlockNumber relallvisible; /* # of all-visible pages as of last
* ANALYZE */
BlockNumber curpages; /* # of pages as of lock/restore */
List *col_stats; /* list of StatsColumnEntry, each element
of which is pg_statistic record of this
relation. */
} StatsRelationEntry;
/*
* Column statistics cache entry. This is for list item for
* StatsRelationEntry.col_stats.
*/
typedef struct StatsColumnEntry
{
bool negative;
int32 attnum;
bool inh;
HeapTuple tuple;
} StatsColumnEntry;
/* Saved hook functions */
get_relation_info_hook_type prev_get_relation_info = NULL;
get_attavgwidth_hook_type prev_get_attavgwidth = NULL;
get_relation_stats_hook_type prev_get_relation_stats = NULL;
get_index_stats_hook_type prev_get_index_stats = NULL;
/* namings */
#define NSPNAME "dbms_stats"
#define RELSTAT_TBLNAME "relation_stats_locked"
#define COLSTAT_TBLNAME "column_stats_locked"
/* rows_query(oid) RETURNS int4, float4, int4 */
static const char *rows_query =
"SELECT relpages, reltuples, curpages"
#if PG_VERSION_NUM >= 90200
", relallvisible"
#endif
" FROM " NSPNAME "." RELSTAT_TBLNAME
" WHERE relid = $1";
static SPIPlanPtr rows_plan = NULL;
/* tuple_query(oid, int2, bool) RETURNS pg_statistic */
static const char *tuple_query =
"SELECT * "
" FROM " NSPNAME "." COLSTAT_TBLNAME
" WHERE starelid = $1 "
" AND staattnum = $2 "
" AND stainherit = $3";
static SPIPlanPtr tuple_plan = NULL;
/* GUC variables */
static bool pg_dbms_stats_use_locked_stats = true;
/* Current nesting depth of SPI calls, used to prevent recursive calls */
static int nested_level = 0;
/*
* The relation_stats_effective statistic cache is stored in hash table.
*/
static HTAB *rel_stats;
/*
* The owner of pg_dbms_stats statistic tables.
*/
static Oid stats_table_owner = InvalidOid;
static char *stats_table_owner_name = "";
#define get_pg_statistic(tuple) ((Form_pg_statistic) GETSTRUCT(tuple))
PG_FUNCTION_INFO_V1(dbms_stats_merge);
PG_FUNCTION_INFO_V1(dbms_stats_invalidate_relation_cache);
PG_FUNCTION_INFO_V1(dbms_stats_invalidate_column_cache);
PG_FUNCTION_INFO_V1(dbms_stats_is_system_schema);
PG_FUNCTION_INFO_V1(dbms_stats_is_system_catalog);
PG_FUNCTION_INFO_V1(dbms_stats_anyary_anyary);
PG_FUNCTION_INFO_V1(dbms_stats_type_is_analyzable);
PG_FUNCTION_INFO_V1(dbms_stats_anyarray_basetype);
extern Datum dbms_stats_merge(PG_FUNCTION_ARGS);
extern Datum dbms_stats_invalidate_relation_cache(PG_FUNCTION_ARGS);
extern Datum dbms_stats_invalidate_column_cache(PG_FUNCTION_ARGS);
extern Datum dbms_stats_is_system_schema(PG_FUNCTION_ARGS);
extern Datum dbms_stats_is_system_catalog(PG_FUNCTION_ARGS);
extern Datum dbms_stats_anyary_anyary(PG_FUNCTION_ARGS);
extern Datum dbms_stats_type_is_analyzable(PG_FUNCTION_ARGS);
extern Datum dbms_stats_anyarray_basetype(PG_FUNCTION_ARGS);
static HeapTuple dbms_stats_merge_internal(HeapTuple lhs, HeapTuple rhs,
TupleDesc tupledesc);
static void dbms_stats_check_tg_event(FunctionCallInfo fcinfo,
TriggerData *trigdata, HeapTuple *invtup, HeapTuple *rettup);
static void dbms_stats_invalidate_cache_internal(Oid relid, bool sta_col);
/* Module callbacks */
void _PG_init(void);
void _PG_fini(void);
static void dbms_stats_get_relation_info(PlannerInfo *root, Oid relid,
bool inhparent, RelOptInfo *rel);
static int32 dbms_stats_get_attavgwidth(Oid relid, AttrNumber attnum);
static bool dbms_stats_get_relation_stats(PlannerInfo *root, RangeTblEntry *rte,
AttrNumber attnum, VariableStatData *vardata);
static bool dbms_stats_get_index_stats(PlannerInfo *root, Oid indexOid,
AttrNumber indexattnum, VariableStatData *vardata);
static void get_merged_relation_stats(Oid relid, BlockNumber *pages,
double *tuples, double *allvisfrac, bool estimate);
static int32 get_merged_avgwidth(Oid relid, AttrNumber attnum);
static HeapTuple get_merged_column_stats(Oid relid, AttrNumber attnum,
bool inh);
static HeapTuple column_cache_search(Oid relid, AttrNumber attnum,
bool inh, bool*negative);
static HeapTuple column_cache_enter(Oid relid, int32 attnum, bool inh,
HeapTuple tuple);
static bool execute_plan(SPIPlanPtr *plan, const char *query, Oid relid,
const AttrNumber *attnum, bool inh);
static void StatsCacheRelCallback(Datum arg, Oid relid);
static void init_rel_stats(void);
static void init_rel_stats_entry(StatsRelationEntry *entry, Oid relid);
/* copied from PG core source tree */
static void dbms_stats_estimate_rel_size(Relation rel, int32 *attr_widths,
BlockNumber *pages, double *tuples, double *allvisfrac,
BlockNumber curpages);
static int32 dbms_stats_get_rel_data_width(Relation rel, int32 *attr_widths);
/* Unit test suit functions */
#ifdef UNIT_TEST
extern void test_import(int *passed, int *total);
extern void test_dump(int *passed, int *total);
extern void test_pg_dbms_stats(int *passed, int *total);
#endif
/* SPI_keepplan() is since 9.2 */
#if PG_VERSION_NUM < 90200
#define SPI_keepplan(pplan) {\
SPIPlanPtr tp = *plan;\
*plan = SPI_saveplan(tp);\
SPI_freeplan(tp);\
}
#endif
/*
* Module load callback
*/
void
_PG_init(void)
{
/* Execute unit test cases */
#ifdef UNIT_TEST
{
int passed = 0;
int total = 0;
test_import(&passed, &total);
test_dump(&passed, &total);
test_pg_dbms_stats(&passed, &total);
elog(WARNING, "TOTAL %d/%d passed", passed, total);
}
#endif
/* Define custom GUC variables. */
DefineCustomBoolVariable("pg_dbms_stats.use_locked_stats",
"Enable user defined statistics.",
NULL,
&pg_dbms_stats_use_locked_stats,
true,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
EmitWarningsOnPlaceholders("pg_dbms_stats");
/* Back up old hooks, and install ours. */
prev_get_relation_info = get_relation_info_hook;
get_relation_info_hook = dbms_stats_get_relation_info;
prev_get_attavgwidth = get_attavgwidth_hook;
get_attavgwidth_hook = dbms_stats_get_attavgwidth;
prev_get_relation_stats = get_relation_stats_hook;
get_relation_stats_hook = dbms_stats_get_relation_stats;
prev_get_index_stats = get_index_stats_hook;
get_index_stats_hook = dbms_stats_get_index_stats;
/* Initialize hash table for statistics caching. */
init_rel_stats();
/* Also set up a callback for relcache SI invalidations */
CacheRegisterRelcacheCallback(StatsCacheRelCallback, (Datum) 0);
}
/*
* Module unload callback
*/
void
_PG_fini(void)
{
/* Restore old hooks. */
get_relation_info_hook = prev_get_relation_info;
get_attavgwidth_hook = prev_get_attavgwidth;
get_relation_stats_hook = prev_get_relation_stats;
get_index_stats_hook = prev_get_index_stats;
/* A function to unregister callback for relcache is NOT provided. */
}
/*
* Function to convert from any array from dbms_stats.anyarray.
*/
Datum
dbms_stats_anyary_anyary(PG_FUNCTION_ARGS)
{
ArrayType *arr = PG_GETARG_ARRAYTYPE_P(0);
if (ARR_NDIM(arr) != 1)
elog(ERROR, "array must be one-dimentional.");
PG_RETURN_ARRAYTYPE_P(arr);
}
/*
* Function to check if the type can have statistics.
*/
Datum
dbms_stats_type_is_analyzable(PG_FUNCTION_ARGS)
{
Oid typid = PG_GETARG_OID(0);
Oid eqopr;
if (!OidIsValid(typid))
PG_RETURN_BOOL(false);
get_sort_group_operators(typid, false, false, false,
NULL, &eqopr, NULL,
NULL);
PG_RETURN_BOOL(OidIsValid(eqopr));
}
/*
* Function to get base type of the value of the type dbms_stats.anyarray.
*/
Datum
dbms_stats_anyarray_basetype(PG_FUNCTION_ARGS)
{
ArrayType *arr = PG_GETARG_ARRAYTYPE_P(0);
Oid elemtype = arr->elemtype;
HeapTuple tp;
Form_pg_type typtup;
Name result;
if (!OidIsValid(elemtype))
elog(ERROR, "invalid base type oid: %u", elemtype);
tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(elemtype));
if (!HeapTupleIsValid(tp)) /* I trust you. */
elog(ERROR, "invalid base type oid: %u", elemtype);
typtup = (Form_pg_type) GETSTRUCT(tp);
result = (Name) palloc0(NAMEDATALEN);
StrNCpy(NameStr(*result), NameStr(typtup->typname), NAMEDATALEN);
ReleaseSysCache(tp);
PG_RETURN_NAME(result);
}
/*
* Find and store the owner of the dummy statistics table.
*
* We will access statistics tables using this owner
*/
static Oid
get_stats_table_owner(void)
{
HeapTuple tp;
if (!OidIsValid(stats_table_owner))
{
tp = SearchSysCache2(RELNAMENSP,
PointerGetDatum(RELSTAT_TBLNAME),
ObjectIdGetDatum(get_namespace_oid(NSPNAME, false)));
if (!HeapTupleIsValid(tp))
elog(ERROR, "table \"%s.%s\" not found in pg_class",
NSPNAME, RELSTAT_TBLNAME);
stats_table_owner = ((Form_pg_class) GETSTRUCT(tp))->relowner;
if (!OidIsValid(stats_table_owner))
elog(ERROR, "owner uid of table \"%s.%s\" is invalid",
NSPNAME, RELSTAT_TBLNAME);
ReleaseSysCache(tp);
tp = SearchSysCache1(AUTHOID, ObjectIdGetDatum(stats_table_owner));
if (!HeapTupleIsValid(tp))
{
elog(ERROR,
"role id %u for the owner of the relation \"%s.%s\"is invalid",
stats_table_owner, NSPNAME, RELSTAT_TBLNAME);
}
/* This will be done once for the session, so not pstrdup. */
stats_table_owner_name =
strdup(NameStr(((Form_pg_authid) GETSTRUCT(tp))->rolname));
ReleaseSysCache(tp);
}
return stats_table_owner;
}
/*
* Store heap tuple header into given heap tuple.
*/
static void
AssignHeapTuple(HeapTuple htup, HeapTupleHeader header)
{
htup->t_len = HeapTupleHeaderGetDatumLength(header);
ItemPointerSetInvalid(&htup->t_self);
htup->t_tableOid = InvalidOid;
htup->t_data = header;
}
/*
* dbms_stats_merge
* called by sql function 'dbms_stats.merge', and return the execution result
* of the function 'dbms_stats_merge_internal'.
*/
Datum
dbms_stats_merge(PG_FUNCTION_ARGS)
{
HeapTupleData lhs;
HeapTupleData rhs;
TupleDesc tupdesc;
HeapTuple ret = NULL;
/* assign HeapTuple of the left statistics data unless null. */
if (PG_ARGISNULL(0))
lhs.t_data = NULL;
else
AssignHeapTuple(&lhs, PG_GETARG_HEAPTUPLEHEADER(0));
/* assign HeapTuple of the right statistics data unless null. */
if (PG_ARGISNULL(1))
rhs.t_data = NULL;
else
AssignHeapTuple(&rhs, PG_GETARG_HEAPTUPLEHEADER(1));
/* fast path for one-side is null */
if (lhs.t_data == NULL && rhs.t_data == NULL)
PG_RETURN_NULL();
/* build a tuple descriptor for our result type */
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
elog(ERROR, "return type must be a row type");
/* merge two statistics tuples into one, and return it */
ret = dbms_stats_merge_internal(&lhs, &rhs, tupdesc);
if (ret)
PG_RETURN_DATUM(HeapTupleGetDatum(ret));
else
PG_RETURN_NULL();
}
/*
* dbms_stats_merge_internal
* merge the dummy statistic (lhs) and the true statistic (rhs), on the basis
* of given TupleDesc.
*
* this function doesn't become an error level of ERROR to meet that the
* result of the SQL is not affected by the query plan.
*/
static HeapTuple
dbms_stats_merge_internal(HeapTuple lhs, HeapTuple rhs, TupleDesc tupdesc)
{
Datum values[Natts_pg_statistic];
bool nulls[Natts_pg_statistic];
int i;
Oid atttype = InvalidOid;
Oid relid;
AttrNumber attnum;
/* fast path for both-sides are null */
if ((lhs == NULL || lhs->t_data == NULL) &&
(rhs == NULL || rhs->t_data == NULL))
return NULL;
/* fast path for one-side is null */
if (lhs == NULL || lhs->t_data == NULL)
{
/* use right tuple */
heap_deform_tuple(rhs, tupdesc, values, nulls);
for (i = 0; i < Anum_pg_statistic_staop1 + STATISTIC_NUM_SLOTS - 1; i++)
if (nulls[i])
return NULL; /* check null constraints */
}
else if (rhs == NULL || rhs->t_data == NULL)
{
/* use left tuple */
heap_deform_tuple(lhs, tupdesc, values, nulls);
for (i = 0; i < Anum_pg_statistic_staop1 + STATISTIC_NUM_SLOTS - 1; i++)
if (nulls[i])
return NULL; /* check null constraints */
}
else
{
/*
* If the column value of the dummy statistic is not NULL, in the
* statistics except the slot, use it. Otherwise we use the column
* value of the true statistic.
*/
heap_deform_tuple(lhs, tupdesc, values, nulls);
for (i = 0; i < Anum_pg_statistic_stakind1 - 1; i++)
{
if (nulls[i])
{
values[i] = fastgetattr(rhs, i + 1, tupdesc, &nulls[i]);
if (nulls[i])
{
ereport(ELEVEL_BADSTATS,
(errmsg("pg_dbms_stats: bad statistics"),
errdetail("column \"%s\" should not be null",
get_attname(StatisticRelationId,
tupdesc->attrs[i]->attnum))));
return NULL; /* should not be null */
}
}
}
/*
* If the column value of the dummy statistic is not all NULL, in the
* statistics the slot, use it. Otherwise we use the column
* value of the true statistic.
*/
for (; i < Anum_pg_statistic_staop1 + STATISTIC_NUM_SLOTS - 1; i++)
{
if (nulls[i])
{
for (i = Anum_pg_statistic_stakind1 - 1;
i < Anum_pg_statistic_stavalues1 + STATISTIC_NUM_SLOTS - 1;
i++)
{
values[i] = fastgetattr(rhs, i + 1, tupdesc, &nulls[i]);
if (i < Anum_pg_statistic_staop1 + STATISTIC_NUM_SLOTS - 1 &&
nulls[i])
{
ereport(ELEVEL_BADSTATS,
(errmsg("pg_dbms_stats: bad statistics"),
errdetail("column \"%s\" should not be null",
get_attname(StatisticRelationId,
tupdesc->attrs[i]->attnum))));
return NULL; /* should not be null */
}
}
break;
}
}
}
/*
* Verify types to work around for ALTER COLUMN TYPE.
*
* Note: We don't need to retrieve atttype when the attribute doesn't have
* neither Most-Common-Value nor Histogram, but we retrieve it always
* because it's not usual.
*/
relid = DatumGetObjectId(values[0]);
attnum = DatumGetInt16(values[1]);
atttype = get_atttype(relid, attnum);
if (atttype == InvalidOid)
{
ereport(WARNING,
(errmsg("pg_dbms_stats: no-longer-existent column"),
errdetail("relid \"%d\" or its column whose attnum is \"%d\" might be deleted",
relid, attnum),
errhint("dbms_stats.clean_up_stats() would fix this.")));
return NULL;
}
for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
{
if ((i + 1 == STATISTIC_KIND_MCV ||
i + 1 == STATISTIC_KIND_HISTOGRAM) &&
!nulls[Anum_pg_statistic_stavalues1 + i - 1])
{
ArrayType *arr;
arr = DatumGetArrayTypeP(
values[Anum_pg_statistic_stavalues1 + i - 1]);
if (arr == NULL || arr->elemtype != atttype)
{
const char *attname = get_attname(relid, attnum);
/*
* relid and attnum must be valid here because valid atttype
* has been gotten already.
*/
Assert(attname);
ereport(ELEVEL_BADSTATS,
(errmsg("pg_dbms_stats: bad column type"),
errdetail("type of column \"%s\" has been changed",
attname),
errhint("need to execute dbms_stats.unlock('%s', '%s')",
get_rel_name(relid), attname)));
return NULL;
}
}
}
return heap_form_tuple(tupdesc, values, nulls);
}
/*
* dbms_stats_invalidate_relation_cache
* Register invalidation of the specified relation's relcache.
*
* CREATE TRIGGER dbms_stats.relation_stats_locked FOR INSERT, UPDATE, DELETE FOR EACH
* ROWS EXECUTE ...
*/
Datum
dbms_stats_invalidate_relation_cache(PG_FUNCTION_ARGS)
{
TriggerData *trigdata = (TriggerData *) fcinfo->context;
HeapTuple invtup; /* tuple to be invalidated */
HeapTuple rettup; /* tuple to be returned */
Datum value;
bool isnull;
/* make sure it's called as a before/after trigger */
dbms_stats_check_tg_event(fcinfo, trigdata, &invtup, &rettup);
/*
* assume that position of dbms_stats.relation_stats_locked.relid is head value of
* tuple.
*/
value = fastgetattr(invtup, 1, trigdata->tg_relation->rd_att, &isnull);
/*
* invalidate prepared statements and force re-planning with pg_dbms_stats.
*/
dbms_stats_invalidate_cache_internal((Oid)value, false);
PG_RETURN_POINTER(rettup);
}
/*
* dbms_stats_invalidate_column_cache
* Register invalidation of the specified relation's relcache.
*
* CREATE TRIGGER dbms_stats.column_stats_locked FOR INSERT, UPDATE, DELETE FOR EACH
* ROWS EXECUTE ...
*/
Datum
dbms_stats_invalidate_column_cache(PG_FUNCTION_ARGS)
{
TriggerData *trigdata = (TriggerData *) fcinfo->context;
Form_pg_statistic form;
HeapTuple invtup; /* tuple to be invalidated */
HeapTuple rettup; /* tuple to be returned */
/* make sure it's called as a before/after trigger */
dbms_stats_check_tg_event(fcinfo, trigdata, &invtup, &rettup);
/*
* assume that both pg_statistic and dbms_stats.column_stats_locked have the same
* definition.
*/
form = get_pg_statistic(invtup);
/*
* invalidate prepared statements and force re-planning with pg_dbms_stats.
*/
dbms_stats_invalidate_cache_internal(form->starelid, true);
PG_RETURN_POINTER(rettup);
}
static void
dbms_stats_check_tg_event(FunctionCallInfo fcinfo,
TriggerData *trigdata,
HeapTuple *invtup,
HeapTuple *rettup)
{
/* make sure it's called as a before/after trigger */
if (!CALLED_AS_TRIGGER(fcinfo) ||
!TRIGGER_FIRED_BEFORE(trigdata->tg_event) ||
!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
elog(ERROR, "pg_dbms_stats: invalid trigger call");
if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
{
/* INSERT */
*rettup = *invtup = trigdata->tg_trigtuple;
}
else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
{
/* DELETE */
*rettup = *invtup = trigdata->tg_trigtuple;
}
else
{
/* UPDATE */
*invtup = trigdata->tg_trigtuple;
*rettup = trigdata->tg_newtuple;
}
}
static void
dbms_stats_invalidate_cache_internal(Oid relid, bool sta_col)
{
Relation rel;
/*
* invalidate prepared statements and force re-planning with pg_dbms_stats.
*/
rel = try_relation_open(relid, NoLock);
if (rel != NULL)
{
if (sta_col &&
rel->rd_rel->relkind == RELKIND_INDEX &&
(rel->rd_indextuple == NULL ||
heap_attisnull(rel->rd_indextuple, Anum_pg_index_indexprs)))
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is an index except an index expression",
RelationGetRelationName(rel))));
if (rel->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is a composite type",
RelationGetRelationName(rel))));
/*
* We need to invalidate relcache of underlying table too, because
* CachedPlan mechanism decides to do re-planning when any relcache of
* used tables was invalid at EXECUTE.
*/
if (rel->rd_rel->relkind == RELKIND_INDEX &&
rel->rd_index && OidIsValid(rel->rd_index->indrelid))
CacheInvalidateRelcacheByRelid(rel->rd_index->indrelid);
CacheInvalidateRelcache(rel);
relation_close(rel, NoLock);
}
}
/*
* dbms_stats_is_system_schema
* called by sql function 'dbms_stats.is_system_schema', and return the
* result of the function 'dbms_stats_is_system_internal'.
*/
Datum
dbms_stats_is_system_schema(PG_FUNCTION_ARGS)
{
text *arg0;
char *schema_name;
bool result;
arg0 = PG_GETARG_TEXT_PP(0);
schema_name = text_to_cstring(arg0);
result = dbms_stats_is_system_schema_internal(schema_name);
PG_FREE_IF_COPY(arg0, 0);
PG_RETURN_BOOL(result);
}
/*
* dbms_stats_is_system_schema_internal
* return whether the given schema contains any system catalog. Here we
* treat dbms_stats objects as system catalogs to avoid infinite loop.
*/
bool
dbms_stats_is_system_schema_internal(char *schema_name)
{
Assert(schema_name != NULL);
/* if the schema is system_schema, return true */
if (strcmp(schema_name, "pg_catalog") == 0 ||
strcmp(schema_name, "pg_toast") == 0 ||
strcmp(schema_name, "information_schema") == 0 ||
strcmp(schema_name, NSPNAME) == 0)
return true;
return false;
}
/*
* dbms_stats_is_system_catalog
* called by sql function 'dbms_stats.is_system_catalog', and return the
* result of the function 'dbms_stats_is_system_catalog_internal'.
*/
Datum
dbms_stats_is_system_catalog(PG_FUNCTION_ARGS)
{
Oid relid;
bool result;
if (PG_ARGISNULL(0))
PG_RETURN_BOOL(true);
relid = PG_GETARG_OID(0);
result = dbms_stats_is_system_catalog_internal(relid);
PG_RETURN_BOOL(result);
}
/*
* dbms_stats_is_system_catalog_internal
* Check whether the given relation is one of system catalogs.
*/
bool
dbms_stats_is_system_catalog_internal(Oid relid)
{
Relation rel;
char *schema_name;
bool result;
/* relid is InvalidOid */
if (!OidIsValid(relid))
return false;
/* no such relation */
rel = try_relation_open(relid, NoLock);
if (rel == NULL)
return false;
/* check by namespace name. */
schema_name = get_namespace_name(rel->rd_rel->relnamespace);
result = dbms_stats_is_system_schema_internal(schema_name);
relation_close(rel, NoLock);
return result;
}
/*
* dbms_stats_get_relation_info
* Hook function for get_relation_info_hook, which implements post-process of
* get_relation_info().
*
* This function is designed on the basis of the fact that only expression
* indexes have statistics.
*/
static void
dbms_stats_get_relation_info(PlannerInfo *root,
Oid relid,
bool inhparent,
RelOptInfo *rel)
{
ListCell *lc;
double allvisfrac; /* dummy */
/*
* Call previously installed hook function regardless to whether
* pg_dbms_stats is enabled or not.
*/
if (prev_get_relation_info)
prev_get_relation_info(root, relid, inhparent, rel);
/* If pg_dbms_stats is disabled, there is no more thing to do. */
if (!pg_dbms_stats_use_locked_stats)
return;
/*
* Adjust stats of table itself, and stats of index
* relation_stats_effective as well
*/
/*
* Estimate relation size --- unless it's an inheritance parent, in which
* case the size will be computed later in set_append_rel_pathlist, and we
* must leave it zero for now to avoid bollixing the total_table_pages
* calculation.
*/
if (!inhparent)
{
#if PG_VERSION_NUM >= 90200
get_merged_relation_stats(relid, &rel->pages, &rel->tuples,
&rel->allvisfrac, true);
#else
get_merged_relation_stats(relid, &rel->pages, &rel->tuples,
&allvisfrac, true);
#endif
}
else
return;
foreach(lc, rel->indexlist)
{
/*
* Estimate the index size. If it's not a partial index, we lock
* the number-of-tuples estimate to equal the parent table; if it
* is partial then we have to use the same methods as we would for
* a table, except we can be sure that the index is not larger
* than the table.
*/
IndexOptInfo *info = (IndexOptInfo *) lfirst(lc);
bool estimate = info->indpred != NIL;
get_merged_relation_stats(info->indexoid, &info->pages, &info->tuples,
&allvisfrac, estimate);
if (!estimate || (estimate && info->tuples > rel->tuples))
info->tuples = rel->tuples;
}
}
/*
* dbms_stats_get_attavgwidth
* Hook function for get_attavgwidth_hook which replaces get_attavgwidth().
* Returning 0 tells caller to use standard routine.
*/
static int32
dbms_stats_get_attavgwidth(Oid relid, AttrNumber attnum)
{
if (pg_dbms_stats_use_locked_stats)
{
int32 width = get_merged_avgwidth(relid, attnum);
if (width > 0)
return width;
}
if (prev_get_attavgwidth)
return prev_get_attavgwidth(relid, attnum);
else
return 0;
}
/*
* We do nothing here, to keep the tuple valid even after examination.
*/
static void
FreeHeapTuple(HeapTuple tuple)
{
/* noop */
}
/*
* dbms_stats_get_relation_stats
* Hook function for get_relation_stats_hook which provides custom
* per-relation statistics.
* Returning false tells caller to use standard (true) statistics.
*/
static bool
dbms_stats_get_relation_stats(PlannerInfo *root,
RangeTblEntry *rte,
AttrNumber attnum,
VariableStatData *vardata)
{
if (pg_dbms_stats_use_locked_stats)
{
HeapTuple tuple;
tuple = get_merged_column_stats(rte->relid, attnum, rte->inh);
vardata->statsTuple = tuple;
if (tuple != NULL)
{
vardata->freefunc = FreeHeapTuple;
return true;
}
}
if (prev_get_relation_stats)
return prev_get_relation_stats(root, rte, attnum, vardata);
else
return false;
}
/*
* dbms_stats_get_index_stats
* Hook function for get_index_stats_hook which provides custom per-relation
* statistics.
* Returning false tells caller to use standard (true) statistics.
*/
static bool
dbms_stats_get_index_stats(PlannerInfo *root,
Oid indexOid,
AttrNumber indexattnum,
VariableStatData *vardata)
{
if (pg_dbms_stats_use_locked_stats)
{
HeapTuple tuple;
tuple = get_merged_column_stats(indexOid, indexattnum, false);
vardata->statsTuple = tuple;
if (tuple != NULL)
{
vardata->freefunc = FreeHeapTuple;
return true;
}
}
if (prev_get_index_stats)
return prev_get_index_stats(root, indexOid, indexattnum, vardata);
else
return false;
}
/*
* Extract binary value from given column.
*/
static Datum
get_binary_datum(int column, bool *isnull)
{
return SPI_getbinval(SPI_tuptable->vals[0],
SPI_tuptable->tupdesc, column, isnull);
}
/*
* get_merged_relation_stats
* get the statistics of the table, # of pages and # of rows, by executing
* SELECT against dbms_stats.relation_stats_locked view.
*/
static void
get_merged_relation_stats(Oid relid, BlockNumber *pages, double *tuples,
double *allvisfrac, bool estimate)
{
StatsRelationEntry *entry;
bool found;
Relation rel;
/* avoid recursive call and system objects */
if (nested_level > 0 || relid < FirstNormalObjectId)
return;
/*
* pg_dbms_stats doesn't handle system catalogs and its internal relation_stats_effective
*/
if (dbms_stats_is_system_catalog_internal(relid))
return;
/*
* First, search from cache. If we have not cached stats for given relid
* yet, initialize newly created entry.
*/
entry = hash_search(rel_stats, &relid, HASH_ENTER, &found);
if (!found)
init_rel_stats_entry(entry, relid);
if (entry->valid)
{
/*
* Valid entry with invalid relpage is a negative cache, which
* eliminates excessive SPI calls below. Negative caches will be
* invalidated again on invalidation of system relation cache, which
* occur on modification of the dummy stats tables
* dbms_stats.relation_stats_locked and column_stats_locked.
*/
if (entry->relpages == InvalidBlockNumber)