Sha256: f020902884dcaa20cc0338791efa347cd8d1910237c2fa9548cf4851f709c345

Contents?: true

Size: 1.18 KB

Versions: 2

Compression:

Stored size: 1.18 KB

Contents

module SQLTree::Node

  class Field < Base

    attr_accessor :name, :table

    alias :field :name
    alias :field= :name=

    def initialize(name, table = nil)
      @name = name
      @table = table
    end

    def quote_var(name)
      return '*' if name == :all
      super(name)
    end

    def to_sql
      @table.nil? ? quote_var(@name) : quote_var(@table) + '.' + quote_var(@name)
    end

    def ==(other)
      other.name == self.name && other.table == self.table
    end

    def self.parse(tokens)
      field_or_table = case tokens.next
        when SQLTree::Token::MULTIPLY then :all
        when SQLTree::Token::Variable then tokens.current.literal
        else raise SQLTree::Parser::UnexpectedToken.new(tokens.current)
      end

      if tokens.peek == SQLTree::Token::DOT
        table = field_or_table
        tokens.consume(SQLTree::Token::DOT)
        field = case tokens.next
          when SQLTree::Token::MULTIPLY then :all
          when SQLTree::Token::Variable then tokens.current.literal
          else raise SQLTree::Parser::UnexpectedToken.new(tokens.current)
        end
        self.new(field, table)
      else
        self.new(field_or_table)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
sql_tree-0.1.0 lib/sql_tree/node/field.rb
sql_tree-0.0.3 lib/sql_tree/node/field.rb