Skip to content

Commit

Permalink
Add support for creating unique indexes (#442)
Browse files Browse the repository at this point in the history
This PR adds a new attribute to `create_index` operation.
From now on it is possible to create a unique index on one or more
columns in a table.
  • Loading branch information
kvch authored Nov 5, 2024
1 parent 898bd84 commit ac1dd85
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 1 deletion.
2 changes: 2 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -974,12 +974,14 @@ A create index operation creates a new index on a set of columns.

The field `method` can be `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`.
You can also specify storage parameters for the index in `storage_parameters`.
To create a unique index set `unique` to `true`.

Example **create index** migrations:

* [10_create_index.json](../examples/10_create_index.json)
* [37_create_partial_index.json](../examples/37_create_partial_index.json)
* [38_create_hash_index_with_fillfactor.json](../examples/38_create_hash_index_with_fillfactor.json)
* [39_create_unique_index.json](../examples/39_create_unique_index.json)

### Create table

Expand Down
15 changes: 15 additions & 0 deletions examples/39_create_unique_index.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "39_create_unique_index",
"operations": [
{
"create_index": {
"name": "idx_fruits_unique_name",
"table": "fruits",
"columns": [
"name"
],
"unique": true
}
}
]
}
6 changes: 5 additions & 1 deletion pkg/migrations/op_create_index.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ var _ Operation = (*OpCreateIndex)(nil)

func (o *OpCreateIndex) Start(ctx context.Context, conn db.DB, latestSchema string, tr SQLTransformer, s *schema.Schema, cbs ...CallbackFn) (*schema.Table, error) {
// create index concurrently
stmt := fmt.Sprintf("CREATE INDEX CONCURRENTLY %s ON %s",
stmtFmt := "CREATE INDEX CONCURRENTLY %s ON %s"
if o.Unique != nil && *o.Unique {
stmtFmt = "CREATE UNIQUE INDEX CONCURRENTLY %s ON %s"
}
stmt := fmt.Sprintf(stmtFmt,
pq.QuoteIdentifier(o.Name),
pq.QuoteIdentifier(o.Table))

Expand Down
3 changes: 3 additions & 0 deletions pkg/migrations/types.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,10 @@
"storage_parameters": {
"description": "Storage parameters for the index",
"type": "string"
},
"unique": {
"description": "Indicates if the index is unique",
"type": "boolean"
}
},
"required": ["columns", "name", "table"],
Expand Down

0 comments on commit ac1dd85

Please sign in to comment.