Skip to content

Instantly share code, notes, and snippets.

@paralin
Created February 16, 2023 10:09
Show Gist options
  • Select an option

  • Save paralin/5e7c3fa55f958ea67d383ed4f7ddeee5 to your computer and use it in GitHub Desktop.

Select an option

Save paralin/5e7c3fa55f958ea67d383ed4f7ddeee5 to your computer and use it in GitHub Desktop.
go parse column type with vitess
package mysql
import (
"strings"
"github.com/dolthub/vitess/go/vt/sqlparser"
"github.com/pkg/errors"
)
// ParseColumnType parses a column type string to a sqlparser.ColumnType.
func ParseColumnType(typeStr string) (*sqlparser.ColumnType, error) {
if len(typeStr) == 0 {
return nil, errors.New("column_type: empty string")
}
var toParse strings.Builder
_, _ = toParse.WriteString("CREATE TABLE t (v ")
_, _ = toParse.WriteString(typeStr)
_, _ = toParse.WriteString(")")
stmt, _, err := sqlparser.ParseOne(toParse.String())
if err != nil {
return nil, err
}
ddl, ok := stmt.(*sqlparser.DDL)
if !ok {
return nil, errors.New("unexpected non-ddl statement while parsing column type")
}
if ddl.TableSpec == nil || len(ddl.TableSpec.Columns) != 1 {
return nil, errors.New("unexpected table spec while parsing column type")
}
colType := ddl.TableSpec.Columns[0].Type
return &colType, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment