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 "utils/rel.h"
45 #include "utils/relcache.h"
46 #include "utils/timestamp.h"
49 #ifdef PG_MODULE_MAGIC
53 static bool online_analyze_enable = true;
54 static bool online_analyze_verbose = true;
55 static double online_analyze_scale_factor = 0.1;
56 static int online_analyze_threshold = 50;
57 static double online_analyze_min_interval = 10000;
62 OATT_PERSISTENT = 0x01,
63 OATT_TEMPORARY = 0x02,
65 } OnlineAnalyzeTableType;
67 static const struct config_enum_entry online_analyze_table_type_options[] =
69 {"all", OATT_ALL, false},
70 {"persistent", OATT_PERSISTENT, false},
71 {"temporary", OATT_TEMPORARY, false},
72 {"none", OATT_NONE, false},
76 static int online_analyze_table_type = (int)OATT_ALL;
78 typedef struct TableList {
84 static TableList excludeTables = {0, NULL, NULL};
85 static TableList includeTables = {0, NULL, NULL};
88 oid_cmp(const void *a, const void *b)
90 if (*(Oid*)a == *(Oid*)b)
92 return (*(Oid*)a > *(Oid*)b) ? 1 : -1;
96 tableListAssign(const char * newval, bool doit, TableList *tbl)
105 rawname = pstrdup(newval);
107 if (!SplitIdentifierString(rawname, ',', &namelist))
112 nOids = list_length(namelist);
113 newOids = malloc(sizeof(Oid) * (nOids+1));
115 elog(ERROR,"could not allocate %d bytes", (int)(sizeof(Oid) * (nOids+1)));
120 char *curname = (char *) lfirst(l);
121 Oid relOid = RangeVarGetRelid(makeRangeVarFromNameList(stringToQualifiedNameList(curname)),
122 #if PG_VERSION_NUM >= 90200
127 if (relOid == InvalidOid)
129 #if PG_VERSION_NUM >= 90100
132 elog(WARNING,"'%s' does not exist", curname);
135 else if ( get_rel_relkind(relOid) != RELKIND_RELATION )
137 #if PG_VERSION_NUM >= 90100
140 elog(WARNING,"'%s' is not an table", curname);
145 newOids[i++] = relOid;
154 tbl->tables = newOids;
155 if (tbl->nTables > 1)
156 qsort(tbl->tables, tbl->nTables, sizeof(tbl->tables[0]), oid_cmp);
172 #if PG_VERSION_NUM >= 90100
174 excludeTablesCheck(char **newval, void **extra, GucSource source)
178 val = (char*)tableListAssign(*newval, false, &excludeTables);
190 excludeTablesAssign(const char *newval, void *extra)
192 tableListAssign(newval, true, &excludeTables);
196 includeTablesCheck(char **newval, void **extra, GucSource source)
200 val = (char*)tableListAssign(*newval, false, &includeTables);
212 includeTablesAssign(const char *newval, void *extra)
214 tableListAssign(newval, true, &excludeTables);
217 #else /* PG_VERSION_NUM < 90100 */
220 excludeTablesAssign(const char * newval, bool doit, GucSource source)
222 return tableListAssign(newval, doit, &excludeTables);
226 includeTablesAssign(const char * newval, bool doit, GucSource source)
228 return tableListAssign(newval, doit, &includeTables);
234 tableListShow(TableList *tbl)
240 len = 1 /* \0 */ + tbl->nTables * (2 * NAMEDATALEN + 2 /* ', ' */ + 1 /* . */);
241 ptr = val = palloc(len);
243 for(i=0; i<tbl->nTables; i++)
245 char *relname = get_rel_name(tbl->tables[i]);
246 Oid nspOid = get_rel_namespace(tbl->tables[i]);
247 char *nspname = get_namespace_name(nspOid);
249 if ( relname == NULL || nspOid == InvalidOid || nspname == NULL )
252 ptr += snprintf(ptr, len - (ptr - val), "%s%s.%s",
261 excludeTablesShow(void)
263 return tableListShow(&excludeTables);
267 includeTablesShow(void)
269 return tableListShow(&includeTables);
273 matchOid(TableList *tbl, Oid oid)
275 Oid *StopLow = tbl->tables,
276 *StopHigh = tbl->tables + tbl->nTables,
279 /* Loop invariant: StopLow <= val < StopHigh */
280 while (StopLow < StopHigh)
282 StopMiddle = StopLow + ((StopHigh - StopLow) >> 1);
284 if (*StopMiddle == oid)
286 else if (*StopMiddle < oid)
287 StopLow = StopMiddle + 1;
289 StopHigh = StopMiddle;
295 static ExecutorEnd_hook_type oldhook = NULL;
298 makeAnalyze(Oid relOid, CmdType operation, uint32 naffected)
300 PgStat_StatTabEntry *tabentry;
301 TimestampTz now = GetCurrentTimestamp();
303 if (relOid == InvalidOid)
306 tabentry = pgstat_fetch_stat_tabentry(relOid);
308 #if PG_VERSION_NUM >= 90000
309 #define changes_since_analyze(t) ((t)->changes_since_analyze)
311 #define changes_since_analyze(t) ((t)->n_live_tuples + (t)->n_dead_tuples - (t)->last_anl_tuples)
315 tabentry == NULL /* a new table */ ||
317 /* do not analyze too often, if both stamps are exceeded the go */
318 TimestampDifferenceExceeds(tabentry->analyze_timestamp, now, online_analyze_min_interval) &&
319 TimestampDifferenceExceeds(tabentry->autovac_analyze_timestamp, now, online_analyze_min_interval) &&
320 /* be in sync with relation_needs_vacanalyze */
321 ((double)(changes_since_analyze(tabentry) + naffected)) >=
322 online_analyze_scale_factor * ((double)(tabentry->n_dead_tuples + tabentry->n_live_tuples)) +
323 (double)online_analyze_threshold
328 TimestampTz startStamp, endStamp;
331 * includeTables overwrites excludeTables
333 switch(online_analyze_table_type)
336 if (matchOid(&excludeTables, relOid) == true && matchOid(&includeTables, relOid) == false)
340 if (matchOid(&includeTables, relOid) == false)
344 case OATT_PERSISTENT:
348 OnlineAnalyzeTableType reltype;
350 rel = RelationIdGetRelation(relOid);
352 #if PG_VERSION_NUM >= 90100
353 (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
355 (rel->rd_istemp || rel->rd_islocaltemp)
357 ? OATT_TEMPORARY : OATT_PERSISTENT;
361 * skip analyze if relation's type doesn't not match online_analyze_table_type
363 if ((online_analyze_table_type & reltype) == 0 || matchOid(&excludeTables, relOid) == true)
365 if (matchOid(&includeTables, relOid) == false)
372 vacstmt.type = T_VacuumStmt;
373 vacstmt.freeze_min_age = -1;
374 vacstmt.freeze_table_age = -1; /* ??? */
375 vacstmt.relation = NULL;
376 vacstmt.va_cols = NIL;
378 #if PG_VERSION_NUM >= 90000
379 vacstmt.options = VACOPT_ANALYZE;
380 if (online_analyze_verbose)
381 vacstmt.options |= VACOPT_VERBOSE;
383 vacstmt.vacuum = vacstmt.full = false;
384 vacstmt.analyze = true;
385 vacstmt.verbose = online_analyze_verbose;
388 if (online_analyze_verbose)
389 startStamp = GetCurrentTimestamp();
391 analyze_rel(relOid, &vacstmt, GetAccessStrategy(BAS_VACUUM)
392 #if (PG_VERSION_NUM < 90004) && (PG_VERSION_NUM >= 90000)
397 if (online_analyze_verbose)
402 endStamp = GetCurrentTimestamp();
403 TimestampDifference(startStamp, endStamp, &secs, µsecs);
404 elog(INFO, "analyze \"%s\" took %.02f seconds",
405 get_rel_name(relOid), ((double)secs) + ((double)microsecs)/1.0e6);
409 if (tabentry == NULL)
412 pgstat_clear_snapshot();
416 /* update last analyze timestamp in local memory of backend */
417 tabentry->analyze_timestamp = now;
420 #if PG_VERSION_NUM >= 90000
421 else if (tabentry != NULL)
423 tabentry->changes_since_analyze += naffected;
428 extern PGDLLIMPORT void onlineAnalyzeHooker(QueryDesc *queryDesc);
430 onlineAnalyzeHooker(QueryDesc *queryDesc)
432 uint32 naffected = 0;
434 if (queryDesc->estate)
435 naffected = queryDesc->estate->es_processed;
437 if (online_analyze_enable && queryDesc->plannedstmt &&
438 (queryDesc->operation == CMD_INSERT ||
439 queryDesc->operation == CMD_UPDATE ||
440 queryDesc->operation == CMD_DELETE ||
441 #if PG_VERSION_NUM >= 90200
442 0 /* (queryDesc->operation == CMD_SELECT && queryDesc->dest && queryDesc->dest == DestIntoRel) */
444 (queryDesc->operation == CMD_SELECT && queryDesc->plannedstmt->intoClause)
448 #if PG_VERSION_NUM < 90200
449 if (queryDesc->operation == CMD_SELECT)
451 Oid relOid = RangeVarGetRelid(queryDesc->plannedstmt->intoClause->rel, true);
453 makeAnalyze(relOid, queryDesc->operation, naffected);
457 if (queryDesc->plannedstmt->resultRelations &&
458 queryDesc->plannedstmt->rtable)
462 foreach(l, queryDesc->plannedstmt->resultRelations)
464 int n = lfirst_int(l);
465 RangeTblEntry *rte = list_nth(queryDesc->plannedstmt->rtable, n-1);
467 if (rte->rtekind == RTE_RELATION)
468 makeAnalyze(rte->relid, queryDesc->operation, naffected);
474 (*oldhook)(queryDesc);
476 standard_ExecutorEnd(queryDesc);
483 oldhook = ExecutorEnd_hook;
485 ExecutorEnd_hook = onlineAnalyzeHooker;
487 DefineCustomBoolVariable(
488 "online_analyze.enable",
489 "Enable on-line analyze",
490 "Enables analyze of table directly after insert/update/delete/select into",
491 &online_analyze_enable,
492 #if PG_VERSION_NUM >= 80400
493 online_analyze_enable,
496 #if PG_VERSION_NUM >= 80400
498 #if PG_VERSION_NUM >= 90100
506 DefineCustomBoolVariable(
507 "online_analyze.verbose",
508 "Verbosity of on-line analyze",
509 "Make ANALYZE VERBOSE after table's changes",
510 &online_analyze_verbose,
511 #if PG_VERSION_NUM >= 80400
512 online_analyze_verbose,
515 #if PG_VERSION_NUM >= 80400
517 #if PG_VERSION_NUM >= 90100
525 DefineCustomRealVariable(
526 "online_analyze.scale_factor",
527 "fraction of table size to start on-line analyze",
528 "fraction of table size to start on-line analyze",
529 &online_analyze_scale_factor,
530 #if PG_VERSION_NUM >= 80400
531 online_analyze_scale_factor,
536 #if PG_VERSION_NUM >= 80400
538 #if PG_VERSION_NUM >= 90100
546 DefineCustomIntVariable(
547 "online_analyze.threshold",
548 "min number of row updates before on-line analyze",
549 "min number of row updates before on-line analyze",
550 &online_analyze_threshold,
551 #if PG_VERSION_NUM >= 80400
552 online_analyze_threshold,
557 #if PG_VERSION_NUM >= 80400
559 #if PG_VERSION_NUM >= 90100
567 DefineCustomRealVariable(
568 "online_analyze.min_interval",
569 "minimum time interval between analyze call (in milliseconds)",
570 "minimum time interval between analyze call (in milliseconds)",
571 &online_analyze_scale_factor,
572 #if PG_VERSION_NUM >= 80400
573 online_analyze_min_interval,
578 #if PG_VERSION_NUM >= 80400
580 #if PG_VERSION_NUM >= 90100
588 DefineCustomEnumVariable(
589 "online_analyze.table_type",
590 "Type(s) of table for online analyze: all(default), persistent, temporary, none",
592 &online_analyze_table_type,
593 #if PG_VERSION_NUM >= 80400
594 online_analyze_table_type,
596 online_analyze_table_type_options,
598 #if PG_VERSION_NUM >= 80400
600 #if PG_VERSION_NUM >= 90100
608 DefineCustomStringVariable(
609 "online_analyze.exclude_tables",
610 "List of tables which will not online analyze",
612 &excludeTables.tableStr,
613 #if PG_VERSION_NUM >= 80400
618 #if PG_VERSION_NUM >= 90100
627 DefineCustomStringVariable(
628 "online_analyze.include_tables",
629 "List of tables which will online analyze",
631 &includeTables.tableStr,
632 #if PG_VERSION_NUM >= 80400
637 #if PG_VERSION_NUM >= 90100
651 ExecutorEnd_hook = oldhook;
653 if (excludeTables.tables)
654 free(excludeTables.tables);
655 if (includeTables.tables)
656 free(includeTables.tables);
658 excludeTables.tables = includeTables.tables = NULL;
659 excludeTables.nTables = includeTables.nTables = 0;