Skip to content

Instantly share code, notes, and snippets.

@alextanhongpin
Created April 13, 2020 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alextanhongpin/6eb1221ddeee95eeb1a04db4bc02038b to your computer and use it in GitHub Desktop.
Save alextanhongpin/6eb1221ddeee95eeb1a04db4bc02038b to your computer and use it in GitHub Desktop.
Sample usage of mysql parser - could be useful to create ERD diagrams from database schema
package main
import (
"fmt"
"log"
"github.com/pingcap/parser"
"github.com/pingcap/parser/ast"
_ "github.com/pingcap/tidb/types/parser_driver"
)
func main() {
p := parser.New()
stmtNodes, _, err := p.Parse(`
create table if not exists users (
id int,
name varchar(255),
role_id int,
PRIMARY KEY (id),
FOREIGN KEY (role_id) REFERENCES roles(id)
)
`, "", "")
if err != nil {
log.Fatal(err)
}
node := stmtNodes[0]
fmt.Printf("%#v\n\n", node)
stmt := node.(*ast.CreateTableStmt)
fmt.Printf("%#v\n\n", stmt.Table)
fmt.Println(stmt.Table)
for _, col := range stmt.Cols {
fmt.Println(col.Name, col.Tp, col.Options)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment