Class: CSQL::SQL

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

Instance Method Summary collapse

Constructor Details

#initialize(filepath) ⇒ SQL

Returns a new instance of SQL.



8
9
10
11
# File 'lib/csql.rb', line 8

def initialize(filepath)
  @parser = SQLParser::Parser.new
  @filepath = filepath
end

Instance Method Details

#execute(query) ⇒ Object



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
# File 'lib/csql.rb', line 13

def execute query
  begin
    modified_query = query.gsub(/csv/, @filepath)
    result,err,process = Open3.capture3("q -H -d \',\' \'#{modified_query}\'")
    if err != ""
      raise CSQLException.new(err)
    end
  end
  ast = @parser.scan_str(query)
  column = ast.query_expression.list.to_sql
  columns = nil
  if column == "*"
    columns = File.open(@filepath,'r').gets.chomp.split(',').map{|c|c.strip}
  else
    columns = column.chomp.split(',').map{|c|c.gsub('`','').split(/as|AS/).last.strip}
  end
  return result.chomp.split("\n").map{|r|
    data = r.split(",")
    hash = Hash.new
    data.size.times do |i|
      hash[columns[i]] = data[i]
    end
    hash
  }
end