Skip to content

Commit

Permalink
Add unique index in fixtures
Browse files Browse the repository at this point in the history
  • Loading branch information
marccampbell committed Aug 13, 2019
1 parent 65b63bf commit 35e5eba
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
15 changes: 15 additions & 0 deletions pkg/database/postgres/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/lib/pq"

schemasv1alpha2 "github.com/schemahero/schemahero/pkg/apis/schemas/v1alpha2"
"github.com/schemahero/schemahero/pkg/database/types"
)

func CreateTableStatement(tableName string, tableSchema *schemasv1alpha2.SQLTableSchema) (string, error) {
Expand All @@ -28,6 +29,20 @@ func CreateTableStatement(tableName string, tableSchema *schemasv1alpha2.SQLTabl
columns = append(columns, fmt.Sprintf("primary key (%s)", strings.Join(primaryKeyColumns, ", ")))
}

if len(tableSchema.Indexes) > 0 {
for _, index := range tableSchema.Indexes {
if index.IsUnique {
uniqueColumns := []string{}
for _, indexColumn := range index.Columns {
uniqueColumns = append(uniqueColumns, pq.QuoteIdentifier(indexColumn))
}
columns = append(columns, fmt.Sprintf("constraint %q unique (%s)", types.GenerateIndexName(tableName, index), strings.Join(uniqueColumns, ", ")))
} else {
// non unique indexes are not supported in fixtures
}
}
}

if tableSchema.ForeignKeys != nil {
for _, foreignKey := range tableSchema.ForeignKeys {
columns = append(columns, foreignKeyConstraintClause(tableName, foreignKey))
Expand Down
30 changes: 30 additions & 0 deletions pkg/database/postgres/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,36 @@ func Test_CreateTableStatement(t *testing.T) {
tableName: "composite_primary_key",
expectedStatement: `create table "composite_primary_key" ("one" integer, "two" integer, "three" character varying (255), primary key ("one", "two"))`,
},
{
name: "composite unique index",
tableSchema: &schemasv1alpha2.SQLTableSchema{
PrimaryKey: []string{
"one",
},
Indexes: []*schemasv1alpha2.SQLTableIndex{
&schemasv1alpha2.SQLTableIndex{
Columns: []string{"two", "three"},
IsUnique: true,
},
},
Columns: []*schemasv1alpha2.SQLTableColumn{
&schemasv1alpha2.SQLTableColumn{
Name: "one",
Type: "integer",
},
&schemasv1alpha2.SQLTableColumn{
Name: "two",
Type: "integer",
},
&schemasv1alpha2.SQLTableColumn{
Name: "three",
Type: "varchar(255)",
},
},
},
tableName: "composite_unique_index",
expectedStatement: `create table "composite_unique_index" ("one" integer, "two" integer, "three" character varying (255), primary key ("one"), constraint "idx_composite_unique_index_two_three" unique ("two", "three"))`,
},
}

for _, test := range tests {
Expand Down

0 comments on commit 35e5eba

Please sign in to comment.