SQL Expressions: Exclude CTEs from required Tables (#106479)

Fixes #105030

---------

Co-authored-by: Sam Jewell <2903904+samjewell@users.noreply.github.com>
This commit is contained in:
Kyle Brandt
2025-06-11 10:36:28 -04:00
committed by GitHub
parent c0e7701ad4
commit 1be9e60667
5 changed files with 62 additions and 20 deletions

View File

@ -3,6 +3,7 @@ package sql
import (
"fmt"
"sort"
"strings"
"github.com/dolthub/vitess/go/vt/sqlparser"
"github.com/grafana/grafana/pkg/infra/log"
@ -10,7 +11,8 @@ import (
var logger = log.New("sql_expr")
// TablesList returns a list of tables for the sql statement
// TablesList returns a list of tables for the sql statement excluding
// CTEs and the 'dual' table. The list is sorted alphabetically.
func TablesList(rawSQL string) ([]string, error) {
stmt, err := sqlparser.Parse(rawSQL)
if err != nil {
@ -19,10 +21,18 @@ func TablesList(rawSQL string) ([]string, error) {
}
tables := make(map[string]struct{})
cteNames := make(map[string]struct{})
walkSubtree := func(node sqlparser.SQLNode) error {
err = sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
switch v := node.(type) {
case *sqlparser.CommonTableExpr:
// Track CTE name from the As field
cteName := v.As.String()
if cteName != "" {
cteNames[strings.ToLower(cteName)] = struct{}{}
}
case *sqlparser.AliasedTableExpr:
if tableName, ok := v.Expr.(sqlparser.TableName); ok {
tables[tableName.Name.String()] = struct{}{}
@ -49,9 +59,15 @@ func TablesList(rawSQL string) ([]string, error) {
// Remove 'dual' table if it exists
// This is a special table in MySQL that always returns a single row with a single column
// See: https://dev.mysql.com/doc/refman/5.7/en/select.html#:~:text=You%20are%20permitted%20to%20specify%20DUAL%20as%20a%20dummy%20table%20name%20in%20situations%20where%20no%20tables%20are%20referenced
if table != "dual" {
result = append(result, table)
if table == "dual" {
continue
}
// Skip CTEs
if _, ok := cteNames[strings.ToLower(table)]; ok {
continue
}
result = append(result, table)
}
sort.Strings(result)