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 "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"
60 #ifdef PG_MODULE_MAGIC
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;
71 static ExecutorEnd_hook_type oldExecutorEndHook = NULL;
72 #if PG_VERSION_NUM >= 90200
73 static ProcessUtility_hook_type oldProcessUtilityHook = NULL;
78 CK_SELECT = CMD_SELECT,
79 CK_UPDATE = CMD_UPDATE,
80 CK_INSERT = CMD_INSERT,
81 CK_DELETE = CMD_DELETE,
89 OATT_PERSISTENT = 0x01,
90 OATT_TEMPORARY = 0x02,
92 } OnlineAnalyzeTableType;
94 static const struct config_enum_entry online_analyze_table_type_options[] =
96 {"all", OATT_ALL, false},
97 {"persistent", OATT_PERSISTENT, false},
98 {"temporary", OATT_TEMPORARY, false},
99 {"none", OATT_NONE, false},
103 static int online_analyze_table_type = (int)OATT_ALL;
105 typedef struct TableList {
111 static TableList excludeTables = {0, NULL, NULL};
112 static TableList includeTables = {0, NULL, NULL};
114 typedef struct OnlineAnalyzeTableStat {
117 PgStat_Counter n_tuples;
118 PgStat_Counter changes_since_analyze;
119 TimestampTz autovac_analyze_timestamp;
120 TimestampTz analyze_timestamp;
121 } OnlineAnalyzeTableStat;
123 static MemoryContext onlineAnalyzeMemoryContext = NULL;
124 static HTAB *relstats = NULL;
126 static void relstatsInit(void);
128 #if PG_VERSION_NUM < 100000
130 oid_cmp(const void *a, const void *b)
132 if (*(Oid*)a == *(Oid*)b)
134 return (*(Oid*)a > *(Oid*)b) ? 1 : -1;
139 tableListAssign(const char * newval, bool doit, TableList *tbl)
148 rawname = pstrdup(newval);
150 if (!SplitIdentifierString(rawname, ',', &namelist))
155 nOids = list_length(namelist);
156 newOids = malloc(sizeof(Oid) * (nOids+1));
158 elog(ERROR,"could not allocate %d bytes",
159 (int)(sizeof(Oid) * (nOids+1)));
164 char *curname = (char *) lfirst(l);
165 #if PG_VERSION_NUM >= 90200
166 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
167 stringToQualifiedNameList(curname)), NoLock, true);
169 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
170 stringToQualifiedNameList(curname)), true);
173 if (relOid == InvalidOid)
175 #if PG_VERSION_NUM >= 90100
178 elog(WARNING,"'%s' does not exist", curname);
181 else if ( get_rel_relkind(relOid) != RELKIND_RELATION )
183 #if PG_VERSION_NUM >= 90100
186 elog(WARNING,"'%s' is not an table", curname);
191 newOids[i++] = relOid;
200 tbl->tables = newOids;
201 if (tbl->nTables > 1)
202 qsort(tbl->tables, tbl->nTables, sizeof(tbl->tables[0]), oid_cmp);
218 #if PG_VERSION_NUM >= 90100
220 excludeTablesCheck(char **newval, void **extra, GucSource source)
224 val = (char*)tableListAssign(*newval, false, &excludeTables);
236 excludeTablesAssign(const char *newval, void *extra)
238 tableListAssign(newval, true, &excludeTables);
242 includeTablesCheck(char **newval, void **extra, GucSource source)
246 val = (char*)tableListAssign(*newval, false, &includeTables);
258 includeTablesAssign(const char *newval, void *extra)
260 tableListAssign(newval, true, &excludeTables);
263 #else /* PG_VERSION_NUM < 90100 */
266 excludeTablesAssign(const char * newval, bool doit, GucSource source)
268 return tableListAssign(newval, doit, &excludeTables);
272 includeTablesAssign(const char * newval, bool doit, GucSource source)
274 return tableListAssign(newval, doit, &includeTables);
280 tableListShow(TableList *tbl)
286 len = 1 /* \0 */ + tbl->nTables * (2 * NAMEDATALEN + 2 /* ', ' */ + 1 /* . */);
287 ptr = val = palloc(len);
289 for(i=0; i<tbl->nTables; i++)
291 char *relname = get_rel_name(tbl->tables[i]);
292 Oid nspOid = get_rel_namespace(tbl->tables[i]);
293 char *nspname = get_namespace_name(nspOid);
295 if ( relname == NULL || nspOid == InvalidOid || nspname == NULL )
298 ptr += snprintf(ptr, len - (ptr - val), "%s%s.%s",
307 excludeTablesShow(void)
309 return tableListShow(&excludeTables);
313 includeTablesShow(void)
315 return tableListShow(&includeTables);
319 matchOid(TableList *tbl, Oid oid)
321 Oid *StopLow = tbl->tables,
322 *StopHigh = tbl->tables + tbl->nTables,
325 /* Loop invariant: StopLow <= val < StopHigh */
326 while (StopLow < StopHigh)
328 StopMiddle = StopLow + ((StopHigh - StopLow) >> 1);
330 if (*StopMiddle == oid)
332 else if (*StopMiddle < oid)
333 StopLow = StopMiddle + 1;
335 StopHigh = StopMiddle;
341 #if PG_VERSION_NUM >= 90500
343 makeRangeVarFromOid(Oid relOid)
346 get_namespace_name(get_rel_namespace(relOid)),
347 get_rel_name(relOid),
355 makeAnalyze(Oid relOid, CmdKind operation, int32 naffected)
357 TimestampTz now = GetCurrentTimestamp();
359 OnlineAnalyzeTableType reltype;
362 OnlineAnalyzeTableStat *rstat,
364 PgStat_StatTabEntry *tabentry = NULL;
366 if (relOid == InvalidOid)
370 /* return if there is no changes */
372 else if (naffected < 0)
373 /* number if affected rows is unknown */
376 rel = RelationIdGetRelation(relOid);
377 if (rel->rd_rel->relkind != RELKIND_RELATION)
384 #if PG_VERSION_NUM >= 90100
385 (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
387 (rel->rd_istemp || rel->rd_islocaltemp)
389 ? OATT_TEMPORARY : OATT_PERSISTENT;
394 * includeTables overwrites excludeTables
396 switch(online_analyze_table_type)
399 if (get_rel_relkind(relOid) != RELKIND_RELATION ||
400 (matchOid(&excludeTables, relOid) == true &&
401 matchOid(&includeTables, relOid) == false))
405 if (get_rel_relkind(relOid) != RELKIND_RELATION ||
406 matchOid(&includeTables, relOid) == false)
410 case OATT_PERSISTENT:
413 * skip analyze if relation's type doesn't not match
414 * online_analyze_table_type
416 if ((online_analyze_table_type & reltype) == 0 ||
417 matchOid(&excludeTables, relOid) == true)
419 if (matchOid(&includeTables, relOid) == false)
426 * Do not store data about persistent table in local memory because we
427 * could not track changes of them: they could be changed by another
428 * backends. So always get a pgstat table entry.
430 if (reltype == OATT_TEMPORARY)
431 rstat = hash_search(relstats, &relOid, HASH_ENTER, &found);
433 rstat = &dummyrstat; /* found == false for following if */
437 MemSet(rstat, 0, sizeof(*rstat));
438 rstat->tableid = relOid;
442 Assert(rstat->tableid == relOid);
444 if (operation != CK_TRUNCATE &&
445 (found == false || rstat->rereadStat == true))
448 rstat->rereadStat = false;
450 tabentry = pgstat_fetch_stat_tabentry(relOid);
454 rstat->n_tuples = tabentry->n_dead_tuples + tabentry->n_live_tuples;
455 rstat->changes_since_analyze =
456 #if PG_VERSION_NUM >= 90000
457 tabentry->changes_since_analyze;
459 tabentry->n_live_tuples + tabentry->n_dead_tuples -
460 tabentry->last_anl_tuples;
462 rstat->autovac_analyze_timestamp =
463 tabentry->autovac_analyze_timestamp;
464 rstat->analyze_timestamp = tabentry->analyze_timestamp;
469 rstat->rereadStat = true;
472 /* force analyze from after truncate */
473 operation == CK_TRUNCATE || (
474 /* do not analyze too often, if both stamps are exceeded the go */
475 TimestampDifferenceExceeds(rstat->analyze_timestamp, now, online_analyze_min_interval) &&
476 TimestampDifferenceExceeds(rstat->autovac_analyze_timestamp, now, online_analyze_min_interval) &&
477 /* be in sync with relation_needs_vacanalyze */
478 ((double)(rstat->changes_since_analyze + naffected)) >=
479 online_analyze_scale_factor * ((double)rstat->n_tuples) +
480 (double)online_analyze_threshold))
482 #if PG_VERSION_NUM < 90500
485 VacuumParams vacstmt;
487 TimestampTz startStamp, endStamp;
490 memset(&startStamp, 0, sizeof(startStamp)); /* keep compiler quiet */
492 memset(&vacstmt, 0, sizeof(vacstmt));
494 vacstmt.freeze_min_age = -1;
495 vacstmt.freeze_table_age = -1; /* ??? */
497 #if PG_VERSION_NUM < 90500
498 vacstmt.type = T_VacuumStmt;
499 vacstmt.relation = NULL;
500 vacstmt.va_cols = NIL;
501 #if PG_VERSION_NUM >= 90000
502 vacstmt.options = VACOPT_ANALYZE;
503 if (online_analyze_verbose)
504 vacstmt.options |= VACOPT_VERBOSE;
506 vacstmt.vacuum = vacstmt.full = false;
507 vacstmt.analyze = true;
508 vacstmt.verbose = online_analyze_verbose;
511 vacstmt.multixact_freeze_min_age = -1;
512 vacstmt.multixact_freeze_table_age = -1;
513 vacstmt.log_min_duration = -1;
516 if (online_analyze_verbose)
517 startStamp = GetCurrentTimestamp();
520 #if PG_VERSION_NUM < 90500
522 #if PG_VERSION_NUM >= 90018
525 , GetAccessStrategy(BAS_VACUUM)
526 #if (PG_VERSION_NUM >= 90000) && (PG_VERSION_NUM < 90004)
530 makeRangeVarFromOid(relOid),
531 VACOPT_ANALYZE | ((online_analyze_verbose) ? VACOPT_VERBOSE : 0),
532 &vacstmt, NULL, true, GetAccessStrategy(BAS_VACUUM)
536 if (online_analyze_verbose)
541 endStamp = GetCurrentTimestamp();
542 TimestampDifference(startStamp, endStamp, &secs, µsecs);
543 elog(INFO, "analyze \"%s\" took %.02f seconds",
544 get_rel_name(relOid),
545 ((double)secs) + ((double)microsecs)/1.0e6);
548 rstat->autovac_analyze_timestamp = now;
549 rstat->changes_since_analyze = 0;
554 rstat->n_tuples += naffected;
557 rstat->n_tuples += naffected;
558 rstat->rereadStat = true;
561 rstat->rereadStat = true;
570 /* update last analyze timestamp in local memory of backend */
573 tabentry->analyze_timestamp = now;
574 tabentry->changes_since_analyze = 0;
577 /* force reload stat for new table */
579 pgstat_clear_snapshot();
584 #if PG_VERSION_NUM >= 90000
586 tabentry->changes_since_analyze += naffected;
591 rstat->changes_since_analyze += naffected;
592 rstat->n_tuples += naffected;
595 rstat->changes_since_analyze += 2 * naffected;
596 rstat->n_tuples += naffected;
598 rstat->changes_since_analyze += naffected;
601 rstat->changes_since_analyze = rstat->n_tuples;
609 /* Reset local cache if we are over limit */
610 if (hash_get_num_entries(relstats) > online_analyze_capacity_threshold)
614 extern PGDLLIMPORT void onlineAnalyzeHooker(QueryDesc *queryDesc);
616 onlineAnalyzeHooker(QueryDesc *queryDesc)
618 uint32 naffected = -1;
620 if (queryDesc->estate)
621 naffected = queryDesc->estate->es_processed;
623 if (online_analyze_enable && queryDesc->plannedstmt &&
624 (queryDesc->operation == CMD_INSERT ||
625 queryDesc->operation == CMD_UPDATE ||
626 queryDesc->operation == CMD_DELETE
627 #if PG_VERSION_NUM < 90200
628 || (queryDesc->operation == CMD_SELECT &&
629 queryDesc->plannedstmt->intoClause)
633 #if PG_VERSION_NUM < 90200
634 if (queryDesc->operation == CMD_SELECT)
636 Oid relOid = RangeVarGetRelid(queryDesc->plannedstmt->intoClause->rel, true);
638 makeAnalyze(relOid, queryDesc->operation, naffected);
642 if (queryDesc->plannedstmt->resultRelations &&
643 queryDesc->plannedstmt->rtable)
647 foreach(l, queryDesc->plannedstmt->resultRelations)
649 int n = lfirst_int(l);
650 RangeTblEntry *rte = list_nth(queryDesc->plannedstmt->rtable, n-1);
652 if (rte->rtekind == RTE_RELATION)
653 makeAnalyze(rte->relid, (CmdKind)queryDesc->operation, naffected);
658 if (oldExecutorEndHook)
659 oldExecutorEndHook(queryDesc);
661 standard_ExecutorEnd(queryDesc);
664 #if PG_VERSION_NUM >= 90200
666 onlineAnalyzeHookerUtility(
667 #if PG_VERSION_NUM >= 100000
672 const char *queryString,
673 #if PG_VERSION_NUM >= 90300
674 ProcessUtilityContext context, ParamListInfo params,
675 #if PG_VERSION_NUM >= 100000
676 QueryEnvironment *queryEnv,
679 ParamListInfo params, bool isTopLevel,
681 DestReceiver *dest, char *completionTag) {
682 List *tblnames = NIL;
683 CmdKind op = CK_INSERT;
684 #if PG_VERSION_NUM >= 100000
685 Node *parsetree = NULL;
687 if (pstmt->commandType == CMD_UTILITY)
688 parsetree = pstmt->utilityStmt;
691 if (parsetree && online_analyze_enable)
693 if (IsA(parsetree, CreateTableAsStmt) &&
694 ((CreateTableAsStmt*)parsetree)->into)
697 list_make1((RangeVar*)copyObject(((CreateTableAsStmt*)parsetree)->into->rel));
700 else if (IsA(parsetree, TruncateStmt))
702 tblnames = list_copy(((TruncateStmt*)parsetree)->relations);
707 #if PG_VERSION_NUM >= 100000
708 #define parsetree pstmt
711 if (oldProcessUtilityHook)
712 oldProcessUtilityHook(parsetree, queryString,
713 #if PG_VERSION_NUM >= 90300
715 #if PG_VERSION_NUM >= 100000
721 dest, completionTag);
723 standard_ProcessUtility(parsetree, queryString,
724 #if PG_VERSION_NUM >= 90300
726 #if PG_VERSION_NUM >= 100000
732 dest, completionTag);
734 #if PG_VERSION_NUM >= 100000
743 RangeVar *tblname = (RangeVar*)lfirst(l);
744 Oid tblOid = RangeVarGetRelid(tblname, NoLock, true);
746 makeAnalyze(tblOid, op, -1);
758 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
760 hash_ctl.hash = oid_hash;
761 flags |= HASH_FUNCTION;
763 if (onlineAnalyzeMemoryContext)
765 Assert(relstats != NULL);
766 MemoryContextReset(onlineAnalyzeMemoryContext);
770 Assert(relstats == NULL);
771 onlineAnalyzeMemoryContext =
772 AllocSetContextCreate(CacheMemoryContext,
773 "online_analyze storage context",
774 #if PG_VERSION_NUM < 90600
775 ALLOCSET_DEFAULT_MINSIZE,
776 ALLOCSET_DEFAULT_INITSIZE,
777 ALLOCSET_DEFAULT_MAXSIZE
779 ALLOCSET_DEFAULT_SIZES
784 hash_ctl.hcxt = onlineAnalyzeMemoryContext;
785 flags |= HASH_CONTEXT;
787 hash_ctl.keysize = sizeof(Oid);
789 hash_ctl.entrysize = sizeof(OnlineAnalyzeTableStat);
792 relstats = hash_create("online_analyze storage", 1024, &hash_ctl, flags);
801 oldExecutorEndHook = ExecutorEnd_hook;
803 ExecutorEnd_hook = onlineAnalyzeHooker;
805 #if PG_VERSION_NUM >= 90200
806 oldProcessUtilityHook = ProcessUtility_hook;
808 ProcessUtility_hook = onlineAnalyzeHookerUtility;
812 DefineCustomBoolVariable(
813 "online_analyze.enable",
814 "Enable on-line analyze",
815 "Enables analyze of table directly after insert/update/delete/select into",
816 &online_analyze_enable,
817 #if PG_VERSION_NUM >= 80400
818 online_analyze_enable,
821 #if PG_VERSION_NUM >= 80400
823 #if PG_VERSION_NUM >= 90100
831 DefineCustomBoolVariable(
832 "online_analyze.verbose",
833 "Verbosity of on-line analyze",
834 "Make ANALYZE VERBOSE after table's changes",
835 &online_analyze_verbose,
836 #if PG_VERSION_NUM >= 80400
837 online_analyze_verbose,
840 #if PG_VERSION_NUM >= 80400
842 #if PG_VERSION_NUM >= 90100
850 DefineCustomRealVariable(
851 "online_analyze.scale_factor",
852 "fraction of table size to start on-line analyze",
853 "fraction of table size to start on-line analyze",
854 &online_analyze_scale_factor,
855 #if PG_VERSION_NUM >= 80400
856 online_analyze_scale_factor,
861 #if PG_VERSION_NUM >= 80400
863 #if PG_VERSION_NUM >= 90100
871 DefineCustomIntVariable(
872 "online_analyze.threshold",
873 "min number of row updates before on-line analyze",
874 "min number of row updates before on-line analyze",
875 &online_analyze_threshold,
876 #if PG_VERSION_NUM >= 80400
877 online_analyze_threshold,
882 #if PG_VERSION_NUM >= 80400
884 #if PG_VERSION_NUM >= 90100
892 DefineCustomIntVariable(
893 "online_analyze.capacity_threshold",
894 "Max local cache table capacity",
895 "Max local cache table capacity",
896 &online_analyze_capacity_threshold,
897 #if PG_VERSION_NUM >= 80400
898 online_analyze_capacity_threshold,
903 #if PG_VERSION_NUM >= 80400
905 #if PG_VERSION_NUM >= 90100
913 DefineCustomRealVariable(
914 "online_analyze.min_interval",
915 "minimum time interval between analyze call (in milliseconds)",
916 "minimum time interval between analyze call (in milliseconds)",
917 &online_analyze_min_interval,
918 #if PG_VERSION_NUM >= 80400
919 online_analyze_min_interval,
924 #if PG_VERSION_NUM >= 80400
926 #if PG_VERSION_NUM >= 90100
934 DefineCustomEnumVariable(
935 "online_analyze.table_type",
936 "Type(s) of table for online analyze: all(default), persistent, temporary, none",
938 &online_analyze_table_type,
939 #if PG_VERSION_NUM >= 80400
940 online_analyze_table_type,
942 online_analyze_table_type_options,
944 #if PG_VERSION_NUM >= 80400
946 #if PG_VERSION_NUM >= 90100
954 DefineCustomStringVariable(
955 "online_analyze.exclude_tables",
956 "List of tables which will not online analyze",
958 &excludeTables.tableStr,
959 #if PG_VERSION_NUM >= 80400
964 #if PG_VERSION_NUM >= 90100
973 DefineCustomStringVariable(
974 "online_analyze.include_tables",
975 "List of tables which will online analyze",
977 &includeTables.tableStr,
978 #if PG_VERSION_NUM >= 80400
983 #if PG_VERSION_NUM >= 90100
997 ExecutorEnd_hook = oldExecutorEndHook;
998 #if PG_VERSION_NUM >= 90200
999 ProcessUtility_hook = oldProcessUtilityHook;
1002 if (excludeTables.tables)
1003 free(excludeTables.tables);
1004 if (includeTables.tables)
1005 free(includeTables.tables);
1007 excludeTables.tables = includeTables.tables = NULL;
1008 excludeTables.nTables = includeTables.nTables = 0;