Sha256: 754bc3c1b9dd2ad3855a18a6fee60ca952267b9cd8688435214e4e347e24cb32

Contents?: true

Size: 1.46 KB

Versions: 2

Compression:

Stored size: 1.46 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
            if ENV['SHIBA_DEBUG']
              raise Shiba::Error.new("unknown stuff: in #{@sql}: #{@sc.rest}")
            end
            return {}
          end

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
shiba-0.9.0 lib/shiba/parsers/mysql_select_fields.rb
shiba-0.8.1 lib/shiba/parsers/mysql_select_fields.rb