This repository has been archived by the owner on Jul 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 329
/
indexcmds.c
1864 lines (1629 loc) · 54.8 KB
/
indexcmds.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*-------------------------------------------------------------------------
*
* indexcmds.c
* POSTGRES define and remove index code.
*
* Portions Copyright (c) 2005-2010, Greenplum inc
* Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/commands/indexcmds.c,v 1.149.2.2 2007/09/10 22:02:05 alvherre Exp $
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/aosegfiles.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/fileam.h"
#include "access/reloptions.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/catquery.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_resqueue.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_type.h"
#include "cdb/cdbpartition.h"
#include "commands/dbcommands.h"
#include "commands/defrem.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "optimizer/clauses.h"
#include "parser/parse_agg.h"
#include "parser/parse_coerce.h"
#include "parser/parse_expr.h"
#include "parser/parse_func.h"
#include "parser/parsetree.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/hsearch.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/relcache.h"
#include "utils/syscache.h"
#include "cdb/cdbdatalocality.h"
#include "cdb/cdbdisp.h"
#include "cdb/cdbdispatchresult.h"
#include "cdb/cdbsrlz.h"
#include "cdb/cdbvars.h"
#include "cdb/cdbcat.h"
#include "cdb/cdbrelsize.h"
#include "cdb/cdboidsync.h"
#include "cdb/dispatcher.h"
/* non-export function prototypes */
static void CheckPredicate(Expr *predicate);
static void ComputeIndexAttrs(IndexInfo *indexInfo, Oid *classOidP,
List *attList,
Oid relId,
char *accessMethodName, Oid accessMethodId,
bool isconstraint);
static Oid GetIndexOpClass(List *opclass, Oid attrType,
char *accessMethodName, Oid accessMethodId);
static bool relationHasPrimaryKey(Relation rel);
static bool relationHasUniqueIndex(Relation rel);
bool gp_hash_index = false; /* hash index phase out. */
/*
* DefineIndex
* Creates a new index.
*
* 'relationId': the OID of the heap relation on which the index is to be
* created
* 'indexRelationName': the name for the new index, or NULL to indicate
* that a nonconflicting default name should be picked.
* 'indexRelationId': normally InvalidOid, but during bootstrap can be
* nonzero to specify a preselected OID for the index.
* 'accessMethodName': name of the AM to use.
* 'tableSpaceName': name of the tablespace to create the index in.
* NULL specifies using the appropriate default.
* 'attributeList': a list of IndexElem specifying columns and expressions
* to index on.
* 'predicate': the partial-index condition, or NULL if none.
* 'rangetable': needed to interpret the predicate.
* 'options': reloptions from WITH (in list-of-DefElem form).
* 'unique': make the index enforce uniqueness.
* 'primary': mark the index as a primary key in the catalogs.
* 'isconstraint': index is for a PRIMARY KEY or UNIQUE constraint,
* so build a pg_constraint entry for it.
* 'is_alter_table': this is due to an ALTER rather than a CREATE operation.
* 'check_rights': check for CREATE rights in the namespace. (This should
* be true except when ALTER is deleting/recreating an index.)
* 'skip_build': make the catalog entries but leave the index file empty;
* it will be filled later.
* 'quiet': suppress the NOTICE chatter ordinarily provided for constraints.
* 'concurrent': avoid blocking writers to the table while building.
* 'part_expanded': is this a lower-level call to index a branch or part of
* a partitioned table?
* 'stmt': the IndexStmt for this index. Many other arguments are just values
* of fields in here.
* XXX One day it might pay to eliminate the redundancy.
*/
void
DefineIndex(Oid relationId,
char *indexRelationName,
Oid indexRelationId,
char *accessMethodName,
char *tableSpaceName,
List *attributeList,
Expr *predicate,
List *rangetable,
List *options,
bool unique,
bool primary,
bool isconstraint,
bool is_alter_table,
bool check_rights,
bool skip_build,
bool quiet,
bool concurrent,
bool part_expanded,
IndexStmt *stmt)
{
Oid *classObjectId;
Oid accessMethodId;
Oid namespaceId;
Oid tablespaceId;
Relation rel;
HeapTuple tuple;
Form_pg_am accessMethodForm;
RegProcedure amoptions;
Datum reloptions;
IndexInfo *indexInfo;
int numberOfAttributes;
int numberOfKeyAttributes;
List *old_xact_list;
ListCell *lc;
uint32 ixcnt;
LockRelId heaprelid;
LOCKTAG heaplocktag;
Snapshot snapshot;
Relation pg_index;
HeapTuple indexTuple;
Form_pg_index indexForm;
LOCKMODE heap_lockmode;
bool need_longlock = true;
bool shouldDispatch = Gp_role == GP_ROLE_DISPATCH && !IsBootstrapProcessingMode();
char *altconname = stmt ? stmt->altconname : NULL;
cqContext cqc;
cqContext *pcqCtx;
cqContext *amcqCtx;
cqContext *attcqCtx;
if (list_intersection(stmt->indexParams, stmt->indexIncludingParams) != NIL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("included columns must not intersect with key columns")));
/*
* count key attributes in index
*/
numberOfKeyAttributes = list_length(stmt->indexParams);
/*
* We append any INCLUDE columns onto the indexParams list so that we have
* one list with all columns. Later we can determine which of these are
* key columns, and which are just part of the INCLUDE list by checking
* the list position. A list item in a position less than
* ii_NumIndexKeyAttrs is part of the key columns, and anything equal to
* and over is part of the INCLUDE columns.
*/
stmt->indexParams = list_concat(stmt->indexParams,
stmt->indexIncludingParams);
numberOfAttributes = list_length(stmt->indexParams);
if (numberOfAttributes <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("must specify at least one column")));
if (numberOfAttributes > INDEX_MAX_KEYS)
ereport(ERROR,
(errcode(ERRCODE_TOO_MANY_COLUMNS),
errmsg("cannot use more than %d columns in an index",
INDEX_MAX_KEYS)));
/*
* Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard
* index build; but for concurrent builds we allow INSERT/UPDATE/DELETE
* (but not VACUUM).
*
* NB: Caller is responsible for making sure that relationId refers
* to the relation on which the index should be built; except in bootstrap
* mode, this will typically require the caller to have already locked
* the relation. To avoid lock upgrade hazards, that lock should be at
* least as strong as the one we take here.
*/
heap_lockmode = concurrent ? ShareUpdateExclusiveLock : ShareLock;
rel = heap_open(relationId, heap_lockmode);
relationId = RelationGetRelid(rel);
namespaceId = RelationGetNamespace(rel);
/* Note: during bootstrap may see uncataloged relation */
if (rel->rd_rel->relkind != RELKIND_RELATION &&
rel->rd_rel->relkind != RELKIND_UNCATALOGED)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is not a table",
RelationGetRelationName(rel)),
errOmitLocation(true)));
/*
* Don't try to CREATE INDEX on temp tables of other backends.
*/
if (isOtherTempNamespace(namespaceId))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot create indexes on temporary tables of other sessions"),
errOmitLocation(true)));
/*
* Verify we (still) have CREATE rights in the rel's namespace.
* (Presumably we did when the rel was created, but maybe not anymore.)
* Skip check if caller doesn't want it. Also skip check if
* bootstrapping, since permissions machinery may not be working yet.
*/
if (check_rights && !IsBootstrapProcessingMode())
{
AclResult aclresult;
aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
get_namespace_name(namespaceId));
}
/*
* Select tablespace to use. If not specified, use default_tablespace
* (which may in turn default to database's default).
*
* Note: This code duplicates code in tablecmds.c
*/
if (tableSpaceName && !dataStoredInMagmaByOid(relationId))
{
tablespaceId = get_tablespace_oid(tableSpaceName);
if (!OidIsValid(tablespaceId))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("tablespace \"%s\" does not exist",
tableSpaceName),
errOmitLocation(true)));
CheckCrossAccessTablespace(tablespaceId);
}
else
{
tablespaceId = GetDefaultTablespace();
/*
* Need the real tablespace id for dispatch,
* Index should not be created on shared storage.
*/
if (!OidIsValid(tablespaceId) || (get_database_dts(MyDatabaseId) != MyDatabaseTableSpace))
tablespaceId = MyDatabaseTableSpace;
else
CheckCrossAccessTablespace(tablespaceId);
/*
* MPP-8238 : inconsistent tablespaces between segments and master
*/
if (shouldDispatch)
stmt->tableSpace = get_tablespace_name(tablespaceId);
}
/* Goh tablespace check. */
RejectAccessTablespace(tablespaceId, "cannot create index on tablespace %s");
/* Check permissions except when using database's default */
if (OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace &&
tablespaceId != get_database_dts(MyDatabaseId))
{
AclResult aclresult;
aclresult = pg_tablespace_aclcheck(tablespaceId, GetUserId(),
ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
get_tablespace_name(tablespaceId));
}
/*
* Force shared indexes into the pg_global tablespace. This is a bit of a
* hack but seems simpler than marking them in the BKI commands.
*/
if (rel->rd_rel->relisshared)
tablespaceId = GLOBALTABLESPACE_OID;
/*
* Select name for index if caller didn't specify
*/
if (indexRelationName == NULL)
{
if (primary)
indexRelationName = ChooseRelationName(RelationGetRelationName(rel),
NULL,
"pkey",
namespaceId,
NULL);
else
{
IndexElem *iparam = (IndexElem *) linitial(attributeList);
indexRelationName = ChooseRelationName(RelationGetRelationName(rel),
iparam->name,
"key",
namespaceId,
NULL);
}
stmt->idxname = indexRelationName;
}
/*
* look up the access method, verify it can handle the requested features
*/
amcqCtx = caql_beginscan(
NULL,
cql("SELECT * FROM pg_am "
" WHERE amname = :1 ",
PointerGetDatum(accessMethodName)));
tuple = caql_getnext(amcqCtx);
if (!HeapTupleIsValid(tuple))
{
caql_endscan(amcqCtx);
/*
* Hack to provide more-or-less-transparent updating of old RTREE
* indexes to GIST: if RTREE is requested and not found, use GIST.
*/
if (strcmp(accessMethodName, "rtree") == 0)
{
ereport(NOTICE,
(errmsg("substituting access method \"gist\" for obsolete method \"rtree\"")));
accessMethodName = "gist";
amcqCtx = caql_beginscan(
NULL,
cql("SELECT * FROM pg_am "
" WHERE amname = :1 ",
PointerGetDatum(accessMethodName)));
tuple = caql_getnext(amcqCtx);
}
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("access method \"%s\" does not exist",
accessMethodName)));
}
accessMethodId = HeapTupleGetOid(tuple);
accessMethodForm = (Form_pg_am) GETSTRUCT(tuple);
if (accessMethodId == HASH_AM_OID)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("hash indexes are not supported")));
/* MPP-9329: disable creation of GIN indexes */
if (accessMethodId == GIN_AM_OID)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("GIN indexes are not supported")));
if (RelationIsMagmaTable2(relationId) && accessMethodId == GIST_AM_OID)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("GIST indexes are not supported")));
if (unique && !accessMethodForm->amcanunique)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("access method \"%s\" does not support unique indexes",
accessMethodName)));
if (numberOfAttributes > 1 && !accessMethodForm->amcanmulticol)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("access method \"%s\" does not support multicolumn indexes",
accessMethodName)));
/* native orc can't support unique/primary index */
if (unique && RelationIsOrc(rel))
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("native orc do not support unique indexes")));
amoptions = accessMethodForm->amoptions;
caql_endscan(amcqCtx);
/*
* If a range table was created then check that only the base rel is
* mentioned.
*/
if (rangetable != NIL)
{
if (list_length(rangetable) != 1 || getrelid(1, rangetable) != relationId)
ereport(ERROR,
(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
errmsg("index expressions and predicates may refer only to the table being indexed")));
}
/*
* Validate predicate, if given
*/
if (predicate)
CheckPredicate(predicate);
/*
* Extra checks when creating a PRIMARY KEY index.
*/
if (primary)
{
List *cmds;
ListCell *keys;
/*
* If ALTER TABLE, check that there isn't already a PRIMARY KEY. In
* CREATE TABLE, we have faith that the parser rejected multiple pkey
* clauses; and CREATE INDEX doesn't have a way to say PRIMARY KEY, so
* it's no problem either.
*/
if (is_alter_table &&
relationHasPrimaryKey(rel))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("multiple primary keys for table \"%s\" are not allowed",
RelationGetRelationName(rel))));
}
/*
* Check that all of the attributes in a primary key are marked as not
* null, otherwise attempt to ALTER TABLE .. SET NOT NULL
*/
cmds = NIL;
foreach(keys, attributeList)
{
IndexElem *key = (IndexElem *) lfirst(keys);
HeapTuple atttuple;
if (!key->name)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("primary keys cannot be expressions")));
/* System attributes are never null, so no problem */
if (SystemAttributeByName(key->name, rel->rd_rel->relhasoids))
continue;
attcqCtx = caql_getattname_scan(NULL, relationId, key->name);
atttuple = caql_get_current(attcqCtx);
if (HeapTupleIsValid(atttuple))
{
if (!((Form_pg_attribute) GETSTRUCT(atttuple))->attnotnull)
{
/* Add a subcommand to make this one NOT NULL */
AlterTableCmd *cmd = makeNode(AlterTableCmd);
cmd->subtype = AT_SetNotNull;
cmd->name = key->name;
cmd->part_expanded = true;
cmds = lappend(cmds, cmd);
}
}
else
{
/*
* This shouldn't happen during CREATE TABLE, but can happen
* during ALTER TABLE. Keep message in sync with
* transformIndexConstraints() in parser/analyze.c.
*/
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" named in key does not exist",
key->name)));
}
caql_endscan(attcqCtx);
}
/*
* XXX: Shouldn't the ALTER TABLE .. SET NOT NULL cascade to child
* tables? Currently, since the PRIMARY KEY itself doesn't cascade,
* we don't cascade the notnull constraint(s) either; but this is
* pretty debatable.
*
* XXX: possible future improvement: when being called from ALTER
* TABLE, it would be more efficient to merge this with the outer
* ALTER TABLE, so as to avoid two scans. But that seems to
* complicate DefineIndex's API unduly.
*/
if (cmds)
AlterTableInternal(relationId, cmds, false);
}
/*
* Parse AM-specific options, convert to text array form, validate
*
* However, accept and only accept tidycat option during upgrade.
* During bootstrap, we don't have any storage option. So, during
* upgrade, we don't need it as well because we're just creating
* catalog objects. Further, we overload the WITH clause to pass-in
* the index oid. So, if we don't strip it out, it'll appear in
* the pg_class.reloptions, and we don't want that.
*/
reloptions = transformRelOptions((Datum) 0, options, false, false);
if (gp_upgrade_mode)
{
TidycatOptions *tidycatoptions = (TidycatOptions*) tidycat_reloptions(reloptions);
indexRelationId = tidycatoptions->indexid;
reloptions = 0;
}
else
(void) index_reloptions(amoptions, reloptions, true);
/*
* Prepare arguments for index_create, primarily an IndexInfo structure.
* Note that ii_Predicate must be in implicit-AND format.
*/
indexInfo = makeNode(IndexInfo);
indexInfo->ii_NumIndexAttrs = numberOfAttributes;
indexInfo->ii_NumIndexKeyAttrs = numberOfKeyAttributes;
indexInfo->ii_Expressions = NIL; /* for now */
indexInfo->ii_ExpressionsState = NIL;
indexInfo->ii_Predicate = make_ands_implicit(predicate);
indexInfo->ii_PredicateState = NIL;
indexInfo->ii_Unique = unique;
indexInfo->ii_Concurrent = concurrent;
indexInfo->opaque = (void*)palloc0(sizeof(IndexInfoOpaque));
classObjectId = (Oid *) palloc(numberOfAttributes * sizeof(Oid));
ComputeIndexAttrs(indexInfo, classObjectId, stmt->indexParams,
relationId, accessMethodName, accessMethodId,
isconstraint);
if (shouldDispatch)
{
if (stmt)
{
Assert(stmt->idxOids == 0);
stmt->idxOids = NIL;
}
if ((primary || unique) && rel->rd_cdbpolicy)
checkPolicyForUniqueIndex(rel,
indexInfo->ii_KeyAttrNumbers,
indexInfo->ii_NumIndexAttrs,
primary,
list_length(indexInfo->ii_Expressions),
primary,
unique);
/* We don't have to worry about constraints on parts. Already checked. */
if ( isconstraint && rel_is_partitioned(relationId) )
checkUniqueConstraintVsPartitioning(rel,
indexInfo->ii_KeyAttrNumbers,
indexInfo->ii_NumIndexAttrs,
primary);
}
else if (Gp_role == GP_ROLE_EXECUTE)
{
if (stmt)
{
IndexInfoOpaque *iio = (IndexInfoOpaque *)indexInfo->opaque;
/* stmt->idxOids can have 7 oids currently. */
Assert(list_length(stmt->idxOids) == 7);
indexRelationId = linitial_oid(stmt->idxOids);
iio->comptypeOid = lsecond_oid(stmt->idxOids);
iio->heapOid = lthird_oid(stmt->idxOids);
iio->indexOid = lfourth_oid(stmt->idxOids);
iio->blkdirRelOid = lfifth_oid(stmt->idxOids);
iio->blkdirIdxOid = lfirst_oid(lnext(lcfifth(stmt->idxOids)));
iio->blkdirComptypeOid = lfirst_oid(lnext(lnext(lcfifth(stmt->idxOids))));
/* Not all Oids are used (and therefore unset) during upgrade index
* creation. So, skip the Oid assert during upgrade.
*
* In normal operations we proactively allocate a bunch of oids to support
* bitmap indexes and ao indexes, however in bootstrap/upgrade mode when we
* create an index using a supplied oid we do not allocate all these
* additional oids. (See the "ShouldDispatch" block below). This implies that
* we cannot currently support bitmap indexes or ao indexes as part of the catalog.
*/
Insist(OidIsValid(indexRelationId));
if (!gp_upgrade_mode)
{
Insist(OidIsValid(iio->comptypeOid));
Insist(OidIsValid(iio->heapOid));
Insist(OidIsValid(iio->indexOid));
Insist(OidIsValid(iio->blkdirRelOid));
Insist(OidIsValid(iio->blkdirIdxOid));
Insist(OidIsValid(iio->blkdirComptypeOid));
}
quiet = true;
}
}
/*
* Report index creation if appropriate (delay this till after most of the
* error checks)
*/
if (isconstraint && !quiet)
if (Gp_role != GP_ROLE_EXECUTE)
ereport(NOTICE,
(errmsg("%s %s will create implicit index \"%s\" for table \"%s\"",
is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /",
primary ? "PRIMARY KEY" : "UNIQUE",
indexRelationName, RelationGetRelationName(rel))));
if (rel_needs_long_lock(RelationGetRelid(rel)))
need_longlock = true;
else
/* if this is a concurrent build, we must lock you long time */
need_longlock = (false || concurrent);
if (shouldDispatch)
{
IndexInfoOpaque *iiopaque = (IndexInfoOpaque*)(indexInfo->opaque);
if (!OidIsValid(indexRelationId))
{
Relation pg_class;
Relation pg_type;
/**
* In HAWQ, only the master have the catalog information.
* So, no need to sync oid to segments.
*/
/* cdb_sync_oid_to_segments(); */
pg_class = heap_open(RelationRelationId, RowExclusiveLock);
indexRelationId = GetNewRelFileNode(tablespaceId, false, pg_class, false);
iiopaque->heapOid = GetNewRelFileNode(tablespaceId, false, pg_class, false);
iiopaque->indexOid = GetNewRelFileNode(tablespaceId, false, pg_class, false);
iiopaque->blkdirRelOid = GetNewRelFileNode(tablespaceId, false, pg_class, false);
iiopaque->blkdirIdxOid = GetNewRelFileNode(tablespaceId, false, pg_class, false);
/* done with pg_class */
heap_close(pg_class, NoLock);
pg_type = heap_open(TypeRelationId, RowExclusiveLock);
iiopaque->comptypeOid = GetNewOid(pg_type);
iiopaque->blkdirComptypeOid = GetNewOid(pg_type);
heap_close(pg_type, NoLock);
}
/* create the index on the QEs first, so we can get their stats when we create on the QD */
if (stmt)
{
Assert(stmt->idxOids == 0 ||
stmt->idxOids == (List*)NULL);
stmt->idxOids = NIL;
stmt->idxOids = lappend_oid(stmt->idxOids, indexRelationId);
stmt->idxOids = lappend_oid(stmt->idxOids, iiopaque->comptypeOid);
stmt->idxOids = lappend_oid(stmt->idxOids, iiopaque->heapOid);
stmt->idxOids = lappend_oid(stmt->idxOids, iiopaque->indexOid);
stmt->idxOids = lappend_oid(stmt->idxOids, iiopaque->blkdirRelOid);
stmt->idxOids = lappend_oid(stmt->idxOids, iiopaque->blkdirIdxOid);
stmt->idxOids = lappend_oid(stmt->idxOids, iiopaque->blkdirComptypeOid);
}
/*
* Lock the index relation exclusively on the QD, before dispatching,
* otherwise we could get a deadlock between QEs trying to do this same work.
*
* MPP-4889
* NOTE: we also have to do the local create before dispatching, otherwise
* competing attempts to create the same index deadlock.
*
* Don't do this for partition children.
*/
if (need_longlock)
LockRelationOid(indexRelationId, AccessExclusiveLock);
/*
* We defer the dispatch of the utility command until after
* index_create(), because that call will *wait*
* for any other transactions touching this new relation,
* which can cause a non-local deadlock if we've already
* dispatched
*/
indexRelationId =
index_create(relationId, indexRelationName, indexRelationId,
indexInfo, accessMethodId, tablespaceId, classObjectId,
reloptions, primary, isconstraint, &(stmt->constrOid),
allowSystemTableModsDDL, skip_build, concurrent, altconname);
/*
* Dispatch the command to all primary and mirror segment dbs.
* Start a global transaction and reconfigure cluster if needed.
* Wait for QEs to finish. Exit via ereport(ERROR,...) if error.
*/
if (stmt->concurrent)
{
/* In hawq, there is no local index, so no need to support this feature. */
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("create index concurrent is not support"),
errOmitLocation(true)));
}
else
{
/* Native orc, heap table and magma support index */
if (!RelationIsOrc(rel) && !RelationIsHeap(rel) && !RelationIsMagmaTable(relationId))
{
ereport(ERROR, (errcode(ERRCODE_CDB_FEATURE_NOT_YET), errmsg("Cannot support DefineIndex")));
}
// dispatch_statement_node((Node *)stmt, NULL, NULL, NULL);
}
}
/* save lockrelid for below, then close rel */
heaprelid = rel->rd_lockInfo.lockRelId;
if (need_longlock)
heap_close(rel, NoLock);
else
heap_close(rel, heap_lockmode);
if (!shouldDispatch)
{
indexRelationId =
index_create(relationId, indexRelationName, indexRelationId,
indexInfo, accessMethodId, tablespaceId, classObjectId,
reloptions, primary, isconstraint, &(stmt->constrOid),
allowSystemTableModsDDL, skip_build, concurrent, altconname);
}
if (!concurrent)
return; /* We're done, in the standard case */
/*
* Phase 2 of concurrent index build (see comments for validate_index()
* for an overview of how this works)
*
* We must commit our current transaction so that the index becomes
* visible; then start another. Note that all the data structures we just
* built are lost in the commit. The only data we keep past here are the
* relation IDs.
*
* Before committing, get a session-level lock on the table, to ensure
* that neither it nor the index can be dropped before we finish. This
* cannot block, even if someone else is waiting for access, because we
* already have the same lock within our transaction.
*
* Note: we don't currently bother with a session lock on the index,
* because there are no operations that could change its state while we
* hold lock on the parent table. This might need to change later.
*/
LockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock);
CommitTransactionCommand();
StartTransactionCommand();
/*
* Now we must wait until no running transaction could have the table open
* with the old list of indexes. To do this, inquire which xacts
* currently would conflict with ShareLock on the table -- ie, which ones
* have a lock that permits writing the table. Then wait for each of
* these xacts to commit or abort. Note we do not need to worry about
* xacts that open the table for writing after this point; they will see
* the new index when they open it.
*
* Note: GetLockConflicts() never reports our own xid, hence we need not
* check for that.
*/
SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId);
old_xact_list = GetLockConflicts(&heaplocktag, ShareLock);
foreach(lc, old_xact_list)
{
TransactionId xid = lfirst_xid(lc);
XactLockTableWait(xid);
}
/*
* Now take the "reference snapshot" that will be used by validate_index()
* to filter candidate tuples. All other transactions running at this
* time will have to be out-waited before we can commit, because we can't
* guarantee that tuples deleted just before this will be in the index.
*
* We also set ActiveSnapshot to this snap, since functions in indexes may
* need a snapshot.
*/
snapshot = CopySnapshot(GetTransactionSnapshot());
ActiveSnapshot = snapshot;
/*
* Scan the index and the heap, insert any missing index entries.
*/
validate_index(relationId, indexRelationId, snapshot);
/*
* The index is now valid in the sense that it contains all currently
* interesting tuples. But since it might not contain tuples deleted just
* before the reference snap was taken, we have to wait out any
* transactions older than the reference snap. We can do this by waiting
* for each xact explicitly listed in the snap.
*
* Note: GetSnapshotData() never stores our own xid into a snap, hence we
* need not check for that.
*/
for (ixcnt = 0; ixcnt < snapshot->xcnt; ixcnt++)
XactLockTableWait(snapshot->xip[ixcnt]);
/* Index can now be marked valid -- update its pg_index entry */
pg_index = heap_open(IndexRelationId, RowExclusiveLock);
pcqCtx = caql_addrel(cqclr(&cqc), pg_index);
indexTuple = caql_getfirst(
pcqCtx,
cql("SELECT * FROM pg_index "
" WHERE indexrelid = :1 "
" FOR UPDATE ",
ObjectIdGetDatum(indexRelationId)));
if (!HeapTupleIsValid(indexTuple))
elog(ERROR, "cache lookup failed for index %u", indexRelationId);
indexForm = (Form_pg_index) GETSTRUCT(indexTuple);
Assert(indexForm->indexrelid = indexRelationId);
Assert(!indexForm->indisvalid);
indexForm->indisvalid = true;
caql_update_current(pcqCtx, indexTuple);
/* and Update indexes (implicit) */
heap_close(pg_index, RowExclusiveLock);
/*
* Last thing to do is release the session-level lock on the parent table.
*/
UnlockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock);
}
/*
* CheckPredicate
* Checks that the given partial-index predicate is valid.
*
* This used to also constrain the form of the predicate to forms that
* indxpath.c could do something with. However, that seems overly
* restrictive. One useful application of partial indexes is to apply
* a UNIQUE constraint across a subset of a table, and in that scenario
* any evaluatable predicate will work. So accept any predicate here
* (except ones requiring a plan), and let indxpath.c fend for itself.
*/
static void
CheckPredicate(Expr *predicate)
{
/*
* We don't currently support generation of an actual query plan for a
* predicate, only simple scalar expressions; hence these restrictions.
*/
if (contain_subplans((Node *) predicate))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot use subquery in index predicate"),
errOmitLocation(true)));
if (contain_agg_clause((Node *) predicate))
ereport(ERROR,
(errcode(ERRCODE_GROUPING_ERROR),
errmsg("cannot use aggregate in index predicate"),
errOmitLocation(true)));
if (checkExprHasWindFuncs((Node *)predicate))
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("cannot use window function in index predicate"),
errOmitLocation(true)));
/*
* A predicate using mutable functions is probably wrong, for the same
* reasons that we don't allow an index expression to use one.
*/
if (contain_mutable_functions((Node *) predicate))
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("functions in index predicate must be marked IMMUTABLE"),
errOmitLocation(true)));
}
extern void
ComputeConstraintAttrs(IndexInfo *indexInfo,
List *attList, /* list of IndexElem's */
Oid relId)
{
ListCell *rest;
int attn = 0;
/*
* process attributeList
*/
foreach(rest, attList)
{
IndexElem *attribute = (IndexElem *) lfirst(rest);
Oid atttype;
if (attribute->name != NULL)
{
/* Simple index attribute */
HeapTuple atttuple;
Form_pg_attribute attform;
cqContext *pcqCtx;
Assert(attribute->expr == NULL);
pcqCtx = caql_getattname_scan(NULL, relId, attribute->name);
atttuple = caql_get_current(pcqCtx);
if (!HeapTupleIsValid(atttuple))
{
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" does not exist",
attribute->name)));
}
attform = (Form_pg_attribute) GETSTRUCT(atttuple);
indexInfo->ii_KeyAttrNumbers[attn] = attform->attnum;
indexInfo->ii_NumIndexAttrs += 1;
atttype = attform->atttypid;
caql_endscan(pcqCtx);
}
else
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("expression for primary key constraint definition is not supported")));
}
attn++;
}
}
static void
ComputeIndexAttrs(IndexInfo *indexInfo,
Oid *classOidP,
List *attList, /* list of IndexElem's */
Oid relId,
char *accessMethodName,
Oid accessMethodId,
bool isconstraint)
{
ListCell *rest;