-
Notifications
You must be signed in to change notification settings - Fork 82
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Retry creating unique index #613
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
64815e8
Introduce retry mechanism for unique index creation
agedemenli 865afa3
Early return in case of fake db
agedemenli 5cff95b
Fix style
agedemenli b76f035
Error in case of index creation failure
agedemenli d209398
Address feedback
agedemenli 7a43c0e
Refactor & Use the new index creation method in other places
agedemenli eb0ad6b
Fix column names quoted twice
agedemenli e08127d
Defer stopping the ticker
agedemenli 6b52509
Test sql generation
agedemenli ebf7097
Add missing QuoteIdentifier for indexName
agedemenli a44ab9f
Style
agedemenli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
package migrations | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"strings" | ||
"time" | ||
|
||
"github.com/lib/pq" | ||
"github.com/xataio/pgroll/pkg/db" | ||
) | ||
|
||
func createUniqueIndexConcurrently(ctx context.Context, conn db.DB, schemaName string, indexName string, tableName string, columnNames []string) error { | ||
quotedQualifiedIndexName := pq.QuoteIdentifier(indexName) | ||
if schemaName != "" { | ||
quotedQualifiedIndexName = fmt.Sprintf("%s.%s", pq.QuoteIdentifier(schemaName), pq.QuoteIdentifier(indexName)) | ||
} | ||
for retryCount := 0; retryCount < 5; retryCount++ { | ||
// Add a unique index to the new column | ||
// Indexes are created in the same schema with the table automatically. Instead of the qualified one, just pass the index name. | ||
createIndexSQL := getCreateUniqueIndexConcurrentlySQL(indexName, schemaName, tableName, columnNames) | ||
if _, err := conn.ExecContext(ctx, createIndexSQL); err != nil { | ||
return fmt.Errorf("failed to add unique index %q: %w", indexName, err) | ||
} | ||
|
||
// Make sure Postgres is done creating the index | ||
isInProgress, err := isIndexInProgress(ctx, conn, quotedQualifiedIndexName) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
ticker := time.NewTicker(500 * time.Millisecond) | ||
defer ticker.Stop() | ||
for isInProgress { | ||
<-ticker.C | ||
isInProgress, err = isIndexInProgress(ctx, conn, quotedQualifiedIndexName) | ||
if err != nil { | ||
return err | ||
} | ||
} | ||
|
||
// Check pg_index to see if it's valid or not. Break if it's valid. | ||
isValid, err := isIndexValid(ctx, conn, quotedQualifiedIndexName) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if isValid { | ||
// success | ||
return nil | ||
} | ||
|
||
// If not valid, since Postgres has already given up validating the index, | ||
// it will remain invalid forever. Drop it and try again. | ||
_, err = conn.ExecContext(ctx, fmt.Sprintf("DROP INDEX IF EXISTS %s", quotedQualifiedIndexName)) | ||
if err != nil { | ||
return fmt.Errorf("failed to drop index: %w", err) | ||
} | ||
} | ||
|
||
// ran out of retries, return an error | ||
return fmt.Errorf("failed to create unique index %q", indexName) | ||
} | ||
|
||
func getCreateUniqueIndexConcurrentlySQL(indexName string, schemaName string, tableName string, columnNames []string) string { | ||
// create unique index concurrently | ||
qualifiedTableName := pq.QuoteIdentifier(tableName) | ||
if schemaName != "" { | ||
qualifiedTableName = fmt.Sprintf("%s.%s", pq.QuoteIdentifier(schemaName), pq.QuoteIdentifier(tableName)) | ||
} | ||
|
||
indexQuery := fmt.Sprintf( | ||
"CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS %s ON %s (%s)", | ||
pq.QuoteIdentifier(indexName), | ||
qualifiedTableName, | ||
strings.Join(quoteColumnNames(columnNames), ", "), | ||
) | ||
|
||
return indexQuery | ||
} | ||
|
||
func isIndexInProgress(ctx context.Context, conn db.DB, quotedQualifiedIndexName string) (bool, error) { | ||
rows, err := conn.QueryContext(ctx, `SELECT EXISTS( | ||
SELECT * FROM pg_catalog.pg_stat_progress_create_index | ||
WHERE index_relid = $1::regclass | ||
)`, quotedQualifiedIndexName) | ||
if err != nil { | ||
return false, fmt.Errorf("getting index in progress with name %q: %w", quotedQualifiedIndexName, err) | ||
} | ||
if rows == nil { | ||
// if rows == nil && err != nil, then it means we have queried a `FakeDB`. | ||
// In that case, we can safely return false. | ||
return false, nil | ||
} | ||
var isInProgress bool | ||
if err := db.ScanFirstValue(rows, &isInProgress); err != nil { | ||
return false, fmt.Errorf("scanning index in progress with name %q: %w", quotedQualifiedIndexName, err) | ||
} | ||
|
||
return isInProgress, nil | ||
} | ||
|
||
func isIndexValid(ctx context.Context, conn db.DB, quotedQualifiedIndexName string) (bool, error) { | ||
rows, err := conn.QueryContext(ctx, `SELECT indisvalid | ||
FROM pg_catalog.pg_index | ||
WHERE indexrelid = $1::regclass`, | ||
quotedQualifiedIndexName) | ||
if err != nil { | ||
return false, fmt.Errorf("getting index with name %q: %w", quotedQualifiedIndexName, err) | ||
} | ||
if rows == nil { | ||
// if rows == nil && err != nil, then it means we have queried a fake db. | ||
// In that case, we can safely return true. | ||
return true, nil | ||
} | ||
var isValid bool | ||
if err := db.ScanFirstValue(rows, &isValid); err != nil { | ||
return false, fmt.Errorf("scanning index with name %q: %w", quotedQualifiedIndexName, err) | ||
} | ||
|
||
return isValid, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice