Skip to content

Commit d2a1212

Browse files
authored
New DBAction to create primary key constraint from index (#901)
Relates to #742
1 parent 07d8d08 commit d2a1212

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

pkg/migrations/dbactions.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,28 @@ func (a *addConstraintUsingUniqueIndexAction) Execute(ctx context.Context) error
175175
return err
176176
}
177177

178+
type addPrimaryKeyAction struct {
179+
conn db.DB
180+
table string
181+
indexName string
182+
}
183+
184+
func NewAddPrimaryKeyAction(conn db.DB, table, indexName string) *addPrimaryKeyAction {
185+
return &addPrimaryKeyAction{
186+
conn: conn,
187+
table: table,
188+
indexName: indexName,
189+
}
190+
}
191+
192+
func (a *addPrimaryKeyAction) Execute(ctx context.Context) error {
193+
_, err := a.conn.ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s ADD PRIMARY KEY USING INDEX %s",
194+
pq.QuoteIdentifier(a.table),
195+
pq.QuoteIdentifier(a.indexName),
196+
))
197+
return err
198+
}
199+
178200
// dropFunctionAction is a DBAction that drops a function and all of its dependencies (cascade).
179201
type dropFunctionAction struct {
180202
conn db.DB

pkg/migrations/op_create_constraint.go

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@ import (
66
"context"
77
"fmt"
88

9-
"github.com/lib/pq"
10-
119
"github.com/xataio/pgroll/pkg/backfill"
1210
"github.com/xataio/pgroll/pkg/db"
1311
"github.com/xataio/pgroll/pkg/schema"
@@ -137,10 +135,7 @@ func (o *OpCreateConstraint) Complete(ctx context.Context, l Logger, conn db.DB,
137135
return err
138136
}
139137
case OpCreateConstraintTypePrimaryKey:
140-
_, err := conn.ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s ADD PRIMARY KEY USING INDEX %s",
141-
pq.QuoteIdentifier(o.Table),
142-
pq.QuoteIdentifier(o.Name),
143-
))
138+
err := NewAddPrimaryKeyAction(conn, o.Table, o.Name).Execute(ctx)
144139
if err != nil {
145140
return err
146141
}

0 commit comments

Comments
 (0)