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;
70 static int online_analyze_lower_limit = 0;
72 static ExecutorEnd_hook_type oldExecutorEndHook = NULL;
73 #if PG_VERSION_NUM >= 90200
74 static ProcessUtility_hook_type oldProcessUtilityHook = NULL;
79 CK_SELECT = CMD_SELECT,
80 CK_UPDATE = CMD_UPDATE,
81 CK_INSERT = CMD_INSERT,
82 CK_DELETE = CMD_DELETE,
90 OATT_PERSISTENT = 0x01,
91 OATT_TEMPORARY = 0x02,
93 } OnlineAnalyzeTableType;
95 static const struct config_enum_entry online_analyze_table_type_options[] =
97 {"all", OATT_ALL, false},
98 {"persistent", OATT_PERSISTENT, false},
99 {"temporary", OATT_TEMPORARY, false},
100 {"none", OATT_NONE, false},
104 static int online_analyze_table_type = (int)OATT_ALL;
106 typedef struct TableList {
112 static TableList excludeTables = {0, NULL, NULL};
113 static TableList includeTables = {0, NULL, NULL};
115 typedef struct OnlineAnalyzeTableStat {
118 PgStat_Counter n_tuples;
119 PgStat_Counter changes_since_analyze;
120 TimestampTz autovac_analyze_timestamp;
121 TimestampTz analyze_timestamp;
122 } OnlineAnalyzeTableStat;
124 static MemoryContext onlineAnalyzeMemoryContext = NULL;
125 static HTAB *relstats = NULL;
127 static void relstatsInit(void);
129 #if PG_VERSION_NUM < 100000
131 oid_cmp(const void *a, const void *b)
133 if (*(Oid*)a == *(Oid*)b)
135 return (*(Oid*)a > *(Oid*)b) ? 1 : -1;
140 tableListAssign(const char * newval, bool doit, TableList *tbl)
149 rawname = pstrdup(newval);
151 if (!SplitIdentifierString(rawname, ',', &namelist))
156 nOids = list_length(namelist);
157 newOids = malloc(sizeof(Oid) * (nOids+1));
159 elog(ERROR,"could not allocate %d bytes",
160 (int)(sizeof(Oid) * (nOids+1)));
165 char *curname = (char *) lfirst(l);
166 #if PG_VERSION_NUM >= 90200
167 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
168 stringToQualifiedNameList(curname)), NoLock, true);
170 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
171 stringToQualifiedNameList(curname)), true);
174 if (relOid == InvalidOid)
176 #if PG_VERSION_NUM >= 90100
179 elog(WARNING,"'%s' does not exist", curname);
182 else if ( get_rel_relkind(relOid) != RELKIND_RELATION )
184 #if PG_VERSION_NUM >= 90100
187 elog(WARNING,"'%s' is not an table", curname);
192 newOids[i++] = relOid;
201 tbl->tables = newOids;
202 if (tbl->nTables > 1)
203 qsort(tbl->tables, tbl->nTables, sizeof(tbl->tables[0]), oid_cmp);
219 #if PG_VERSION_NUM >= 90100
221 excludeTablesCheck(char **newval, void **extra, GucSource source)
225 val = (char*)tableListAssign(*newval, false, &excludeTables);
237 excludeTablesAssign(const char *newval, void *extra)
239 tableListAssign(newval, true, &excludeTables);
243 includeTablesCheck(char **newval, void **extra, GucSource source)
247 val = (char*)tableListAssign(*newval, false, &includeTables);
259 includeTablesAssign(const char *newval, void *extra)
261 tableListAssign(newval, true, &excludeTables);
264 #else /* PG_VERSION_NUM < 90100 */
267 excludeTablesAssign(const char * newval, bool doit, GucSource source)
269 return tableListAssign(newval, doit, &excludeTables);
273 includeTablesAssign(const char * newval, bool doit, GucSource source)
275 return tableListAssign(newval, doit, &includeTables);
281 tableListShow(TableList *tbl)
287 len = 1 /* \0 */ + tbl->nTables * (2 * NAMEDATALEN + 2 /* ', ' */ + 1 /* . */);
288 ptr = val = palloc(len);
290 for(i=0; i<tbl->nTables; i++)
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);
296 if ( relname == NULL || nspOid == InvalidOid || nspname == NULL )
299 ptr += snprintf(ptr, len - (ptr - val), "%s%s.%s",
308 excludeTablesShow(void)
310 return tableListShow(&excludeTables);
314 includeTablesShow(void)
316 return tableListShow(&includeTables);
320 matchOid(TableList *tbl, Oid oid)
322 Oid *StopLow = tbl->tables,
323 *StopHigh = tbl->tables + tbl->nTables,
326 /* Loop invariant: StopLow <= val < StopHigh */
327 while (StopLow < StopHigh)
329 StopMiddle = StopLow + ((StopHigh - StopLow) >> 1);
331 if (*StopMiddle == oid)
333 else if (*StopMiddle < oid)
334 StopLow = StopMiddle + 1;
336 StopHigh = StopMiddle;
342 #if PG_VERSION_NUM >= 90500
344 makeRangeVarFromOid(Oid relOid)
347 get_namespace_name(get_rel_namespace(relOid)),
348 get_rel_name(relOid),
356 makeAnalyze(Oid relOid, CmdKind operation, int64 naffected)
358 TimestampTz now = GetCurrentTimestamp();
360 OnlineAnalyzeTableType reltype;
363 OnlineAnalyzeTableStat *rstat,
365 PgStat_StatTabEntry *tabentry = NULL;
367 if (relOid == InvalidOid)
371 /* return if there is no changes */
373 else if (naffected < 0)
374 /* number if affected rows is unknown */
377 rel = RelationIdGetRelation(relOid);
378 if (rel->rd_rel->relkind != RELKIND_RELATION)
385 #if PG_VERSION_NUM >= 90100
386 (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
388 (rel->rd_istemp || rel->rd_islocaltemp)
390 ? OATT_TEMPORARY : OATT_PERSISTENT;
395 * includeTables overwrites excludeTables
397 switch(online_analyze_table_type)
400 if (get_rel_relkind(relOid) != RELKIND_RELATION ||
401 (matchOid(&excludeTables, relOid) == true &&
402 matchOid(&includeTables, relOid) == false))
406 if (get_rel_relkind(relOid) != RELKIND_RELATION ||
407 matchOid(&includeTables, relOid) == false)
411 case OATT_PERSISTENT:
414 * skip analyze if relation's type doesn't not match
415 * online_analyze_table_type
417 if ((online_analyze_table_type & reltype) == 0 ||
418 matchOid(&excludeTables, relOid) == true)
420 if (matchOid(&includeTables, relOid) == false)
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.
431 if (reltype == OATT_TEMPORARY)
432 rstat = hash_search(relstats, &relOid, HASH_ENTER, &found);
434 rstat = &dummyrstat; /* found == false for following if */
438 MemSet(rstat, 0, sizeof(*rstat));
439 rstat->tableid = relOid;
443 Assert(rstat->tableid == relOid);
445 if (operation != CK_TRUNCATE &&
446 (found == false || rstat->rereadStat == true))
449 rstat->rereadStat = false;
451 tabentry = pgstat_fetch_stat_tabentry(relOid);
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;
460 tabentry->n_live_tuples + tabentry->n_dead_tuples -
461 tabentry->last_anl_tuples;
463 rstat->autovac_analyze_timestamp =
464 tabentry->autovac_analyze_timestamp;
465 rstat->analyze_timestamp = tabentry->analyze_timestamp;
470 rstat->rereadStat = true;
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))
485 #if PG_VERSION_NUM < 90500
488 VacuumParams vacstmt;
490 TimestampTz startStamp, endStamp;
493 memset(&startStamp, 0, sizeof(startStamp)); /* keep compiler quiet */
495 memset(&vacstmt, 0, sizeof(vacstmt));
497 vacstmt.freeze_min_age = -1;
498 vacstmt.freeze_table_age = -1; /* ??? */
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;
509 vacstmt.vacuum = vacstmt.full = false;
510 vacstmt.analyze = true;
511 vacstmt.verbose = online_analyze_verbose;
514 vacstmt.multixact_freeze_min_age = -1;
515 vacstmt.multixact_freeze_table_age = -1;
516 vacstmt.log_min_duration = -1;
519 if (online_analyze_verbose)
520 startStamp = GetCurrentTimestamp();
523 #if PG_VERSION_NUM < 90500
525 #if PG_VERSION_NUM >= 90018
528 , GetAccessStrategy(BAS_VACUUM)
529 #if (PG_VERSION_NUM >= 90000) && (PG_VERSION_NUM < 90004)
533 makeRangeVarFromOid(relOid),
534 VACOPT_ANALYZE | ((online_analyze_verbose) ? VACOPT_VERBOSE : 0),
535 &vacstmt, NULL, true, GetAccessStrategy(BAS_VACUUM)
539 if (online_analyze_verbose)
544 endStamp = GetCurrentTimestamp();
545 TimestampDifference(startStamp, endStamp, &secs, µsecs);
546 elog(INFO, "analyze \"%s\" took %.02f seconds",
547 get_rel_name(relOid),
548 ((double)secs) + ((double)microsecs)/1.0e6);
551 rstat->autovac_analyze_timestamp = now;
552 rstat->changes_since_analyze = 0;
557 rstat->n_tuples += naffected;
560 rstat->n_tuples += naffected;
561 rstat->rereadStat = true;
564 rstat->rereadStat = true;
573 /* update last analyze timestamp in local memory of backend */
576 tabentry->analyze_timestamp = now;
577 tabentry->changes_since_analyze = 0;
580 /* force reload stat for new table */
582 pgstat_clear_snapshot();
587 #if PG_VERSION_NUM >= 90000
589 tabentry->changes_since_analyze += naffected;
594 rstat->changes_since_analyze += naffected;
595 rstat->n_tuples += naffected;
598 rstat->changes_since_analyze += 2 * naffected;
599 rstat->n_tuples += naffected;
601 rstat->changes_since_analyze += naffected;
604 rstat->changes_since_analyze = rstat->n_tuples;
612 /* Reset local cache if we are over limit */
613 if (hash_get_num_entries(relstats) > online_analyze_capacity_threshold)
617 extern PGDLLIMPORT void onlineAnalyzeHooker(QueryDesc *queryDesc);
619 onlineAnalyzeHooker(QueryDesc *queryDesc)
621 int64 naffected = -1;
623 if (queryDesc->estate)
624 naffected = queryDesc->estate->es_processed;
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)
636 #if PG_VERSION_NUM < 90200
637 if (queryDesc->operation == CMD_SELECT)
639 Oid relOid = RangeVarGetRelid(queryDesc->plannedstmt->intoClause->rel, true);
641 makeAnalyze(relOid, queryDesc->operation, naffected);
645 if (queryDesc->plannedstmt->resultRelations &&
646 queryDesc->plannedstmt->rtable)
650 foreach(l, queryDesc->plannedstmt->resultRelations)
652 int n = lfirst_int(l);
653 RangeTblEntry *rte = list_nth(queryDesc->plannedstmt->rtable, n-1);
655 if (rte->rtekind == RTE_RELATION)
656 makeAnalyze(rte->relid, (CmdKind)queryDesc->operation, naffected);
661 if (oldExecutorEndHook)
662 oldExecutorEndHook(queryDesc);
664 standard_ExecutorEnd(queryDesc);
667 #if PG_VERSION_NUM >= 90200
669 onlineAnalyzeHookerUtility(
670 #if PG_VERSION_NUM >= 100000
675 const char *queryString,
676 #if PG_VERSION_NUM >= 90300
677 ProcessUtilityContext context, ParamListInfo params,
678 #if PG_VERSION_NUM >= 100000
679 QueryEnvironment *queryEnv,
682 ParamListInfo params, bool isTopLevel,
684 DestReceiver *dest, char *completionTag) {
685 List *tblnames = NIL;
686 CmdKind op = CK_INSERT;
687 #if PG_VERSION_NUM >= 100000
688 Node *parsetree = NULL;
690 if (pstmt->commandType == CMD_UTILITY)
691 parsetree = pstmt->utilityStmt;
694 if (parsetree && online_analyze_enable)
696 if (IsA(parsetree, CreateTableAsStmt) &&
697 ((CreateTableAsStmt*)parsetree)->into)
700 list_make1((RangeVar*)copyObject(((CreateTableAsStmt*)parsetree)->into->rel));
703 else if (IsA(parsetree, TruncateStmt))
705 tblnames = list_copy(((TruncateStmt*)parsetree)->relations);
710 #if PG_VERSION_NUM >= 100000
711 #define parsetree pstmt
714 if (oldProcessUtilityHook)
715 oldProcessUtilityHook(parsetree, queryString,
716 #if PG_VERSION_NUM >= 90300
718 #if PG_VERSION_NUM >= 100000
724 dest, completionTag);
726 standard_ProcessUtility(parsetree, queryString,
727 #if PG_VERSION_NUM >= 90300
729 #if PG_VERSION_NUM >= 100000
735 dest, completionTag);
737 #if PG_VERSION_NUM >= 100000
746 RangeVar *tblname = (RangeVar*)lfirst(l);
747 Oid tblOid = RangeVarGetRelid(tblname, NoLock, true);
749 makeAnalyze(tblOid, op, -1);
761 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
763 hash_ctl.hash = oid_hash;
764 flags |= HASH_FUNCTION;
766 if (onlineAnalyzeMemoryContext)
768 Assert(relstats != NULL);
769 MemoryContextReset(onlineAnalyzeMemoryContext);
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
782 ALLOCSET_DEFAULT_SIZES
787 hash_ctl.hcxt = onlineAnalyzeMemoryContext;
788 flags |= HASH_CONTEXT;
790 hash_ctl.keysize = sizeof(Oid);
792 hash_ctl.entrysize = sizeof(OnlineAnalyzeTableStat);
795 relstats = hash_create("online_analyze storage", 1024, &hash_ctl, flags);
804 oldExecutorEndHook = ExecutorEnd_hook;
806 ExecutorEnd_hook = onlineAnalyzeHooker;
808 #if PG_VERSION_NUM >= 90200
809 oldProcessUtilityHook = ProcessUtility_hook;
811 ProcessUtility_hook = onlineAnalyzeHookerUtility;
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,
824 #if PG_VERSION_NUM >= 80400
826 #if PG_VERSION_NUM >= 90100
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,
843 #if PG_VERSION_NUM >= 80400
845 #if PG_VERSION_NUM >= 90100
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,
864 #if PG_VERSION_NUM >= 80400
866 #if PG_VERSION_NUM >= 90100
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,
885 #if PG_VERSION_NUM >= 80400
887 #if PG_VERSION_NUM >= 90100
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,
906 #if PG_VERSION_NUM >= 80400
908 #if PG_VERSION_NUM >= 90100
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,
927 #if PG_VERSION_NUM >= 80400
929 #if PG_VERSION_NUM >= 90100
937 DefineCustomEnumVariable(
938 "online_analyze.table_type",
939 "Type(s) of table for online analyze: all(default), persistent, temporary, none",
941 &online_analyze_table_type,
942 #if PG_VERSION_NUM >= 80400
943 online_analyze_table_type,
945 online_analyze_table_type_options,
947 #if PG_VERSION_NUM >= 80400
949 #if PG_VERSION_NUM >= 90100
957 DefineCustomStringVariable(
958 "online_analyze.exclude_tables",
959 "List of tables which will not online analyze",
961 &excludeTables.tableStr,
962 #if PG_VERSION_NUM >= 80400
967 #if PG_VERSION_NUM >= 90100
976 DefineCustomStringVariable(
977 "online_analyze.include_tables",
978 "List of tables which will online analyze",
980 &includeTables.tableStr,
981 #if PG_VERSION_NUM >= 80400
986 #if PG_VERSION_NUM >= 90100
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,
1006 #if PG_VERSION_NUM >= 80400
1008 #if PG_VERSION_NUM >= 90100
1018 void _PG_fini(void);
1022 ExecutorEnd_hook = oldExecutorEndHook;
1023 #if PG_VERSION_NUM >= 90200
1024 ProcessUtility_hook = oldProcessUtilityHook;
1027 if (excludeTables.tables)
1028 free(excludeTables.tables);
1029 if (includeTables.tables)
1030 free(includeTables.tables);
1032 excludeTables.tables = includeTables.tables = NULL;
1033 excludeTables.nTables = includeTables.nTables = 0;