5ef74dd9fe38414a83c2ebf80c6cb1e8d1ddc7ab
[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                 Oid                     indexOid = RangeVarGetRelid(makeRangeVarFromNameList(stringToQualifiedNameList(curname)), 
85 #if PG_VERSION_NUM >= 90200
86                                                                                                 NoLock,
87 #endif
88                                                                                                 true);
89
90                 if (indexOid == InvalidOid)
91                 {
92 #if PG_VERSION_NUM >= 90100
93                         if (doit == false)
94 #endif
95                                 elog(WARNING,"'%s' does not exist", curname);
96                         continue;
97                 }
98                 else if ( get_rel_relkind(indexOid) != RELKIND_INDEX )
99                 {
100 #if PG_VERSION_NUM >= 90100
101                         if (doit == false)
102 #endif
103                                 elog(WARNING,"'%s' is not an index", curname);
104                         continue;
105                 }
106                 else if (doit)
107                 {
108                         newOids[i++] = indexOid;
109                 }
110         }
111
112         if (doit) 
113         {
114                 if (isDisable)
115                 {
116                         nDisabledIndexes = nOids;
117                         disabledIndexes = newOids;
118                 }
119                 else
120                 {
121                         nEnabledIndexes = nOids;
122                         enabledIndexes = newOids;
123                 }
124         }
125
126         pfree(rawname);
127         list_free(namelist);
128
129         return newval;
130
131 cleanup:
132         if (newOids)
133                 free(newOids);
134         pfree(rawname);
135         list_free(namelist);
136         return NULL;
137 }
138
139 static const char *
140 assignDisabledIndexes(const char * newval, bool doit, GucSource source)
141 {
142         return indexesAssign(newval, doit, source, true);       
143 }
144
145 static const char *
146 assignEnabledIndexes(const char * newval, bool doit, GucSource source)
147 {
148         return indexesAssign(newval, doit, source, false);      
149 }
150
151 #if PG_VERSION_NUM >= 90100
152
153 static bool
154 checkDisabledIndexes(char **newval, void **extra, GucSource source)
155 {
156         char *val;
157
158         val = (char*)indexesAssign(*newval, false, source, true);
159
160         if (val)
161         {
162                 *newval = val;
163                 return true;
164         }
165
166         return false;
167 }
168
169 static bool
170 checkEnabledIndexes(char **newval, void **extra, GucSource source)
171 {
172         char *val;
173
174         val = (char*)indexesAssign(*newval, false, source, false);
175
176         if (val)
177         {
178                 *newval = val;
179                 return true;
180         }
181
182         return false;
183 }
184
185 static void
186 assignDisabledIndexesNew(const char *newval, void *extra)
187 {
188         assignDisabledIndexes(newval, true, PGC_S_USER /* doesn't matter */);
189 }
190
191 static void
192 assignEnabledIndexesNew(const char *newval, void *extra)
193 {
194         assignEnabledIndexes(newval, true, PGC_S_USER /* doesn't matter */);
195 }
196
197 #endif
198
199 static void
200 indexFilter(PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel) {
201         int i;
202
203         for(i=0;i<nDisabledIndexes;i++)
204         {
205                 ListCell   *l;
206
207                 foreach(l, rel->indexlist)
208                 {
209                         IndexOptInfo    *info = (IndexOptInfo*)lfirst(l);
210
211                         if (disabledIndexes[i] == info->indexoid)
212                         {
213                                 int j;
214
215                                 for(j=0; j<nEnabledIndexes; j++)
216                                         if (enabledIndexes[j] == info->indexoid)
217                                                 break;
218
219                                 if (j >= nEnabledIndexes)
220                                         rel->indexlist = list_delete_ptr(rel->indexlist, info);
221
222                                 break;
223                         }
224                 }
225         }
226
227         if (fix_empty_table && rel)
228         {
229                 
230
231         }
232
233 }
234
235 static void
236 execPlantuner(PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel) {
237         Relation        relation;
238
239         relation = heap_open(relationObjectId, NoLock);
240         if (relation->rd_rel->relkind == RELKIND_RELATION)
241         {
242                 if (fix_empty_table && RelationGetNumberOfBlocks(relation) == 0)
243                 {
244                         /*
245                          * estimate_rel_size() could be too pessimistic for particular
246                          * workload
247                          */
248                         rel->pages = 0.0;
249                         rel->tuples = 0.0;
250                 }
251
252                 indexFilter(root, relationObjectId, inhparent, rel);
253         }
254         heap_close(relation, NoLock);
255
256         /*
257          * Call next hook if it exists 
258          */
259         if (prevHook)
260                 prevHook(root, relationObjectId, inhparent, rel);
261 }
262
263 static const char*
264 IndexFilterShow(Oid* indexes, int nIndexes) 
265 {
266         char    *val, *ptr;
267         int     i,
268                         len;
269
270         len = 1 /* \0 */ + nIndexes * (2 * NAMEDATALEN + 2 /* ', ' */ + 1 /* . */);
271         ptr = val = palloc(len);
272
273         *ptr ='\0';
274         for(i=0; i<nIndexes; i++)
275         {
276                 char    *relname = get_rel_name(indexes[i]);
277                 Oid     nspOid = get_rel_namespace(indexes[i]);
278                 char    *nspname = get_namespace_name(nspOid); 
279
280                 if ( relname == NULL || nspOid == InvalidOid || nspname == NULL )
281                         continue;
282
283                 ptr += snprintf(ptr, len - (ptr - val), "%s%s.%s",
284                                                                                                 (i==0) ? "" : ", ",
285                                                                                                 nspname,
286                                                                                                 relname);
287         }
288
289         return val;
290 }
291
292 static const char*
293 disabledIndexFilterShow()
294 {
295         return IndexFilterShow(disabledIndexes, nDisabledIndexes);
296 }
297
298 static const char*
299 enabledIndexFilterShow()
300 {
301         return IndexFilterShow(enabledIndexes, nEnabledIndexes);
302 }
303
304 void _PG_init(void);
305 void
306 _PG_init(void) 
307 {
308     DefineCustomStringVariable(
309                 "plantuner.forbid_index",
310                 "List of forbidden indexes (deprecated)",
311                 "Listed indexes will not be used in queries (deprecated, use plantuner.disable_index)",
312                 &disableIndexesOutStr,
313                 "",
314                 PGC_USERSET,
315                 0,
316 #if PG_VERSION_NUM >= 90100
317                 checkDisabledIndexes,
318                 assignDisabledIndexesNew,
319 #else
320                 assignDisabledIndexes,
321 #endif
322                 disabledIndexFilterShow
323         );
324
325     DefineCustomStringVariable(
326                 "plantuner.disable_index",
327                 "List of disabled indexes",
328                 "Listed indexes will not be used in queries",
329                 &disableIndexesOutStr,
330                 "",
331                 PGC_USERSET,
332                 0,
333 #if PG_VERSION_NUM >= 90100
334                 checkDisabledIndexes,
335                 assignDisabledIndexesNew,
336 #else
337                 assignDisabledIndexes,
338 #endif
339                 disabledIndexFilterShow
340         );
341
342     DefineCustomStringVariable(
343                 "plantuner.enable_index",
344                 "List of enabled indexes (overload plantuner.disable_index)",
345                 "Listed indexes which could be used in queries even they are listed in plantuner.disable_index",
346                 &enableIndexesOutStr,
347                 "",
348                 PGC_USERSET,
349                 0,
350 #if PG_VERSION_NUM >= 90100
351                 checkEnabledIndexes,
352                 assignEnabledIndexesNew,
353 #else
354                 assignEnabledIndexes,
355 #endif
356                 enabledIndexFilterShow
357         );
358
359     DefineCustomBoolVariable(
360                 "plantuner.fix_empty_table",
361                 "Sets to zero estimations for empty tables",
362                 "Sets to zero estimations for empty or newly created tables",
363                 &fix_empty_table,
364 #if PG_VERSION_NUM >= 80400
365                 fix_empty_table,
366 #endif
367                 PGC_USERSET,
368 #if PG_VERSION_NUM >= 80400
369                 GUC_NOT_IN_SAMPLE,
370 #if PG_VERSION_NUM >= 90100
371                 NULL,
372 #endif
373 #endif
374                 NULL,
375                 NULL
376         );
377
378         if (get_relation_info_hook != execPlantuner )
379         {
380                 prevHook = get_relation_info_hook;
381                 get_relation_info_hook = execPlantuner;
382         }
383 }