Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions parser/createtable_visitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,18 @@ type Column struct {
func (c *CreateTable) Convert() *Table {
var ret Table
ret.Name = onlyTableName(c.Name)
primaryKeyExists := checkIfPrimaryKeyExists(c.Constraints)
for _, e := range c.Columns {
definition := e.ColumnDefinition
var data Column
data.Name = e.Name
if definition != nil {
data.DataType = definition.DataType
data.Constraint = definition.ColumnConstraint

if definition.ColumnConstraint != nil && !primaryKeyExists && definition.ColumnConstraint.Primary {
c.Constraints = append(c.Constraints, &TableConstraint{ColumnPrimaryKey: []string{e.Name}})
}
}
ret.Columns = append(ret.Columns, &data)
}
Expand All @@ -177,3 +182,13 @@ func onlyTableName(name string) string {
ss := strings.Split(name, "`.`")
return ss[len(ss)-1]
}

func checkIfPrimaryKeyExists(constraints []*TableConstraint) bool {
for _, constraint := range constraints {
if len(constraint.ColumnPrimaryKey) > 0 {
return true
}
}

return false
}
78 changes: 78 additions & 0 deletions parser/createtable_visitor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,81 @@ func Test_onlyTableName(t *testing.T) {
})
}
}

func Test_checkIfPrimaryKeyExists(t *testing.T) {
type args struct {
constraints []*TableConstraint
}

tests := []struct {
name string
args args
want bool
}{
{
name: "No constraints (nil slice)",
args: args{
constraints: nil,
},
want: false,
},
{
name: "Empty constraints slice",
args: args{
constraints: []*TableConstraint{},
},
want: false,
},
{
name: "One constraint without primary key",
args: args{
constraints: []*TableConstraint{
{
ColumnPrimaryKey: []string{},
},
},
},
want: false,
},
{
name: "Multiple constraints, none with primary key",
args: args{
constraints: []*TableConstraint{
{ColumnPrimaryKey: []string{}},
{ColumnPrimaryKey: []string{}},
},
},
want: false,
},
{
name: "One constraint with primary key",
args: args{
constraints: []*TableConstraint{
{
ColumnPrimaryKey: []string{"id"},
},
},
},
want: true,
},
{
name: "Multiple constraints, one with primary key",
args: args{
constraints: []*TableConstraint{
{ColumnPrimaryKey: []string{}},
{ColumnPrimaryKey: []string{"user_id"}},
{ColumnPrimaryKey: []string{}},
},
},
want: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := checkIfPrimaryKeyExists(tt.args.constraints); got != tt.want {
t.Errorf("checkIfPrimaryKeyExists() = %v, want %v", got, tt.want)
}
})
}
}