Sha256: 39e41cb327cc6f011d08da85a1d3a7209c4cd5b19025a824733c55314f63e8cb

Contents?: true

Size: 1.37 KB

Versions: 5

Compression:

Stored size: 1.37 KB

Contents

require 'shiba/parsers/shiba_string_scanner'

module Shiba
  module Parsers
    class MysqlSelectFields
      def initialize(sql)
        @sql = sql
        @sc = ShibaStringScanner.new(@sql)
      end
      attr_reader :sc

      BACKTICK = "`"

      def tick_match
        sc.match_quoted_double_escape(BACKTICK)
      end

      def parse_fields
        tables = {}

        sc.scan(%r{/\*.*?\*/ select })

        while !sc.scan(/ from/i)
          sc.scan(/distinct /)

          if sc.scan(/\w+\(/)
            parens = 1
            while parens > 0
              case sc.getch
              when '('
                parens += 1
              when ')'
                parens -= 1
              end
            end
            sc.scan(/ AS /)
            tick_match
            # parse function
          elsif sc.scan(/`(.*?)`\.`(.*?)`\.`(.*?)` AS `(.*?)`/)
            db = sc[1]
            table = sc[2]
            col = sc[3]

            tables[table] ||= []
            tables[table] << col

          elsif sc.scan(/`(.*?)`\.`(.*?)` AS `(.*?)`/)
            table = sc[1]
            col = sc[2]

            tables[table] ||= []
            tables[table] << col
          elsif sc.scan(/(\d+|NULL|'.*?') AS `(.*?)`/m)
          else
            raise "unknown stuff: in #{@sql}: #{@sc.rest}"
          end

          sc.scan(/,/)
        end
        tables
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
shiba-0.6.4 lib/shiba/parsers/mysql_select_fields.rb
shiba-0.6.3 lib/shiba/parsers/mysql_select_fields.rb
shiba-0.6.2 lib/shiba/parsers/mysql_select_fields.rb
shiba-0.6.1 lib/shiba/parsers/mysql_select_fields.rb
shiba-0.6.0 lib/shiba/parsers/mysql_select_fields.rb