Class: Extract::Export::Table

Inherits:
Object
  • Object
show all
Includes:
FromHash
Defined in:
lib/extract/export/table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#nameObject

Returns the value of attribute name.



5
6
7
# File 'lib/extract/export/table.rb', line 5

def name
  @name
end

Instance Method Details

#colsObject



8
9
10
# File 'lib/extract/export/table.rb', line 8

def cols
  rows.map { |x| x.keys }.flatten.uniq
end

#create_table_sqlObject



21
22
23
24
25
26
# File 'lib/extract/export/table.rb', line 21

def create_table_sql
  col_str = cols.map { |x| "  #{quoted_col(x)} varchar(255)" }.join(",\n")
  "CREATE TABLE #{name} (
#{col_str}
);"
end

#insertsObject



28
29
30
31
32
33
34
35
36
37
# File 'lib/extract/export/table.rb', line 28

def inserts
  res = []
  rows.each do |row|
    col_str = row.keys.map { |x| quoted_col(x) }.join(",")
    val_str = row.values.map { |x| "'#{x}'" }.join(',')
    str = "INSERT INTO #{name} (#{col_str}) VALUES (#{val_str});"
    res << str
  end
  res
end

#quoted_col(col) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/extract/export/table.rb', line 12

def quoted_col(col)
  return col
  if col.to_s[0..0] =~ /\d/
    "\"#{col}\""
  else
    col
  end
end

#sqlObject



43
44
45
# File 'lib/extract/export/table.rb', line 43

def sql
  sql_statements.join("\n")
end

#sql_statementsObject



39
40
41
# File 'lib/extract/export/table.rb', line 39

def sql_statements
  [create_table_sql,inserts].flatten
end