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 PG_VERSION_NUM >= 170000
175 if (MyProcNumber == INVALID_PROC_NUMBER ||
177 if (MyBackendId == InvalidBackendId ||
179 !IsUnderPostmaster ||
180 !IsTransactionState())
182 includeTables.inited = false;
183 excludeTables.inited = false;
189 nOids = list_length(namelist);
190 newOids = malloc(sizeof(Oid) * (nOids+1));
192 elog(ERROR,"could not allocate %d bytes",
193 (int)(sizeof(Oid) * (nOids+1)));
198 char *curname = (char *) lfirst(l);
199 #if PG_VERSION_NUM >= 160000
200 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
201 stringToQualifiedNameList(curname, NULL)), NoLock, true);
202 #elif PG_VERSION_NUM >= 90200
203 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
204 stringToQualifiedNameList(curname)), NoLock, true);
206 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
207 stringToQualifiedNameList(curname)), true);
210 if (relOid == InvalidOid)
212 #if PG_VERSION_NUM >= 90100
215 elog(WARNING,"'%s' does not exist", curname);
218 else if ( get_rel_relkind(relOid) != RELKIND_RELATION )
220 #if PG_VERSION_NUM >= 90100
223 elog(WARNING,"'%s' is not an table", curname);
228 newOids[i++] = relOid;
237 tbl->tables = newOids;
238 if (tbl->nTables > 1)
239 qsort(tbl->tables, tbl->nTables, sizeof(tbl->tables[0]), oid_cmp);
255 #if PG_VERSION_NUM >= 90100
257 excludeTablesCheck(char **newval, void **extra, GucSource source)
261 val = (char*)tableListAssign(*newval, false, &excludeTables);
273 excludeTablesAssign(const char *newval, void *extra)
275 tableListAssign(newval, true, &excludeTables);
279 includeTablesCheck(char **newval, void **extra, GucSource source)
283 val = (char*)tableListAssign(*newval, false, &includeTables);
295 includeTablesAssign(const char *newval, void *extra)
297 tableListAssign(newval, true, &includeTables);
300 #else /* PG_VERSION_NUM < 90100 */
303 excludeTablesAssign(const char * newval, bool doit, GucSource source)
305 return tableListAssign(newval, doit, &excludeTables);
309 includeTablesAssign(const char * newval, bool doit, GucSource source)
311 return tableListAssign(newval, doit, &includeTables);
319 TableList *tl[] = {&includeTables, &excludeTables};
322 #if PG_VERSION_NUM >= 170000
323 if (MyProcNumber == INVALID_PROC_NUMBER ||
325 if (MyBackendId == InvalidBackendId ||
327 !IsUnderPostmaster ||
328 !IsTransactionState())
329 return; /* we aren't in connected state */
331 for(i=0; i<lengthof(tl); i++)
333 TableList *tbl = tl[i];
335 if (tbl->inited == false)
336 tableListAssign(tbl->tableStr, true, tbl);
342 tableListShow(TableList *tbl)
350 len = 1 /* \0 */ + tbl->nTables * (2 * NAMEDATALEN + 2 /* ', ' */ + 1 /* . */);
351 ptr = val = palloc(len);
353 for(i=0; i<tbl->nTables; i++)
355 char *relname = get_rel_name(tbl->tables[i]);
356 Oid nspOid = get_rel_namespace(tbl->tables[i]);
357 char *nspname = get_namespace_name(nspOid);
359 if ( relname == NULL || nspOid == InvalidOid || nspname == NULL )
362 ptr += snprintf(ptr, len - (ptr - val), "%s%s.%s",
371 excludeTablesShow(void)
373 return tableListShow(&excludeTables);
377 includeTablesShow(void)
379 return tableListShow(&includeTables);
383 matchOid(TableList *tbl, Oid oid)
385 Oid *StopLow = tbl->tables,
386 *StopHigh = tbl->tables + tbl->nTables,
389 /* Loop invariant: StopLow <= val < StopHigh */
390 while (StopLow < StopHigh)
392 StopMiddle = StopLow + ((StopHigh - StopLow) >> 1);
394 if (*StopMiddle == oid)
396 else if (*StopMiddle < oid)
397 StopLow = StopMiddle + 1;
399 StopHigh = StopMiddle;
405 #if PG_VERSION_NUM >= 90500
407 makeRangeVarFromOid(Oid relOid)
410 get_namespace_name(get_rel_namespace(relOid)),
411 get_rel_name(relOid),
419 makeAnalyze(Oid relOid, CmdKind operation, int64 naffected)
421 TimestampTz now = GetCurrentTimestamp();
423 OnlineAnalyzeTableType reltype;
426 OnlineAnalyzeTableStat *rstat,
428 PgStat_StatTabEntry *tabentry = NULL;
430 if (relOid == InvalidOid)
434 /* return if there is no changes */
436 else if (naffected < 0)
437 /* number if affected rows is unknown */
440 rel = RelationIdGetRelation(relOid);
441 if (rel->rd_rel->relkind != RELKIND_RELATION)
448 #if PG_VERSION_NUM >= 90100
449 (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
451 (rel->rd_istemp || rel->rd_islocaltemp)
453 ? OATT_TEMPORARY : OATT_PERSISTENT;
458 * includeTables overwrites excludeTables
460 switch(online_analyze_table_type)
463 if (get_rel_relkind(relOid) != RELKIND_RELATION ||
464 (matchOid(&excludeTables, relOid) == true &&
465 matchOid(&includeTables, relOid) == false))
469 if (get_rel_relkind(relOid) != RELKIND_RELATION ||
470 matchOid(&includeTables, relOid) == false)
474 case OATT_PERSISTENT:
477 * skip analyze if relation's type doesn't not match
478 * online_analyze_table_type
480 if ((online_analyze_table_type & reltype) == 0 ||
481 matchOid(&excludeTables, relOid) == true)
483 if (matchOid(&includeTables, relOid) == false)
490 * Do not store data about persistent table in local memory because we
491 * could not track changes of them: they could be changed by another
492 * backends. So always get a pgstat table entry.
494 if (reltype == OATT_TEMPORARY)
495 rstat = hash_search(relstats, &relOid, HASH_ENTER, &found);
497 rstat = &dummyrstat; /* found == false for following if */
501 MemSet(rstat, 0, sizeof(*rstat));
502 rstat->tableid = relOid;
506 if (operation == CK_VACUUM)
508 /* force reread because vacuum could change n_tuples */
509 rstat->rereadStat = true;
512 else if (operation == CK_ANALYZE)
515 rstat->mod_since_analyze = 0;
516 rstat->last_analyze_time = now;
518 rstat->rereadStat = true;
522 Assert(rstat->tableid == relOid);
525 /* do not reread data if it was a truncation */
526 operation != CK_TRUNCATE && operation != CK_FASTTRUNCATE &&
527 /* read for persistent table and for temp teble if it allowed */
528 (reltype == OATT_PERSISTENT || online_analyze_local_tracking == false) &&
529 /* read only for new table or we know that it's needed */
530 (newTable == true || rstat->rereadStat == true)
533 rstat->rereadStat = false;
535 tabentry = pgstat_fetch_stat_tabentry(relOid);
540 #if PG_VERSION_NUM >= 160000
541 tabentry->dead_tuples + tabentry->live_tuples;
543 tabentry->n_dead_tuples + tabentry->n_live_tuples;
546 rstat->mod_since_analyze =
547 #if PG_VERSION_NUM >= 160000
548 tabentry->mod_since_analyze;
549 #elif PG_VERSION_NUM >= 90000
550 tabentry->changes_since_analyze;
552 tabentry->n_live_tuples + tabentry->n_dead_tuples -
553 tabentry->last_anl_tuples;
556 rstat->last_autoanalyze_time =
557 #if PG_VERSION_NUM >= 160000
558 tabentry->last_autoanalyze_time;
560 tabentry->autovac_analyze_timestamp;
563 rstat->last_analyze_time =
564 #if PG_VERSION_NUM >= 160000
565 tabentry->last_analyze_time;
567 tabentry->analyze_timestamp;
573 /* force analyze after truncate, fasttruncate already did analyze */
574 operation == CK_TRUNCATE || (
575 /* do not analyze too often, if both stamps are exceeded the go */
576 TimestampDifferenceExceeds(rstat->last_analyze_time, now, online_analyze_min_interval) &&
577 TimestampDifferenceExceeds(rstat->last_autoanalyze_time, now, online_analyze_min_interval) &&
578 /* do not analyze too small tables */
579 rstat->n_tuples + rstat->mod_since_analyze + naffected > online_analyze_lower_limit &&
580 /* be in sync with relation_needs_vacanalyze */
581 ((double)(rstat->mod_since_analyze + naffected)) >=
582 online_analyze_scale_factor * ((double)rstat->n_tuples) +
583 (double)online_analyze_threshold))
585 #if PG_VERSION_NUM < 90500
588 VacuumParams vacstmt;
590 TimestampTz startStamp, endStamp;
594 /* ATX is not compatible with online_analyze */
595 if (getNestLevelATX() != 0)
599 memset(&startStamp, 0, sizeof(startStamp)); /* keep compiler quiet */
601 memset(&vacstmt, 0, sizeof(vacstmt));
603 vacstmt.freeze_min_age = -1;
604 vacstmt.freeze_table_age = -1; /* ??? */
606 #if PG_VERSION_NUM < 90500
607 vacstmt.type = T_VacuumStmt;
608 vacstmt.relation = NULL;
609 vacstmt.va_cols = NIL;
610 #if PG_VERSION_NUM >= 90000
611 vacstmt.options = VACOPT_ANALYZE;
612 if (online_analyze_verbose)
613 vacstmt.options |= VACOPT_VERBOSE;
615 vacstmt.vacuum = vacstmt.full = false;
616 vacstmt.analyze = true;
617 vacstmt.verbose = online_analyze_verbose;
620 vacstmt.multixact_freeze_min_age = -1;
621 vacstmt.multixact_freeze_table_age = -1;
622 vacstmt.log_min_duration = -1;
626 if (online_analyze_verbose)
627 startStamp = GetCurrentTimestamp();
629 flags = VACOPT_ANALYZE | VACOPT_NOWAIT |
630 ((online_analyze_verbose) ? VACOPT_VERBOSE : 0);
632 #if PG_VERSION_NUM >= 120000
633 vacstmt.options = flags;
636 #if PG_VERSION_NUM < 90500
638 #if PG_VERSION_NUM >= 90018
641 , GetAccessStrategy(BAS_VACUUM)
642 #if (PG_VERSION_NUM >= 90000) && (PG_VERSION_NUM < 90004)
646 makeRangeVarFromOid(relOid),
647 #if PG_VERSION_NUM < 120000
650 &vacstmt, NULL, true, GetAccessStrategy(BAS_VACUUM)
654 /* Make changes visible to subsequent calls */
655 CommandCounterIncrement();
657 if (online_analyze_verbose)
662 endStamp = GetCurrentTimestamp();
663 TimestampDifference(startStamp, endStamp, &secs, µsecs);
664 elog(INFO, "analyze \"%s\" took %.02f seconds",
665 get_rel_name(relOid),
666 ((double)secs) + ((double)microsecs)/1.0e6);
669 rstat->last_autoanalyze_time = now;
670 rstat->mod_since_analyze = 0;
677 rstat->n_tuples += naffected;
680 rstat->rereadStat = (reltype == OATT_PERSISTENT);
683 case CK_FASTTRUNCATE:
684 rstat->rereadStat = false;
691 /* update last analyze timestamp in local memory of backend */
694 #if PG_VERSION_NUM >= 160000
695 tabentry->last_analyze_time = now;
696 tabentry->mod_since_analyze = 0;
698 tabentry->analyze_timestamp = now;
699 tabentry->changes_since_analyze = 0;
703 /* force reload stat for new table */
705 pgstat_clear_snapshot();
710 #if PG_VERSION_NUM >= 90000
712 #if PG_VERSION_NUM >= 160000
713 tabentry->mod_since_analyze += naffected;
715 tabentry->changes_since_analyze += naffected;
722 rstat->mod_since_analyze += naffected;
723 rstat->n_tuples += naffected;
726 rstat->mod_since_analyze += 2 * naffected;
727 rstat->n_tuples += naffected;
730 rstat->mod_since_analyze += naffected;
733 case CK_FASTTRUNCATE:
734 rstat->mod_since_analyze = 0;
742 /* Reset local cache if we are over limit */
743 if (hash_get_num_entries(relstats) > online_analyze_capacity_threshold)
748 isFastTruncateCall(QueryDesc *queryDesc)
755 queryDesc->plannedstmt &&
756 queryDesc->operation == CMD_SELECT &&
757 queryDesc->plannedstmt->planTree &&
758 queryDesc->plannedstmt->planTree->targetlist &&
759 list_length(queryDesc->plannedstmt->planTree->targetlist) == 1
763 te = linitial(queryDesc->plannedstmt->planTree->targetlist);
765 if (!IsA(te, TargetEntry))
768 fe = (FuncExpr*)te->expr;
771 fe && IsA(fe, FuncExpr) &&
772 fe->funcid >= FirstNormalObjectId &&
773 fe->funcretset == false &&
774 fe->funcresulttype == VOIDOID &&
775 fe->funcvariadic == false &&
776 list_length(fe->args) == 1
780 constval = linitial(fe->args);
783 IsA(constval,Const) &&
784 constval->consttype == TEXTOID &&
785 strcmp(get_func_name(fe->funcid), "fasttruncate") == 0
793 extern PGDLLIMPORT void onlineAnalyzeHooker(QueryDesc *queryDesc);
795 onlineAnalyzeHooker(QueryDesc *queryDesc)
797 int64 naffected = -1;
800 if (queryDesc->estate)
801 naffected = queryDesc->estate->es_processed;
805 #if PG_VERSION_NUM >= 90200
806 if (online_analyze_enable &&
807 (constval = isFastTruncateCall(queryDesc)) != NULL)
809 Datum tblnamed = constval->constvalue;
810 char *tblname = text_to_cstring(DatumGetTextP(tblnamed));
811 #if PG_VERSION_NUM >= 160000
813 makeRangeVarFromNameList(stringToQualifiedNameList(tblname, NULL));
816 makeRangeVarFromNameList(stringToQualifiedNameList(tblname));
819 makeAnalyze(RangeVarGetRelid(tblvar,
822 CK_FASTTRUNCATE, -1);
826 if (online_analyze_enable && queryDesc->plannedstmt &&
827 (queryDesc->operation == CMD_INSERT ||
828 queryDesc->operation == CMD_UPDATE ||
829 queryDesc->operation == CMD_DELETE
830 #if PG_VERSION_NUM < 90200
831 || (queryDesc->operation == CMD_SELECT &&
832 queryDesc->plannedstmt->intoClause)
836 #if PG_VERSION_NUM < 90200
837 if (queryDesc->operation == CMD_SELECT)
839 Oid relOid = RangeVarGetRelid(queryDesc->plannedstmt->intoClause->rel, true);
841 makeAnalyze(relOid, queryDesc->operation, naffected);
845 if (queryDesc->plannedstmt->resultRelations &&
846 queryDesc->plannedstmt->rtable)
850 foreach(l, queryDesc->plannedstmt->resultRelations)
852 int n = lfirst_int(l);
853 RangeTblEntry *rte = list_nth(queryDesc->plannedstmt->rtable, n-1);
855 if (rte->rtekind == RTE_RELATION)
856 makeAnalyze(rte->relid, (CmdKind)queryDesc->operation, naffected);
861 if (oldExecutorEndHook)
862 oldExecutorEndHook(queryDesc);
864 standard_ExecutorEnd(queryDesc);
867 static List *toremove = NIL;
870 * removeTable called on transaction end, see call RegisterXactCallback() below
873 removeTable(XactEvent event, void *arg)
879 case XACT_EVENT_COMMIT:
881 case XACT_EVENT_ABORT:
887 foreach(cell, toremove)
889 Oid relOid = lfirst_oid(cell);
891 hash_search(relstats, &relOid, HASH_REMOVE, NULL);
897 #if PG_VERSION_NUM >= 120000
899 parse_vacuum_opt(VacuumStmt *vacstmt)
901 int options = vacstmt->is_vacuumcmd ? VACOPT_VACUUM : VACOPT_ANALYZE;
904 foreach(lc, vacstmt->options)
906 DefElem *opt = (DefElem *) lfirst(lc);
908 /* Parse common options for VACUUM and ANALYZE */
909 if (strcmp(opt->defname, "verbose") == 0)
910 options |= VACOPT_VERBOSE;
911 else if (strcmp(opt->defname, "skip_locked") == 0)
912 options |= VACOPT_SKIP_LOCKED;
913 else if (strcmp(opt->defname, "analyze") == 0)
914 options |= VACOPT_ANALYZE;
915 else if (strcmp(opt->defname, "freeze") == 0)
916 options |= VACOPT_FREEZE;
917 else if (strcmp(opt->defname, "full") == 0)
918 options |= VACOPT_FULL;
919 else if (strcmp(opt->defname, "disable_page_skipping") == 0)
920 options |= VACOPT_DISABLE_PAGE_SKIPPING;
928 #if PG_VERSION_NUM >= 90200
930 onlineAnalyzeHookerUtility(
931 #if PG_VERSION_NUM >= 100000
936 const char *queryString,
937 #if PG_VERSION_NUM >= 140000
940 #if PG_VERSION_NUM >= 90300
941 ProcessUtilityContext context, ParamListInfo params,
942 #if PG_VERSION_NUM >= 100000
943 QueryEnvironment *queryEnv,
946 ParamListInfo params, bool isTopLevel,
949 #if PG_VERSION_NUM >= 130000
950 QueryCompletion *completionTag
955 List *tblnames = NIL;
956 CmdKind op = CK_INSERT;
957 #if PG_VERSION_NUM >= 100000
958 Node *parsetree = NULL;
960 if (pstmt->commandType == CMD_UTILITY)
961 parsetree = pstmt->utilityStmt;
966 if (parsetree && online_analyze_enable)
968 if (IsA(parsetree, CreateTableAsStmt) &&
969 ((CreateTableAsStmt*)parsetree)->into)
972 list_make1((RangeVar*)copyObject(((CreateTableAsStmt*)parsetree)->into->rel));
975 else if (IsA(parsetree, TruncateStmt))
977 tblnames = list_copy(((TruncateStmt*)parsetree)->relations);
980 else if (IsA(parsetree, DropStmt) &&
981 ((DropStmt*)parsetree)->removeType == OBJECT_TABLE)
985 foreach(cell, ((DropStmt*)parsetree)->objects)
987 List *relname = (List *) lfirst(cell);
988 RangeVar *rel = makeRangeVarFromNameList(relname);
989 Oid relOid = RangeVarGetRelid(rel, NoLock, true);
991 if (OidIsValid(relOid))
995 ctx = MemoryContextSwitchTo(TopTransactionContext);
996 toremove = lappend_oid(toremove, relOid);
997 MemoryContextSwitchTo(ctx);
1001 else if (IsA(parsetree, VacuumStmt))
1003 VacuumStmt *vac = (VacuumStmt*)parsetree;
1005 #if PG_VERSION_NUM >= 120000
1006 parse_vacuum_opt(vac)
1013 #if PG_VERSION_NUM >= 110000
1014 tblnames = vac->rels;
1017 tblnames = list_make1(vac->relation);
1020 if (options & (VACOPT_VACUUM | VACOPT_FULL | VACOPT_FREEZE))
1022 /* optionally with analyze */
1025 /* drop all collected stat */
1026 if (tblnames == NIL)
1029 else if (options & VACOPT_ANALYZE)
1033 /* should reset all counters */
1034 if (tblnames == NIL)
1037 OnlineAnalyzeTableStat *rstat;
1038 TimestampTz now = GetCurrentTimestamp();
1040 hash_seq_init(&hs, relstats);
1042 while((rstat = hash_seq_search(&hs)) != NULL)
1044 rstat->mod_since_analyze = 0;
1045 rstat->last_analyze_time = now;
1054 #if PG_VERSION_NUM >= 100000
1055 #define parsetree pstmt
1058 if (oldProcessUtilityHook)
1059 oldProcessUtilityHook(parsetree, queryString,
1060 #if PG_VERSION_NUM >= 140000
1063 #if PG_VERSION_NUM >= 90300
1065 #if PG_VERSION_NUM >= 100000
1071 dest, completionTag);
1073 standard_ProcessUtility(parsetree, queryString,
1074 #if PG_VERSION_NUM >= 140000
1077 #if PG_VERSION_NUM >= 90300
1079 #if PG_VERSION_NUM >= 100000
1085 dest, completionTag);
1087 #if PG_VERSION_NUM >= 100000
1094 foreach(l, tblnames)
1097 #if PG_VERSION_NUM >= 110000
1098 (IsA(lfirst(l), VacuumRelation)) ?
1099 ((VacuumRelation*)lfirst(l))->relation :
1101 (RangeVar*)lfirst(l);
1104 Assert(IsA(tblname, RangeVar));
1106 tblOid = RangeVarGetRelid(tblname, NoLock, true);
1107 makeAnalyze(tblOid, op, -1);
1120 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
1122 hash_ctl.hash = oid_hash;
1123 flags |= HASH_FUNCTION;
1125 if (onlineAnalyzeMemoryContext)
1127 Assert(relstats != NULL);
1128 MemoryContextReset(onlineAnalyzeMemoryContext);
1132 Assert(relstats == NULL);
1134 #if PG_VERSION_NUM < 90600
1135 onlineAnalyzeMemoryContext =
1136 AllocSetContextCreate(CacheMemoryContext,
1137 "online_analyze storage context",
1138 ALLOCSET_DEFAULT_MINSIZE,
1139 ALLOCSET_DEFAULT_INITSIZE,
1140 ALLOCSET_DEFAULT_MAXSIZE
1143 onlineAnalyzeMemoryContext =
1144 AllocSetContextCreate(CacheMemoryContext,
1145 "online_analyze storage context", ALLOCSET_DEFAULT_SIZES);
1149 hash_ctl.hcxt = onlineAnalyzeMemoryContext;
1150 flags |= HASH_CONTEXT;
1152 hash_ctl.keysize = sizeof(Oid);
1154 hash_ctl.entrysize = sizeof(OnlineAnalyzeTableStat);
1157 relstats = hash_create("online_analyze storage", 1024, &hash_ctl, flags);
1160 void _PG_init(void);
1166 oldExecutorEndHook = ExecutorEnd_hook;
1168 ExecutorEnd_hook = onlineAnalyzeHooker;
1170 #if PG_VERSION_NUM >= 90200
1171 oldProcessUtilityHook = ProcessUtility_hook;
1173 ProcessUtility_hook = onlineAnalyzeHookerUtility;
1177 DefineCustomBoolVariable(
1178 "online_analyze.enable",
1179 "Enable on-line analyze",
1180 "Enables analyze of table directly after insert/update/delete/select into",
1181 &online_analyze_enable,
1182 #if PG_VERSION_NUM >= 80400
1183 online_analyze_enable,
1186 #if PG_VERSION_NUM >= 80400
1188 #if PG_VERSION_NUM >= 90100
1196 DefineCustomBoolVariable(
1197 "online_analyze.local_tracking",
1198 "Per backend tracking",
1199 "Per backend tracking for temp tables (do not use system statistic)",
1200 &online_analyze_local_tracking,
1201 #if PG_VERSION_NUM >= 80400
1202 online_analyze_local_tracking,
1205 #if PG_VERSION_NUM >= 80400
1207 #if PG_VERSION_NUM >= 90100
1215 DefineCustomBoolVariable(
1216 "online_analyze.verbose",
1217 "Verbosity of on-line analyze",
1218 "Make ANALYZE VERBOSE after table's changes",
1219 &online_analyze_verbose,
1220 #if PG_VERSION_NUM >= 80400
1221 online_analyze_verbose,
1224 #if PG_VERSION_NUM >= 80400
1226 #if PG_VERSION_NUM >= 90100
1234 DefineCustomRealVariable(
1235 "online_analyze.scale_factor",
1236 "fraction of table size to start on-line analyze",
1237 "fraction of table size to start on-line analyze",
1238 &online_analyze_scale_factor,
1239 #if PG_VERSION_NUM >= 80400
1240 online_analyze_scale_factor,
1245 #if PG_VERSION_NUM >= 80400
1247 #if PG_VERSION_NUM >= 90100
1255 DefineCustomIntVariable(
1256 "online_analyze.threshold",
1257 "min number of row updates before on-line analyze",
1258 "min number of row updates before on-line analyze",
1259 &online_analyze_threshold,
1260 #if PG_VERSION_NUM >= 80400
1261 online_analyze_threshold,
1266 #if PG_VERSION_NUM >= 80400
1268 #if PG_VERSION_NUM >= 90100
1276 DefineCustomIntVariable(
1277 "online_analyze.capacity_threshold",
1278 "Max local cache table capacity",
1279 "Max local cache table capacity",
1280 &online_analyze_capacity_threshold,
1281 #if PG_VERSION_NUM >= 80400
1282 online_analyze_capacity_threshold,
1287 #if PG_VERSION_NUM >= 80400
1289 #if PG_VERSION_NUM >= 90100
1297 DefineCustomRealVariable(
1298 "online_analyze.min_interval",
1299 "minimum time interval between analyze call (in milliseconds)",
1300 "minimum time interval between analyze call (in milliseconds)",
1301 &online_analyze_min_interval,
1302 #if PG_VERSION_NUM >= 80400
1303 online_analyze_min_interval,
1308 #if PG_VERSION_NUM >= 80400
1310 #if PG_VERSION_NUM >= 90100
1318 DefineCustomEnumVariable(
1319 "online_analyze.table_type",
1320 "Type(s) of table for online analyze: all(default), persistent, temporary, none",
1322 &online_analyze_table_type,
1323 #if PG_VERSION_NUM >= 80400
1324 online_analyze_table_type,
1326 online_analyze_table_type_options,
1328 #if PG_VERSION_NUM >= 80400
1330 #if PG_VERSION_NUM >= 90100
1338 DefineCustomStringVariable(
1339 "online_analyze.exclude_tables",
1340 "List of tables which will not online analyze",
1342 &excludeTables.tableStr,
1343 #if PG_VERSION_NUM >= 80400
1348 #if PG_VERSION_NUM >= 90100
1350 excludeTablesAssign,
1352 excludeTablesAssign,
1357 DefineCustomStringVariable(
1358 "online_analyze.include_tables",
1359 "List of tables which will online analyze",
1361 &includeTables.tableStr,
1362 #if PG_VERSION_NUM >= 80400
1367 #if PG_VERSION_NUM >= 90100
1369 includeTablesAssign,
1371 includeTablesAssign,
1376 DefineCustomIntVariable(
1377 "online_analyze.lower_limit",
1378 "min number of rows in table to analyze",
1379 "min number of rows in table to analyze",
1380 &online_analyze_lower_limit,
1381 #if PG_VERSION_NUM >= 80400
1382 online_analyze_lower_limit,
1387 #if PG_VERSION_NUM >= 80400
1389 #if PG_VERSION_NUM >= 90100
1397 RegisterXactCallback(removeTable, NULL);
1400 #if PG_VERSION_NUM < 150000
1401 void _PG_fini(void);
1405 ExecutorEnd_hook = oldExecutorEndHook;
1406 #if PG_VERSION_NUM >= 90200
1407 ProcessUtility_hook = oldProcessUtilityHook;
1410 if (excludeTables.tables)
1411 free(excludeTables.tables);
1412 if (includeTables.tables)
1413 free(includeTables.tables);
1415 excludeTables.tables = includeTables.tables = NULL;
1416 excludeTables.nTables = includeTables.nTables = 0;