2 * Copyright (c) 2011 Teodor Sigaev <teodor@sigaev.ru>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
33 #include "miscadmin.h"
34 #include "access/transam.h"
35 #include "access/xact.h"
36 #include "catalog/namespace.h"
37 #include "commands/vacuum.h"
38 #include "executor/executor.h"
39 #include "nodes/nodes.h"
40 #include "nodes/parsenodes.h"
41 #include "storage/bufmgr.h"
42 #include "utils/builtins.h"
43 #include "utils/hsearch.h"
44 #include "utils/memutils.h"
45 #include "utils/lsyscache.h"
46 #include "utils/guc.h"
47 #if PG_VERSION_NUM >= 90200
48 #include "catalog/pg_class.h"
49 #include "nodes/primnodes.h"
50 #include "tcop/utility.h"
51 #include "utils/rel.h"
52 #include "utils/relcache.h"
53 #include "utils/timestamp.h"
54 #if PG_VERSION_NUM >= 90500
55 #include "nodes/makefuncs.h"
56 #if PG_VERSION_NUM >= 100000
57 #include "utils/varlena.h"
58 #include "utils/regproc.h"
59 #if PG_VERSION_NUM >= 130000
60 #include "common/hashfn.h"
66 #ifdef PG_MODULE_MAGIC
70 static bool online_analyze_enable = true;
71 static bool online_analyze_local_tracking = false;
72 static bool online_analyze_verbose = true;
73 static double online_analyze_scale_factor = 0.1;
74 static int online_analyze_threshold = 50;
75 static int online_analyze_capacity_threshold = 100000;
76 static double online_analyze_min_interval = 10000;
77 static int online_analyze_lower_limit = 0;
79 static ExecutorEnd_hook_type oldExecutorEndHook = NULL;
80 #if PG_VERSION_NUM >= 90200
81 static ProcessUtility_hook_type oldProcessUtilityHook = NULL;
84 #if PG_VERSION_NUM >= 120000
85 #define VACOPT_NOWAIT VACOPT_SKIP_LOCKED
90 CK_SELECT = CMD_SELECT,
91 CK_UPDATE = CMD_UPDATE,
92 CK_INSERT = CMD_INSERT,
93 CK_DELETE = CMD_DELETE,
105 OATT_PERSISTENT = 0x01,
106 OATT_TEMPORARY = 0x02,
108 } OnlineAnalyzeTableType;
110 static const struct config_enum_entry online_analyze_table_type_options[] =
112 {"all", OATT_ALL, false},
113 {"persistent", OATT_PERSISTENT, false},
114 {"temporary", OATT_TEMPORARY, false},
115 {"none", OATT_NONE, false},
119 static int online_analyze_table_type = (int)OATT_ALL;
121 typedef struct TableList {
128 static TableList excludeTables = {0, NULL, NULL, false};
129 static TableList includeTables = {0, NULL, NULL, false};
131 typedef struct OnlineAnalyzeTableStat {
134 PgStat_Counter n_tuples;
135 PgStat_Counter mod_since_analyze;
136 TimestampTz last_autoanalyze_time;
137 TimestampTz last_analyze_time;
138 } OnlineAnalyzeTableStat;
140 static MemoryContext onlineAnalyzeMemoryContext = NULL;
141 static HTAB *relstats = NULL;
143 static void relstatsInit(void);
145 #if PG_VERSION_NUM < 100000
147 oid_cmp(const void *a, const void *b)
149 if (*(Oid*)a == *(Oid*)b)
151 return (*(Oid*)a > *(Oid*)b) ? 1 : -1;
156 tableListAssign(const char * newval, bool doit, TableList *tbl)
165 rawname = pstrdup(newval);
167 if (!SplitIdentifierString(rawname, ',', &namelist))
171 * follow work could be done only in normal processing because of
172 * accsess to system catalog
174 if (MyBackendId == InvalidBackendId || !IsUnderPostmaster ||
175 !IsTransactionState())
177 includeTables.inited = false;
178 excludeTables.inited = false;
184 nOids = list_length(namelist);
185 newOids = malloc(sizeof(Oid) * (nOids+1));
187 elog(ERROR,"could not allocate %d bytes",
188 (int)(sizeof(Oid) * (nOids+1)));
193 char *curname = (char *) lfirst(l);
194 #if PG_VERSION_NUM >= 160000
195 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
196 stringToQualifiedNameList(curname, NULL)), NoLock, true);
197 #elif PG_VERSION_NUM >= 90200
198 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
199 stringToQualifiedNameList(curname)), NoLock, true);
201 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
202 stringToQualifiedNameList(curname)), true);
205 if (relOid == InvalidOid)
207 #if PG_VERSION_NUM >= 90100
210 elog(WARNING,"'%s' does not exist", curname);
213 else if ( get_rel_relkind(relOid) != RELKIND_RELATION )
215 #if PG_VERSION_NUM >= 90100
218 elog(WARNING,"'%s' is not an table", curname);
223 newOids[i++] = relOid;
232 tbl->tables = newOids;
233 if (tbl->nTables > 1)
234 qsort(tbl->tables, tbl->nTables, sizeof(tbl->tables[0]), oid_cmp);
250 #if PG_VERSION_NUM >= 90100
252 excludeTablesCheck(char **newval, void **extra, GucSource source)
256 val = (char*)tableListAssign(*newval, false, &excludeTables);
268 excludeTablesAssign(const char *newval, void *extra)
270 tableListAssign(newval, true, &excludeTables);
274 includeTablesCheck(char **newval, void **extra, GucSource source)
278 val = (char*)tableListAssign(*newval, false, &includeTables);
290 includeTablesAssign(const char *newval, void *extra)
292 tableListAssign(newval, true, &includeTables);
295 #else /* PG_VERSION_NUM < 90100 */
298 excludeTablesAssign(const char * newval, bool doit, GucSource source)
300 return tableListAssign(newval, doit, &excludeTables);
304 includeTablesAssign(const char * newval, bool doit, GucSource source)
306 return tableListAssign(newval, doit, &includeTables);
314 TableList *tl[] = {&includeTables, &excludeTables};
317 if (MyBackendId == InvalidBackendId || !IsUnderPostmaster ||
318 !IsTransactionState())
319 return; /* we aren't in connected state */
321 for(i=0; i<lengthof(tl); i++)
323 TableList *tbl = tl[i];
325 if (tbl->inited == false)
326 tableListAssign(tbl->tableStr, true, tbl);
332 tableListShow(TableList *tbl)
340 len = 1 /* \0 */ + tbl->nTables * (2 * NAMEDATALEN + 2 /* ', ' */ + 1 /* . */);
341 ptr = val = palloc(len);
343 for(i=0; i<tbl->nTables; i++)
345 char *relname = get_rel_name(tbl->tables[i]);
346 Oid nspOid = get_rel_namespace(tbl->tables[i]);
347 char *nspname = get_namespace_name(nspOid);
349 if ( relname == NULL || nspOid == InvalidOid || nspname == NULL )
352 ptr += snprintf(ptr, len - (ptr - val), "%s%s.%s",
361 excludeTablesShow(void)
363 return tableListShow(&excludeTables);
367 includeTablesShow(void)
369 return tableListShow(&includeTables);
373 matchOid(TableList *tbl, Oid oid)
375 Oid *StopLow = tbl->tables,
376 *StopHigh = tbl->tables + tbl->nTables,
379 /* Loop invariant: StopLow <= val < StopHigh */
380 while (StopLow < StopHigh)
382 StopMiddle = StopLow + ((StopHigh - StopLow) >> 1);
384 if (*StopMiddle == oid)
386 else if (*StopMiddle < oid)
387 StopLow = StopMiddle + 1;
389 StopHigh = StopMiddle;
395 #if PG_VERSION_NUM >= 90500
397 makeRangeVarFromOid(Oid relOid)
400 get_namespace_name(get_rel_namespace(relOid)),
401 get_rel_name(relOid),
409 makeAnalyze(Oid relOid, CmdKind operation, int64 naffected)
411 TimestampTz now = GetCurrentTimestamp();
413 OnlineAnalyzeTableType reltype;
416 OnlineAnalyzeTableStat *rstat,
418 PgStat_StatTabEntry *tabentry = NULL;
420 if (relOid == InvalidOid)
424 /* return if there is no changes */
426 else if (naffected < 0)
427 /* number if affected rows is unknown */
430 rel = RelationIdGetRelation(relOid);
431 if (rel->rd_rel->relkind != RELKIND_RELATION)
438 #if PG_VERSION_NUM >= 90100
439 (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
441 (rel->rd_istemp || rel->rd_islocaltemp)
443 ? OATT_TEMPORARY : OATT_PERSISTENT;
448 * includeTables overwrites excludeTables
450 switch(online_analyze_table_type)
453 if (get_rel_relkind(relOid) != RELKIND_RELATION ||
454 (matchOid(&excludeTables, relOid) == true &&
455 matchOid(&includeTables, relOid) == false))
459 if (get_rel_relkind(relOid) != RELKIND_RELATION ||
460 matchOid(&includeTables, relOid) == false)
464 case OATT_PERSISTENT:
467 * skip analyze if relation's type doesn't not match
468 * online_analyze_table_type
470 if ((online_analyze_table_type & reltype) == 0 ||
471 matchOid(&excludeTables, relOid) == true)
473 if (matchOid(&includeTables, relOid) == false)
480 * Do not store data about persistent table in local memory because we
481 * could not track changes of them: they could be changed by another
482 * backends. So always get a pgstat table entry.
484 if (reltype == OATT_TEMPORARY)
485 rstat = hash_search(relstats, &relOid, HASH_ENTER, &found);
487 rstat = &dummyrstat; /* found == false for following if */
491 MemSet(rstat, 0, sizeof(*rstat));
492 rstat->tableid = relOid;
496 if (operation == CK_VACUUM)
498 /* force reread because vacuum could change n_tuples */
499 rstat->rereadStat = true;
502 else if (operation == CK_ANALYZE)
505 rstat->mod_since_analyze = 0;
506 rstat->last_analyze_time = now;
508 rstat->rereadStat = true;
512 Assert(rstat->tableid == relOid);
515 /* do not reread data if it was a truncation */
516 operation != CK_TRUNCATE && operation != CK_FASTTRUNCATE &&
517 /* read for persistent table and for temp teble if it allowed */
518 (reltype == OATT_PERSISTENT || online_analyze_local_tracking == false) &&
519 /* read only for new table or we know that it's needed */
520 (newTable == true || rstat->rereadStat == true)
523 rstat->rereadStat = false;
525 tabentry = pgstat_fetch_stat_tabentry(relOid);
530 #if PG_VERSION_NUM >= 160000
531 tabentry->dead_tuples + tabentry->live_tuples;
533 tabentry->n_dead_tuples + tabentry->n_live_tuples;
536 rstat->mod_since_analyze =
537 #if PG_VERSION_NUM >= 160000
538 tabentry->mod_since_analyze;
539 #elif PG_VERSION_NUM >= 90000
540 tabentry->changes_since_analyze;
542 tabentry->n_live_tuples + tabentry->n_dead_tuples -
543 tabentry->last_anl_tuples;
546 rstat->last_autoanalyze_time =
547 #if PG_VERSION_NUM >= 160000
548 tabentry->last_autoanalyze_time;
550 tabentry->autovac_analyze_timestamp;
553 rstat->last_analyze_time =
554 #if PG_VERSION_NUM >= 160000
555 tabentry->last_analyze_time;
557 tabentry->analyze_timestamp;
563 /* force analyze after truncate, fasttruncate already did analyze */
564 operation == CK_TRUNCATE || (
565 /* do not analyze too often, if both stamps are exceeded the go */
566 TimestampDifferenceExceeds(rstat->last_analyze_time, now, online_analyze_min_interval) &&
567 TimestampDifferenceExceeds(rstat->last_autoanalyze_time, now, online_analyze_min_interval) &&
568 /* do not analyze too small tables */
569 rstat->n_tuples + rstat->mod_since_analyze + naffected > online_analyze_lower_limit &&
570 /* be in sync with relation_needs_vacanalyze */
571 ((double)(rstat->mod_since_analyze + naffected)) >=
572 online_analyze_scale_factor * ((double)rstat->n_tuples) +
573 (double)online_analyze_threshold))
575 #if PG_VERSION_NUM < 90500
578 VacuumParams vacstmt;
580 TimestampTz startStamp, endStamp;
584 /* ATX is not compatible with online_analyze */
585 if (getNestLevelATX() != 0)
589 memset(&startStamp, 0, sizeof(startStamp)); /* keep compiler quiet */
591 memset(&vacstmt, 0, sizeof(vacstmt));
593 vacstmt.freeze_min_age = -1;
594 vacstmt.freeze_table_age = -1; /* ??? */
596 #if PG_VERSION_NUM < 90500
597 vacstmt.type = T_VacuumStmt;
598 vacstmt.relation = NULL;
599 vacstmt.va_cols = NIL;
600 #if PG_VERSION_NUM >= 90000
601 vacstmt.options = VACOPT_ANALYZE;
602 if (online_analyze_verbose)
603 vacstmt.options |= VACOPT_VERBOSE;
605 vacstmt.vacuum = vacstmt.full = false;
606 vacstmt.analyze = true;
607 vacstmt.verbose = online_analyze_verbose;
610 vacstmt.multixact_freeze_min_age = -1;
611 vacstmt.multixact_freeze_table_age = -1;
612 vacstmt.log_min_duration = -1;
616 if (online_analyze_verbose)
617 startStamp = GetCurrentTimestamp();
619 flags = VACOPT_ANALYZE | VACOPT_NOWAIT |
620 ((online_analyze_verbose) ? VACOPT_VERBOSE : 0);
622 #if PG_VERSION_NUM >= 120000
623 vacstmt.options = flags;
626 #if PG_VERSION_NUM < 90500
628 #if PG_VERSION_NUM >= 90018
631 , GetAccessStrategy(BAS_VACUUM)
632 #if (PG_VERSION_NUM >= 90000) && (PG_VERSION_NUM < 90004)
636 makeRangeVarFromOid(relOid),
637 #if PG_VERSION_NUM < 120000
640 &vacstmt, NULL, true, GetAccessStrategy(BAS_VACUUM)
644 /* Make changes visible to subsequent calls */
645 CommandCounterIncrement();
647 if (online_analyze_verbose)
652 endStamp = GetCurrentTimestamp();
653 TimestampDifference(startStamp, endStamp, &secs, µsecs);
654 elog(INFO, "analyze \"%s\" took %.02f seconds",
655 get_rel_name(relOid),
656 ((double)secs) + ((double)microsecs)/1.0e6);
659 rstat->last_autoanalyze_time = now;
660 rstat->mod_since_analyze = 0;
667 rstat->n_tuples += naffected;
670 rstat->rereadStat = (reltype == OATT_PERSISTENT);
673 case CK_FASTTRUNCATE:
674 rstat->rereadStat = false;
681 /* update last analyze timestamp in local memory of backend */
684 #if PG_VERSION_NUM >= 160000
685 tabentry->last_analyze_time = now;
686 tabentry->mod_since_analyze = 0;
688 tabentry->analyze_timestamp = now;
689 tabentry->changes_since_analyze = 0;
693 /* force reload stat for new table */
695 pgstat_clear_snapshot();
700 #if PG_VERSION_NUM >= 90000
702 #if PG_VERSION_NUM >= 160000
703 tabentry->mod_since_analyze += naffected;
705 tabentry->changes_since_analyze += naffected;
712 rstat->mod_since_analyze += naffected;
713 rstat->n_tuples += naffected;
716 rstat->mod_since_analyze += 2 * naffected;
717 rstat->n_tuples += naffected;
720 rstat->mod_since_analyze += naffected;
723 case CK_FASTTRUNCATE:
724 rstat->mod_since_analyze = 0;
732 /* Reset local cache if we are over limit */
733 if (hash_get_num_entries(relstats) > online_analyze_capacity_threshold)
738 isFastTruncateCall(QueryDesc *queryDesc)
745 queryDesc->plannedstmt &&
746 queryDesc->operation == CMD_SELECT &&
747 queryDesc->plannedstmt->planTree &&
748 queryDesc->plannedstmt->planTree->targetlist &&
749 list_length(queryDesc->plannedstmt->planTree->targetlist) == 1
753 te = linitial(queryDesc->plannedstmt->planTree->targetlist);
755 if (!IsA(te, TargetEntry))
758 fe = (FuncExpr*)te->expr;
761 fe && IsA(fe, FuncExpr) &&
762 fe->funcid >= FirstNormalObjectId &&
763 fe->funcretset == false &&
764 fe->funcresulttype == VOIDOID &&
765 fe->funcvariadic == false &&
766 list_length(fe->args) == 1
770 constval = linitial(fe->args);
773 IsA(constval,Const) &&
774 constval->consttype == TEXTOID &&
775 strcmp(get_func_name(fe->funcid), "fasttruncate") == 0
783 extern PGDLLIMPORT void onlineAnalyzeHooker(QueryDesc *queryDesc);
785 onlineAnalyzeHooker(QueryDesc *queryDesc)
787 int64 naffected = -1;
790 if (queryDesc->estate)
791 naffected = queryDesc->estate->es_processed;
795 #if PG_VERSION_NUM >= 90200
796 if (online_analyze_enable &&
797 (constval = isFastTruncateCall(queryDesc)) != NULL)
799 Datum tblnamed = constval->constvalue;
800 char *tblname = text_to_cstring(DatumGetTextP(tblnamed));
801 #if PG_VERSION_NUM >= 160000
803 makeRangeVarFromNameList(stringToQualifiedNameList(tblname, NULL));
806 makeRangeVarFromNameList(stringToQualifiedNameList(tblname));
809 makeAnalyze(RangeVarGetRelid(tblvar,
812 CK_FASTTRUNCATE, -1);
816 if (online_analyze_enable && queryDesc->plannedstmt &&
817 (queryDesc->operation == CMD_INSERT ||
818 queryDesc->operation == CMD_UPDATE ||
819 queryDesc->operation == CMD_DELETE
820 #if PG_VERSION_NUM < 90200
821 || (queryDesc->operation == CMD_SELECT &&
822 queryDesc->plannedstmt->intoClause)
826 #if PG_VERSION_NUM < 90200
827 if (queryDesc->operation == CMD_SELECT)
829 Oid relOid = RangeVarGetRelid(queryDesc->plannedstmt->intoClause->rel, true);
831 makeAnalyze(relOid, queryDesc->operation, naffected);
835 if (queryDesc->plannedstmt->resultRelations &&
836 queryDesc->plannedstmt->rtable)
840 foreach(l, queryDesc->plannedstmt->resultRelations)
842 int n = lfirst_int(l);
843 RangeTblEntry *rte = list_nth(queryDesc->plannedstmt->rtable, n-1);
845 if (rte->rtekind == RTE_RELATION)
846 makeAnalyze(rte->relid, (CmdKind)queryDesc->operation, naffected);
851 if (oldExecutorEndHook)
852 oldExecutorEndHook(queryDesc);
854 standard_ExecutorEnd(queryDesc);
857 static List *toremove = NIL;
860 * removeTable called on transaction end, see call RegisterXactCallback() below
863 removeTable(XactEvent event, void *arg)
869 case XACT_EVENT_COMMIT:
871 case XACT_EVENT_ABORT:
877 foreach(cell, toremove)
879 Oid relOid = lfirst_oid(cell);
881 hash_search(relstats, &relOid, HASH_REMOVE, NULL);
887 #if PG_VERSION_NUM >= 120000
889 parse_vacuum_opt(VacuumStmt *vacstmt)
891 int options = vacstmt->is_vacuumcmd ? VACOPT_VACUUM : VACOPT_ANALYZE;
894 foreach(lc, vacstmt->options)
896 DefElem *opt = (DefElem *) lfirst(lc);
898 /* Parse common options for VACUUM and ANALYZE */
899 if (strcmp(opt->defname, "verbose") == 0)
900 options |= VACOPT_VERBOSE;
901 else if (strcmp(opt->defname, "skip_locked") == 0)
902 options |= VACOPT_SKIP_LOCKED;
903 else if (strcmp(opt->defname, "analyze") == 0)
904 options |= VACOPT_ANALYZE;
905 else if (strcmp(opt->defname, "freeze") == 0)
906 options |= VACOPT_FREEZE;
907 else if (strcmp(opt->defname, "full") == 0)
908 options |= VACOPT_FULL;
909 else if (strcmp(opt->defname, "disable_page_skipping") == 0)
910 options |= VACOPT_DISABLE_PAGE_SKIPPING;
918 #if PG_VERSION_NUM >= 90200
920 onlineAnalyzeHookerUtility(
921 #if PG_VERSION_NUM >= 100000
926 const char *queryString,
927 #if PG_VERSION_NUM >= 140000
930 #if PG_VERSION_NUM >= 90300
931 ProcessUtilityContext context, ParamListInfo params,
932 #if PG_VERSION_NUM >= 100000
933 QueryEnvironment *queryEnv,
936 ParamListInfo params, bool isTopLevel,
939 #if PG_VERSION_NUM >= 130000
940 QueryCompletion *completionTag
945 List *tblnames = NIL;
946 CmdKind op = CK_INSERT;
947 #if PG_VERSION_NUM >= 100000
948 Node *parsetree = NULL;
950 if (pstmt->commandType == CMD_UTILITY)
951 parsetree = pstmt->utilityStmt;
956 if (parsetree && online_analyze_enable)
958 if (IsA(parsetree, CreateTableAsStmt) &&
959 ((CreateTableAsStmt*)parsetree)->into)
962 list_make1((RangeVar*)copyObject(((CreateTableAsStmt*)parsetree)->into->rel));
965 else if (IsA(parsetree, TruncateStmt))
967 tblnames = list_copy(((TruncateStmt*)parsetree)->relations);
970 else if (IsA(parsetree, DropStmt) &&
971 ((DropStmt*)parsetree)->removeType == OBJECT_TABLE)
975 foreach(cell, ((DropStmt*)parsetree)->objects)
977 List *relname = (List *) lfirst(cell);
978 RangeVar *rel = makeRangeVarFromNameList(relname);
979 Oid relOid = RangeVarGetRelid(rel, NoLock, true);
981 if (OidIsValid(relOid))
985 ctx = MemoryContextSwitchTo(TopTransactionContext);
986 toremove = lappend_oid(toremove, relOid);
987 MemoryContextSwitchTo(ctx);
991 else if (IsA(parsetree, VacuumStmt))
993 VacuumStmt *vac = (VacuumStmt*)parsetree;
995 #if PG_VERSION_NUM >= 120000
996 parse_vacuum_opt(vac)
1003 #if PG_VERSION_NUM >= 110000
1004 tblnames = vac->rels;
1007 tblnames = list_make1(vac->relation);
1010 if (options & (VACOPT_VACUUM | VACOPT_FULL | VACOPT_FREEZE))
1012 /* optionally with analyze */
1015 /* drop all collected stat */
1016 if (tblnames == NIL)
1019 else if (options & VACOPT_ANALYZE)
1023 /* should reset all counters */
1024 if (tblnames == NIL)
1027 OnlineAnalyzeTableStat *rstat;
1028 TimestampTz now = GetCurrentTimestamp();
1030 hash_seq_init(&hs, relstats);
1032 while((rstat = hash_seq_search(&hs)) != NULL)
1034 rstat->mod_since_analyze = 0;
1035 rstat->last_analyze_time = now;
1044 #if PG_VERSION_NUM >= 100000
1045 #define parsetree pstmt
1048 if (oldProcessUtilityHook)
1049 oldProcessUtilityHook(parsetree, queryString,
1050 #if PG_VERSION_NUM >= 140000
1053 #if PG_VERSION_NUM >= 90300
1055 #if PG_VERSION_NUM >= 100000
1061 dest, completionTag);
1063 standard_ProcessUtility(parsetree, queryString,
1064 #if PG_VERSION_NUM >= 140000
1067 #if PG_VERSION_NUM >= 90300
1069 #if PG_VERSION_NUM >= 100000
1075 dest, completionTag);
1077 #if PG_VERSION_NUM >= 100000
1084 foreach(l, tblnames)
1087 #if PG_VERSION_NUM >= 110000
1088 (IsA(lfirst(l), VacuumRelation)) ?
1089 ((VacuumRelation*)lfirst(l))->relation :
1091 (RangeVar*)lfirst(l);
1094 Assert(IsA(tblname, RangeVar));
1096 tblOid = RangeVarGetRelid(tblname, NoLock, true);
1097 makeAnalyze(tblOid, op, -1);
1110 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
1112 hash_ctl.hash = oid_hash;
1113 flags |= HASH_FUNCTION;
1115 if (onlineAnalyzeMemoryContext)
1117 Assert(relstats != NULL);
1118 MemoryContextReset(onlineAnalyzeMemoryContext);
1122 Assert(relstats == NULL);
1124 #if PG_VERSION_NUM < 90600
1125 onlineAnalyzeMemoryContext =
1126 AllocSetContextCreate(CacheMemoryContext,
1127 "online_analyze storage context",
1128 ALLOCSET_DEFAULT_MINSIZE,
1129 ALLOCSET_DEFAULT_INITSIZE,
1130 ALLOCSET_DEFAULT_MAXSIZE
1133 onlineAnalyzeMemoryContext =
1134 AllocSetContextCreate(CacheMemoryContext,
1135 "online_analyze storage context", ALLOCSET_DEFAULT_SIZES);
1139 hash_ctl.hcxt = onlineAnalyzeMemoryContext;
1140 flags |= HASH_CONTEXT;
1142 hash_ctl.keysize = sizeof(Oid);
1144 hash_ctl.entrysize = sizeof(OnlineAnalyzeTableStat);
1147 relstats = hash_create("online_analyze storage", 1024, &hash_ctl, flags);
1150 void _PG_init(void);
1156 oldExecutorEndHook = ExecutorEnd_hook;
1158 ExecutorEnd_hook = onlineAnalyzeHooker;
1160 #if PG_VERSION_NUM >= 90200
1161 oldProcessUtilityHook = ProcessUtility_hook;
1163 ProcessUtility_hook = onlineAnalyzeHookerUtility;
1167 DefineCustomBoolVariable(
1168 "online_analyze.enable",
1169 "Enable on-line analyze",
1170 "Enables analyze of table directly after insert/update/delete/select into",
1171 &online_analyze_enable,
1172 #if PG_VERSION_NUM >= 80400
1173 online_analyze_enable,
1176 #if PG_VERSION_NUM >= 80400
1178 #if PG_VERSION_NUM >= 90100
1186 DefineCustomBoolVariable(
1187 "online_analyze.local_tracking",
1188 "Per backend tracking",
1189 "Per backend tracking for temp tables (do not use system statistic)",
1190 &online_analyze_local_tracking,
1191 #if PG_VERSION_NUM >= 80400
1192 online_analyze_local_tracking,
1195 #if PG_VERSION_NUM >= 80400
1197 #if PG_VERSION_NUM >= 90100
1205 DefineCustomBoolVariable(
1206 "online_analyze.verbose",
1207 "Verbosity of on-line analyze",
1208 "Make ANALYZE VERBOSE after table's changes",
1209 &online_analyze_verbose,
1210 #if PG_VERSION_NUM >= 80400
1211 online_analyze_verbose,
1214 #if PG_VERSION_NUM >= 80400
1216 #if PG_VERSION_NUM >= 90100
1224 DefineCustomRealVariable(
1225 "online_analyze.scale_factor",
1226 "fraction of table size to start on-line analyze",
1227 "fraction of table size to start on-line analyze",
1228 &online_analyze_scale_factor,
1229 #if PG_VERSION_NUM >= 80400
1230 online_analyze_scale_factor,
1235 #if PG_VERSION_NUM >= 80400
1237 #if PG_VERSION_NUM >= 90100
1245 DefineCustomIntVariable(
1246 "online_analyze.threshold",
1247 "min number of row updates before on-line analyze",
1248 "min number of row updates before on-line analyze",
1249 &online_analyze_threshold,
1250 #if PG_VERSION_NUM >= 80400
1251 online_analyze_threshold,
1256 #if PG_VERSION_NUM >= 80400
1258 #if PG_VERSION_NUM >= 90100
1266 DefineCustomIntVariable(
1267 "online_analyze.capacity_threshold",
1268 "Max local cache table capacity",
1269 "Max local cache table capacity",
1270 &online_analyze_capacity_threshold,
1271 #if PG_VERSION_NUM >= 80400
1272 online_analyze_capacity_threshold,
1277 #if PG_VERSION_NUM >= 80400
1279 #if PG_VERSION_NUM >= 90100
1287 DefineCustomRealVariable(
1288 "online_analyze.min_interval",
1289 "minimum time interval between analyze call (in milliseconds)",
1290 "minimum time interval between analyze call (in milliseconds)",
1291 &online_analyze_min_interval,
1292 #if PG_VERSION_NUM >= 80400
1293 online_analyze_min_interval,
1298 #if PG_VERSION_NUM >= 80400
1300 #if PG_VERSION_NUM >= 90100
1308 DefineCustomEnumVariable(
1309 "online_analyze.table_type",
1310 "Type(s) of table for online analyze: all(default), persistent, temporary, none",
1312 &online_analyze_table_type,
1313 #if PG_VERSION_NUM >= 80400
1314 online_analyze_table_type,
1316 online_analyze_table_type_options,
1318 #if PG_VERSION_NUM >= 80400
1320 #if PG_VERSION_NUM >= 90100
1328 DefineCustomStringVariable(
1329 "online_analyze.exclude_tables",
1330 "List of tables which will not online analyze",
1332 &excludeTables.tableStr,
1333 #if PG_VERSION_NUM >= 80400
1338 #if PG_VERSION_NUM >= 90100
1340 excludeTablesAssign,
1342 excludeTablesAssign,
1347 DefineCustomStringVariable(
1348 "online_analyze.include_tables",
1349 "List of tables which will online analyze",
1351 &includeTables.tableStr,
1352 #if PG_VERSION_NUM >= 80400
1357 #if PG_VERSION_NUM >= 90100
1359 includeTablesAssign,
1361 includeTablesAssign,
1366 DefineCustomIntVariable(
1367 "online_analyze.lower_limit",
1368 "min number of rows in table to analyze",
1369 "min number of rows in table to analyze",
1370 &online_analyze_lower_limit,
1371 #if PG_VERSION_NUM >= 80400
1372 online_analyze_lower_limit,
1377 #if PG_VERSION_NUM >= 80400
1379 #if PG_VERSION_NUM >= 90100
1387 RegisterXactCallback(removeTable, NULL);
1390 #if PG_VERSION_NUM < 150000
1391 void _PG_fini(void);
1395 ExecutorEnd_hook = oldExecutorEndHook;
1396 #if PG_VERSION_NUM >= 90200
1397 ProcessUtility_hook = oldProcessUtilityHook;
1400 if (excludeTables.tables)
1401 free(excludeTables.tables);
1402 if (includeTables.tables)
1403 free(includeTables.tables);
1405 excludeTables.tables = includeTables.tables = NULL;
1406 excludeTables.nTables = includeTables.nTables = 0;