Class: Dbviewer::Security::SqlParser

Inherits:
Object
  • Object
show all
Defined in:
lib/dbviewer/security/sql_parser.rb

Overview

SQL parser for extracting table names from SQL queries Handles complex SQL including CTEs, subqueries, joins, and DML operations

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extract_table_names(sql) ⇒ Array<String>

Parse SQL query and extract all table names

Parameters:

  • sql (String)

    The SQL query to parse

Returns:

  • (Array<String>)

    List of table names found in the query



11
12
13
# File 'lib/dbviewer/security/sql_parser.rb', line 11

def self.extract_table_names(sql)
  new.extract_table_names(sql)
end

Instance Method Details

#extract_table_names(sql) ⇒ Array<String>

Parse SQL query and extract all table names

Parameters:

  • sql (String)

    The SQL query to parse

Returns:

  • (Array<String>)

    List of table names found in the query



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/dbviewer/security/sql_parser.rb', line 18

def extract_table_names(sql)
  return [] if sql.nil? || sql.strip.empty?

  # Remove comments and normalize whitespace
  cleaned_sql = clean_sql(sql)

  # Use a more sophisticated approach to handle complex queries
  table_names = Set.new

  # Split by semicolons to handle multiple statements
  statements = cleaned_sql.split(";").map(&:strip).reject(&:empty?)

  statements.each do |statement|
    table_names.merge(extract_tables_from_statement(statement))
  end

  table_names.to_a.compact
end