Skip to content

Commit a1939ab

Browse files
committed
GetPrimaryKey returns pointer to the ColumnDefinition instead of the name of the column; thus we can change the property of the column
1 parent d76aa02 commit a1939ab

File tree

2 files changed

+33
-7
lines changed

2 files changed

+33
-7
lines changed

analyzer.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,19 +25,19 @@ func GetTableName(node SimpleTableExpr) string {
2525
}
2626

2727
// Get the primary key of the table, sqlNode must be a CreateTable struct
28-
func GetPrimaryKey(sqlNode SQLNode) (string, error) {
28+
func GetPrimaryKey(sqlNode SQLNode) (*ColumnDefinition, error) {
2929
node, ok := sqlNode.(*CreateTable)
3030
if !ok {
31-
return "", errors.New("fail to convert interface SQLNode to struct CreateTable")
31+
return nil, errors.New("fail to convert interface SQLNode to struct CreateTable")
3232
}
3333
for _, col := range node.ColumnDefinitions {
3434
for _, att := range col.ColumnAtts {
3535
if att == AST_PRIMARY_KEY {
36-
return col.ColName, nil
36+
return col, nil
3737
}
3838
}
3939
}
40-
return "", errors.New("unable to find primary key")
40+
return nil, errors.New("unable to find primary key")
4141
}
4242

4343
// GetColName returns the column name, only if

analyzer_test.go

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,41 @@ func TestPrimaryKey(t *testing.T) {
1818
assert.Nil(t, err)
1919
primary_key, err := GetPrimaryKey(tree)
2020
assert.Nil(t, err)
21-
assert.Equal(t, "ID", primary_key)
21+
assert.Equal(t, "ID", primary_key.ColName)
2222

23-
sql = `create table t1 (
23+
}
24+
func TestNoPrimaryKey(t *testing.T) {
25+
sql := `create table t1 (
2426
LastName varchar(255),
2527
FirstName varchar(255),
2628
ID int unique key
2729
)`
28-
tree, err = Parse(sql)
30+
tree, err := Parse(sql)
2931
assert.Nil(t, err)
3032
_, err = GetPrimaryKey(tree)
3133
assert.NotNil(t, err)
3234
}
35+
36+
func TestChangePrimaryKeyProperty(t *testing.T) {
37+
sql := `create table t1 (
38+
LastName varchar(255),
39+
FirstName varchar(255),
40+
ID int primary key
41+
)`
42+
43+
tree, err := Parse(sql)
44+
assert.Nil(t, err)
45+
primary_key, err := GetPrimaryKey(tree)
46+
assert.Nil(t, err)
47+
48+
primary_key.ColumnAtts = append(primary_key.ColumnAtts, "auto_increment")
49+
50+
sql_actual := String(tree)
51+
52+
sql_expected := `create table t1 (
53+
LastName varchar(255),
54+
FirstName varchar(255),
55+
ID int primary key auto_increment
56+
)`
57+
assert.Equal(t, sql_expected, sql_actual)
58+
}

0 commit comments

Comments
 (0)