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/lsyscache.h"
41 #include "utils/guc.h"
42 #if PG_VERSION_NUM >= 90200
43 #include "catalog/pg_class.h"
44 #include "nodes/primnodes.h"
45 #include "tcop/utility.h"
46 #include "utils/rel.h"
47 #include "utils/relcache.h"
48 #include "utils/timestamp.h"
49 #if PG_VERSION_NUM >= 90500
50 #include "nodes/makefuncs.h"
54 #ifdef PG_MODULE_MAGIC
58 static bool online_analyze_enable = true;
59 static bool online_analyze_verbose = true;
60 static double online_analyze_scale_factor = 0.1;
61 static int online_analyze_threshold = 50;
62 static double online_analyze_min_interval = 10000;
64 static ExecutorEnd_hook_type oldExecutorEndHook = NULL;
65 #if PG_VERSION_NUM >= 90200
66 static ProcessUtility_hook_type oldProcessUtilityHook = NULL;
72 OATT_PERSISTENT = 0x01,
73 OATT_TEMPORARY = 0x02,
75 } OnlineAnalyzeTableType;
77 static const struct config_enum_entry online_analyze_table_type_options[] =
79 {"all", OATT_ALL, false},
80 {"persistent", OATT_PERSISTENT, false},
81 {"temporary", OATT_TEMPORARY, false},
82 {"none", OATT_NONE, false},
86 static int online_analyze_table_type = (int)OATT_ALL;
88 typedef struct TableList {
94 static TableList excludeTables = {0, NULL, NULL};
95 static TableList includeTables = {0, NULL, NULL};
98 oid_cmp(const void *a, const void *b)
100 if (*(Oid*)a == *(Oid*)b)
102 return (*(Oid*)a > *(Oid*)b) ? 1 : -1;
106 tableListAssign(const char * newval, bool doit, TableList *tbl)
115 rawname = pstrdup(newval);
117 if (!SplitIdentifierString(rawname, ',', &namelist))
122 nOids = list_length(namelist);
123 newOids = malloc(sizeof(Oid) * (nOids+1));
125 elog(ERROR,"could not allocate %d bytes",
126 (int)(sizeof(Oid) * (nOids+1)));
131 char *curname = (char *) lfirst(l);
132 #if PG_VERSION_NUM >= 90200
133 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
134 stringToQualifiedNameList(curname)), NoLock, true);
136 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(
137 stringToQualifiedNameList(curname)), true);
140 if (relOid == InvalidOid)
142 #if PG_VERSION_NUM >= 90100
145 elog(WARNING,"'%s' does not exist", curname);
148 else if ( get_rel_relkind(relOid) != RELKIND_RELATION )
150 #if PG_VERSION_NUM >= 90100
153 elog(WARNING,"'%s' is not an table", curname);
158 newOids[i++] = relOid;
167 tbl->tables = newOids;
168 if (tbl->nTables > 1)
169 qsort(tbl->tables, tbl->nTables, sizeof(tbl->tables[0]), oid_cmp);
185 #if PG_VERSION_NUM >= 90100
187 excludeTablesCheck(char **newval, void **extra, GucSource source)
191 val = (char*)tableListAssign(*newval, false, &excludeTables);
203 excludeTablesAssign(const char *newval, void *extra)
205 tableListAssign(newval, true, &excludeTables);
209 includeTablesCheck(char **newval, void **extra, GucSource source)
213 val = (char*)tableListAssign(*newval, false, &includeTables);
225 includeTablesAssign(const char *newval, void *extra)
227 tableListAssign(newval, true, &excludeTables);
230 #else /* PG_VERSION_NUM < 90100 */
233 excludeTablesAssign(const char * newval, bool doit, GucSource source)
235 return tableListAssign(newval, doit, &excludeTables);
239 includeTablesAssign(const char * newval, bool doit, GucSource source)
241 return tableListAssign(newval, doit, &includeTables);
247 tableListShow(TableList *tbl)
253 len = 1 /* \0 */ + tbl->nTables * (2 * NAMEDATALEN + 2 /* ', ' */ + 1 /* . */);
254 ptr = val = palloc(len);
256 for(i=0; i<tbl->nTables; i++)
258 char *relname = get_rel_name(tbl->tables[i]);
259 Oid nspOid = get_rel_namespace(tbl->tables[i]);
260 char *nspname = get_namespace_name(nspOid);
262 if ( relname == NULL || nspOid == InvalidOid || nspname == NULL )
265 ptr += snprintf(ptr, len - (ptr - val), "%s%s.%s",
274 excludeTablesShow(void)
276 return tableListShow(&excludeTables);
280 includeTablesShow(void)
282 return tableListShow(&includeTables);
286 matchOid(TableList *tbl, Oid oid)
288 Oid *StopLow = tbl->tables,
289 *StopHigh = tbl->tables + tbl->nTables,
292 /* Loop invariant: StopLow <= val < StopHigh */
293 while (StopLow < StopHigh)
295 StopMiddle = StopLow + ((StopHigh - StopLow) >> 1);
297 if (*StopMiddle == oid)
299 else if (*StopMiddle < oid)
300 StopLow = StopMiddle + 1;
302 StopHigh = StopMiddle;
308 #if PG_VERSION_NUM >= 90500
310 makeRangeVarFromOid(Oid relOid)
313 get_namespace_name(get_rel_namespace(relOid)),
314 get_rel_name(relOid),
322 makeAnalyze(Oid relOid, CmdType operation, int32 naffected)
324 PgStat_StatTabEntry *tabentry;
325 TimestampTz now = GetCurrentTimestamp();
327 if (relOid == InvalidOid)
331 /* return if there is not changes */
333 else if (naffected < 0)
334 /* number if affected rows is unknown */
338 * includeTables overwrites excludeTables
340 switch(online_analyze_table_type)
343 if (get_rel_relkind(relOid) != RELKIND_RELATION ||
344 (matchOid(&excludeTables, relOid) == true &&
345 matchOid(&includeTables, relOid) == false))
349 if (get_rel_relkind(relOid) != RELKIND_RELATION ||
350 matchOid(&includeTables, relOid) == false)
354 case OATT_PERSISTENT:
358 OnlineAnalyzeTableType reltype;
360 rel = RelationIdGetRelation(relOid);
362 if (rel->rd_rel->relkind != RELKIND_RELATION)
369 #if PG_VERSION_NUM >= 90100
370 (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
372 (rel->rd_istemp || rel->rd_islocaltemp)
374 ? OATT_TEMPORARY : OATT_PERSISTENT;
378 * skip analyze if relation's type doesn't not match
379 * online_analyze_table_type
381 if ((online_analyze_table_type & reltype) == 0 ||
382 matchOid(&excludeTables, relOid) == true)
384 if (matchOid(&includeTables, relOid) == false)
391 tabentry = pgstat_fetch_stat_tabentry(relOid);
393 #if PG_VERSION_NUM >= 90000
394 #define changes_since_analyze(t) ((t)->changes_since_analyze)
396 #define changes_since_analyze(t) ((t)->n_live_tuples + (t)->n_dead_tuples - (t)->last_anl_tuples)
400 tabentry == NULL /* a new table */ ||
402 /* do not analyze too often, if both stamps are exceeded the go */
403 TimestampDifferenceExceeds(tabentry->analyze_timestamp, now, online_analyze_min_interval) &&
404 TimestampDifferenceExceeds(tabentry->autovac_analyze_timestamp, now, online_analyze_min_interval) &&
405 /* be in sync with relation_needs_vacanalyze */
406 ((double)(changes_since_analyze(tabentry) + naffected)) >=
407 online_analyze_scale_factor * ((double)(tabentry->n_dead_tuples + tabentry->n_live_tuples)) +
408 (double)online_analyze_threshold
412 #if PG_VERSION_NUM < 90500
415 VacuumParams vacstmt;
417 TimestampTz startStamp, endStamp;
419 memset(&startStamp, 0, sizeof(startStamp)); /* keep compiler quiet */
421 memset(&vacstmt, 0, sizeof(vacstmt));
423 vacstmt.freeze_min_age = -1;
424 vacstmt.freeze_table_age = -1; /* ??? */
426 #if PG_VERSION_NUM < 90500
427 vacstmt.type = T_VacuumStmt;
428 vacstmt.relation = NULL;
429 vacstmt.va_cols = NIL;
430 #if PG_VERSION_NUM >= 90000
431 vacstmt.options = VACOPT_ANALYZE;
432 if (online_analyze_verbose)
433 vacstmt.options |= VACOPT_VERBOSE;
435 vacstmt.vacuum = vacstmt.full = false;
436 vacstmt.analyze = true;
437 vacstmt.verbose = online_analyze_verbose;
440 vacstmt.multixact_freeze_min_age = -1;
441 vacstmt.multixact_freeze_table_age = -1;
442 vacstmt.log_min_duration = -1;
445 if (online_analyze_verbose)
446 startStamp = GetCurrentTimestamp();
449 #if PG_VERSION_NUM < 90500
451 #if PG_VERSION_NUM >= 90018
454 , GetAccessStrategy(BAS_VACUUM)
455 #if (PG_VERSION_NUM >= 90000) && (PG_VERSION_NUM < 90004)
459 makeRangeVarFromOid(relOid),
460 VACOPT_ANALYZE | ((online_analyze_verbose) ? VACOPT_VERBOSE : 0),
461 &vacstmt, NULL, true, GetAccessStrategy(BAS_VACUUM)
465 if (online_analyze_verbose)
470 endStamp = GetCurrentTimestamp();
471 TimestampDifference(startStamp, endStamp, &secs, µsecs);
472 elog(INFO, "analyze \"%s\" took %.02f seconds",
473 get_rel_name(relOid),
474 ((double)secs) + ((double)microsecs)/1.0e6);
477 if (tabentry == NULL)
480 pgstat_clear_snapshot();
484 /* update last analyze timestamp in local memory of backend */
485 tabentry->analyze_timestamp = now;
488 #if PG_VERSION_NUM >= 90000
489 else if (tabentry != NULL)
491 tabentry->changes_since_analyze += naffected;
496 extern PGDLLIMPORT void onlineAnalyzeHooker(QueryDesc *queryDesc);
498 onlineAnalyzeHooker(QueryDesc *queryDesc)
500 uint32 naffected = -1;
502 if (queryDesc->estate)
503 naffected = queryDesc->estate->es_processed;
505 if (online_analyze_enable && queryDesc->plannedstmt &&
506 (queryDesc->operation == CMD_INSERT ||
507 queryDesc->operation == CMD_UPDATE ||
508 queryDesc->operation == CMD_DELETE
509 #if PG_VERSION_NUM < 90200
510 || (queryDesc->operation == CMD_SELECT &&
511 queryDesc->plannedstmt->intoClause)
515 #if PG_VERSION_NUM < 90200
516 if (queryDesc->operation == CMD_SELECT)
518 Oid relOid = RangeVarGetRelid(queryDesc->plannedstmt->intoClause->rel, true);
520 makeAnalyze(relOid, queryDesc->operation, naffected);
524 if (queryDesc->plannedstmt->resultRelations &&
525 queryDesc->plannedstmt->rtable)
529 foreach(l, queryDesc->plannedstmt->resultRelations)
531 int n = lfirst_int(l);
532 RangeTblEntry *rte = list_nth(queryDesc->plannedstmt->rtable, n-1);
534 if (rte->rtekind == RTE_RELATION)
535 makeAnalyze(rte->relid, queryDesc->operation, naffected);
540 if (oldExecutorEndHook)
541 oldExecutorEndHook(queryDesc);
543 standard_ExecutorEnd(queryDesc);
546 #if PG_VERSION_NUM >= 90200
548 onlineAnalyzeHookerUtility(Node *parsetree, const char *queryString,
549 #if PG_VERSION_NUM >= 90300
550 ProcessUtilityContext context, ParamListInfo params,
552 ParamListInfo params, bool isTopLevel,
554 DestReceiver *dest, char *completionTag) {
555 RangeVar *tblname = NULL;
557 if (IsA(parsetree, CreateTableAsStmt) && ((CreateTableAsStmt*)parsetree)->into)
558 tblname = (RangeVar*)copyObject(((CreateTableAsStmt*)parsetree)->into->rel);
560 if (oldProcessUtilityHook)
561 oldProcessUtilityHook(parsetree, queryString,
562 #if PG_VERSION_NUM >= 90300
567 dest, completionTag);
569 standard_ProcessUtility(parsetree, queryString,
570 #if PG_VERSION_NUM >= 90300
575 dest, completionTag);
578 Oid tblOid = RangeVarGetRelid(tblname, NoLock, true);
580 makeAnalyze(tblOid, CMD_INSERT, -1);
589 oldExecutorEndHook = ExecutorEnd_hook;
591 ExecutorEnd_hook = onlineAnalyzeHooker;
593 #if PG_VERSION_NUM >= 90200
594 oldProcessUtilityHook = ProcessUtility_hook;
596 ProcessUtility_hook = onlineAnalyzeHookerUtility;
600 DefineCustomBoolVariable(
601 "online_analyze.enable",
602 "Enable on-line analyze",
603 "Enables analyze of table directly after insert/update/delete/select into",
604 &online_analyze_enable,
605 #if PG_VERSION_NUM >= 80400
606 online_analyze_enable,
609 #if PG_VERSION_NUM >= 80400
611 #if PG_VERSION_NUM >= 90100
619 DefineCustomBoolVariable(
620 "online_analyze.verbose",
621 "Verbosity of on-line analyze",
622 "Make ANALYZE VERBOSE after table's changes",
623 &online_analyze_verbose,
624 #if PG_VERSION_NUM >= 80400
625 online_analyze_verbose,
628 #if PG_VERSION_NUM >= 80400
630 #if PG_VERSION_NUM >= 90100
638 DefineCustomRealVariable(
639 "online_analyze.scale_factor",
640 "fraction of table size to start on-line analyze",
641 "fraction of table size to start on-line analyze",
642 &online_analyze_scale_factor,
643 #if PG_VERSION_NUM >= 80400
644 online_analyze_scale_factor,
649 #if PG_VERSION_NUM >= 80400
651 #if PG_VERSION_NUM >= 90100
659 DefineCustomIntVariable(
660 "online_analyze.threshold",
661 "min number of row updates before on-line analyze",
662 "min number of row updates before on-line analyze",
663 &online_analyze_threshold,
664 #if PG_VERSION_NUM >= 80400
665 online_analyze_threshold,
670 #if PG_VERSION_NUM >= 80400
672 #if PG_VERSION_NUM >= 90100
680 DefineCustomRealVariable(
681 "online_analyze.min_interval",
682 "minimum time interval between analyze call (in milliseconds)",
683 "minimum time interval between analyze call (in milliseconds)",
684 &online_analyze_min_interval,
685 #if PG_VERSION_NUM >= 80400
686 online_analyze_min_interval,
691 #if PG_VERSION_NUM >= 80400
693 #if PG_VERSION_NUM >= 90100
701 DefineCustomEnumVariable(
702 "online_analyze.table_type",
703 "Type(s) of table for online analyze: all(default), persistent, temporary, none",
705 &online_analyze_table_type,
706 #if PG_VERSION_NUM >= 80400
707 online_analyze_table_type,
709 online_analyze_table_type_options,
711 #if PG_VERSION_NUM >= 80400
713 #if PG_VERSION_NUM >= 90100
721 DefineCustomStringVariable(
722 "online_analyze.exclude_tables",
723 "List of tables which will not online analyze",
725 &excludeTables.tableStr,
726 #if PG_VERSION_NUM >= 80400
731 #if PG_VERSION_NUM >= 90100
740 DefineCustomStringVariable(
741 "online_analyze.include_tables",
742 "List of tables which will online analyze",
744 &includeTables.tableStr,
745 #if PG_VERSION_NUM >= 80400
750 #if PG_VERSION_NUM >= 90100
764 ExecutorEnd_hook = oldExecutorEndHook;
765 #if PG_VERSION_NUM >= 90200
766 ProcessUtility_hook = oldProcessUtilityHook;
769 if (excludeTables.tables)
770 free(excludeTables.tables);
771 if (includeTables.tables)
772 free(includeTables.tables);
774 excludeTables.tables = includeTables.tables = NULL;
775 excludeTables.nTables = includeTables.nTables = 0;