fix support of v11
[online_analyze.git] / online_analyze.c
1 /*
2  * Copyright (c) 2011 Teodor Sigaev <teodor@sigaev.ru>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *              notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *              notice, this list of conditions and the following disclaimer in the
12  *              documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the author nor the names of any co-contributors
14  *              may be used to endorse or promote products derived from this software
15  *              without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
23  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
26  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
27  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "postgres.h"
31
32 #include "pgstat.h"
33 #include "access/transam.h"
34 #include "access/xact.h"
35 #include "catalog/namespace.h"
36 #include "commands/vacuum.h"
37 #include "executor/executor.h"
38 #include "nodes/nodes.h"
39 #include "nodes/parsenodes.h"
40 #include "storage/bufmgr.h"
41 #include "utils/builtins.h"
42 #include "utils/hsearch.h"
43 #include "utils/memutils.h"
44 #include "utils/lsyscache.h"
45 #include "utils/guc.h"
46 #if PG_VERSION_NUM >= 90200
47 #include "catalog/pg_class.h"
48 #include "nodes/primnodes.h"
49 #include "tcop/utility.h"
50 #include "utils/rel.h"
51 #include "utils/relcache.h"
52 #include "utils/timestamp.h"
53 #if PG_VERSION_NUM >= 90500
54 #include "nodes/makefuncs.h"
55 #if PG_VERSION_NUM >= 100000
56 #include "utils/varlena.h"
57 #include "utils/regproc.h"
58 #endif
59 #endif
60 #endif
61
62 #ifdef PG_MODULE_MAGIC
63 PG_MODULE_MAGIC;
64 #endif
65
66 static bool online_analyze_enable = true;
67 static bool online_analyze_local_tracking = false;
68 static bool online_analyze_verbose = true;
69 static double online_analyze_scale_factor = 0.1;
70 static int online_analyze_threshold = 50;
71 static int online_analyze_capacity_threshold = 100000;
72 static double online_analyze_min_interval = 10000;
73 static int online_analyze_lower_limit = 0;
74
75 static ExecutorEnd_hook_type oldExecutorEndHook = NULL;
76 #if PG_VERSION_NUM >= 90200
77 static ProcessUtility_hook_type oldProcessUtilityHook = NULL;
78 #endif
79
80 typedef enum CmdKind
81 {
82         CK_SELECT = CMD_SELECT,
83         CK_UPDATE = CMD_UPDATE,
84         CK_INSERT = CMD_INSERT,
85         CK_DELETE = CMD_DELETE,
86         CK_TRUNCATE,
87         CK_FASTTRUNCATE,
88         CK_CREATE,
89         CK_ANALYZE,
90         CK_VACUUM
91 } CmdKind;
92
93
94 typedef enum
95 {
96         OATT_ALL                = 0x03,
97         OATT_PERSISTENT = 0x01,
98         OATT_TEMPORARY  = 0x02,
99         OATT_NONE               = 0x00
100 } OnlineAnalyzeTableType;
101
102 static const struct config_enum_entry online_analyze_table_type_options[] =
103 {
104         {"all", OATT_ALL, false},
105         {"persistent", OATT_PERSISTENT, false},
106         {"temporary", OATT_TEMPORARY, false},
107         {"none", OATT_NONE, false},
108         {NULL, 0, false},
109 };
110
111 static int online_analyze_table_type = (int)OATT_ALL;
112
113 typedef struct TableList {
114         int             nTables;
115         Oid             *tables;
116         char    *tableStr;
117 } TableList;
118
119 static TableList excludeTables = {0, NULL, NULL};
120 static TableList includeTables = {0, NULL, NULL};
121
122 typedef struct OnlineAnalyzeTableStat {
123         Oid                             tableid;
124         bool                    rereadStat;
125         PgStat_Counter  n_tuples;
126         PgStat_Counter  changes_since_analyze;
127         TimestampTz             autovac_analyze_timestamp;
128         TimestampTz             analyze_timestamp;
129 } OnlineAnalyzeTableStat;
130
131 static  MemoryContext   onlineAnalyzeMemoryContext = NULL;
132 static  HTAB    *relstats = NULL;
133
134 static void relstatsInit(void);
135
136 #if PG_VERSION_NUM < 100000
137 static int
138 oid_cmp(const void *a, const void *b)
139 {
140         if (*(Oid*)a == *(Oid*)b)
141                 return 0;
142         return (*(Oid*)a > *(Oid*)b) ? 1 : -1;
143 }
144 #endif
145
146 static const char *
147 tableListAssign(const char * newval, bool doit, TableList *tbl)
148 {
149         char            *rawname;
150         List            *namelist;
151         ListCell        *l;
152         Oid                     *newOids = NULL;
153         int                     nOids = 0,
154                                 i = 0;
155
156         rawname = pstrdup(newval);
157
158         if (!SplitIdentifierString(rawname, ',', &namelist))
159                 goto cleanup;
160
161         if (doit)
162         {
163                 nOids = list_length(namelist);
164                 newOids = malloc(sizeof(Oid) * (nOids+1));
165                 if (!newOids)
166                         elog(ERROR,"could not allocate %d bytes",
167                                  (int)(sizeof(Oid) * (nOids+1)));
168         }
169
170         foreach(l, namelist)
171         {
172                 char    *curname = (char *) lfirst(l);
173 #if PG_VERSION_NUM >= 90200
174                 Oid             relOid = RangeVarGetRelid(makeRangeVarFromNameList(
175                                                         stringToQualifiedNameList(curname)), NoLock, true);
176 #else
177                 Oid             relOid = RangeVarGetRelid(makeRangeVarFromNameList(
178                                                         stringToQualifiedNameList(curname)), true);
179 #endif
180
181                 if (relOid == InvalidOid)
182                 {
183 #if PG_VERSION_NUM >= 90100
184                         if (doit == false)
185 #endif
186                         elog(WARNING,"'%s' does not exist", curname);
187                         continue;
188                 }
189                 else if ( get_rel_relkind(relOid) != RELKIND_RELATION )
190                 {
191 #if PG_VERSION_NUM >= 90100
192                         if (doit == false)
193 #endif
194                                 elog(WARNING,"'%s' is not an table", curname);
195                         continue;
196                 }
197                 else if (doit)
198                 {
199                         newOids[i++] = relOid;
200                 }
201         }
202
203         if (doit)
204         {
205                 tbl->nTables = i;
206                 if (tbl->tables)
207                         free(tbl->tables);
208                 tbl->tables = newOids;
209                 if (tbl->nTables > 1)
210                         qsort(tbl->tables, tbl->nTables, sizeof(tbl->tables[0]), oid_cmp);
211         }
212
213         pfree(rawname);
214         list_free(namelist);
215
216         return newval;
217
218 cleanup:
219         if (newOids)
220                 free(newOids);
221         pfree(rawname);
222         list_free(namelist);
223         return NULL;
224 }
225
226 #if PG_VERSION_NUM >= 90100
227 static bool
228 excludeTablesCheck(char **newval, void **extra, GucSource source)
229 {
230         char *val;
231
232         val = (char*)tableListAssign(*newval, false, &excludeTables);
233
234         if (val)
235         {
236                 *newval = val;
237                 return true;
238         }
239
240         return false;
241 }
242
243 static void
244 excludeTablesAssign(const char *newval, void *extra)
245 {
246         tableListAssign(newval, true, &excludeTables);
247 }
248
249 static bool
250 includeTablesCheck(char **newval, void **extra, GucSource source)
251 {
252         char *val;
253
254         val = (char*)tableListAssign(*newval, false, &includeTables);
255
256         if (val)
257         {
258                 *newval = val;
259                 return true;
260         }
261
262         return false;
263 }
264
265 static void
266 includeTablesAssign(const char *newval, void *extra)
267 {
268         tableListAssign(newval, true, &excludeTables);
269 }
270
271 #else /* PG_VERSION_NUM < 90100 */
272
273 static const char *
274 excludeTablesAssign(const char * newval, bool doit, GucSource source)
275 {
276         return tableListAssign(newval, doit, &excludeTables);
277 }
278
279 static const char *
280 includeTablesAssign(const char * newval, bool doit, GucSource source)
281 {
282         return tableListAssign(newval, doit, &includeTables);
283 }
284
285 #endif
286
287 static const char*
288 tableListShow(TableList *tbl)
289 {
290         char    *val, *ptr;
291         int             i,
292                         len;
293
294         len = 1 /* \0 */ + tbl->nTables * (2 * NAMEDATALEN + 2 /* ', ' */ + 1 /* . */);
295         ptr = val = palloc(len);
296         *ptr ='\0';
297         for(i=0; i<tbl->nTables; i++)
298         {
299                 char    *relname = get_rel_name(tbl->tables[i]);
300                 Oid             nspOid = get_rel_namespace(tbl->tables[i]);
301                 char    *nspname = get_namespace_name(nspOid);
302
303                 if ( relname == NULL || nspOid == InvalidOid || nspname == NULL )
304                         continue;
305
306                 ptr += snprintf(ptr, len - (ptr - val), "%s%s.%s",
307                                                                                                         (i==0) ? "" : ", ",
308                                                                                                         nspname, relname);
309         }
310
311         return val;
312 }
313
314 static const char*
315 excludeTablesShow(void)
316 {
317         return tableListShow(&excludeTables);
318 }
319
320 static const char*
321 includeTablesShow(void)
322 {
323         return tableListShow(&includeTables);
324 }
325
326 static bool
327 matchOid(TableList *tbl, Oid oid)
328 {
329         Oid     *StopLow = tbl->tables,
330                 *StopHigh = tbl->tables + tbl->nTables,
331                 *StopMiddle;
332
333         /* Loop invariant: StopLow <= val < StopHigh */
334         while (StopLow < StopHigh)
335         {
336                 StopMiddle = StopLow + ((StopHigh - StopLow) >> 1);
337
338                 if (*StopMiddle == oid)
339                         return true;
340                 else  if (*StopMiddle < oid)
341                         StopLow = StopMiddle + 1;
342                 else
343                         StopHigh = StopMiddle;
344         }
345
346         return false;
347 }
348
349 #if PG_VERSION_NUM >= 90500
350 static RangeVar*
351 makeRangeVarFromOid(Oid relOid)
352 {
353         return makeRangeVar(
354                                 get_namespace_name(get_rel_namespace(relOid)),
355                                 get_rel_name(relOid),
356                                 -1
357                         );
358
359 }
360 #endif
361
362 static void
363 makeAnalyze(Oid relOid, CmdKind operation, int64 naffected)
364 {
365         TimestampTz                             now = GetCurrentTimestamp();
366         Relation                                rel;
367         OnlineAnalyzeTableType  reltype;
368         bool                                    found = false,
369                                                         newTable = false;
370         OnlineAnalyzeTableStat  *rstat,
371                                                         dummyrstat;
372         PgStat_StatTabEntry             *tabentry = NULL;
373
374         if (relOid == InvalidOid)
375                 return;
376
377         if (naffected == 0)
378                 /* return if there is no changes */
379                 return;
380         else if (naffected < 0)
381                 /* number if affected rows is unknown */
382                 naffected = 0;
383
384         rel = RelationIdGetRelation(relOid);
385         if (rel->rd_rel->relkind != RELKIND_RELATION)
386         {
387                 RelationClose(rel);
388                 return;
389         }
390
391         reltype =
392 #if PG_VERSION_NUM >= 90100
393                 (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
394 #else
395                 (rel->rd_istemp || rel->rd_islocaltemp)
396 #endif
397                         ? OATT_TEMPORARY : OATT_PERSISTENT;
398
399         RelationClose(rel);
400
401         /*
402          * includeTables overwrites excludeTables
403          */
404         switch(online_analyze_table_type)
405         {
406                 case OATT_ALL:
407                         if (get_rel_relkind(relOid) != RELKIND_RELATION ||
408                                 (matchOid(&excludeTables, relOid) == true &&
409                                 matchOid(&includeTables, relOid) == false))
410                                 return;
411                         break;
412                 case OATT_NONE:
413                         if (get_rel_relkind(relOid) != RELKIND_RELATION ||
414                                 matchOid(&includeTables, relOid) == false)
415                                 return;
416                         break;
417                 case OATT_TEMPORARY:
418                 case OATT_PERSISTENT:
419                 default:
420                         /*
421                          * skip analyze if relation's type doesn't not match
422                          * online_analyze_table_type
423                          */
424                         if ((online_analyze_table_type & reltype) == 0 ||
425                                 matchOid(&excludeTables, relOid) == true)
426                         {
427                                 if (matchOid(&includeTables, relOid) == false)
428                                         return;
429                         }
430                         break;
431         }
432
433         /*
434          * Do not store data about persistent table in local memory because we
435          * could not track changes of them: they could be changed by another
436          * backends. So always get a pgstat table entry.
437          */
438         if (reltype == OATT_TEMPORARY)
439                 rstat = hash_search(relstats, &relOid, HASH_ENTER, &found);
440         else
441                 rstat = &dummyrstat; /* found == false for following if */
442
443         if (!found)
444         {
445                 MemSet(rstat, 0, sizeof(*rstat));
446                 rstat->tableid = relOid;
447                 newTable = true;
448         }
449         else if (operation == CK_VACUUM)
450         {
451                 /* force reread becouse vacuum could change n_tuples */
452                 rstat->rereadStat = true;
453                 return;
454         }
455         else if (operation == CK_ANALYZE)
456         {
457                 /* only analyze */
458                 rstat->changes_since_analyze = 0;
459                 rstat->analyze_timestamp = now;
460                 return;
461         }
462
463         Assert(rstat->tableid == relOid);
464
465         if (
466                 /* do not reread data if it was a truncation */
467                 operation != CK_TRUNCATE && operation != CK_FASTTRUNCATE &&
468                 /* read  for persistent table and for temp teble if it allowed */
469                 (reltype == OATT_PERSISTENT || online_analyze_local_tracking == false) &&
470                 /* read only for new table or we know that it's needed */
471                 (newTable == true || rstat->rereadStat == true)
472            )
473         {
474                 rstat->rereadStat = false;
475
476                 tabentry = pgstat_fetch_stat_tabentry(relOid);
477
478                 if (tabentry)
479                 {
480                         rstat->n_tuples = tabentry->n_dead_tuples + tabentry->n_live_tuples;
481                         rstat->changes_since_analyze =
482 #if PG_VERSION_NUM >= 90000
483                                 tabentry->changes_since_analyze;
484 #else
485                                 tabentry->n_live_tuples + tabentry->n_dead_tuples -
486                                         tabentry->last_anl_tuples;
487 #endif
488                         rstat->autovac_analyze_timestamp =
489                                 tabentry->autovac_analyze_timestamp;
490                         rstat->analyze_timestamp = tabentry->analyze_timestamp;
491                 }
492         }
493
494         if (newTable ||
495                 /* force analyze after truncate, fasttruncate already did analyze */
496                 operation == CK_TRUNCATE || (
497                 /* do not analyze too often, if both stamps are exceeded the go */
498                 TimestampDifferenceExceeds(rstat->analyze_timestamp, now, online_analyze_min_interval) &&
499                 TimestampDifferenceExceeds(rstat->autovac_analyze_timestamp, now, online_analyze_min_interval) &&
500                 /* do not analyze too small tables */
501                 rstat->n_tuples + rstat->changes_since_analyze + naffected > online_analyze_lower_limit &&
502                 /* be in sync with relation_needs_vacanalyze */
503                 ((double)(rstat->changes_since_analyze + naffected)) >=
504                          online_analyze_scale_factor * ((double)rstat->n_tuples) +
505                          (double)online_analyze_threshold))
506         {
507 #if PG_VERSION_NUM < 90500
508                 VacuumStmt                              vacstmt;
509 #else
510                 VacuumParams                    vacstmt;
511 #endif
512                 TimestampTz                             startStamp, endStamp;
513
514
515                 memset(&startStamp, 0, sizeof(startStamp)); /* keep compiler quiet */
516
517                 memset(&vacstmt, 0, sizeof(vacstmt));
518
519                 vacstmt.freeze_min_age = -1;
520                 vacstmt.freeze_table_age = -1; /* ??? */
521
522 #if PG_VERSION_NUM < 90500
523                 vacstmt.type = T_VacuumStmt;
524                 vacstmt.relation = NULL;
525                 vacstmt.va_cols = NIL;
526 #if PG_VERSION_NUM >= 90000
527                 vacstmt.options = VACOPT_ANALYZE;
528                 if (online_analyze_verbose)
529                         vacstmt.options |= VACOPT_VERBOSE;
530 #else
531                 vacstmt.vacuum = vacstmt.full = false;
532                 vacstmt.analyze = true;
533                 vacstmt.verbose = online_analyze_verbose;
534 #endif
535 #else
536                 vacstmt.multixact_freeze_min_age = -1;
537                 vacstmt.multixact_freeze_table_age = -1;
538                 vacstmt.log_min_duration = -1;
539 #endif
540
541                 if (online_analyze_verbose)
542                         startStamp = GetCurrentTimestamp();
543
544                 analyze_rel(relOid,
545 #if PG_VERSION_NUM < 90500
546                         &vacstmt
547 #if PG_VERSION_NUM >= 90018
548                         , true
549 #endif
550                         , GetAccessStrategy(BAS_VACUUM)
551 #if (PG_VERSION_NUM >= 90000) && (PG_VERSION_NUM < 90004)
552                         , true
553 #endif
554 #else
555                         makeRangeVarFromOid(relOid),
556                         VACOPT_ANALYZE | ((online_analyze_verbose) ? VACOPT_VERBOSE : 0),
557                         &vacstmt, NULL, true, GetAccessStrategy(BAS_VACUUM)
558 #endif
559                 );
560
561                 /* Make changes visible to subsequent calls */
562                 CommandCounterIncrement();
563
564                 if (online_analyze_verbose)
565                 {
566                         long    secs;
567                         int             microsecs;
568
569                         endStamp = GetCurrentTimestamp();
570                         TimestampDifference(startStamp, endStamp, &secs, &microsecs);
571                         elog(INFO, "analyze \"%s\" took %.02f seconds",
572                                 get_rel_name(relOid),
573                                 ((double)secs) + ((double)microsecs)/1.0e6);
574                 }
575
576                 rstat->autovac_analyze_timestamp = now;
577                 rstat->changes_since_analyze = 0;
578
579                 switch(operation)
580                 {
581                         case CK_CREATE:
582                         case CK_INSERT:
583                         case CK_UPDATE:
584                                 rstat->n_tuples += naffected;
585                         case CK_DELETE:
586                                 rstat->rereadStat = (reltype == OATT_PERSISTENT);
587                                 break;
588                         case CK_TRUNCATE:
589                         case CK_FASTTRUNCATE:
590                                 rstat->rereadStat = false;
591                                 rstat->n_tuples = 0;
592                                 break;
593                         default:
594                                 break;
595                 }
596
597                 /* update last analyze timestamp in local memory of backend */
598                 if (tabentry)
599                 {
600                         tabentry->analyze_timestamp = now;
601                         tabentry->changes_since_analyze = 0;
602                 }
603 #if 0
604                 /* force reload stat for new table */
605                 if (newTable)
606                         pgstat_clear_snapshot();
607 #endif
608         }
609         else
610         {
611 #if PG_VERSION_NUM >= 90000
612                 if (tabentry)
613                         tabentry->changes_since_analyze += naffected;
614 #endif
615                 switch(operation)
616                 {
617                         case CK_CREATE:
618                         case CK_INSERT:
619                                 rstat->changes_since_analyze += naffected;
620                                 rstat->n_tuples += naffected;
621                                 break;
622                         case CK_UPDATE:
623                                 rstat->changes_since_analyze += 2 * naffected;
624                                 rstat->n_tuples += naffected;
625                         case CK_DELETE:
626                                 rstat->changes_since_analyze += naffected;
627                                 break;
628                         case CK_TRUNCATE:
629                         case CK_FASTTRUNCATE:
630                                 rstat->changes_since_analyze = 0;
631                                 rstat->n_tuples = 0;
632                                 break;
633                         default:
634                                 break;
635                 }
636         }
637
638         /* Reset local cache if we are over limit */
639         if (hash_get_num_entries(relstats) > online_analyze_capacity_threshold)
640                 relstatsInit();
641 }
642
643 static Const*
644 isFastTruncateCall(QueryDesc *queryDesc)
645 {
646         TargetEntry     *te;
647         FuncExpr        *fe;
648         Const           *constval;
649
650         if (!(
651                   queryDesc->plannedstmt &&
652                   queryDesc->operation == CMD_SELECT &&
653                   queryDesc->plannedstmt->planTree &&
654                   queryDesc->plannedstmt->planTree->targetlist &&
655                   list_length(queryDesc->plannedstmt->planTree->targetlist) == 1
656                  ))
657                 return NULL;
658
659         te = linitial(queryDesc->plannedstmt->planTree->targetlist);
660
661         if (!IsA(te, TargetEntry))
662                 return NULL;
663
664         fe = (FuncExpr*)te->expr;
665
666         if (!(
667                   fe && IsA(fe, FuncExpr) &&
668                   fe->funcid >= FirstNormalObjectId &&
669                   fe->funcretset == false &&
670                   fe->funcresulttype == VOIDOID &&
671                   fe->funcvariadic == false &&
672                   list_length(fe->args) == 1
673                  ))
674                 return NULL;
675
676         constval = linitial(fe->args);
677
678         if (!(
679                   IsA(constval,Const) &&
680                   constval->consttype == TEXTOID &&
681                   strcmp(get_func_name(fe->funcid), "fasttruncate") == 0
682                  ))
683                 return NULL;
684
685         return constval;
686 }
687
688
689 extern PGDLLIMPORT void onlineAnalyzeHooker(QueryDesc *queryDesc);
690 void
691 onlineAnalyzeHooker(QueryDesc *queryDesc)
692 {
693         int64   naffected = -1;
694         Const   *constval;
695
696         if (queryDesc->estate)
697                 naffected = queryDesc->estate->es_processed;
698
699 #if PG_VERSION_NUM >= 90200
700         if (online_analyze_enable &&
701                 (constval = isFastTruncateCall(queryDesc)) != NULL)
702         {
703                 Datum           tblnamed = constval->constvalue;
704                 char            *tblname = text_to_cstring(DatumGetTextP(tblnamed));
705                 RangeVar        *tblvar =
706                         makeRangeVarFromNameList(stringToQualifiedNameList(tblname));
707
708                 makeAnalyze(RangeVarGetRelid(tblvar,
709                                                                          NoLock,
710                                                                          false),
711                                         CK_FASTTRUNCATE, -1);
712         }
713 #endif
714
715         if (online_analyze_enable && queryDesc->plannedstmt &&
716                         (queryDesc->operation == CMD_INSERT ||
717                          queryDesc->operation == CMD_UPDATE ||
718                          queryDesc->operation == CMD_DELETE
719 #if PG_VERSION_NUM < 90200
720                          || (queryDesc->operation == CMD_SELECT &&
721                                  queryDesc->plannedstmt->intoClause)
722 #endif
723                          ))
724         {
725 #if PG_VERSION_NUM < 90200
726                 if (queryDesc->operation == CMD_SELECT)
727                 {
728                         Oid     relOid = RangeVarGetRelid(queryDesc->plannedstmt->intoClause->rel, true);
729
730                         makeAnalyze(relOid, queryDesc->operation, naffected);
731                 }
732                 else
733 #endif
734                 if (queryDesc->plannedstmt->resultRelations &&
735                                  queryDesc->plannedstmt->rtable)
736                 {
737                         ListCell        *l;
738
739                         foreach(l, queryDesc->plannedstmt->resultRelations)
740                         {
741                                 int                             n = lfirst_int(l);
742                                 RangeTblEntry   *rte = list_nth(queryDesc->plannedstmt->rtable, n-1);
743
744                                 if (rte->rtekind == RTE_RELATION)
745                                         makeAnalyze(rte->relid, (CmdKind)queryDesc->operation, naffected);
746                         }
747                 }
748         }
749
750         if (oldExecutorEndHook)
751                 oldExecutorEndHook(queryDesc);
752         else
753                 standard_ExecutorEnd(queryDesc);
754 }
755
756 static List             *toremove = NIL;
757
758 /*
759  * removeTable called on transaction end, see call RegisterXactCallback() below
760  */
761 static void
762 removeTable(XactEvent event, void *arg)
763 {
764         ListCell        *cell;
765
766         switch(event)
767         {
768                 case XACT_EVENT_COMMIT:
769                         break;
770                 case XACT_EVENT_ABORT:
771                         toremove = NIL;
772                 default:
773                         return;
774         }
775
776         foreach(cell, toremove)
777         {
778                 Oid     relOid = lfirst_oid(cell);
779
780                 hash_search(relstats, &relOid, HASH_REMOVE, NULL);
781         }
782
783         toremove = NIL;
784 }
785
786
787 #if PG_VERSION_NUM >= 90200
788 static void
789 onlineAnalyzeHookerUtility(
790 #if PG_VERSION_NUM >= 100000
791                                                    PlannedStmt *pstmt,
792 #else
793                                                    Node *parsetree,
794 #endif
795                                                    const char *queryString,
796 #if PG_VERSION_NUM >= 90300
797                                                         ProcessUtilityContext context, ParamListInfo params,
798 #if PG_VERSION_NUM >= 100000
799                                                         QueryEnvironment *queryEnv,
800 #endif
801 #else
802                                                         ParamListInfo params, bool isTopLevel,
803 #endif
804                                                         DestReceiver *dest, char *completionTag) {
805         List            *tblnames = NIL;
806         CmdKind         op = CK_INSERT;
807 #if PG_VERSION_NUM >= 100000
808         Node            *parsetree = NULL;
809
810         if (pstmt->commandType == CMD_UTILITY)
811                 parsetree = pstmt->utilityStmt;
812 #endif
813
814         if (parsetree && online_analyze_enable)
815         {
816                 if (IsA(parsetree, CreateTableAsStmt) &&
817                         ((CreateTableAsStmt*)parsetree)->into)
818                 {
819                         tblnames =
820                                 list_make1((RangeVar*)copyObject(((CreateTableAsStmt*)parsetree)->into->rel));
821                         op = CK_CREATE;
822                 }
823                 else if (IsA(parsetree, TruncateStmt))
824                 {
825                         tblnames = list_copy(((TruncateStmt*)parsetree)->relations);
826                         op = CK_TRUNCATE;
827                 }
828                 else if (IsA(parsetree, DropStmt) &&
829                                  ((DropStmt*)parsetree)->removeType == OBJECT_TABLE)
830                 {
831                         ListCell        *cell;
832
833                         foreach(cell, ((DropStmt*)parsetree)->objects)
834                         {
835                                 List            *relname = (List *) lfirst(cell);
836                                 RangeVar        *rel = makeRangeVarFromNameList(relname);
837                                 Oid                     relOid = RangeVarGetRelid(rel, NoLock, true);
838
839                                 if (OidIsValid(relOid))
840                                 {
841                                         MemoryContext   ctx;
842
843                                         ctx = MemoryContextSwitchTo(TopTransactionContext);
844                                         toremove = lappend_oid(toremove, relOid);
845                                         MemoryContextSwitchTo(ctx);
846                                 }
847                         }
848                 }
849                 else if (IsA(parsetree, VacuumStmt))
850                 {
851                         VacuumStmt      *vac = (VacuumStmt*)parsetree;
852
853 #if PG_VERSION_NUM >= 110000
854                         tblnames = vac->rels;
855 #else
856                         if (vac->relation)
857                                 tblnames = list_make1(vac->relation);
858 #endif
859
860                         if (vac->options & (VACOPT_VACUUM | VACOPT_FULL | VACOPT_FREEZE))
861                         {
862                                 /* optionally with analyze */
863                                 op = CK_VACUUM;
864
865                                 /* drop all collected stat */
866                                 if (tblnames == NIL)
867                                         relstatsInit();
868                         }
869                         else if (vac->options & VACOPT_ANALYZE)
870                         {
871                                 op = CK_ANALYZE;
872
873                                 /* should reset all counters */
874                                 if (tblnames == NIL)
875                                 {
876                                         HASH_SEQ_STATUS                 hs;
877                                         OnlineAnalyzeTableStat  *rstat;
878                                         TimestampTz                             now = GetCurrentTimestamp();
879
880                                         hash_seq_init(&hs, relstats);
881
882                                         while((rstat = hash_seq_search(&hs)) != NULL)
883                                         {
884                                                 rstat->changes_since_analyze = 0;
885                                                 rstat->analyze_timestamp = now;
886                                         }
887                                 }
888                         }
889                         else
890                                 tblnames = NIL;
891                 }
892         }
893
894 #if PG_VERSION_NUM >= 100000
895 #define parsetree pstmt
896 #endif
897
898         if (oldProcessUtilityHook)
899                 oldProcessUtilityHook(parsetree, queryString,
900 #if PG_VERSION_NUM >= 90300
901                                                           context, params,
902 #if PG_VERSION_NUM >= 100000
903                                                           queryEnv,
904 #endif
905 #else
906                                                           params, isTopLevel,
907 #endif
908                                                           dest, completionTag);
909         else
910                 standard_ProcessUtility(parsetree, queryString,
911 #if PG_VERSION_NUM >= 90300
912                                                                 context, params,
913 #if PG_VERSION_NUM >= 100000
914                                                                 queryEnv,
915 #endif
916 #else
917                                                                 params, isTopLevel,
918 #endif
919                                                                 dest, completionTag);
920
921 #if PG_VERSION_NUM >= 100000
922 #undef parsetree
923 #endif
924
925         if (tblnames) {
926                 ListCell        *l;
927
928                 foreach(l, tblnames)
929                 {
930                         RangeVar        *tblname =
931 #if PG_VERSION_NUM >= 110000
932                                 (IsA(lfirst(l), VacuumRelation)) ?
933                                         ((VacuumRelation*)lfirst(l))->relation :
934 #endif
935                                         (RangeVar*)lfirst(l);
936                         Oid     tblOid = RangeVarGetRelid(tblname, NoLock, true);
937
938                         makeAnalyze(tblOid, op, -1);
939                 }
940         }
941 }
942 #endif
943
944 static void
945 relstatsInit(void)
946 {
947         HASHCTL hash_ctl;
948         int             flags = 0;
949
950         MemSet(&hash_ctl, 0, sizeof(hash_ctl));
951
952         hash_ctl.hash = oid_hash;
953         flags |= HASH_FUNCTION;
954
955         if (onlineAnalyzeMemoryContext)
956         {
957                 Assert(relstats != NULL);
958                 MemoryContextReset(onlineAnalyzeMemoryContext);
959         }
960         else
961         {
962                 Assert(relstats == NULL);
963                 onlineAnalyzeMemoryContext =
964                         AllocSetContextCreate(CacheMemoryContext,
965                                                                   "online_analyze storage context",
966 #if PG_VERSION_NUM < 90600
967                                                                   ALLOCSET_DEFAULT_MINSIZE,
968                                                                   ALLOCSET_DEFAULT_INITSIZE,
969                                                                   ALLOCSET_DEFAULT_MAXSIZE
970 #else
971                                                                   ALLOCSET_DEFAULT_SIZES
972 #endif
973                                                                  );
974         }
975
976         hash_ctl.hcxt = onlineAnalyzeMemoryContext;
977         flags |= HASH_CONTEXT;
978
979         hash_ctl.keysize = sizeof(Oid);
980
981         hash_ctl.entrysize = sizeof(OnlineAnalyzeTableStat);
982         flags |= HASH_ELEM;
983
984         relstats = hash_create("online_analyze storage", 1024, &hash_ctl, flags);
985 }
986
987 void _PG_init(void);
988 void
989 _PG_init(void)
990 {
991         relstatsInit();
992
993         oldExecutorEndHook = ExecutorEnd_hook;
994
995         ExecutorEnd_hook = onlineAnalyzeHooker;
996
997 #if PG_VERSION_NUM >= 90200
998         oldProcessUtilityHook = ProcessUtility_hook;
999
1000         ProcessUtility_hook = onlineAnalyzeHookerUtility;
1001 #endif
1002
1003
1004         DefineCustomBoolVariable(
1005                 "online_analyze.enable",
1006                 "Enable on-line analyze",
1007                 "Enables analyze of table directly after insert/update/delete/select into",
1008                 &online_analyze_enable,
1009 #if PG_VERSION_NUM >= 80400
1010                 online_analyze_enable,
1011 #endif
1012                 PGC_USERSET,
1013 #if PG_VERSION_NUM >= 80400
1014                 GUC_NOT_IN_SAMPLE,
1015 #if PG_VERSION_NUM >= 90100
1016                 NULL,
1017 #endif
1018 #endif
1019                 NULL,
1020                 NULL
1021         );
1022
1023         DefineCustomBoolVariable(
1024                 "online_analyze.local_tracking",
1025                 "Per backend tracking",
1026                 "Per backend tracking for temp tables (do not use system statistic)",
1027                 &online_analyze_local_tracking,
1028 #if PG_VERSION_NUM >= 80400
1029                 online_analyze_local_tracking,
1030 #endif
1031                 PGC_USERSET,
1032 #if PG_VERSION_NUM >= 80400
1033                 GUC_NOT_IN_SAMPLE,
1034 #if PG_VERSION_NUM >= 90100
1035                 NULL,
1036 #endif
1037 #endif
1038                 NULL,
1039                 NULL
1040         );
1041
1042         DefineCustomBoolVariable(
1043                 "online_analyze.verbose",
1044                 "Verbosity of on-line analyze",
1045                 "Make ANALYZE VERBOSE after table's changes",
1046                 &online_analyze_verbose,
1047 #if PG_VERSION_NUM >= 80400
1048                 online_analyze_verbose,
1049 #endif
1050                 PGC_USERSET,
1051 #if PG_VERSION_NUM >= 80400
1052                 GUC_NOT_IN_SAMPLE,
1053 #if PG_VERSION_NUM >= 90100
1054                 NULL,
1055 #endif
1056 #endif
1057                 NULL,
1058                 NULL
1059         );
1060
1061         DefineCustomRealVariable(
1062                 "online_analyze.scale_factor",
1063                 "fraction of table size to start on-line analyze",
1064                 "fraction of table size to start on-line analyze",
1065                 &online_analyze_scale_factor,
1066 #if PG_VERSION_NUM >= 80400
1067                 online_analyze_scale_factor,
1068 #endif
1069                 0.0,
1070                 1.0,
1071                 PGC_USERSET,
1072 #if PG_VERSION_NUM >= 80400
1073                 GUC_NOT_IN_SAMPLE,
1074 #if PG_VERSION_NUM >= 90100
1075                 NULL,
1076 #endif
1077 #endif
1078                 NULL,
1079                 NULL
1080         );
1081
1082         DefineCustomIntVariable(
1083                 "online_analyze.threshold",
1084                 "min number of row updates before on-line analyze",
1085                 "min number of row updates before on-line analyze",
1086                 &online_analyze_threshold,
1087 #if PG_VERSION_NUM >= 80400
1088                 online_analyze_threshold,
1089 #endif
1090                 0,
1091                 0x7fffffff,
1092                 PGC_USERSET,
1093 #if PG_VERSION_NUM >= 80400
1094                 GUC_NOT_IN_SAMPLE,
1095 #if PG_VERSION_NUM >= 90100
1096                 NULL,
1097 #endif
1098 #endif
1099                 NULL,
1100                 NULL
1101         );
1102
1103         DefineCustomIntVariable(
1104                 "online_analyze.capacity_threshold",
1105                 "Max local cache table capacity",
1106                 "Max local cache table capacity",
1107                 &online_analyze_capacity_threshold,
1108 #if PG_VERSION_NUM >= 80400
1109                 online_analyze_capacity_threshold,
1110 #endif
1111                 0,
1112                 0x7fffffff,
1113                 PGC_USERSET,
1114 #if PG_VERSION_NUM >= 80400
1115                 GUC_NOT_IN_SAMPLE,
1116 #if PG_VERSION_NUM >= 90100
1117                 NULL,
1118 #endif
1119 #endif
1120                 NULL,
1121                 NULL
1122         );
1123
1124         DefineCustomRealVariable(
1125                 "online_analyze.min_interval",
1126                 "minimum time interval between analyze call (in milliseconds)",
1127                 "minimum time interval between analyze call (in milliseconds)",
1128                 &online_analyze_min_interval,
1129 #if PG_VERSION_NUM >= 80400
1130                 online_analyze_min_interval,
1131 #endif
1132                 0.0,
1133                 1e30,
1134                 PGC_USERSET,
1135 #if PG_VERSION_NUM >= 80400
1136                 GUC_NOT_IN_SAMPLE,
1137 #if PG_VERSION_NUM >= 90100
1138                 NULL,
1139 #endif
1140 #endif
1141                 NULL,
1142                 NULL
1143         );
1144
1145         DefineCustomEnumVariable(
1146                 "online_analyze.table_type",
1147                 "Type(s) of table for online analyze: all(default), persistent, temporary, none",
1148                 NULL,
1149                 &online_analyze_table_type,
1150 #if PG_VERSION_NUM >= 80400
1151                 online_analyze_table_type,
1152 #endif
1153                 online_analyze_table_type_options,
1154                 PGC_USERSET,
1155 #if PG_VERSION_NUM >= 80400
1156                 GUC_NOT_IN_SAMPLE,
1157 #if PG_VERSION_NUM >= 90100
1158                 NULL,
1159 #endif
1160 #endif
1161                 NULL,
1162                 NULL
1163         );
1164
1165         DefineCustomStringVariable(
1166                 "online_analyze.exclude_tables",
1167                 "List of tables which will not online analyze",
1168                 NULL,
1169                 &excludeTables.tableStr,
1170 #if PG_VERSION_NUM >= 80400
1171                 "",
1172 #endif
1173                 PGC_USERSET,
1174                 0,
1175 #if PG_VERSION_NUM >= 90100
1176                 excludeTablesCheck,
1177                 excludeTablesAssign,
1178 #else
1179                 excludeTablesAssign,
1180 #endif
1181                 excludeTablesShow
1182         );
1183
1184         DefineCustomStringVariable(
1185                 "online_analyze.include_tables",
1186                 "List of tables which will online analyze",
1187                 NULL,
1188                 &includeTables.tableStr,
1189 #if PG_VERSION_NUM >= 80400
1190                 "",
1191 #endif
1192                 PGC_USERSET,
1193                 0,
1194 #if PG_VERSION_NUM >= 90100
1195                 includeTablesCheck,
1196                 includeTablesAssign,
1197 #else
1198                 includeTablesAssign,
1199 #endif
1200                 includeTablesShow
1201         );
1202
1203         DefineCustomIntVariable(
1204                 "online_analyze.lower_limit",
1205                 "min number of rows in table to analyze",
1206                 "min number of rows in table to analyze",
1207                 &online_analyze_lower_limit,
1208 #if PG_VERSION_NUM >= 80400
1209                 online_analyze_lower_limit,
1210 #endif
1211                 0,
1212                 0x7fffffff,
1213                 PGC_USERSET,
1214 #if PG_VERSION_NUM >= 80400
1215                 GUC_NOT_IN_SAMPLE,
1216 #if PG_VERSION_NUM >= 90100
1217                 NULL,
1218 #endif
1219 #endif
1220                 NULL,
1221                 NULL
1222         );
1223
1224         RegisterXactCallback(removeTable, NULL);
1225 }
1226
1227 void _PG_fini(void);
1228 void
1229 _PG_fini(void)
1230 {
1231         ExecutorEnd_hook = oldExecutorEndHook;
1232 #if PG_VERSION_NUM >= 90200
1233         ProcessUtility_hook = oldProcessUtilityHook;
1234 #endif
1235
1236         if (excludeTables.tables)
1237                 free(excludeTables.tables);
1238         if (includeTables.tables)
1239                 free(includeTables.tables);
1240
1241         excludeTables.tables = includeTables.tables = NULL;
1242         excludeTables.nTables = includeTables.nTables = 0;
1243 }