Skip to content

Commit

Permalink
sql/sqlspec: allow labeling primary keys (#3351)
Browse files Browse the repository at this point in the history
  • Loading branch information
a8m authored Jan 29, 2025
1 parent d723234 commit 951410f
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions sql/internal/specutil/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,7 @@ func PrimaryKey(spec *sqlspec.PrimaryKey, parent *schema.Table) (*schema.Index,
})
}
pk := &schema.Index{
Name: spec.Name,
Table: parent,
Parts: parts,
}
Expand Down
1 change: 1 addition & 0 deletions sql/sqlspec/sqlspec.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ type (

// PrimaryKey holds a specification for the primary key of a table.
PrimaryKey struct {
Name string `spec:",name"` // Optional name.
Parts []*IndexPart `spec:"on"`
Columns []*schemahcl.Ref `spec:"columns"`
schemahcl.DefaultExtension
Expand Down
43 changes: 43 additions & 0 deletions sql/sqlspec/sqlspec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ package sqlspec
import (
"testing"

"ariga.io/atlas/schemahcl"

"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -55,3 +57,44 @@ SELECT
require.Equal(t, tt.expected, MightHeredoc(tt.input))
}
}

func TestMarshalPrimaryKey(t *testing.T) {
spec := &Table{
Name: "users",
Columns: []*Column{
{Name: "id", Type: &schemahcl.Type{T: "text"}},
},
PrimaryKey: &PrimaryKey{
Columns: []*schemahcl.Ref{
{V: "$column.id"},
},
},
}
buf, err := schemahcl.Marshal.MarshalSpec(spec)
require.NoError(t, err)
require.Equal(t, `table "users" {
column "id" {
null = false
type = sql("text")
}
primary_key {
columns = [column.id]
}
}
`, string(buf))

// Include primary key on marshaling.
spec.PrimaryKey.Name = "custom_name"
buf, err = schemahcl.Marshal.MarshalSpec(spec)
require.NoError(t, err)
require.Equal(t, `table "users" {
column "id" {
null = false
type = sql("text")
}
primary_key "custom_name" {
columns = [column.id]
}
}
`, string(buf))
}

0 comments on commit 951410f

Please sign in to comment.