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"
51 #ifdef PG_MODULE_MAGIC
55 static bool online_analyze_enable = true;
56 static bool online_analyze_verbose = true;
57 static double online_analyze_scale_factor = 0.1;
58 static int online_analyze_threshold = 50;
59 static double online_analyze_min_interval = 10000;
61 static ExecutorEnd_hook_type oldExecutorEndHook = NULL;
62 #if PG_VERSION_NUM >= 90200
63 static ProcessUtility_hook_type oldProcessUtilityHook = NULL;
69 OATT_PERSISTENT = 0x01,
70 OATT_TEMPORARY = 0x02,
72 } OnlineAnalyzeTableType;
74 static const struct config_enum_entry online_analyze_table_type_options[] =
76 {"all", OATT_ALL, false},
77 {"persistent", OATT_PERSISTENT, false},
78 {"temporary", OATT_TEMPORARY, false},
79 {"none", OATT_NONE, false},
83 static int online_analyze_table_type = (int)OATT_ALL;
85 typedef struct TableList {
91 static TableList excludeTables = {0, NULL, NULL};
92 static TableList includeTables = {0, NULL, NULL};
95 oid_cmp(const void *a, const void *b)
97 if (*(Oid*)a == *(Oid*)b)
99 return (*(Oid*)a > *(Oid*)b) ? 1 : -1;
103 tableListAssign(const char * newval, bool doit, TableList *tbl)
112 rawname = pstrdup(newval);
114 if (!SplitIdentifierString(rawname, ',', &namelist))
119 nOids = list_length(namelist);
120 newOids = malloc(sizeof(Oid) * (nOids+1));
122 elog(ERROR,"could not allocate %d bytes", (int)(sizeof(Oid) * (nOids+1)));
127 char *curname = (char *) lfirst(l);
128 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(stringToQualifiedNameList(curname)),
129 #if PG_VERSION_NUM >= 90200
134 if (relOid == InvalidOid)
136 #if PG_VERSION_NUM >= 90100
139 elog(WARNING,"'%s' does not exist", curname);
142 else if ( get_rel_relkind(relOid) != RELKIND_RELATION )
144 #if PG_VERSION_NUM >= 90100
147 elog(WARNING,"'%s' is not an table", curname);
152 newOids[i++] = relOid;
161 tbl->tables = newOids;
162 if (tbl->nTables > 1)
163 qsort(tbl->tables, tbl->nTables, sizeof(tbl->tables[0]), oid_cmp);
179 #if PG_VERSION_NUM >= 90100
181 excludeTablesCheck(char **newval, void **extra, GucSource source)
185 val = (char*)tableListAssign(*newval, false, &excludeTables);
197 excludeTablesAssign(const char *newval, void *extra)
199 tableListAssign(newval, true, &excludeTables);
203 includeTablesCheck(char **newval, void **extra, GucSource source)
207 val = (char*)tableListAssign(*newval, false, &includeTables);
219 includeTablesAssign(const char *newval, void *extra)
221 tableListAssign(newval, true, &excludeTables);
224 #else /* PG_VERSION_NUM < 90100 */
227 excludeTablesAssign(const char * newval, bool doit, GucSource source)
229 return tableListAssign(newval, doit, &excludeTables);
233 includeTablesAssign(const char * newval, bool doit, GucSource source)
235 return tableListAssign(newval, doit, &includeTables);
241 tableListShow(TableList *tbl)
247 len = 1 /* \0 */ + tbl->nTables * (2 * NAMEDATALEN + 2 /* ', ' */ + 1 /* . */);
248 ptr = val = palloc(len);
250 for(i=0; i<tbl->nTables; i++)
252 char *relname = get_rel_name(tbl->tables[i]);
253 Oid nspOid = get_rel_namespace(tbl->tables[i]);
254 char *nspname = get_namespace_name(nspOid);
256 if ( relname == NULL || nspOid == InvalidOid || nspname == NULL )
259 ptr += snprintf(ptr, len - (ptr - val), "%s%s.%s",
268 excludeTablesShow(void)
270 return tableListShow(&excludeTables);
274 includeTablesShow(void)
276 return tableListShow(&includeTables);
280 matchOid(TableList *tbl, Oid oid)
282 Oid *StopLow = tbl->tables,
283 *StopHigh = tbl->tables + tbl->nTables,
286 /* Loop invariant: StopLow <= val < StopHigh */
287 while (StopLow < StopHigh)
289 StopMiddle = StopLow + ((StopHigh - StopLow) >> 1);
291 if (*StopMiddle == oid)
293 else if (*StopMiddle < oid)
294 StopLow = StopMiddle + 1;
296 StopHigh = StopMiddle;
303 makeAnalyze(Oid relOid, CmdType operation, uint32 naffected)
305 PgStat_StatTabEntry *tabentry;
306 TimestampTz now = GetCurrentTimestamp();
308 if (relOid == InvalidOid)
311 tabentry = pgstat_fetch_stat_tabentry(relOid);
313 #if PG_VERSION_NUM >= 90000
314 #define changes_since_analyze(t) ((t)->changes_since_analyze)
316 #define changes_since_analyze(t) ((t)->n_live_tuples + (t)->n_dead_tuples - (t)->last_anl_tuples)
320 tabentry == NULL /* a new table */ ||
322 /* do not analyze too often, if both stamps are exceeded the go */
323 TimestampDifferenceExceeds(tabentry->analyze_timestamp, now, online_analyze_min_interval) &&
324 TimestampDifferenceExceeds(tabentry->autovac_analyze_timestamp, now, online_analyze_min_interval) &&
325 /* be in sync with relation_needs_vacanalyze */
326 ((double)(changes_since_analyze(tabentry) + naffected)) >=
327 online_analyze_scale_factor * ((double)(tabentry->n_dead_tuples + tabentry->n_live_tuples)) +
328 (double)online_analyze_threshold
333 TimestampTz startStamp, endStamp;
336 * includeTables overwrites excludeTables
338 switch(online_analyze_table_type)
341 if (matchOid(&excludeTables, relOid) == true && matchOid(&includeTables, relOid) == false)
345 if (matchOid(&includeTables, relOid) == false)
349 case OATT_PERSISTENT:
353 OnlineAnalyzeTableType reltype;
355 rel = RelationIdGetRelation(relOid);
357 #if PG_VERSION_NUM >= 90100
358 (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
360 (rel->rd_istemp || rel->rd_islocaltemp)
362 ? OATT_TEMPORARY : OATT_PERSISTENT;
366 * skip analyze if relation's type doesn't not match online_analyze_table_type
368 if ((online_analyze_table_type & reltype) == 0 || matchOid(&excludeTables, relOid) == true)
370 if (matchOid(&includeTables, relOid) == false)
377 vacstmt.type = T_VacuumStmt;
378 vacstmt.freeze_min_age = -1;
379 vacstmt.freeze_table_age = -1; /* ??? */
380 vacstmt.relation = NULL;
381 vacstmt.va_cols = NIL;
383 #if PG_VERSION_NUM >= 90000
384 vacstmt.options = VACOPT_ANALYZE;
385 if (online_analyze_verbose)
386 vacstmt.options |= VACOPT_VERBOSE;
388 vacstmt.vacuum = vacstmt.full = false;
389 vacstmt.analyze = true;
390 vacstmt.verbose = online_analyze_verbose;
393 if (online_analyze_verbose)
394 startStamp = GetCurrentTimestamp();
396 analyze_rel(relOid, &vacstmt, GetAccessStrategy(BAS_VACUUM)
397 #if (PG_VERSION_NUM < 90004) && (PG_VERSION_NUM >= 90000)
402 if (online_analyze_verbose)
407 endStamp = GetCurrentTimestamp();
408 TimestampDifference(startStamp, endStamp, &secs, µsecs);
409 elog(INFO, "analyze \"%s\" took %.02f seconds",
410 get_rel_name(relOid), ((double)secs) + ((double)microsecs)/1.0e6);
414 if (tabentry == NULL)
417 pgstat_clear_snapshot();
421 /* update last analyze timestamp in local memory of backend */
422 tabentry->analyze_timestamp = now;
425 #if PG_VERSION_NUM >= 90000
426 else if (tabentry != NULL)
428 tabentry->changes_since_analyze += naffected;
433 extern PGDLLIMPORT void onlineAnalyzeHooker(QueryDesc *queryDesc);
435 onlineAnalyzeHooker(QueryDesc *queryDesc)
437 uint32 naffected = 0;
439 if (queryDesc->estate)
440 naffected = queryDesc->estate->es_processed;
442 if (online_analyze_enable && queryDesc->plannedstmt &&
443 (queryDesc->operation == CMD_INSERT ||
444 queryDesc->operation == CMD_UPDATE ||
445 queryDesc->operation == CMD_DELETE ||
446 #if PG_VERSION_NUM >= 90200
447 0 /* (queryDesc->operation == CMD_SELECT && queryDesc->dest && queryDesc->dest == DestIntoRel) */
449 (queryDesc->operation == CMD_SELECT && queryDesc->plannedstmt->intoClause)
453 #if PG_VERSION_NUM < 90200
454 if (queryDesc->operation == CMD_SELECT)
456 Oid relOid = RangeVarGetRelid(queryDesc->plannedstmt->intoClause->rel, true);
458 makeAnalyze(relOid, queryDesc->operation, naffected);
462 if (queryDesc->plannedstmt->resultRelations &&
463 queryDesc->plannedstmt->rtable)
467 foreach(l, queryDesc->plannedstmt->resultRelations)
469 int n = lfirst_int(l);
470 RangeTblEntry *rte = list_nth(queryDesc->plannedstmt->rtable, n-1);
472 if (rte->rtekind == RTE_RELATION)
473 makeAnalyze(rte->relid, queryDesc->operation, naffected);
478 if (oldExecutorEndHook)
479 oldExecutorEndHook(queryDesc);
481 standard_ExecutorEnd(queryDesc);
484 #if PG_VERSION_NUM >= 90200
486 onlineAnalyzeHookerUtility(Node *parsetree, const char *queryString,
487 ParamListInfo params, bool isTopLevel,
488 DestReceiver *dest, char *completionTag) {
489 RangeVar *tblname = NULL;
491 if (IsA(parsetree, CreateTableAsStmt) && ((CreateTableAsStmt*)parsetree)->into)
492 tblname = (RangeVar*)copyObject(((CreateTableAsStmt*)parsetree)->into->rel);
494 if (oldProcessUtilityHook)
495 oldProcessUtilityHook(parsetree, queryString, params, isTopLevel, dest, completionTag);
497 standard_ProcessUtility(parsetree, queryString, params, isTopLevel, dest, completionTag);
500 Oid tblOid = RangeVarGetRelid(tblname, NoLock, true);
502 makeAnalyze(tblOid, CMD_INSERT, 0);
511 oldExecutorEndHook = ExecutorEnd_hook;
513 ExecutorEnd_hook = onlineAnalyzeHooker;
515 #if PG_VERSION_NUM >= 90200
516 oldProcessUtilityHook = ProcessUtility_hook;
518 ProcessUtility_hook = onlineAnalyzeHookerUtility;
522 DefineCustomBoolVariable(
523 "online_analyze.enable",
524 "Enable on-line analyze",
525 "Enables analyze of table directly after insert/update/delete/select into",
526 &online_analyze_enable,
527 #if PG_VERSION_NUM >= 80400
528 online_analyze_enable,
531 #if PG_VERSION_NUM >= 80400
533 #if PG_VERSION_NUM >= 90100
541 DefineCustomBoolVariable(
542 "online_analyze.verbose",
543 "Verbosity of on-line analyze",
544 "Make ANALYZE VERBOSE after table's changes",
545 &online_analyze_verbose,
546 #if PG_VERSION_NUM >= 80400
547 online_analyze_verbose,
550 #if PG_VERSION_NUM >= 80400
552 #if PG_VERSION_NUM >= 90100
560 DefineCustomRealVariable(
561 "online_analyze.scale_factor",
562 "fraction of table size to start on-line analyze",
563 "fraction of table size to start on-line analyze",
564 &online_analyze_scale_factor,
565 #if PG_VERSION_NUM >= 80400
566 online_analyze_scale_factor,
571 #if PG_VERSION_NUM >= 80400
573 #if PG_VERSION_NUM >= 90100
581 DefineCustomIntVariable(
582 "online_analyze.threshold",
583 "min number of row updates before on-line analyze",
584 "min number of row updates before on-line analyze",
585 &online_analyze_threshold,
586 #if PG_VERSION_NUM >= 80400
587 online_analyze_threshold,
592 #if PG_VERSION_NUM >= 80400
594 #if PG_VERSION_NUM >= 90100
602 DefineCustomRealVariable(
603 "online_analyze.min_interval",
604 "minimum time interval between analyze call (in milliseconds)",
605 "minimum time interval between analyze call (in milliseconds)",
606 &online_analyze_scale_factor,
607 #if PG_VERSION_NUM >= 80400
608 online_analyze_min_interval,
613 #if PG_VERSION_NUM >= 80400
615 #if PG_VERSION_NUM >= 90100
623 DefineCustomEnumVariable(
624 "online_analyze.table_type",
625 "Type(s) of table for online analyze: all(default), persistent, temporary, none",
627 &online_analyze_table_type,
628 #if PG_VERSION_NUM >= 80400
629 online_analyze_table_type,
631 online_analyze_table_type_options,
633 #if PG_VERSION_NUM >= 80400
635 #if PG_VERSION_NUM >= 90100
643 DefineCustomStringVariable(
644 "online_analyze.exclude_tables",
645 "List of tables which will not online analyze",
647 &excludeTables.tableStr,
648 #if PG_VERSION_NUM >= 80400
653 #if PG_VERSION_NUM >= 90100
662 DefineCustomStringVariable(
663 "online_analyze.include_tables",
664 "List of tables which will online analyze",
666 &includeTables.tableStr,
667 #if PG_VERSION_NUM >= 80400
672 #if PG_VERSION_NUM >= 90100
686 ExecutorEnd_hook = oldExecutorEndHook;
687 #if PG_VERSION_NUM >= 90200
688 ProcessUtility_hook = oldProcessUtilityHook;
691 if (excludeTables.tables)
692 free(excludeTables.tables);
693 if (includeTables.tables)
694 free(includeTables.tables);
696 excludeTables.tables = includeTables.tables = NULL;
697 excludeTables.nTables = includeTables.nTables = 0;