Created
April 13, 2020 18:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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