登录
首页 >  Golang >  Go问答

提取 SQL 查询语句中的表名

来源:stackoverflow

时间:2024-03-01 12:51:24 480浏览 收藏

golang学习网今天将给大家带来《提取 SQL 查询语句中的表名》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

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

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

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

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


解决方案


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

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 类型的(子)字段,其中包含语句中请求的表。

我从 @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
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《提取 SQL 查询语句中的表名》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>