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