-
Notifications
You must be signed in to change notification settings - Fork 59
/
hypopg.c
553 lines (480 loc) · 12 KB
/
hypopg.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
/*-------------------------------------------------------------------------
*
* hypopg.c: Implementation of hypothetical indexes for PostgreSQL
*
* Some functions are imported from PostgreSQL source code, theses are present
* in hypopg_import.* files.
*
* This program is open source, licensed under the PostgreSQL license.
* For license terms, see the LICENSE file.
*
* Copyright (C) 2015-2024: Julien Rouhaud
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "fmgr.h"
#if PG_VERSION_NUM < 120000
#include "access/sysattr.h"
#endif
#include "access/transam.h"
#if PG_VERSION_NUM < 140000
#include "catalog/indexing.h"
#endif
#if PG_VERSION_NUM >= 110000
#include "catalog/partition.h"
#include "nodes/pg_list.h"
#include "utils/lsyscache.h"
#endif
#include "executor/spi.h"
#include "miscadmin.h"
#include "utils/elog.h"
#include "include/hypopg.h"
#include "include/hypopg_import.h"
#include "include/hypopg_index.h"
PG_MODULE_MAGIC;
/*--- Variables exported ---*/
bool isExplain;
bool hypo_is_enabled;
bool hypo_use_real_oids;
MemoryContext HypoMemoryContext;
/*--- Private variables ---*/
static Oid last_oid = InvalidOid;
static Oid min_fake_oid = InvalidOid;
static bool oid_wraparound = false;
/*--- Functions --- */
PGDLLEXPORT void _PG_init(void);
PGDLLEXPORT Datum hypopg_reset(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(hypopg_reset);
static void
hypo_utility_hook(
#if PG_VERSION_NUM >= 100000
PlannedStmt *pstmt,
#else
Node *parsetree,
#endif
const char *queryString,
#if PG_VERSION_NUM >= 140000
bool readOnlyTree,
#endif
#if PG_VERSION_NUM >= 90300
ProcessUtilityContext context,
#endif
ParamListInfo params,
#if PG_VERSION_NUM >= 100000
QueryEnvironment *queryEnv,
#endif
#if PG_VERSION_NUM < 90300
bool isTopLevel,
#endif
DestReceiver *dest,
#if PG_VERSION_NUM < 130000
char *completionTag
#else
QueryCompletion *qc
#endif
);
static ProcessUtility_hook_type prev_utility_hook = NULL;
static void hypo_executorEnd_hook(QueryDesc *queryDesc);
static ExecutorEnd_hook_type prev_ExecutorEnd_hook = NULL;
static Oid hypo_get_min_fake_oid(void);
static void hypo_get_relation_info_hook(PlannerInfo *root,
Oid relationObjectId,
bool inhparent,
RelOptInfo *rel);
static get_relation_info_hook_type prev_get_relation_info_hook = NULL;
static bool hypo_index_match_table(hypoIndex *entry, Oid relid);
static bool hypo_is_simple_explain(Node *node);
void
_PG_init(void)
{
/* Install hooks */
prev_utility_hook = ProcessUtility_hook;
ProcessUtility_hook = hypo_utility_hook;
prev_ExecutorEnd_hook = ExecutorEnd_hook;
ExecutorEnd_hook = hypo_executorEnd_hook;
prev_get_relation_info_hook = get_relation_info_hook;
get_relation_info_hook = hypo_get_relation_info_hook;
prev_explain_get_index_name_hook = explain_get_index_name_hook;
explain_get_index_name_hook = hypo_explain_get_index_name_hook;
isExplain = false;
hypoIndexes = NIL;
hypoHiddenIndexes = NIL;
HypoMemoryContext = AllocSetContextCreate(TopMemoryContext,
"HypoPG context",
#if PG_VERSION_NUM >= 90600
ALLOCSET_DEFAULT_SIZES
#else
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE
#endif
);
DefineCustomBoolVariable("hypopg.enabled",
"Enable / Disable hypopg",
NULL,
&hypo_is_enabled,
true,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("hypopg.use_real_oids",
"Use real oids rather than the range < 16384",
NULL,
&hypo_use_real_oids,
false,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
EmitWarningsOnPlaceholders("hypopg");
}
/*---------------------------------
* Return a new OID for an hypothetical index.
*
* To avoid locking on pg_class (required to safely call GetNewOidWithIndex or
* similar) and to be usable on a standby node, use the oids unused in the
* FirstBootstrapObjectId / FirstNormalObjectId range rather than real oids.
* For performance, always start with the biggest oid lesser than
* FirstNormalObjectId. This way the loop to find an unused oid will only
* happens once a single backend has created more than ~2.5k hypothetical
* indexes.
*
* For people needing to have thousands of hypothetical indexes at the same
* time, we also allow to use the initial implementation that relies on real
* oids, which comes with all the limitations mentioned above.
*/
Oid
hypo_getNewOid(Oid relid)
{
Oid newoid = InvalidOid;
if (hypo_use_real_oids)
{
Relation pg_class;
Relation relation;
/* Open the relation on which we want a new OID */
relation = table_open(relid, AccessShareLock);
/* Close the relation and release the lock now */
table_close(relation, AccessShareLock);
/* Open pg_class to aks a new OID */
pg_class = table_open(RelationRelationId, RowExclusiveLock);
/* ask for a new Oid */
newoid = GetNewOidWithIndex(pg_class, ClassOidIndexId,
#if PG_VERSION_NUM < 120000
ObjectIdAttributeNumber
#else
Anum_pg_class_oid
#endif
);
/* Close pg_class and release the lock now */
table_close(pg_class, RowExclusiveLock);
}
else
{
/*
* First, make sure we know what is the biggest oid smaller than
* FirstNormalObjectId present in pg_class. This can never change so
* we cache the value.
*/
if (!OidIsValid(min_fake_oid))
min_fake_oid = hypo_get_min_fake_oid();
Assert(OidIsValid(min_fake_oid));
/* Make sure there's enough room to get one more Oid */
if (list_length(hypoIndexes) >= (FirstNormalObjectId - min_fake_oid))
{
ereport(ERROR,
(errmsg("hypopg: not more oid available"),
errhint("Remove hypothetical indexes "
"or enable hypopg.use_real_oids")));
}
while(!OidIsValid(newoid))
{
CHECK_FOR_INTERRUPTS();
if (!OidIsValid(last_oid))
newoid = last_oid = min_fake_oid;
else
newoid = ++last_oid;
/* Check if we just exceeded the fake oids range */
if (newoid >= FirstNormalObjectId)
{
newoid = min_fake_oid;
last_oid = InvalidOid;
oid_wraparound = true;
}
/*
* If we already used all available fake oids, we have to make sure
* that the oid isn't used anymore.
*/
if (oid_wraparound)
{
if (hypo_get_index(newoid) != NULL)
{
/* We can't use this oid. Reset newoid and start again */
newoid = InvalidOid;
}
}
}
}
Assert(OidIsValid(newoid));
return newoid;
}
/* Reset the state of the fake oid generator. */
void
hypo_reset_fake_oids(void)
{
Assert(hypoIndexes == NIL);
last_oid = InvalidOid;
oid_wraparound = false;
}
/* This function setup the "isExplain" flag for next hooks.
* If this flag is setup, we can add hypothetical indexes.
*/
void
hypo_utility_hook(
#if PG_VERSION_NUM >= 100000
PlannedStmt *pstmt,
#else
Node *parsetree,
#endif
const char *queryString,
#if PG_VERSION_NUM >= 140000
bool readOnlyTree,
#endif
#if PG_VERSION_NUM >= 90300
ProcessUtilityContext context,
#endif
ParamListInfo params,
#if PG_VERSION_NUM >= 100000
QueryEnvironment *queryEnv,
#endif
#if PG_VERSION_NUM < 90300
bool isTopLevel,
#endif
DestReceiver *dest,
#if PG_VERSION_NUM < 130000
char *completionTag
#else
QueryCompletion *qc
#endif
)
{
isExplain = hypo_is_simple_explain(
#if PG_VERSION_NUM >= 100000
(Node *) pstmt
#else
parsetree
#endif
);
if (prev_utility_hook)
prev_utility_hook(
#if PG_VERSION_NUM >= 100000
pstmt,
#else
parsetree,
#endif
queryString,
#if PG_VERSION_NUM >= 140000
readOnlyTree,
#endif
#if PG_VERSION_NUM >= 90300
context,
#endif
params,
#if PG_VERSION_NUM >= 100000
queryEnv,
#endif
#if PG_VERSION_NUM < 90300
isTopLevel,
#endif
dest,
#if PG_VERSION_NUM < 130000
completionTag
#else
qc
#endif
);
else
standard_ProcessUtility(
#if PG_VERSION_NUM >= 100000
pstmt,
#else
parsetree,
#endif
queryString,
#if PG_VERSION_NUM >= 140000
readOnlyTree,
#endif
#if PG_VERSION_NUM >= 90300
context,
#endif
params,
#if PG_VERSION_NUM >= 100000
queryEnv,
#endif
#if PG_VERSION_NUM < 90300
isTopLevel,
#endif
dest,
#if PG_VERSION_NUM < 130000
completionTag
#else
qc
#endif
);
}
static bool
hypo_index_match_table(hypoIndex *entry, Oid relid)
{
/* Hypothetical index on the exact same relation, use it. */
if (entry->relid == relid)
return true;
#if PG_VERSION_NUM >= 110000
/*
* If the table is a partition, see if the hypothetical index belongs to
* one of the partition parent.
*/
if (get_rel_relispartition(relid))
{
List *parents = get_partition_ancestors(relid);
ListCell *lc;
foreach(lc, parents)
{
Oid oid = lfirst_oid(lc);
if (oid == entry->relid)
return true;
}
}
#endif
return false;
}
/* Detect if the current utility command is compatible with hypothetical indexes
* i.e. an EXPLAIN, no ANALYZE
*/
static bool
hypo_is_simple_explain(Node *parsetree)
{
if (parsetree == NULL)
return false;
#if PG_VERSION_NUM >= 100000
parsetree = ((PlannedStmt *) parsetree)->utilityStmt;
if (parsetree == NULL)
return false;
#endif
switch (nodeTag(parsetree))
{
case T_ExplainStmt:
{
ListCell *lc;
foreach(lc, ((ExplainStmt *) parsetree)->options)
{
DefElem *opt = (DefElem *) lfirst(lc);
if (strcmp(opt->defname, "analyze") == 0)
return false;
}
}
return true;
break;
default:
return false;
}
return false;
}
/* Reset the isExplain flag after each query */
static void
hypo_executorEnd_hook(QueryDesc *queryDesc)
{
isExplain = false;
if (prev_ExecutorEnd_hook)
prev_ExecutorEnd_hook(queryDesc);
else
standard_ExecutorEnd(queryDesc);
}
/*
* Return the minmum usable oid in the FirstBootstrapObjectId -
* FirstNormalObjectId range.
*/
static Oid
hypo_get_min_fake_oid(void)
{
int ret, nb;
Oid oid = InvalidOid;
/*
* Connect to SPI manager
*/
if ((ret = SPI_connect()) < 0)
/* internal error */
elog(ERROR, "SPI connect failure - returned %d", ret);
ret = SPI_execute("SELECT max(oid)"
" FROM pg_catalog.pg_class"
" WHERE oid < " CppAsString2(FirstNormalObjectId),
true, 1);
nb = SPI_processed;
if (ret != SPI_OK_SELECT || nb == 0)
{
SPI_finish();
elog(ERROR, "hypopg: could not find the minimum fake oid");
}
oid = atooid(SPI_getvalue(SPI_tuptable->vals[0],
SPI_tuptable->tupdesc,
1)) + 1;
/* release SPI related resources (and return to caller's context) */
SPI_finish();
Assert(OidIsValid(oid));
return oid;
}
/*
* This function will execute the "hypo_injectHypotheticalIndex" for every
* hypothetical index found for each relation if the isExplain flag is setup.
*/
static void
hypo_get_relation_info_hook(PlannerInfo *root,
Oid relationObjectId,
bool inhparent,
RelOptInfo *rel)
{
if (isExplain && hypo_is_enabled)
{
Relation relation;
/* Open the current relation */
relation = table_open(relationObjectId, AccessShareLock);
if (relation->rd_rel->relkind == RELKIND_RELATION
#if PG_VERSION_NUM >= 90300
|| relation->rd_rel->relkind == RELKIND_MATVIEW
#endif
)
{
ListCell *lc;
foreach(lc, hypoIndexes)
{
hypoIndex *entry = (hypoIndex *) lfirst(lc);
if (hypo_index_match_table(entry, RelationGetRelid(relation)))
{
/*
* hypothetical index found, add it to the relation's
* indextlist
*/
hypo_injectHypotheticalIndex(root, relationObjectId,
inhparent, rel, relation, entry);
}
}
/* Check if we need to hide any existing index. */
hypo_hideIndexes(rel);
}
/* Close the relation release the lock now */
table_close(relation, AccessShareLock);
}
if (prev_get_relation_info_hook)
prev_get_relation_info_hook(root, relationObjectId, inhparent, rel);
}
/*
* Reset statistics.
*/
PGDLLEXPORT Datum
hypopg_reset(PG_FUNCTION_ARGS)
{
hypo_index_reset();
PG_RETURN_VOID();
}