parser icon indicating copy to clipboard operation
parser copied to clipboard

How to get *model.ColumnInfo and *model.TableInfo from mysql instance

Open jiashiwen opened this issue 5 years ago • 2 comments

Question

Before asking a question, make sure you have:

jiashiwen avatar Mar 02 '20 04:03 jiashiwen

Hi.

Currently you can't get the ColumnInfo/TableInfo from the pingcap/parser package alone, because these also record states exclusive for TiDB.

If you already have a running TiDB instance, you can deserialize the TableInfo through the status port (read JSON from http://tidb-instance:10080/schema/DBNAME/TABLENAME).

Otherwise, you can extract the table's schema through SHOW CREATE TABLE xxxx, then parse that string into an *ast.CreateTableStmt, and use ddl.MockTableInfo to convert this into a TableInfo.

import (
	"github.com/pingcap/parser"
	"github.com/pingcap/parser/ast"
	"github.com/pingcap/tidb/ddl"
	"github.com/pingcap/tidb/util/mock"
)

p := parser.New()
se := mock.NewContext()
node, err := p.ParseOneStmt(`CREATE TABLE ...`, "", "")
tableInfo, err := ddl.MockTableInfo(se, node.(*ast.CreateTableStmt), 1)

kennytm avatar Mar 02 '20 06:03 kennytm

Hi.

Currently you can't get the ColumnInfo/TableInfo from the pingcap/parser package alone, because these also record states exclusive for TiDB.

If you already have a running TiDB instance, you can deserialize the TableInfo through the status port (read JSON from http://tidb-instance:10080/schema/DBNAME/TABLENAME).

Otherwise, you can extract the table's schema through SHOW CREATE TABLE xxxx, then parse that string into an *ast.CreateTableStmt, and use ddl.MockTableInfo to convert this into a TableInfo.

import (
	"github.com/pingcap/parser"
	"github.com/pingcap/parser/ast"
	"github.com/pingcap/tidb/ddl"
	"github.com/pingcap/tidb/util/mock"
)

p := parser.New()
se := mock.NewContext()
node, err := p.ParseOneStmt(`CREATE TABLE ...`, "", "")
tableInfo, err := ddl.MockTableInfo(se, node.(*ast.CreateTableStmt), 1)

This way is helpful,but miss one point. We need to import _ "github.com/pingcap/tidb/planner/core", in order to initialize something like expression.EvalAstExpr

waterandair avatar Nov 16 '20 00:11 waterandair