Merge branch 'local_hash' into n_tuples_limit
[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 "catalog/namespace.h"
34 #include "commands/vacuum.h"
35 #include "executor/executor.h"
36 #include "nodes/nodes.h"
37 #include "nodes/parsenodes.h"
38 #include "storage/bufmgr.h"
39 #include "utils/builtins.h"
40 #include "utils/hsearch.h"
41 #include "utils/memutils.h"
42 #include "utils/lsyscache.h"
43 #include "utils/guc.h"
44 #if PG_VERSION_NUM >= 90200
45 #include "catalog/pg_class.h"
46 #include "nodes/primnodes.h"
47 #include "tcop/utility.h"
48 #include "utils/rel.h"
49 #include "utils/relcache.h"
50 #include "utils/timestamp.h"
51 #if PG_VERSION_NUM >= 90500
52 #include "nodes/makefuncs.h"
53 #if PG_VERSION_NUM >= 100000
54 #include "utils/varlena.h"
55 #include "utils/regproc.h"
56 #endif
57 #endif
58 #endif
59
60 #ifdef PG_MODULE_MAGIC
61 PG_MODULE_MAGIC;
62 #endif
63
64 static bool online_analyze_enable = true;
65 static bool online_analyze_verbose = true;
66 static double online_analyze_scale_factor = 0.1;
67 static int online_analyze_threshold = 50;
68 static int online_analyze_capacity_threshold = 100000;
69 static double online_analyze_min_interval = 10000;
70 static int online_analyze_lower_limit = 0;
71
72 static ExecutorEnd_hook_type oldExecutorEndHook = NULL;
73 #if PG_VERSION_NUM >= 90200
74 static ProcessUtility_hook_type oldProcessUtilityHook = NULL;
75 #endif
76
77 typedef enum CmdKind
78 {
79         CK_SELECT = CMD_SELECT,
80         CK_UPDATE = CMD_UPDATE,
81         CK_INSERT = CMD_INSERT,
82         CK_DELETE = CMD_DELETE,
83         CK_TRUNCATE,
84         CK_CREATE
85 } CmdKind;
86
87 typedef enum
88 {
89         OATT_ALL                = 0x03,
90         OATT_PERSISTENT = 0x01,
91         OATT_TEMPORARY  = 0x02,
92         OATT_NONE               = 0x00
93 } OnlineAnalyzeTableType;
94
95 static const struct config_enum_entry online_analyze_table_type_options[] =
96 {
97         {"all", OATT_ALL, false},
98         {"persistent", OATT_PERSISTENT, false},
99         {"temporary", OATT_TEMPORARY, false},
100         {"none", OATT_NONE, false},
101         {NULL, 0, false},
102 };
103
104 static int online_analyze_table_type = (int)OATT_ALL;
105
106 typedef struct TableList {
107         int             nTables;
108         Oid             *tables;
109         char    *tableStr;
110 } TableList;
111
112 static TableList excludeTables = {0, NULL, NULL};
113 static TableList includeTables = {0, NULL, NULL};
114
115 typedef struct OnlineAnalyzeTableStat {
116         Oid                             tableid;
117         bool                    rereadStat;
118         PgStat_Counter  n_tuples;
119         PgStat_Counter  changes_since_analyze;
120         TimestampTz             autovac_analyze_timestamp;
121         TimestampTz             analyze_timestamp;
122 } OnlineAnalyzeTableStat;
123
124 static  MemoryContext   onlineAnalyzeMemoryContext = NULL;
125 static  HTAB    *relstats = NULL;
126
127 static void relstatsInit(void);
128
129 #if PG_VERSION_NUM < 100000
130 static int
131 oid_cmp(const void *a, const void *b)
132 {
133         if (*(Oid*)a == *(Oid*)b)
134                 return 0;
135         return (*(Oid*)a > *(Oid*)b) ? 1 : -1;
136 }
137 #endif
138
139 static const char *
140 tableListAssign(const char * newval, bool doit, TableList *tbl)
141 {
142         char            *rawname;
143         List            *namelist;
144         ListCell        *l;
145         Oid                     *newOids = NULL;
146         int                     nOids = 0,
147                                 i = 0;
148
149         rawname = pstrdup(newval);
150
151         if (!SplitIdentifierString(rawname, ',', &namelist))
152                 goto cleanup;
153
154         if (doit)
155         {
156                 nOids = list_length(namelist);
157                 newOids = malloc(sizeof(Oid) * (nOids+1));
158                 if (!newOids)
159                         elog(ERROR,"could not allocate %d bytes",
160                                  (int)(sizeof(Oid) * (nOids+1)));
161         }
162
163         foreach(l, namelist)
164         {
165                 char    *curname = (char *) lfirst(l);
166 #if PG_VERSION_NUM >= 90200
167                 Oid             relOid = RangeVarGetRelid(makeRangeVarFromNameList(
168                                                         stringToQualifiedNameList(curname)), NoLock, true);
169 #else
170                 Oid             relOid = RangeVarGetRelid(makeRangeVarFromNameList(
171                                                         stringToQualifiedNameList(curname)), true);
172 #endif
173
174                 if (relOid == InvalidOid)
175                 {
176 #if PG_VERSION_NUM >= 90100
177                         if (doit == false)
178 #endif
179                         elog(WARNING,"'%s' does not exist", curname);
180                         continue;
181                 }
182                 else if ( get_rel_relkind(relOid) != RELKIND_RELATION )
183                 {
184 #if PG_VERSION_NUM >= 90100
185                         if (doit == false)
186 #endif
187                                 elog(WARNING,"'%s' is not an table", curname);
188                         continue;
189                 }
190                 else if (doit)
191                 {
192                         newOids[i++] = relOid;
193                 }
194         }
195
196         if (doit)
197         {
198                 tbl->nTables = i;
199                 if (tbl->tables)
200                         free(tbl->tables);
201                 tbl->tables = newOids;
202                 if (tbl->nTables > 1)
203                         qsort(tbl->tables, tbl->nTables, sizeof(tbl->tables[0]), oid_cmp);
204         }
205
206         pfree(rawname);
207         list_free(namelist);
208
209         return newval;
210
211 cleanup:
212         if (newOids)
213                 free(newOids);
214         pfree(rawname);
215         list_free(namelist);
216         return NULL;
217 }
218
219 #if PG_VERSION_NUM >= 90100
220 static bool
221 excludeTablesCheck(char **newval, void **extra, GucSource source)
222 {
223         char *val;
224
225         val = (char*)tableListAssign(*newval, false, &excludeTables);
226
227         if (val)
228         {
229                 *newval = val;
230                 return true;
231         }
232
233         return false;
234 }
235
236 static void
237 excludeTablesAssign(const char *newval, void *extra)
238 {
239         tableListAssign(newval, true, &excludeTables);
240 }
241
242 static bool
243 includeTablesCheck(char **newval, void **extra, GucSource source)
244 {
245         char *val;
246
247         val = (char*)tableListAssign(*newval, false, &includeTables);
248
249         if (val)
250         {
251                 *newval = val;
252                 return true;
253         }
254
255         return false;
256 }
257
258 static void
259 includeTablesAssign(const char *newval, void *extra)
260 {
261         tableListAssign(newval, true, &excludeTables);
262 }
263
264 #else /* PG_VERSION_NUM < 90100 */
265
266 static const char *
267 excludeTablesAssign(const char * newval, bool doit, GucSource source)
268 {
269         return tableListAssign(newval, doit, &excludeTables);
270 }
271
272 static const char *
273 includeTablesAssign(const char * newval, bool doit, GucSource source)
274 {
275         return tableListAssign(newval, doit, &includeTables);
276 }
277
278 #endif
279
280 static const char*
281 tableListShow(TableList *tbl)
282 {
283         char    *val, *ptr;
284         int             i,
285                         len;
286
287         len = 1 /* \0 */ + tbl->nTables * (2 * NAMEDATALEN + 2 /* ', ' */ + 1 /* . */);
288         ptr = val = palloc(len);
289         *ptr ='\0';
290         for(i=0; i<tbl->nTables; i++)
291         {
292                 char    *relname = get_rel_name(tbl->tables[i]);
293                 Oid             nspOid = get_rel_namespace(tbl->tables[i]);
294                 char    *nspname = get_namespace_name(nspOid);
295
296                 if ( relname == NULL || nspOid == InvalidOid || nspname == NULL )
297                         continue;
298
299                 ptr += snprintf(ptr, len - (ptr - val), "%s%s.%s",
300                                                                                                         (i==0) ? "" : ", ",
301                                                                                                         nspname, relname);
302         }
303
304         return val;
305 }
306
307 static const char*
308 excludeTablesShow(void)
309 {
310         return tableListShow(&excludeTables);
311 }
312
313 static const char*
314 includeTablesShow(void)
315 {
316         return tableListShow(&includeTables);
317 }
318
319 static bool
320 matchOid(TableList *tbl, Oid oid)
321 {
322         Oid     *StopLow = tbl->tables,
323                 *StopHigh = tbl->tables + tbl->nTables,
324                 *StopMiddle;
325
326         /* Loop invariant: StopLow <= val < StopHigh */
327         while (StopLow < StopHigh)
328         {
329                 StopMiddle = StopLow + ((StopHigh - StopLow) >> 1);
330
331                 if (*StopMiddle == oid)
332                         return true;
333                 else  if (*StopMiddle < oid)
334                         StopLow = StopMiddle + 1;
335                 else
336                         StopHigh = StopMiddle;
337         }
338
339         return false;
340 }
341
342 #if PG_VERSION_NUM >= 90500
343 static RangeVar*
344 makeRangeVarFromOid(Oid relOid)
345 {
346         return makeRangeVar(
347                                 get_namespace_name(get_rel_namespace(relOid)),
348                                 get_rel_name(relOid),
349                                 -1
350                         );
351
352 }
353 #endif
354
355 static void
356 makeAnalyze(Oid relOid, CmdKind operation, int64 naffected)
357 {
358         TimestampTz                             now = GetCurrentTimestamp();
359         Relation                                rel;
360         OnlineAnalyzeTableType  reltype;
361         bool                                    found = false,
362                                                         newTable = false;
363         OnlineAnalyzeTableStat  *rstat,
364                                                         dummyrstat;
365         PgStat_StatTabEntry             *tabentry = NULL;
366
367         if (relOid == InvalidOid)
368                 return;
369
370         if (naffected == 0)
371                 /* return if there is no changes */
372                 return;
373         else if (naffected < 0)
374                 /* number if affected rows is unknown */
375                 naffected = 0;
376
377         rel = RelationIdGetRelation(relOid);
378         if (rel->rd_rel->relkind != RELKIND_RELATION)
379         {
380                 RelationClose(rel);
381                 return;
382         }
383
384         reltype =
385 #if PG_VERSION_NUM >= 90100
386                 (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
387 #else
388                 (rel->rd_istemp || rel->rd_islocaltemp)
389 #endif
390                         ? OATT_TEMPORARY : OATT_PERSISTENT;
391
392         RelationClose(rel);
393
394         /*
395          * includeTables overwrites excludeTables
396          */
397         switch(online_analyze_table_type)
398         {
399                 case OATT_ALL:
400                         if (get_rel_relkind(relOid) != RELKIND_RELATION ||
401                                 (matchOid(&excludeTables, relOid) == true &&
402                                 matchOid(&includeTables, relOid) == false))
403                                 return;
404                         break;
405                 case OATT_NONE:
406                         if (get_rel_relkind(relOid) != RELKIND_RELATION ||
407                                 matchOid(&includeTables, relOid) == false)
408                                 return;
409                         break;
410                 case OATT_TEMPORARY:
411                 case OATT_PERSISTENT:
412                 default:
413                         /*
414                          * skip analyze if relation's type doesn't not match
415                          * online_analyze_table_type
416                          */
417                         if ((online_analyze_table_type & reltype) == 0 ||
418                                 matchOid(&excludeTables, relOid) == true)
419                         {
420                                 if (matchOid(&includeTables, relOid) == false)
421                                         return;
422                         }
423                         break;
424         }
425
426         /*
427          * Do not store data about persistent table in local memory because we
428          * could not track changes of them: they could be changed by another
429          * backends. So always get a pgstat table entry.
430          */
431         if (reltype == OATT_TEMPORARY)
432                 rstat = hash_search(relstats, &relOid, HASH_ENTER, &found);
433         else
434                 rstat = &dummyrstat; /* found == false for following if */
435
436         if (!found)
437         {
438                 MemSet(rstat, 0, sizeof(*rstat));
439                 rstat->tableid = relOid;
440                 newTable = true;
441         }
442
443         Assert(rstat->tableid == relOid);
444
445         if (operation != CK_TRUNCATE &&
446                 (found == false || rstat->rereadStat == true))
447         {
448
449                 rstat->rereadStat = false;
450
451                 tabentry = pgstat_fetch_stat_tabentry(relOid);
452
453                 if (tabentry)
454                 {
455                         rstat->n_tuples = tabentry->n_dead_tuples + tabentry->n_live_tuples;
456                         rstat->changes_since_analyze =
457 #if PG_VERSION_NUM >= 90000
458                                 tabentry->changes_since_analyze;
459 #else
460                                 tabentry->n_live_tuples + tabentry->n_dead_tuples -
461                                         tabentry->last_anl_tuples;
462 #endif
463                         rstat->autovac_analyze_timestamp =
464                                 tabentry->autovac_analyze_timestamp;
465                         rstat->analyze_timestamp = tabentry->analyze_timestamp;
466                 }
467         }
468
469         if (naffected == 0)
470                 rstat->rereadStat = true;
471
472         if (newTable ||
473                 /* force analyze from after truncate */
474                 operation == CK_TRUNCATE || (
475                 /* do not analyze too often, if both stamps are exceeded the go */
476                 TimestampDifferenceExceeds(rstat->analyze_timestamp, now, online_analyze_min_interval) &&
477                 TimestampDifferenceExceeds(rstat->autovac_analyze_timestamp, now, online_analyze_min_interval) &&
478                 /* do not analyze too small tables */
479                 rstat->n_tuples + rstat->changes_since_analyze + naffected > online_analyze_lower_limit &&
480                 /* be in sync with relation_needs_vacanalyze */
481                 ((double)(rstat->changes_since_analyze + naffected)) >=
482                          online_analyze_scale_factor * ((double)rstat->n_tuples) +
483                          (double)online_analyze_threshold))
484         {
485 #if PG_VERSION_NUM < 90500
486                 VacuumStmt                              vacstmt;
487 #else
488                 VacuumParams                    vacstmt;
489 #endif
490                 TimestampTz                             startStamp, endStamp;
491
492
493                 memset(&startStamp, 0, sizeof(startStamp)); /* keep compiler quiet */
494
495                 memset(&vacstmt, 0, sizeof(vacstmt));
496
497                 vacstmt.freeze_min_age = -1;
498                 vacstmt.freeze_table_age = -1; /* ??? */
499
500 #if PG_VERSION_NUM < 90500
501                 vacstmt.type = T_VacuumStmt;
502                 vacstmt.relation = NULL;
503                 vacstmt.va_cols = NIL;
504 #if PG_VERSION_NUM >= 90000
505                 vacstmt.options = VACOPT_ANALYZE;
506                 if (online_analyze_verbose)
507                         vacstmt.options |= VACOPT_VERBOSE;
508 #else
509                 vacstmt.vacuum = vacstmt.full = false;
510                 vacstmt.analyze = true;
511                 vacstmt.verbose = online_analyze_verbose;
512 #endif
513 #else
514                 vacstmt.multixact_freeze_min_age = -1;
515                 vacstmt.multixact_freeze_table_age = -1;
516                 vacstmt.log_min_duration = -1;
517 #endif
518
519                 if (online_analyze_verbose)
520                         startStamp = GetCurrentTimestamp();
521
522                 analyze_rel(relOid,
523 #if PG_VERSION_NUM < 90500
524                         &vacstmt
525 #if PG_VERSION_NUM >= 90018
526                         , true
527 #endif
528                         , GetAccessStrategy(BAS_VACUUM)
529 #if (PG_VERSION_NUM >= 90000) && (PG_VERSION_NUM < 90004)
530                         , true
531 #endif
532 #else
533                         makeRangeVarFromOid(relOid),
534                         VACOPT_ANALYZE | ((online_analyze_verbose) ? VACOPT_VERBOSE : 0),
535                         &vacstmt, NULL, true, GetAccessStrategy(BAS_VACUUM)
536 #endif
537                 );
538
539                 if (online_analyze_verbose)
540                 {
541                         long    secs;
542                         int             microsecs;
543
544                         endStamp = GetCurrentTimestamp();
545                         TimestampDifference(startStamp, endStamp, &secs, &microsecs);
546                         elog(INFO, "analyze \"%s\" took %.02f seconds",
547                                 get_rel_name(relOid),
548                                 ((double)secs) + ((double)microsecs)/1.0e6);
549                 }
550
551                 rstat->autovac_analyze_timestamp = now;
552                 rstat->changes_since_analyze = 0;
553
554                 switch(operation)
555                 {
556                         case CK_INSERT:
557                                 rstat->n_tuples += naffected;
558                                 break;
559                         case CK_UPDATE:
560                                 rstat->n_tuples += naffected;
561                                 rstat->rereadStat = true;
562                                 break;
563                         case CK_DELETE:
564                                 rstat->rereadStat = true;
565                                 break;
566                         case CK_TRUNCATE:
567                                 rstat->n_tuples = 0;
568                                 break;
569                         default:
570                                 break;
571                 }
572
573                 /* update last analyze timestamp in local memory of backend */
574                 if (tabentry)
575                 {
576                         tabentry->analyze_timestamp = now;
577                         tabentry->changes_since_analyze = 0;
578                 }
579 #if 0
580                 /* force reload stat for new table */
581                 if (newTable)
582                         pgstat_clear_snapshot();
583 #endif
584         }
585         else
586         {
587 #if PG_VERSION_NUM >= 90000
588                 if (tabentry)
589                         tabentry->changes_since_analyze += naffected;
590 #endif
591                 switch(operation)
592                 {
593                         case CK_INSERT:
594                                 rstat->changes_since_analyze += naffected;
595                                 rstat->n_tuples += naffected;
596                                 break;
597                         case CK_UPDATE:
598                                 rstat->changes_since_analyze += 2 * naffected;
599                                 rstat->n_tuples += naffected;
600                         case CK_DELETE:
601                                 rstat->changes_since_analyze += naffected;
602                                 break;
603                         case CK_TRUNCATE:
604                                 rstat->changes_since_analyze = rstat->n_tuples;
605                                 rstat->n_tuples = 0;
606                                 break;
607                         default:
608                                 break;
609                 }
610         }
611
612         /* Reset local cache if we are over limit */
613         if (hash_get_num_entries(relstats) > online_analyze_capacity_threshold)
614                 relstatsInit();
615 }
616
617 extern PGDLLIMPORT void onlineAnalyzeHooker(QueryDesc *queryDesc);
618 void
619 onlineAnalyzeHooker(QueryDesc *queryDesc)
620 {
621         int64   naffected = -1;
622
623         if (queryDesc->estate)
624                 naffected = queryDesc->estate->es_processed;
625
626         if (online_analyze_enable && queryDesc->plannedstmt &&
627                         (queryDesc->operation == CMD_INSERT ||
628                          queryDesc->operation == CMD_UPDATE ||
629                          queryDesc->operation == CMD_DELETE
630 #if PG_VERSION_NUM < 90200
631                          || (queryDesc->operation == CMD_SELECT &&
632                                  queryDesc->plannedstmt->intoClause)
633 #endif
634                          ))
635         {
636 #if PG_VERSION_NUM < 90200
637                 if (queryDesc->operation == CMD_SELECT)
638                 {
639                         Oid     relOid = RangeVarGetRelid(queryDesc->plannedstmt->intoClause->rel, true);
640
641                         makeAnalyze(relOid, queryDesc->operation, naffected);
642                 }
643                 else
644 #endif
645                 if (queryDesc->plannedstmt->resultRelations &&
646                                  queryDesc->plannedstmt->rtable)
647                 {
648                         ListCell        *l;
649
650                         foreach(l, queryDesc->plannedstmt->resultRelations)
651                         {
652                                 int                             n = lfirst_int(l);
653                                 RangeTblEntry   *rte = list_nth(queryDesc->plannedstmt->rtable, n-1);
654
655                                 if (rte->rtekind == RTE_RELATION)
656                                         makeAnalyze(rte->relid, (CmdKind)queryDesc->operation, naffected);
657                         }
658                 }
659         }
660
661         if (oldExecutorEndHook)
662                 oldExecutorEndHook(queryDesc);
663         else
664                 standard_ExecutorEnd(queryDesc);
665 }
666
667 #if PG_VERSION_NUM >= 90200
668 static void
669 onlineAnalyzeHookerUtility(
670 #if PG_VERSION_NUM >= 100000
671                                                    PlannedStmt *pstmt,
672 #else
673                                                    Node *parsetree,
674 #endif
675                                                    const char *queryString,
676 #if PG_VERSION_NUM >= 90300
677                                                         ProcessUtilityContext context, ParamListInfo params,
678 #if PG_VERSION_NUM >= 100000
679                                                         QueryEnvironment *queryEnv,
680 #endif
681 #else
682                                                         ParamListInfo params, bool isTopLevel,
683 #endif
684                                                         DestReceiver *dest, char *completionTag) {
685         List            *tblnames = NIL;
686         CmdKind         op = CK_INSERT;
687 #if PG_VERSION_NUM >= 100000
688         Node            *parsetree = NULL;
689
690         if (pstmt->commandType == CMD_UTILITY)
691                 parsetree = pstmt->utilityStmt;
692 #endif
693
694         if (parsetree && online_analyze_enable)
695         {
696                 if (IsA(parsetree, CreateTableAsStmt) &&
697                         ((CreateTableAsStmt*)parsetree)->into)
698                 {
699                         tblnames =
700                                 list_make1((RangeVar*)copyObject(((CreateTableAsStmt*)parsetree)->into->rel));
701                         op = CK_CREATE;
702                 }
703                 else if (IsA(parsetree, TruncateStmt))
704                 {
705                         tblnames = list_copy(((TruncateStmt*)parsetree)->relations);
706                         op = CK_TRUNCATE;
707                 }
708         }
709
710 #if PG_VERSION_NUM >= 100000
711 #define parsetree pstmt
712 #endif
713
714         if (oldProcessUtilityHook)
715                 oldProcessUtilityHook(parsetree, queryString,
716 #if PG_VERSION_NUM >= 90300
717                                                           context, params,
718 #if PG_VERSION_NUM >= 100000
719                                                           queryEnv,
720 #endif
721 #else
722                                                           params, isTopLevel,
723 #endif
724                                                           dest, completionTag);
725         else
726                 standard_ProcessUtility(parsetree, queryString,
727 #if PG_VERSION_NUM >= 90300
728                                                                 context, params,
729 #if PG_VERSION_NUM >= 100000
730                                                                 queryEnv,
731 #endif
732 #else
733                                                                 params, isTopLevel,
734 #endif
735                                                                 dest, completionTag);
736
737 #if PG_VERSION_NUM >= 100000
738 #undef parsetree
739 #endif
740
741         if (tblnames) {
742                 ListCell        *l;
743
744                 foreach(l, tblnames)
745                 {
746                         RangeVar        *tblname = (RangeVar*)lfirst(l);
747                         Oid     tblOid = RangeVarGetRelid(tblname, NoLock, true);
748
749                         makeAnalyze(tblOid, op, -1);
750                 }
751         }
752 }
753 #endif
754
755 static void
756 relstatsInit(void)
757 {
758         HASHCTL hash_ctl;
759         int             flags = 0;
760
761         MemSet(&hash_ctl, 0, sizeof(hash_ctl));
762
763         hash_ctl.hash = oid_hash;
764         flags |= HASH_FUNCTION;
765
766         if (onlineAnalyzeMemoryContext)
767         {
768                 Assert(relstats != NULL);
769                 MemoryContextReset(onlineAnalyzeMemoryContext);
770         }
771         else
772         {
773                 Assert(relstats == NULL);
774                 onlineAnalyzeMemoryContext =
775                         AllocSetContextCreate(CacheMemoryContext,
776                                                                   "online_analyze storage context",
777 #if PG_VERSION_NUM < 90600
778                                                                   ALLOCSET_DEFAULT_MINSIZE,
779                                                                   ALLOCSET_DEFAULT_INITSIZE,
780                                                                   ALLOCSET_DEFAULT_MAXSIZE
781 #else
782                                                                   ALLOCSET_DEFAULT_SIZES
783 #endif
784                                                                  );
785         }
786
787         hash_ctl.hcxt = onlineAnalyzeMemoryContext;
788         flags |= HASH_CONTEXT;
789
790         hash_ctl.keysize = sizeof(Oid);
791
792         hash_ctl.entrysize = sizeof(OnlineAnalyzeTableStat);
793         flags |= HASH_ELEM;
794
795         relstats = hash_create("online_analyze storage", 1024, &hash_ctl, flags);
796 }
797
798 void _PG_init(void);
799 void
800 _PG_init(void)
801 {
802         relstatsInit();
803
804         oldExecutorEndHook = ExecutorEnd_hook;
805
806         ExecutorEnd_hook = onlineAnalyzeHooker;
807
808 #if PG_VERSION_NUM >= 90200
809         oldProcessUtilityHook = ProcessUtility_hook;
810
811         ProcessUtility_hook = onlineAnalyzeHookerUtility;
812 #endif
813
814
815         DefineCustomBoolVariable(
816                 "online_analyze.enable",
817                 "Enable on-line analyze",
818                 "Enables analyze of table directly after insert/update/delete/select into",
819                 &online_analyze_enable,
820 #if PG_VERSION_NUM >= 80400
821                 online_analyze_enable,
822 #endif
823                 PGC_USERSET,
824 #if PG_VERSION_NUM >= 80400
825                 GUC_NOT_IN_SAMPLE,
826 #if PG_VERSION_NUM >= 90100
827                 NULL,
828 #endif
829 #endif
830                 NULL,
831                 NULL
832         );
833
834         DefineCustomBoolVariable(
835                 "online_analyze.verbose",
836                 "Verbosity of on-line analyze",
837                 "Make ANALYZE VERBOSE after table's changes",
838                 &online_analyze_verbose,
839 #if PG_VERSION_NUM >= 80400
840                 online_analyze_verbose,
841 #endif
842                 PGC_USERSET,
843 #if PG_VERSION_NUM >= 80400
844                 GUC_NOT_IN_SAMPLE,
845 #if PG_VERSION_NUM >= 90100
846                 NULL,
847 #endif
848 #endif
849                 NULL,
850                 NULL
851         );
852
853         DefineCustomRealVariable(
854                 "online_analyze.scale_factor",
855                 "fraction of table size to start on-line analyze",
856                 "fraction of table size to start on-line analyze",
857                 &online_analyze_scale_factor,
858 #if PG_VERSION_NUM >= 80400
859                 online_analyze_scale_factor,
860 #endif
861                 0.0,
862                 1.0,
863                 PGC_USERSET,
864 #if PG_VERSION_NUM >= 80400
865                 GUC_NOT_IN_SAMPLE,
866 #if PG_VERSION_NUM >= 90100
867                 NULL,
868 #endif
869 #endif
870                 NULL,
871                 NULL
872         );
873
874         DefineCustomIntVariable(
875                 "online_analyze.threshold",
876                 "min number of row updates before on-line analyze",
877                 "min number of row updates before on-line analyze",
878                 &online_analyze_threshold,
879 #if PG_VERSION_NUM >= 80400
880                 online_analyze_threshold,
881 #endif
882                 0,
883                 0x7fffffff,
884                 PGC_USERSET,
885 #if PG_VERSION_NUM >= 80400
886                 GUC_NOT_IN_SAMPLE,
887 #if PG_VERSION_NUM >= 90100
888                 NULL,
889 #endif
890 #endif
891                 NULL,
892                 NULL
893         );
894
895         DefineCustomIntVariable(
896                 "online_analyze.capacity_threshold",
897                 "Max local cache table capacity",
898                 "Max local cache table capacity",
899                 &online_analyze_capacity_threshold,
900 #if PG_VERSION_NUM >= 80400
901                 online_analyze_capacity_threshold,
902 #endif
903                 0,
904                 0x7fffffff,
905                 PGC_USERSET,
906 #if PG_VERSION_NUM >= 80400
907                 GUC_NOT_IN_SAMPLE,
908 #if PG_VERSION_NUM >= 90100
909                 NULL,
910 #endif
911 #endif
912                 NULL,
913                 NULL
914         );
915
916         DefineCustomRealVariable(
917                 "online_analyze.min_interval",
918                 "minimum time interval between analyze call (in milliseconds)",
919                 "minimum time interval between analyze call (in milliseconds)",
920                 &online_analyze_min_interval,
921 #if PG_VERSION_NUM >= 80400
922                 online_analyze_min_interval,
923 #endif
924                 0.0,
925                 1e30,
926                 PGC_USERSET,
927 #if PG_VERSION_NUM >= 80400
928                 GUC_NOT_IN_SAMPLE,
929 #if PG_VERSION_NUM >= 90100
930                 NULL,
931 #endif
932 #endif
933                 NULL,
934                 NULL
935         );
936
937         DefineCustomEnumVariable(
938                 "online_analyze.table_type",
939                 "Type(s) of table for online analyze: all(default), persistent, temporary, none",
940                 NULL,
941                 &online_analyze_table_type,
942 #if PG_VERSION_NUM >= 80400
943                 online_analyze_table_type,
944 #endif
945                 online_analyze_table_type_options,
946                 PGC_USERSET,
947 #if PG_VERSION_NUM >= 80400
948                 GUC_NOT_IN_SAMPLE,
949 #if PG_VERSION_NUM >= 90100
950                 NULL,
951 #endif
952 #endif
953                 NULL,
954                 NULL
955         );
956
957         DefineCustomStringVariable(
958                 "online_analyze.exclude_tables",
959                 "List of tables which will not online analyze",
960                 NULL,
961                 &excludeTables.tableStr,
962 #if PG_VERSION_NUM >= 80400
963                 "",
964 #endif
965                 PGC_USERSET,
966                 0,
967 #if PG_VERSION_NUM >= 90100
968                 excludeTablesCheck,
969                 excludeTablesAssign,
970 #else
971                 excludeTablesAssign,
972 #endif
973                 excludeTablesShow
974         );
975
976         DefineCustomStringVariable(
977                 "online_analyze.include_tables",
978                 "List of tables which will online analyze",
979                 NULL,
980                 &includeTables.tableStr,
981 #if PG_VERSION_NUM >= 80400
982                 "",
983 #endif
984                 PGC_USERSET,
985                 0,
986 #if PG_VERSION_NUM >= 90100
987                 includeTablesCheck,
988                 includeTablesAssign,
989 #else
990                 includeTablesAssign,
991 #endif
992                 includeTablesShow
993         );
994
995         DefineCustomIntVariable(
996                 "online_analyze.lower_limit",
997                 "min number of rows in table to analyze",
998                 "min number of rows in table to analyze",
999                 &online_analyze_lower_limit,
1000 #if PG_VERSION_NUM >= 80400
1001                 online_analyze_lower_limit,
1002 #endif
1003                 0,
1004                 0x7fffffff,
1005                 PGC_USERSET,
1006 #if PG_VERSION_NUM >= 80400
1007                 GUC_NOT_IN_SAMPLE,
1008 #if PG_VERSION_NUM >= 90100
1009                 NULL,
1010 #endif
1011 #endif
1012                 NULL,
1013                 NULL
1014         );
1015
1016 }
1017
1018 void _PG_fini(void);
1019 void
1020 _PG_fini(void)
1021 {
1022         ExecutorEnd_hook = oldExecutorEndHook;
1023 #if PG_VERSION_NUM >= 90200
1024         ProcessUtility_hook = oldProcessUtilityHook;
1025 #endif
1026
1027         if (excludeTables.tables)
1028                 free(excludeTables.tables);
1029         if (includeTables.tables)
1030                 free(includeTables.tables);
1031
1032         excludeTables.tables = includeTables.tables = NULL;
1033         excludeTables.nTables = includeTables.nTables = 0;
1034 }