Class: RealDataTests::SqlDumpParser

Inherits:
Object
  • Object
show all
Defined in:
lib/real_data_tests/sql_dump_parser.rb

Overview

Splits a SQL dump into executable blocks. Regular statements become one block each (terminated by ";"); COPY ... FROM stdin blocks span from the COPY line through the "." terminator, preserving the data lines between.

Defined Under Namespace

Classes: SqlBlock

Class Method Summary collapse

Class Method Details

.parse(content) ⇒ Object

Returns an array of SqlBlock in dump order.



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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/real_data_tests/sql_dump_parser.rb', line 9

def self.parse(content)
  blocks = []
  current_block = []
  in_copy_block = false

  content.each_line do |line|
    line = line.chomp

    # Skip empty lines and comments unless in COPY block
    next if !in_copy_block && (line.empty? || line.start_with?('--'))

    # Handle start of COPY block
    if !in_copy_block && line.upcase.match?(/\ACOPY.*FROM stdin/i)
      current_block = [line]
      in_copy_block = true
      next
    end

    # Handle end of COPY block
    if in_copy_block && line == '\\.'
      current_block << line
      blocks << SqlBlock.new(current_block.join("\n"))
      current_block = []
      in_copy_block = false
      next
    end

    # Accumulate lines in COPY block
    if in_copy_block
      current_block << line
      next
    end

    # Handle regular SQL statements
    current_block << line
    if line.end_with?(';')
      blocks << SqlBlock.new(current_block.join("\n"))
      current_block = []
    end
  end

  # Handle any remaining block
  blocks << SqlBlock.new(current_block.join("\n")) unless current_block.empty?
  blocks
end