从SQL查询中获取表名

时间:2019-01-14 09:41:42

标签: sql go sql-parser

我正在使用golang SQL parser从实际的SQL查询字符串中获取与查询相关的信息。我可以使用以下代码找到查询的类型:

queryType := sqlparser.StmtType(sqlparser.Preview(sql))
fmt.Println(queryType)

但是我不确定如何从sql查询中获取实际的表名。该文档也不清楚。我从parse函数获得的唯一信息是一条语句

有人可以指导我如何使用golang sqlparser获取此信息吗?

3 个答案:

答案 0 :(得分:2)

要获取所有表名,您可能必须使用反射将它们从Statement返回的Parse中拉出。如果您运行以下代码:

stmt, _ := sqlparser.Parse("insert into my_table set my_column=1")
fmt.Printf("%#v\n", stmt)

您将获得输出(为便于阅读而缩进):

&sqlparser.Insert{
    Action:"insert", 
    Comments:sqlparser.Comments(nil), 
    Ignore:"", 
    Table:sqlparser.TableName{
        Name:sqlparser.TableIdent{v:"my_table"}, 
        Qualifier:sqlparser.TableIdent{v:""}
    }, 
    Partitions:sqlparser.Partitions(nil), 
    Columns:sqlparser.Columns{sqlparser.ColIdent{_:[0]struct { _ []uint8 }{}, val:"my_column", lowered:""}}, 
    Rows:sqlparser.Values{sqlparser.ValTuple{(*sqlparser.SQLVal)(0xc00000a0c0)}}, 
    OnDup:sqlparser.OnDup(nil)
}

如您所见,它包含类型TableIdent的(子)字段,其中包含该语句中请求的表。

答案 1 :(得分:0)

我从@ rob74的注释中摘录了一段代码,这很棒,并将其修改为仅返回表名。原始代码段还返回了表的别名。例如。

select * from my_table as mt join other_table using(my_key)
original snippet returns: [my_table, mt, other_table]
new snippet returns:      [my_table, other_table]

rob74的原始摘要:play.golang.org/p/B31wr2w1AL8

package main

import (
    "fmt"
    "github.com/xwb1989/sqlparser"
    "reflect"
)

func main() {
    stmt, _ := sqlparser.Parse("select * from my_table as mt join other_table using(my_key)")
    var tables []string
    tables = getTableNames(reflect.Indirect(reflect.ValueOf(stmt)), tables, 0, false)
    fmt.Printf("%s", tables)
}

func getTableNames(v reflect.Value, tables []string, level int, isTable bool) []string {
    switch v.Kind() {
    case reflect.Struct:
        if v.Type().Name() == "TableIdent" {
            // if this is a TableIdent struct, extract the table name
            tableName := v.FieldByName("v").String()
            if tableName != "" && isTable{
                tables = append(tables, tableName)
            }
        } else {
            // otherwise enumerate all fields of the struct and process further
            for i := 0; i < v.NumField(); i++ {
                tables = getTableNames(reflect.Indirect(v.Field(i)), tables, level+1, isTable)
            }
        }
    case reflect.Array, reflect.Slice:
        for i := 0; i < v.Len(); i++ {
            // enumerate all elements of an array/slice and process further
            tables = getTableNames(reflect.Indirect(v.Index(i)), tables, level+1, isTable)
        }
    case reflect.Interface:
        if v.Type().Name() == "SimpleTableExpr" {
            isTable = true
        }
        // get the actual object that satisfies an interface and process further
        tables = getTableNames(reflect.Indirect(reflect.ValueOf(v.Interface())), tables, level+1, isTable)
    }

    return tables
}

答案 2 :(得分:0)

我为SQL查询写了一些字符串操作库来获取表名:

queryString := sqlstr.NewQueryString(`SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;`)

tableNames := queryString.TableNames()

fmt.Println(tableNames)

// Output:
// [table1 table2]
相关问题