@@ -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 )
0 commit comments