Sha256: 2ec87f11b159afacf63c45ac23b223ca73bada9557839f8e3e1c7187d4c1aa85

Contents?: true

Size: 1.6 KB

Versions: 1

Compression:

Stored size: 1.6 KB

Contents

module SQLTree::Node

  class InsertQuery < Base

    attr_accessor :table, :fields, :values

    def initialize(table, fields = nil, values = [])
      @table, @fields, @values  = table, fields, values
    end

    def to_sql
      sql = "INSERT INTO #{self.quote_var(table)} "
      sql << '(' + fields.map { |f| f.to_sql }.join(', ') + ') ' if fields
      sql << 'VALUES (' + values.map { |v| v.to_sql }.join(', ') + ')'
      sql
    end
    
    def self.parse_field_list(tokens)
      tokens.consume(SQLTree::Token::LPAREN)
      fields = [SQLTree::Node::Variable.parse(tokens)]
      while tokens.peek == SQLTree::Token::COMMA
        tokens.consume(SQLTree::Token::COMMA)
        fields << SQLTree::Node::Variable.parse(tokens)
      end
      tokens.consume(SQLTree::Token::RPAREN)
      return fields
    end
    
    def self.parse_value_list(tokens)
      tokens.consume(SQLTree::Token::VALUES)
      tokens.consume(SQLTree::Token::LPAREN)
      values = [SQLTree::Node::Expression.parse(tokens)]
      while tokens.peek == SQLTree::Token::COMMA
        tokens.consume(SQLTree::Token::COMMA)
        values << SQLTree::Node::Expression.parse(tokens)
      end
      tokens.consume(SQLTree::Token::RPAREN)
      return values
    end
    
    def self.parse(tokens)
      tokens.consume(SQLTree::Token::INSERT)
      tokens.consume(SQLTree::Token::INTO)
      insert_query = self.new(SQLTree::Node::Variable.parse(tokens).name)

      insert_query.fields = self.parse_field_list(tokens) if tokens.peek == SQLTree::Token::LPAREN
      insert_query.values = self.parse_value_list(tokens)
      return insert_query
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
sql_tree-0.1.0 lib/sql_tree/node/insert_query.rb