cf5ccf34fbc5306d74a3b2b3e6c9d702243ebd2f
[plantuner.git] / plantuner.c
1 /*
2  * Copyright (c) 2009 Teodor Sigaev <teodor@sigaev.ru>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
16  *
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.
28  */
29
30 #include <postgres.h>
31
32 #include <fmgr.h>
33 #include <access/heapam.h>
34 #include <catalog/namespace.h>
35 #include <catalog/pg_class.h>
36 #include <nodes/pg_list.h>
37 #include <optimizer/plancat.h>
38 #include <storage/bufmgr.h>
39 #include <utils/builtins.h>
40 #include <utils/guc.h>
41 #include <utils/lsyscache.h>
42 #include <utils/rel.h>
43
44 PG_MODULE_MAGIC;
45
46 static int      nDisabledIndexes = 0;
47 static Oid      *disabledIndexes = NULL;
48 static char *disableIndexesOutStr = "";
49
50 static int      nEnabledIndexes = 0;
51 static Oid      *enabledIndexes = NULL;
52 static char *enableIndexesOutStr = "";
53
54 get_relation_info_hook_type     prevHook = NULL;
55 static bool     fix_empty_table = false;
56
57
58 static const char *
59 indexesAssign(const char * newval, bool doit, GucSource source, bool isDisable) 
60 {
61         char       *rawname;
62         List       *namelist;
63         ListCell   *l;
64         Oid                     *newOids = NULL;
65         int                     nOids = 0,
66                                 i = 0;
67
68         rawname = pstrdup(newval);
69
70         if (!SplitIdentifierString(rawname, ',', &namelist))
71                 goto cleanup;
72
73         if (doit) 
74         {
75                 nOids = list_length(namelist);
76                 newOids = malloc(sizeof(Oid) * (nOids+1));
77                 if (!newOids)
78                         elog(ERROR,"could not allocate %d bytes", (int)(sizeof(Oid) * (nOids+1)));
79         }
80
81         foreach(l, namelist)
82         {
83                 char            *curname = (char *) lfirst(l);
84 #if PG_VERSION_NUM >= 90200
85                 Oid                     indexOid = RangeVarGetRelid(makeRangeVarFromNameList(stringToQualifiedNameList(curname)), 
86                                                                                                 NoLock, true);
87 #else
88                 Oid                     indexOid = RangeVarGetRelid(makeRangeVarFromNameList(stringToQualifiedNameList(curname)), 
89                                                                                                 true);
90 #endif
91
92                 if (indexOid == InvalidOid)
93                 {
94 #if PG_VERSION_NUM >= 90100
95                         if (doit == false)
96 #endif
97                                 elog(WARNING,"'%s' does not exist", curname);
98                         continue;
99                 }
100                 else if ( get_rel_relkind(indexOid) != RELKIND_INDEX )
101                 {
102 #if PG_VERSION_NUM >= 90100
103                         if (doit == false)
104 #endif
105                                 elog(WARNING,"'%s' is not an index", curname);
106                         continue;
107                 }
108                 else if (doit)
109                 {
110                         newOids[i++] = indexOid;
111                 }
112         }
113
114         if (doit) 
115         {
116                 if (isDisable)
117                 {
118                         nDisabledIndexes = nOids;
119                         disabledIndexes = newOids;
120                 }
121                 else
122                 {
123                         nEnabledIndexes = nOids;
124                         enabledIndexes = newOids;
125                 }
126         }
127
128         pfree(rawname);
129         list_free(namelist);
130
131         return newval;
132
133 cleanup:
134         if (newOids)
135                 free(newOids);
136         pfree(rawname);
137         list_free(namelist);
138         return NULL;
139 }
140
141 static const char *
142 assignDisabledIndexes(const char * newval, bool doit, GucSource source)
143 {
144         return indexesAssign(newval, doit, source, true);       
145 }
146
147 static const char *
148 assignEnabledIndexes(const char * newval, bool doit, GucSource source)
149 {
150         return indexesAssign(newval, doit, source, false);      
151 }
152
153 #if PG_VERSION_NUM >= 90100
154
155 static bool
156 checkDisabledIndexes(char **newval, void **extra, GucSource source)
157 {
158         char *val;
159
160         val = (char*)indexesAssign(*newval, false, source, true);
161
162         if (val)
163         {
164                 *newval = val;
165                 return true;
166         }
167
168         return false;
169 }
170
171 static bool
172 checkEnabledIndexes(char **newval, void **extra, GucSource source)
173 {
174         char *val;
175
176         val = (char*)indexesAssign(*newval, false, source, false);
177
178         if (val)
179         {
180                 *newval = val;
181                 return true;
182         }
183
184         return false;
185 }
186
187 static void
188 assignDisabledIndexesNew(const char *newval, void *extra)
189 {
190         assignDisabledIndexes(newval, true, PGC_S_USER /* doesn't matter */);
191 }
192
193 static void
194 assignEnabledIndexesNew(const char *newval, void *extra)
195 {
196         assignEnabledIndexes(newval, true, PGC_S_USER /* doesn't matter */);
197 }
198
199 #endif
200
201 static void
202 indexFilter(PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel) {
203         int i;
204
205         for(i=0;i<nDisabledIndexes;i++)
206         {
207                 ListCell   *l;
208
209                 foreach(l, rel->indexlist)
210                 {
211                         IndexOptInfo    *info = (IndexOptInfo*)lfirst(l);
212
213                         if (disabledIndexes[i] == info->indexoid)
214                         {
215                                 int j;
216
217                                 for(j=0; j<nEnabledIndexes; j++)
218                                         if (enabledIndexes[j] == info->indexoid)
219                                                 break;
220
221                                 if (j >= nEnabledIndexes)
222                                         rel->indexlist = list_delete_ptr(rel->indexlist, info);
223
224                                 break;
225                         }
226                 }
227         }
228 }
229
230 static void
231 execPlantuner(PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel) {
232         Relation        relation;
233
234         relation = heap_open(relationObjectId, NoLock);
235         if (relation->rd_rel->relkind == RELKIND_RELATION)
236         {
237                 if (fix_empty_table && RelationGetNumberOfBlocks(relation) == 0)
238                 {
239                         /*
240                          * estimate_rel_size() could be too pessimistic for particular
241                          * workload
242                          */
243                         rel->pages = 0.0;
244                         rel->tuples = 0.0;
245                 }
246
247                 indexFilter(root, relationObjectId, inhparent, rel);
248         }
249         heap_close(relation, NoLock);
250
251         /*
252          * Call next hook if it exists 
253          */
254         if (prevHook)
255                 prevHook(root, relationObjectId, inhparent, rel);
256 }
257
258 static const char*
259 IndexFilterShow(Oid* indexes, int nIndexes) 
260 {
261         char    *val, *ptr;
262         int     i,
263                         len;
264
265         len = 1 /* \0 */ + nIndexes * (2 * NAMEDATALEN + 2 /* ', ' */ + 1 /* . */);
266         ptr = val = palloc(len);
267
268         *ptr =(char)'\0';
269         for(i=0; i<nIndexes; i++)
270         {
271                 char    *relname = get_rel_name(indexes[i]);
272                 Oid     nspOid = get_rel_namespace(indexes[i]);
273                 char    *nspname = get_namespace_name(nspOid); 
274
275                 if ( relname == NULL || nspOid == InvalidOid || nspname == NULL )
276                         continue;
277
278                 ptr += snprintf(ptr, len - (ptr - val), "%s%s.%s",
279                                                                                                 (i==0) ? "" : ", ",
280                                                                                                 nspname,
281                                                                                                 relname);
282         }
283
284         return val;
285 }
286
287 static const char*
288 disabledIndexFilterShow(void)
289 {
290         return IndexFilterShow(disabledIndexes, nDisabledIndexes);
291 }
292
293 static const char*
294 enabledIndexFilterShow(void)
295 {
296         return IndexFilterShow(enabledIndexes, nEnabledIndexes);
297 }
298
299 void _PG_init(void);
300 void
301 _PG_init(void) 
302 {
303     DefineCustomStringVariable(
304                 "plantuner.forbid_index",
305                 "List of forbidden indexes (deprecated)",
306                 "Listed indexes will not be used in queries (deprecated, use plantuner.disable_index)",
307                 &disableIndexesOutStr,
308                 "",
309                 PGC_USERSET,
310                 0,
311 #if PG_VERSION_NUM >= 90100
312                 checkDisabledIndexes,
313                 assignDisabledIndexesNew,
314 #else
315                 assignDisabledIndexes,
316 #endif
317                 disabledIndexFilterShow
318         );
319
320     DefineCustomStringVariable(
321                 "plantuner.disable_index",
322                 "List of disabled indexes",
323                 "Listed indexes will not be used in queries",
324                 &disableIndexesOutStr,
325                 "",
326                 PGC_USERSET,
327                 0,
328 #if PG_VERSION_NUM >= 90100
329                 checkDisabledIndexes,
330                 assignDisabledIndexesNew,
331 #else
332                 assignDisabledIndexes,
333 #endif
334                 disabledIndexFilterShow
335         );
336
337     DefineCustomStringVariable(
338                 "plantuner.enable_index",
339                 "List of enabled indexes (overload plantuner.disable_index)",
340                 "Listed indexes which could be used in queries even they are listed in plantuner.disable_index",
341                 &enableIndexesOutStr,
342                 "",
343                 PGC_USERSET,
344                 0,
345 #if PG_VERSION_NUM >= 90100
346                 checkEnabledIndexes,
347                 assignEnabledIndexesNew,
348 #else
349                 assignEnabledIndexes,
350 #endif
351                 enabledIndexFilterShow
352         );
353
354     DefineCustomBoolVariable(
355                 "plantuner.fix_empty_table",
356                 "Sets to zero estimations for empty tables",
357                 "Sets to zero estimations for empty or newly created tables",
358                 &fix_empty_table,
359 #if PG_VERSION_NUM >= 80400
360                 fix_empty_table,
361 #endif
362                 PGC_USERSET,
363 #if PG_VERSION_NUM >= 80400
364                 GUC_NOT_IN_SAMPLE,
365 #if PG_VERSION_NUM >= 90100
366                 NULL,
367 #endif
368 #endif
369                 NULL,
370                 NULL
371         );
372
373         if (get_relation_info_hook != execPlantuner )
374         {
375                 prevHook = get_relation_info_hook;
376                 get_relation_info_hook = execPlantuner;
377         }
378 }