Class: GData::Client::FusionTables

Inherits:
Base
  • Object
show all
Defined in:
lib/fusion_tables/data/data.rb,
lib/fusion_tables/data/table.rb,
lib/fusion_tables/ext/fusion_tables.rb,
lib/fusion_tables/client/fusion_tables.rb

Defined Under Namespace

Classes: Data, Table

Constant Summary collapse

SERVICE_URL =
"https://www.googleapis.com/fusiontables/v1/query"
DATATYPES =
%w(number string location datetime)

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ FusionTables

Returns a new instance of FusionTables.



23
24
25
26
27
# File 'lib/fusion_tables/client/fusion_tables.rb', line 23

def initialize(options = {})
  options[:clientlogin_service] ||= 'fusiontables'
  options[:headers] = { 'Content-Type' => 'application/x-www-form-urlencoded'}
  super(options)
end

Instance Method Details

#auth_handler=(handler) ⇒ Object

Overrides auth_handler= so if the authentication changes, the session cookie is cleared.



48
49
50
51
# File 'lib/fusion_tables/client/fusion_tables.rb', line 48

def auth_handler=(handler)
  @session_cookie = nil
  return super(handler)
end

#create_table(table_name, columns) ⇒ Object

Create a new table. Return the corresponding table

Columns specified as [=> ‘my_col_name’, :type => ‘my_type’]

Type must be one of:

  • number

  • string

  • location

  • datetime



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/fusion_tables/ext/fusion_tables.rb', line 65

def create_table(table_name, columns)

  # Sanity check name
  table_name = table_name.strip.gsub(/ /,'_')

  # ensure all column types are valid
  columns.each do |col|
    col[:name] = col[:name].to_s
    col[:type] = col[:type].to_s

    if !DATATYPES.include? col[:type].downcase
      raise ArgumentError, "Ensure input types are: 'number', 'string', 'location' or 'datetime'"
    end
  end

  # generate sql
  fields = columns.map{ |col| "'#{col[:name]}': #{col[:type].upcase}" }.join(", ")
  sql = "CREATE TABLE #{table_name} (#{fields})"

  # create table
  resp = self.sql_post(sql)
  raise "unknown column type" if resp.body == "Unknown column type."

  # construct table object and return
  json_resp = JSON.parse(resp.body)
  table_id = json_resp['rows'][0][0]
  table = GData::Client::FusionTables::Table.new(self, :table_id => table_id, :name => table_name)
  table.get_headers
  table
end

#drop(options) ⇒ Object

Drops Fusion Tables

options can be:

  • an integer for single drop

  • array of integers for multi drop

  • a regex against table_name for flexible multi_drop



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/fusion_tables/ext/fusion_tables.rb', line 104

def drop(options)
  # collect ids
  ids = []
  ids << options  if options.class == Integer || options.class == String || Fixnum
  ids =  options  if options.class == Array

  if options.class == Regexp
    tables = show_tables
    ids = tables.map { |table| table.id if options =~ table.name }.compact
  end

  # drop tables
  delete_count = 0
  ids.each do |id|
    resp = self.sql_post("DROP TABLE #{id}")
    delete_count += 1 if resp.status_code == 200
  end
  delete_count
end

#execute(sql) ⇒ Object

Helper method to run FT SQL and return FT data object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/fusion_tables/ext/fusion_tables.rb', line 20

def execute(sql)
  http_req = sql.upcase.match(/^(DESCRIBE|SHOW|SELECT)/) ? :sql_get : :sql_post
  json_resp = JSON.parse(self.send(http_req, sql).body)
  
  # probably a much cleaner way to do this
  rows = json_resp['rows']
  columns = json_resp['columns']
  correlated = []
  (0...rows.length).each do|row|
    h = {}
    (0...columns.length).each do|column|
      h[columns[column].gsub(/\s+/, "_").downcase.to_sym] = rows[row][column]
    end
    correlated << h
  end
  # puts correlated.inspect

  correlated
end

#make_request(method, url, body = '', retries = 10) ⇒ Object

Overrides make_request to handle 500 redirects with a session cookie.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/fusion_tables/client/fusion_tables.rb', line 54

def make_request(method, url, body = '', retries = 10)
  begin
    response = super(method, url, body)
  rescue GData::Client::ServerError => e
    if e.response.status_code == 500 and retries > 0
      sleep_time = 11 - retries 
      sleep sleep_time # <= Fusion tables has rate of 5 calls per second. Be nice, get longer
      @session_cookie = e.response.headers['set-cookie']          
      return self.make_request(method, url, body, retries - 1)
    else
      return e.response
    end  
  end  
end

#prepare_headersObject

Custom prepare_headers to include the session cookie if it exists



70
71
72
73
74
75
# File 'lib/fusion_tables/client/fusion_tables.rb', line 70

def prepare_headers
  if @session_cookie
    @headers['cookie'] = @session_cookie
  end
  super
end

#set_api_key(api_key) ⇒ Object



40
41
42
# File 'lib/fusion_tables/ext/fusion_tables.rb', line 40

def set_api_key(api_key)
  @api_key = api_key
end

#show_tablesObject

Show a list of fusion tables



45
46
47
48
49
50
51
52
# File 'lib/fusion_tables/ext/fusion_tables.rb', line 45

def show_tables
  data = self.execute "SHOW TABLES"

  data.inject([]) do |x, row|
    x << GData::Client::FusionTables::Table.new(self, row)
    x
  end
end

#sql_encode(sql) ⇒ Object



29
30
31
32
# File 'lib/fusion_tables/client/fusion_tables.rb', line 29

def sql_encode(sql)
  # puts sql
  "sql=" + CGI::escape(sql)
end

#sql_get(sql) ⇒ Object



34
35
36
# File 'lib/fusion_tables/client/fusion_tables.rb', line 34

def sql_get(sql)
  resp = self.get(SERVICE_URL + "?" + sql_encode(sql) + "&key=#{@api_key}")
end

#sql_post(sql) ⇒ Object



38
39
40
# File 'lib/fusion_tables/client/fusion_tables.rb', line 38

def sql_post(sql)
  resp = self.post(SERVICE_URL, sql_encode(sql) + "&key=#{@api_key}")
end

#sql_put(sql) ⇒ Object



42
43
44
# File 'lib/fusion_tables/client/fusion_tables.rb', line 42

def sql_put(sql)
  resp = self.put(SERVICE_URL, sql_encode(sql) + "&key=#{@api_key}")
end