Skip to content

Commit

Permalink
Fix show create table matches prefix of the table name (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
yfuruyama authored Jun 10, 2020
1 parent b83c050 commit 3897e3a
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
8 changes: 7 additions & 1 deletion statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ func (s *ShowCreateTableStatement) Execute(session *Session) (*Result, error) {
return nil, err
}
for _, stmt := range ddlResponse.Statements {
if regexp.MustCompile(`(?i)^CREATE TABLE ` + s.Table).MatchString(stmt) {
if isCreateTableDDL(stmt, s.Table) {
resultRow := Row{
Columns: []string{s.Table, stmt},
}
Expand All @@ -406,6 +406,12 @@ func (s *ShowCreateTableStatement) Execute(session *Session) (*Result, error) {
return result, nil
}

func isCreateTableDDL(ddl string, table string) bool {
table = regexp.QuoteMeta(table)
re := fmt.Sprintf("(?i)^CREATE TABLE (%s|`%s`)\\s*\\(", table, table)
return regexp.MustCompile(re).MatchString(ddl)
}

type ShowTablesStatement struct{}

func (s *ShowTablesStatement) Execute(session *Session) (*Result, error) {
Expand Down
52 changes: 52 additions & 0 deletions statement_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,3 +287,55 @@ func TestBuildStatement(t *testing.T) {
}
}
}

func TestIsCreateTableDDL(t *testing.T) {
for _, tt := range []struct {
desc string
ddl string
table string
want bool
}{
{
desc: "exact match",
ddl: "CREATE TABLE t1 (\n",
table: "t1",
want: true,
},
{
desc: "given table is prefix of DDL's table",
ddl: "CREATE TABLE t12 (\n",
table: "t1",
want: false,
},
{
desc: "DDL's table is prefix of given table",
ddl: "CREATE TABLE t1 (\n",
table: "t12",
want: false,
},
{
desc: "given table has reserved word",
ddl: "CREATE TABLE `create` (\n",
table: "create",
want: true,
},
{
desc: "given table is regular expression",
ddl: "CREATE TABLE t1 (\n",
table: `..`,
want: false,
},
{
desc: "given table is invalid regular expression",
ddl: "CREATE TABLE t1 (\n",
table: `[\]`,
want: false,
},
} {
t.Run(tt.desc, func(t *testing.T) {
if got := isCreateTableDDL(tt.ddl, tt.table); got != tt.want {
t.Errorf("isCreateTableDDL(%q, %q) = %v, but want %v", tt.ddl, tt.table, got, tt.want)
}
})
}
}

0 comments on commit 3897e3a

Please sign in to comment.