Class: Glancer::Workflow::SQLExtractor

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

Constant Summary collapse

SQL_START =
/\A\s*(select|with|explain)\b/i

Class Method Summary collapse

Class Method Details

.extract(text) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/glancer/workflow/sql_extractor.rb', line 8

def self.extract(text)
  Glancer::Utils::Logger.info("Workflow::SQLExtractor", "Extracting SQL from text response...")

  # Match ```sql, ```SQL, or plain ``` fenced blocks
  if text =~ /```(?:sql)?\s*\n?(.*?)\s*```/mi
    sql = ::Regexp.last_match(1).strip
    Glancer::Utils::Logger.debug("Workflow::SQLExtractor", "Extracted SQL from formatted code block.")
  else
    # Fallback: find the first line that looks like the start of a SQL statement
    # and take everything from there, ignoring leading explanation text.
    lines = text.lines
    start_idx = lines.index { |l| l.strip.match?(SQL_START) }

    sql = if start_idx
            lines[start_idx..].join.strip
          else
            text.lines.map(&:strip).reject(&:empty?).join(" ")
          end

    fallback_type = start_idx ? " (SQL found at line #{start_idx})" : " (raw join)"
    Glancer::Utils::Logger.debug("Workflow::SQLExtractor",
                                 "No code block found. Fallback extraction#{fallback_type}.")
  end

  Glancer::Utils::Logger.debug("Workflow::SQLExtractor", "Final extracted SQL:\n#{sql}")

  sql
rescue StandardError => e
  Glancer::Utils::Logger.error("Workflow::SQLExtractor", "SQL extraction failed: #{e.class} - #{e.message}")
  Glancer::Utils::Logger.debug("Workflow::SQLExtractor", "Backtrace:\n#{e.backtrace.join("\n")}")
  raise Glancer::Error, "SQL extraction failed: #{e.message}"
end