Skip to content

Commit 3a42b7a

Browse files
committed
add analyzer fix to resolve create select and add tests
# Conflicts: # enginetest/queries/script_queries.go
1 parent c8d8087 commit 3a42b7a

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

sql/analyzer/resolve_create_select.go

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,48 @@ func resolveCreateSelect(ctx *sql.Context, a *Analyzer, n sql.Node, scope *plan.
3838
newSch[i] = &tempCol
3939
}
4040

41+
// Apply primary key constraints from index definitions to the merged schema
4142
pkOrdinals := make([]int, 0)
43+
var nonPkIndexes sql.IndexDefs
44+
for _, idx := range ct.Indexes() {
45+
if idx.IsPrimary() {
46+
for _, idxCol := range idx.Columns {
47+
for i, schCol := range newSch {
48+
if schCol.Name == idxCol.Name {
49+
newSch[i].PrimaryKey = true
50+
pkOrdinals = append(pkOrdinals, i)
51+
break
52+
}
53+
}
54+
}
55+
} else {
56+
// Keep non-primary key indexes
57+
nonPkIndexes = append(nonPkIndexes, idx)
58+
}
59+
}
60+
61+
// Also check for columns already marked as primary key
4262
for i, col := range newSch {
4363
if col.PrimaryKey {
44-
pkOrdinals = append(pkOrdinals, i)
64+
found := false
65+
for _, pk := range pkOrdinals {
66+
if pk == i {
67+
found = true
68+
break
69+
}
70+
}
71+
if !found {
72+
pkOrdinals = append(pkOrdinals, i)
73+
}
4574
}
4675
}
4776

4877
newSpec := &plan.TableSpec{
49-
Schema: sql.NewPrimaryKeySchema(newSch, pkOrdinals...),
78+
Schema: sql.NewPrimaryKeySchema(newSch, pkOrdinals...),
79+
IdxDefs: nonPkIndexes, // Only pass non-PK indexes since PK is in schema
80+
FkDefs: ct.ForeignKeys(),
81+
ChDefs: ct.Checks(),
82+
Collation: ct.Collation,
5083
}
5184

5285
newCreateTable := plan.NewCreateTable(ct.Database(), ct.Name(), ct.IfNotExists(), ct.Temporary(), newSpec)

sql/analyzer/validate_create_table.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,13 @@ func validateCreateTable(ctx *sql.Context, a *Analyzer, n sql.Node, scope *plan.
3838
return nil, transform.SameTree, err
3939
}
4040

41+
// For CREATE TABLE AS SELECT, skip validation here because the schema isn't complete yet.
42+
// The resolveCreateSelect analyzer rule will merge schemas and create a new CreateTable node,
43+
// which will be validated separately after the merge.
44+
if ct.Select() != nil {
45+
return n, transform.SameTree, nil
46+
}
47+
4148
sch := ct.PkSchema().Schema
4249
idxs := ct.Indexes()
4350

0 commit comments

Comments
 (0)