-
Notifications
You must be signed in to change notification settings - Fork 59
/
hypopg_index.c
2373 lines (2044 loc) · 64.8 KB
/
hypopg_index.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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* hypopg_index.c: Implementation of hypothetical indexes for PostgreSQL
*
* This file contains all the internal code related to hypothetical indexes
* support.
*
* This program is open source, licensed under the PostgreSQL license.
* For license terms, see the LICENSE file.
*
* Copyright (C) 2015-2024: Julien Rouhaud
*
*-------------------------------------------------------------------------
*/
#include <unistd.h>
#include <math.h>
#include "postgres.h"
#include "fmgr.h"
#include "funcapi.h"
#include "miscadmin.h"
#if PG_VERSION_NUM >= 90500
#include "access/brin.h"
#include "access/brin_page.h"
#include "access/brin_tuple.h"
#endif
#include "access/gist.h"
#if PG_VERSION_NUM >= 90300
#include "access/htup_details.h"
#endif
#include "access/nbtree.h"
#include "access/reloptions.h"
#include "access/spgist.h"
#include "access/spgist_private.h"
#include "access/sysattr.h"
#include "access/xlog.h"
#include "catalog/namespace.h"
#include "catalog/pg_am.h"
#include "catalog/pg_amproc.h"
#include "catalog/pg_class.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#if PG_VERSION_NUM >= 120000
#include "nodes/makefuncs.h"
#endif
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#if PG_VERSION_NUM < 120000
#include "optimizer/var.h"
#else
#include "optimizer/optimizer.h"
#endif
#include "parser/parse_utilcmd.h"
#include "parser/parser.h"
#if PG_VERSION_NUM >= 120000
#include "port/pg_bitutils.h"
#endif
#include "storage/bufmgr.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#if PG_VERSION_NUM >= 90500
#include "utils/ruleutils.h"
#endif
#include "utils/syscache.h"
#include "include/hypopg.h"
#include "include/hypopg_index.h"
#if PG_VERSION_NUM >= 90600
/* this will be updated, when needed, by hypo_discover_am */
static Oid BLOOM_AM_OID = InvalidOid;
#endif
/*--- Variables exported ---*/
explain_get_index_name_hook_type prev_explain_get_index_name_hook;
List *hypoIndexes;
List *hypoHiddenIndexes;
/*--- Functions --- */
PG_FUNCTION_INFO_V1(hypopg);
PG_FUNCTION_INFO_V1(hypopg_create_index);
PG_FUNCTION_INFO_V1(hypopg_drop_index);
PG_FUNCTION_INFO_V1(hypopg_relation_size);
PG_FUNCTION_INFO_V1(hypopg_get_indexdef);
PG_FUNCTION_INFO_V1(hypopg_reset_index);
PG_FUNCTION_INFO_V1(hypopg_hide_index);
PG_FUNCTION_INFO_V1(hypopg_unhide_index);
PG_FUNCTION_INFO_V1(hypopg_unhide_all_indexes);
PG_FUNCTION_INFO_V1(hypopg_hidden_indexes);
static void hypo_addIndex(hypoIndex * entry);
static bool hypo_can_return(hypoIndex * entry, Oid atttype, int i, char *amname);
static void hypo_discover_am(char *amname, Oid oid);
static void hypo_estimate_index_simple(hypoIndex * entry,
BlockNumber *pages, double *tuples);
static void hypo_estimate_index(hypoIndex * entry, RelOptInfo *rel);
static int hypo_estimate_index_colsize(hypoIndex * entry, int col);
static void hypo_index_pfree(hypoIndex * entry);
static bool hypo_index_remove(Oid indexid);
static bool hypo_index_unhide(Oid indexid);
static const hypoIndex *hypo_index_store_parsetree(IndexStmt *node,
const char *queryString);
static hypoIndex * hypo_newIndex(Oid relid, char *accessMethod, int nkeycolumns,
int ninccolumns,
List *options);
static void hypo_set_indexname(hypoIndex * entry, char *indexname);
/*
* palloc a new hypoIndex, and give it a new OID, and some other global stuff.
* This function also parse index storage options (if any) to check if they're
* valid.
*/
static hypoIndex *
hypo_newIndex(Oid relid, char *accessMethod, int nkeycolumns, int ninccolumns,
List *options)
{
/* must be declared "volatile", because used in a PG_CATCH() */
hypoIndex *volatile entry;
MemoryContext oldcontext;
HeapTuple tuple;
Oid oid;
#if PG_VERSION_NUM >= 90600
IndexAmRoutine *amroutine;
amoptions_function amoptions;
#else
RegProcedure amoptions;
#endif
tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethod));
if (!HeapTupleIsValid(tuple))
{
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("hypopg: access method \"%s\" does not exist",
accessMethod)));
}
#if PG_VERSION_NUM < 120000
oid = HeapTupleGetOid(tuple);
#else
oid = ((Form_pg_am) GETSTRUCT(tuple))->oid;
#endif
hypo_discover_am(accessMethod, oid);
oldcontext = MemoryContextSwitchTo(HypoMemoryContext);
entry = palloc0(sizeof(hypoIndex));
entry->relam = oid;
#if PG_VERSION_NUM >= 90600
/*
* Since 9.6, AM informations are available through an amhandler function,
* returning an IndexAmRoutine containing what's needed.
*/
amroutine = GetIndexAmRoutine(((Form_pg_am) GETSTRUCT(tuple))->amhandler);
entry->amcostestimate = amroutine->amcostestimate;
entry->amcanreturn = amroutine->amcanreturn;
entry->amcanorderbyop = amroutine->amcanorderbyop;
entry->amoptionalkey = amroutine->amoptionalkey;
entry->amsearcharray = amroutine->amsearcharray;
entry->amsearchnulls = amroutine->amsearchnulls;
entry->amhasgettuple = (amroutine->amgettuple != NULL);
entry->amhasgetbitmap = (amroutine->amgetbitmap != NULL);
entry->amcanunique = amroutine->amcanunique;
entry->amcanmulticol = amroutine->amcanmulticol;
amoptions = amroutine->amoptions;
entry->amcanorder = amroutine->amcanorder;
#if PG_VERSION_NUM >= 110000
entry->amcanparallel = amroutine->amcanparallel;
entry->amcaninclude = amroutine->amcaninclude;
#endif
#else
/* Up to 9.5, all information is available in the pg_am tuple */
entry->amcostestimate = ((Form_pg_am) GETSTRUCT(tuple))->amcostestimate;
entry->amcanreturn = ((Form_pg_am) GETSTRUCT(tuple))->amcanreturn;
entry->amcanorderbyop = ((Form_pg_am) GETSTRUCT(tuple))->amcanorderbyop;
entry->amoptionalkey = ((Form_pg_am) GETSTRUCT(tuple))->amoptionalkey;
entry->amsearcharray = ((Form_pg_am) GETSTRUCT(tuple))->amsearcharray;
entry->amsearchnulls = ((Form_pg_am) GETSTRUCT(tuple))->amsearchnulls;
entry->amhasgettuple = OidIsValid(((Form_pg_am) GETSTRUCT(tuple))->amgettuple);
entry->amhasgetbitmap = OidIsValid(((Form_pg_am) GETSTRUCT(tuple))->amgetbitmap);
entry->amcanunique = ((Form_pg_am) GETSTRUCT(tuple))->amcanunique;
entry->amcanmulticol = ((Form_pg_am) GETSTRUCT(tuple))->amcanmulticol;
amoptions = ((Form_pg_am) GETSTRUCT(tuple))->amoptions;
entry->amcanorder = ((Form_pg_am) GETSTRUCT(tuple))->amcanorder;
#endif
ReleaseSysCache(tuple);
entry->indexname = palloc0(NAMEDATALEN);
/* palloc all arrays */
entry->indexkeys = palloc0(sizeof(short int) * (nkeycolumns + ninccolumns));
entry->indexcollations = palloc0(sizeof(Oid) * nkeycolumns);
entry->opfamily = palloc0(sizeof(Oid) * nkeycolumns);
entry->opclass = palloc0(sizeof(Oid) * nkeycolumns);
entry->opcintype = palloc0(sizeof(Oid) * nkeycolumns);
/* only palloc sort related fields if needed */
if ((entry->relam == BTREE_AM_OID) || (entry->amcanorder))
{
if (entry->relam != BTREE_AM_OID)
entry->sortopfamily = palloc0(sizeof(Oid) * nkeycolumns);
entry->reverse_sort = palloc0(sizeof(bool) * nkeycolumns);
entry->nulls_first = palloc0(sizeof(bool) * nkeycolumns);
}
else
{
entry->sortopfamily = NULL;
entry->reverse_sort = NULL;
entry->nulls_first = NULL;
}
#if PG_VERSION_NUM >= 90500
entry->canreturn = palloc0(sizeof(bool) * (nkeycolumns + ninccolumns));
#endif
entry->indexprs = NIL;
entry->indpred = NIL;
entry->options = (List *) copyObject(options);
MemoryContextSwitchTo(oldcontext);
entry->oid = hypo_getNewOid(relid);
entry->relid = relid;
entry->immediate = true;
if (options != NIL)
{
Datum reloptions;
/*
* Parse AM-specific options, convert to text array form, validate.
*/
reloptions = transformRelOptions((Datum) 0, options,
NULL, NULL, false, false);
(void) index_reloptions(amoptions, reloptions, true);
}
PG_TRY();
{
/*
* reject unsupported am. It could be done earlier but it's simpler
* (and was previously done) here.
*/
if (entry->relam != BTREE_AM_OID
#if PG_VERSION_NUM >= 90500
&& entry->relam != BRIN_AM_OID
#endif
#if PG_VERSION_NUM >= 90600
&& entry->relam != BLOOM_AM_OID
#endif
#if PG_VERSION_NUM >= 100000
/*
* Only support hash indexes for pg10+. In previous version they
* weren't crash safe, and changes in pg10+ also significantly
* changed the disk space allocation.
*/
&& entry->relam != HASH_AM_OID
#endif
)
{
/*
* do not store hypothetical indexes with access method not
* supported
*/
elog(ERROR, "hypopg: access method \"%s\" is not supported",
accessMethod);
break;
}
/* No more elog beyond this point. */
}
PG_CATCH();
{
/* Free what was palloc'd in HypoMemoryContext */
hypo_index_pfree(entry);
PG_RE_THROW();
}
PG_END_TRY();
return entry;
}
/* Add an hypoIndex to hypoIndexes */
static void
hypo_addIndex(hypoIndex * entry)
{
MemoryContext oldcontext;
oldcontext = MemoryContextSwitchTo(HypoMemoryContext);
hypoIndexes = lappend(hypoIndexes, entry);
MemoryContextSwitchTo(oldcontext);
}
/*
* Remove cleanly all hypothetical indexes by calling hypo_index_remove() on
* each entry. hypo_index_remove() function pfree all allocated memory
*/
void
hypo_index_reset(void)
{
ListCell *lc;
/*
* The cell is removed in hypo_index_remove(), so we can't iterate using
* standard foreach / lnext macros.
*/
while ((lc = list_head(hypoIndexes)) != NULL)
{
hypoIndex *entry = (hypoIndex *) lfirst(lc);
hypo_index_remove(entry->oid);
}
list_free(hypoIndexes);
hypoIndexes = NIL;
hypo_reset_fake_oids();
return;
}
/*
* Create an hypothetical index from its CREATE INDEX parsetree. This function
* is where all the hypothetic index creation is done, except the index size
* estimation.
*/
static const hypoIndex *
hypo_index_store_parsetree(IndexStmt *node, const char *queryString)
{
/* must be declared "volatile", because used in a PG_CATCH() */
hypoIndex *volatile entry;
Form_pg_attribute attform;
Oid relid;
StringInfoData indexRelationName;
int nkeycolumns,
ninccolumns;
ListCell *lc;
int attn;
/*
* Support for hypothetical BRIN indexes is broken in some minor versions
* of pg10, pg11 and pg12. For simplicity, check PG_VERSION_NUM rather
* than the real instance version, which should be right most of the
* time. When it's not, the only effect is to have a less user-friendly
* error message.
*/
#if ((PG_VERSION_NUM >= 100000 && PG_VERSION_NUM < 100012) || \
(PG_VERSION_NUM >= 110000 && PG_VERSION_NUM < 110007) || \
(PG_VERSION_NUM >= 120000 && PG_VERSION_NUM < 120002))
if (get_am_oid(node->accessMethod, true) == BRIN_AM_OID)
{
elog(ERROR, "hypopg: BRIN hypothetical indexes are only supported"
" with PostgreSQL "
#if PG_VERSION_NUM >= 120000
"12.2"
#else
#if PG_VERSION_NUM >= 110000
"11.7"
#else
"10.12"
#endif /* pg 11 */
#endif /* pg 12 */
" and later.");
}
#endif
relid = RangeVarGetRelid(node->relation, AccessShareLock, false);
/* Some sanity checks */
switch (get_rel_relkind(relid))
{
#if PG_VERSION_NUM >= 90300
case RELKIND_MATVIEW:
#endif
#if PG_VERSION_NUM >= 110000
case RELKIND_PARTITIONED_TABLE:
#endif
case RELKIND_RELATION:
/* this is supported */
break;
#if PG_VERSION_NUM >= 100000 && PG_VERSION_NUM < 110000
case RELKIND_PARTITIONED_TABLE:
elog(ERROR, "hypopg: cannot create hypothetical index on"
" partitioned table \"%s\"", node->relation->relname);
break;
#endif
default:
#if PG_VERSION_NUM >= 90300
elog(ERROR, "hypopg: \"%s\" is not a table or materialized view",
node->relation->relname);
#else
elog(ERROR, "hypopg: \"%s\" is not a table",
node->relation->relname);
#endif
}
/* Run parse analysis ... */
node = transformIndexStmt(relid, node, queryString);
nkeycolumns = list_length(node->indexParams);
#if PG_VERSION_NUM >= 110000
if (list_intersection(node->indexParams, node->indexIncludingParams) != NIL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("hypopg: included columns must not intersect with key columns")));
ninccolumns = list_length(node->indexIncludingParams);
#else
ninccolumns = 0;
#endif
if (nkeycolumns > INDEX_MAX_KEYS)
elog(ERROR, "hypopg: cannot use more thant %d columns in an index",
INDEX_MAX_KEYS);
initStringInfo(&indexRelationName);
appendStringInfo(&indexRelationName, "%s", node->accessMethod);
appendStringInfo(&indexRelationName, "_");
if (node->relation->schemaname != NULL &&
(strcmp(node->relation->schemaname, "public") != 0))
{
appendStringInfo(&indexRelationName, "%s", node->relation->schemaname);
appendStringInfo(&indexRelationName, "_");
}
appendStringInfo(&indexRelationName, "%s", node->relation->relname);
/* now create the hypothetical index entry */
entry = hypo_newIndex(relid, node->accessMethod, nkeycolumns, ninccolumns,
node->options);
PG_TRY();
{
HeapTuple tuple;
int ind_avg_width = 0;
if (node->unique && !entry->amcanunique)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("hypopg: access method \"%s\" does not support unique indexes",
node->accessMethod)));
if (nkeycolumns > 1 && !entry->amcanmulticol)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("hypopg: access method \"%s\" does not support multicolumn indexes",
node->accessMethod)));
#if PG_VERSION_NUM >= 110000
if (node-> indexIncludingParams != NIL && !entry->amcaninclude)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("hypopg: access method \"%s\" does not support included columns",
node->accessMethod)));
#endif
entry->unique = node->unique;
entry->ncolumns = nkeycolumns + ninccolumns;
entry->nkeycolumns = nkeycolumns;
/* handle predicate if present */
if (node->whereClause)
{
MemoryContext oldcontext;
List *pred;
CheckPredicate((Expr *) node->whereClause);
pred = make_ands_implicit((Expr *) node->whereClause);
oldcontext = MemoryContextSwitchTo(HypoMemoryContext);
entry->indpred = (List *) copyObject(pred);
MemoryContextSwitchTo(oldcontext);
}
else
{
entry->indpred = NIL;
}
/*
* process attributeList
*/
attn = 0;
foreach(lc, node->indexParams)
{
IndexElem *attribute = (IndexElem *) lfirst(lc);
Oid atttype = InvalidOid;
Oid opclass;
appendStringInfo(&indexRelationName, "_");
/*
* Process the column-or-expression to be indexed.
*/
if (attribute->name != NULL)
{
/* Simple index attribute */
appendStringInfo(&indexRelationName, "%s", attribute->name);
/* get the attribute catalog info */
tuple = SearchSysCacheAttName(relid, attribute->name);
if (!HeapTupleIsValid(tuple))
{
elog(ERROR, "hypopg: column \"%s\" does not exist",
attribute->name);
}
attform = (Form_pg_attribute) GETSTRUCT(tuple);
/* setup the attnum */
entry->indexkeys[attn] = attform->attnum;
/* setup the collation */
entry->indexcollations[attn] = attform->attcollation;
/* get the atttype */
atttype = attform->atttypid;
ReleaseSysCache(tuple);
}
else
{
/*---------------------------
* handle index on expression
*
* Adapted from DefineIndex() and ComputeIndexAttrs()
*
* Statistics on expression index will be really wrong, since
* they're only computed when a real index exists (selectivity
* and average width).
*/
MemoryContext oldcontext;
Node *expr = attribute->expr;
Assert(expr != NULL);
entry->indexcollations[attn] = exprCollation(attribute->expr);
atttype = exprType(attribute->expr);
appendStringInfo(&indexRelationName, "expr");
/*
* Strip any top-level COLLATE clause. This ensures that we
* treat "x COLLATE y" and "(x COLLATE y)" alike.
*/
while (IsA(expr, CollateExpr))
expr = (Node *) ((CollateExpr *) expr)->arg;
if (IsA(expr, Var) &&
((Var *) expr)->varattno != InvalidAttrNumber)
{
/*
* User wrote "(column)" or "(column COLLATE something)".
* Treat it like simple attribute anyway.
*/
entry->indexkeys[attn] = ((Var *) expr)->varattno;
/*
* Generated index name will have _expr instead of attname
* in generated index name, and error message will also be
* slightly different in case on unexisting column from a
* simple attribute, but that's how ComputeIndexAttrs()
* proceed.
*/
}
else
{
/*
* transformExpr() should have already rejected
* subqueries, aggregates, and window functions, based on
* the EXPR_KIND_ for an index expression.
*/
/*
* An expression using mutable functions is probably
* wrong, since if you aren't going to get the same result
* for the same data every time, it's not clear what the
* index entries mean at all.
*/
if (CheckMutability((Expr *) expr))
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("hypopg: functions in index expression must be marked IMMUTABLE")));
entry->indexkeys[attn] = 0; /* marks expression */
oldcontext = MemoryContextSwitchTo(HypoMemoryContext);
entry->indexprs = lappend(entry->indexprs,
(Node *) copyObject(attribute->expr));
MemoryContextSwitchTo(oldcontext);
}
}
ind_avg_width += hypo_estimate_index_colsize(entry, attn);
/*
* Apply collation override if any
*/
if (attribute->collation)
entry->indexcollations[attn] =
get_collation_oid(attribute->collation, false);
/*
* Check we have a collation iff it's a collatable type. The only
* expected failures here are (1) COLLATE applied to a
* noncollatable type, or (2) index expression had an unresolved
* collation. But we might as well code this to be a complete
* consistency check.
*/
if (type_is_collatable(atttype))
{
if (!OidIsValid(entry->indexcollations[attn]))
ereport(ERROR,
(errcode(ERRCODE_INDETERMINATE_COLLATION),
errmsg("hypopg: could not determine which collation to use for index expression"),
errhint("Use the COLLATE clause to set the collation explicitly.")));
}
else
{
if (OidIsValid(entry->indexcollations[attn]))
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("hypopg: collations are not supported by type %s",
format_type_be(atttype))));
}
/* get the opclass */
#if PG_VERSION_NUM < 100000
opclass = GetIndexOpClass(attribute->opclass,
atttype,
node->accessMethod,
entry->relam);
#else
opclass = ResolveOpClass(attribute->opclass,
atttype,
node->accessMethod,
entry->relam);
#endif
entry->opclass[attn] = opclass;
/* set up the opfamily */
entry->opfamily[attn] = get_opclass_family(opclass);
entry->opcintype[attn] = get_opclass_input_type(opclass);
/* setup the sort info if am handles it */
if (entry->amcanorder)
{
/* setup NULLS LAST, NULLS FIRST cases are handled below */
entry->nulls_first[attn] = false;
/* default ordering is ASC */
entry->reverse_sort[attn] = (attribute->ordering == SORTBY_DESC);
/* default null ordering is LAST for ASC, FIRST for DESC */
if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT)
{
if (attribute->ordering == SORTBY_DESC)
entry->nulls_first[attn] = true;
}
else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST)
entry->nulls_first[attn] = true;
}
/* handle index-only scan info */
#if PG_VERSION_NUM < 90500
/*
* OIS info is global for the index before 9.5, so look for the
* information only once in that case.
*/
if (attn == 0)
{
/*
* specify first column, but it doesn't matter as this will
* only be used with GiST am, which cannot do IOS prior pg 9.5
*/
entry->canreturn = hypo_can_return(entry, atttype, 0,
node->accessMethod);
}
#else
/* per-column IOS information */
entry->canreturn[attn] = hypo_can_return(entry, atttype, attn,
node->accessMethod);
#endif
attn++;
}
Assert(attn == nkeycolumns);
/*
* We disallow indexes on system columns other than OID. They would
* not necessarily get updated correctly, and they don't seem useful
* anyway.
*/
for (attn = 0; attn < nkeycolumns; attn++)
{
AttrNumber attno = entry->indexkeys[attn];
if (attno < 0
#if PG_VERSION_NUM < 120000
&& attno != ObjectIdAttributeNumber
#endif
)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("hypopg: index creation on system columns is not supported")));
}
#if PG_VERSION_NUM >= 110000
attn = nkeycolumns;
foreach(lc, node->indexIncludingParams)
{
IndexElem *attribute = (IndexElem *) lfirst(lc);
Oid atttype = InvalidOid;
appendStringInfo(&indexRelationName, "_");
/* Handle not supported features as in ComputeIndexAttrs() */
if (attribute->collation)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("hypopg: including column does not support a collation")));
if (attribute->opclass)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("hypopg: including column does not support an operator class")));
if (attribute->ordering != SORTBY_DEFAULT)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("hypopg: including column does not support ASC/DESC options")));
if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("hypopg: including column does not support NULLS FIRST/LAST options")));
/*
* Process the column-or-expression to be indexed.
*/
if (attribute->name != NULL)
{
/* Simple index attribute */
appendStringInfo(&indexRelationName, "%s", attribute->name);
/* get the attribute catalog info */
tuple = SearchSysCacheAttName(relid, attribute->name);
if (!HeapTupleIsValid(tuple))
{
elog(ERROR, "hypopg: column \"%s\" does not exist",
attribute->name);
}
attform = (Form_pg_attribute) GETSTRUCT(tuple);
/* setup the attnum */
entry->indexkeys[attn] = attform->attnum;
/* get the atttype */
atttype = attform->atttypid;
ReleaseSysCache(tuple);
}
else
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("hypopg: expressions are not supported in included columns")));
}
ind_avg_width += hypo_estimate_index_colsize(entry, attn);
/* per-column IOS information */
entry->canreturn[attn] = hypo_can_return(entry, atttype, attn,
node->accessMethod);
attn++;
}
Assert(attn == (nkeycolumns + ninccolumns));
#endif
/*
* Also check for system columns used in expressions or predicates.
*/
if (entry->indexprs || entry->indpred)
{
Bitmapset *indexattrs = NULL;
int i;
pull_varattnos((Node *) entry->indexprs, 1, &indexattrs);
pull_varattnos((Node *) entry->indpred, 1, &indexattrs);
for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
{
if (
#if PG_VERSION_NUM < 120000
i != ObjectIdAttributeNumber &&
#endif
bms_is_member(i - FirstLowInvalidHeapAttributeNumber,
indexattrs))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("hypopg: index creation on system columns is not supported")));
}
}
/* Check if the average size fits in a btree index */
if (entry->relam == BTREE_AM_OID)
{
if (ind_avg_width >= HYPO_BTMaxItemSize)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("hypopg: estimated index row size %d "
"exceeds maximum %ld",
ind_avg_width, HYPO_BTMaxItemSize),
errhint("Values larger than 1/3 of a buffer page "
"cannot be indexed.\nConsider a function index "
" of an MD5 hash of the value, or use full text "
"indexing\n(which is not yet supported by hypopg)."
)));
/* Warn about possible error with an 80% avg size */
else if (ind_avg_width >= HYPO_BTMaxItemSize * .8)
ereport(WARNING,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("hypopg: estimated index row size %d "
"is close to maximum %ld",
ind_avg_width, HYPO_BTMaxItemSize),
errhint("Values larger than 1/3 of a buffer page "
"cannot be indexed.\nConsider a function index "
" of an MD5 hash of the value, or use full text "
"indexing\n(which is not yet supported by hypopg)."
)));
}
/* No more elog beyond this point. */
}
PG_CATCH();
{
/* Free what was palloc'd in HypoMemoryContext */
hypo_index_pfree(entry);
PG_RE_THROW();
}
PG_END_TRY();
/*
* Fetch the ordering information for the index, if any. Adapted from
* plancat.c - get_relation_info().
*/
if ((entry->relam != BTREE_AM_OID) && entry->amcanorder)
{
/*
* Otherwise, identify the corresponding btree opfamilies by trying to
* map this index's "<" operators into btree. Since "<" uniquely
* defines the behavior of a sort order, this is a sufficient test.
*
* XXX This method is rather slow and also requires the undesirable
* assumption that the other index AM numbers its strategies the same
* as btree. It'd be better to have a way to explicitly declare the
* corresponding btree opfamily for each opfamily of the other index
* type. But given the lack of current or foreseeable amcanorder
* index types, it's not worth expending more effort on now.
*/
for (attn = 0; attn < nkeycolumns; attn++)
{
Oid ltopr;
Oid btopfamily;
Oid btopcintype;
int16 btstrategy;
ltopr = get_opfamily_member(entry->opfamily[attn],
entry->opcintype[attn],
entry->opcintype[attn],
BTLessStrategyNumber);
if (OidIsValid(ltopr) &&
get_ordering_op_properties(ltopr,
&btopfamily,
&btopcintype,
&btstrategy) &&
btopcintype == entry->opcintype[attn] &&
btstrategy == BTLessStrategyNumber)
{
/* Successful mapping */
entry->sortopfamily[attn] = btopfamily;
}
else
{
/* Fail ... quietly treat index as unordered */
/* also pfree allocated memory */
pfree(entry->sortopfamily);
pfree(entry->reverse_sort);
pfree(entry->nulls_first);
entry->sortopfamily = NULL;
entry->reverse_sort = NULL;
entry->nulls_first = NULL;
break;
}
}
}
hypo_set_indexname(entry, indexRelationName.data);
hypo_addIndex(entry);
return entry;
}
/*
* Remove an hypothetical index from the list of hypothetical indexes.
* pfree (by calling hypo_index_pfree) all memory that has been allocated.
*/
static bool
hypo_index_remove(Oid indexid)
{
ListCell *lc;
/* remove this index from the list of hidden indexes if present */
hypo_index_unhide(indexid);
foreach(lc, hypoIndexes)
{
hypoIndex *entry = (hypoIndex *) lfirst(lc);
if (entry->oid == indexid)
{
hypoIndexes = list_delete_ptr(hypoIndexes, entry);
hypo_index_pfree(entry);
return true;
}
}
return false;
}
/* pfree all allocated memory for within an hypoIndex and the entry itself. */
static void
hypo_index_pfree(hypoIndex * entry)
{
/* pfree all memory that has been allocated */
pfree(entry->indexname);
pfree(entry->indexkeys);
pfree(entry->indexcollations);
pfree(entry->opfamily);
pfree(entry->opclass);
pfree(entry->opcintype);
if ((entry->relam == BTREE_AM_OID) || entry->amcanorder)
{
if ((entry->relam != BTREE_AM_OID) && entry->sortopfamily)
pfree(entry->sortopfamily);
if (entry->reverse_sort)
pfree(entry->reverse_sort);
if (entry->nulls_first)
pfree(entry->nulls_first);
}
if (entry->indexprs)
list_free_deep(entry->indexprs);
if (entry->indpred)
pfree(entry->indpred);
#if PG_VERSION_NUM >= 90500
pfree(entry->canreturn);
#endif
/* finally pfree the entry */
pfree(entry);
}
/*--------------------------------------------------
* Add an hypothetical index to the list of indexes.
* Caller should have check that the specified hypoIndex does belong to the
* specified relation. This function also assume that the specified entry
* already contains every needed information, so we just basically need to copy
* it from the hypoIndex to the new IndexOptInfo. Every specific handling is
* done at store time (i.e., hypo_index_store_parsetree). The only exception is
* the size estimation, recomputed every time, as it needs up-to-date statistics.
*/
void
hypo_injectHypotheticalIndex(PlannerInfo *root,
Oid relationObjectId,
bool inhparent,
RelOptInfo *rel,
Relation relation,
hypoIndex * entry)
{
IndexOptInfo *index;
int ncolumns,
/*