Class: Glancer::Workflow::SQLValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/glancer/workflow/sql_validator.rb

Class Method Summary collapse

Class Method Details

.extract_table_names(sql) ⇒ Object



32
33
34
35
36
# File 'lib/glancer/workflow/sql_validator.rb', line 32

def self.extract_table_names(sql)
  sql.scan(/\bfrom\s+([a-zA-Z0-9_."]+)/i).flatten.map do |name|
    name.gsub('"', "").downcase.strip
  end.uniq
end

.indexed_schema_table_namesObject



43
44
45
46
47
48
49
50
51
# File 'lib/glancer/workflow/sql_validator.rb', line 43

def self.indexed_schema_table_names
  Glancer::Embedding
    .where(source_type: "schema")
    .pluck(:source_path)
    .map { |path| path[/#(.*?)\z/, 1] }
    .compact
    .map(&:downcase)
    .uniq
end

.system_schemasObject



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/glancer/workflow/sql_validator.rb', line 53

def self.system_schemas
  case Glancer.configuration.resolved_adapter.to_s
  when "postgres", "postgresql"
    %w[information_schema pg_catalog pg_toast]
  when "mysql", "mysql2"
    %w[information_schema mysql performance_schema sys]
  when "sqlite", "sqlite3"
    %w[sqlite_master]
  else
    []
  end
end

.system_table?(table_name) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
41
# File 'lib/glancer/workflow/sql_validator.rb', line 38

def self.system_table?(table_name)
  schema = table_name.include?(".") ? table_name.split(".").first.downcase : table_name
  system_schemas.include?(schema)
end

.validate_tables_exist!(sql) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/glancer/workflow/sql_validator.rb', line 6

def self.validate_tables_exist!(sql)
  Glancer::Utils::Logger.info("Workflow::SQLValidator", "Validating presence of tables in indexed schema...")

  tables_in_sql = extract_table_names(sql)
  Glancer::Utils::Logger.debug("Workflow::SQLValidator", "Tables found in SQL: #{tables_in_sql.inspect}")

  indexed_tables = indexed_schema_table_names
  Glancer::Utils::Logger.debug("Workflow::SQLValidator",
                               "Tables available in indexed schema: #{indexed_tables.inspect}")

  missing = tables_in_sql.reject do |table|
    system_table?(table) || indexed_tables.include?(table)
  end

  if missing.any?
    Glancer::Utils::Logger.error("Workflow::SQLValidator", "Missing table(s): #{missing.join(", ")}")
    raise Glancer::Error, "Missing table(s) in indexed schema: #{missing.join(", ")}"
  end

  Glancer::Utils::Logger.info("Workflow::SQLValidator", "All referenced tables are present in indexed schema.")
rescue StandardError => e
  Glancer::Utils::Logger.error("Workflow::SQLValidator", "Table validation failed: #{e.class} - #{e.message}")
  Glancer::Utils::Logger.debug("Workflow::SQLValidator", "Backtrace:\n#{e.backtrace.join("\n")}")
  raise Glancer::Error, "Table validation failed: #{e.message}"
end