Class: CartoDB::Client::Connection::PostgreSQL

Inherits:
Object
  • Object
show all
Includes:
Helpers::SqlHelper
Defined in:
lib/cartodb-rb-client/cartodb/client/connection/postgres.rb

Constant Summary collapse

DATA_TYPES_TRANSLATION_TABLE =
{
  'int4'      => 'number',
  'numeric'   => 'number',
  'text'      => 'string',
  'varchar'   => 'string',
  'date'      => 'date',
  'timestamp' => 'date',
  'bool'      => 'boolean',
  'geometry'  => 'geometry'
}

Instance Method Summary collapse

Methods included from Helpers::SqlHelper

#prepare_data

Constructor Details

#initialize(connection_settings) ⇒ PostgreSQL

Returns a new instance of PostgreSQL.



18
19
20
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 18

def initialize(connection_settings)
  @pg = connect_to_postgres(connection_settings)
end

Instance Method Details

#add_column(table_name, column_name, column_type) ⇒ Object



77
78
79
80
81
82
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 77

def add_column(table_name, column_name, column_type)
  @pg.query("    ALTER TABLE \#{table_name} ADD COLUMN \#{column_name} \#{column_type};\n  SQL\n  )\nend\n"

#change_column(table_name, old_column_name, new_column_name, column_type) ⇒ Object



91
92
93
94
95
96
97
98
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 91

def change_column(table_name, old_column_name, new_column_name, column_type)
  add_column table_name, new_column_name, column_type
  @pg.query("    UPDATE \#{table_name} SET \#{new_column_name}=cast(\#{old_column_name} as \#{column_type})\n  SQL\n  )\n  drop_column table_name, old_column_name\nend\n"

#create_table(table_name = nil, schema_or_file = nil, the_geom_type = 'Point') ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 35

def create_table(table_name = nil, schema_or_file = nil, the_geom_type = 'Point')
  schema = schema_or_file if schema_or_file && schema_or_file.is_a?(Array)
  file   = schema_or_file if schema_or_file && schema_or_file.is_a?(File)

  params = {:name => table_name}
  params[:file] = file if file

  table_name = table_name.sanitize

  if schema.nil? || schema.empty?
    schema = []
    schema << {:name => 'name',        :type => 'text'} if schema.select{|c| c[:name].eql?('name')}.empty?
    schema << {:name => 'description', :type => 'text'} if schema.select{|c| c[:name].eql?('description')}.empty?
    create_the_geom = "SELECT AddGeometryColumn('public', '#{table_name}', 'the_geom', 4326, 'POINT', 2)"
  end

  schema << {:name => 'cartodb_id',  :type => 'serial',    :extra => 'NOT NULL'}                                                                 if schema.select{|c| c[:name].eql?('cartodb_id')}.empty?
  schema << {:name => 'created_at',  :type => 'timestamp', :extra => 'without time zone DEFAULT current_timestamp::timestamp without time zone'} if schema.select{|c| c[:name].eql?('created_at')}.empty?
  schema << {:name => 'updated_at',  :type => 'timestamp', :extra => 'without time zone DEFAULT current_timestamp::timestamp without time zone'} if schema.select{|c| c[:name].eql?('updated_at')}.empty?
  if schema.any? && schema.select{|c| c[:name].downcase.match(/geo/)}.any?
    the_geom_field = schema.select{|c| c[:name].downcase.match(/geo/)}.first
    create_the_geom = "SELECT AddGeometryColumn('public', '#{table_name}', 'the_geom', 4326, '#{the_geom_field[:geometry_type].upcase}', 2)"
    schema.reject!{|c| c[:name].downcase.match(/geo/)}
  end

  @pg.query("    CREATE TABLE \#{table_name}\n    (\n      \#{schema.map{|s| \"\#{s[:name]} \#{s[:type]} \#{s[:extra]}\"}.join(', ')}\n    )\n    WITH (\n      OIDS=FALSE\n    );\n    ALTER TABLE \#{table_name} OWNER TO \#{@pg.user};\n  SQL\n  )\n\n  @pg.query(create_the_geom) if create_the_geom\n\n  table table_name\nend\n"

#delete_row(table_name, row_id) ⇒ Object



203
204
205
206
207
208
209
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 203

def delete_row(table_name, row_id)
  @pg.query("    DELETE FROM \#{table_name}\n    WHERE cartodb_id = \#{row_id}\n  SQL\n  )\nend\n"

#drop_column(table_name, column_name) ⇒ Object



84
85
86
87
88
89
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 84

def drop_column(table_name, column_name)
  @pg.query("    ALTER TABLE \#{table_name} DROP COLUMN \#{column_name};\n  SQL\n  )\nend\n"

#drop_table(table_name) ⇒ Object



151
152
153
154
155
156
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 151

def drop_table(table_name)
  @pg.query("    DROP TABLE \#{table_name}\n  SQL\n  )\nend\n"

#insert_row(table_name, row) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 169

def insert_row(table_name, row)
  row = prepare_data(row)

  results = query("    INSERT INTO \#{table_name}\n    (\#{row.keys.join(',')})\n    VALUES (\#{row.values.join(',')});\n\n    SELECT \#{table_name}.cartodb_id as id, \#{table_name}.*\n    FROM \#{table_name}\n    WHERE cartodb_id = currval('public.\#{table_name}_cartodb_id_seq');\n  SQL\n  )\n\n  results.rows.first\nend\n"

#query(sql, options = {}) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 223

def query(sql, options = {})
  sql = sql.strip if sql

  if sql.include?('*')
    table_name = sql.match(/select(.*)\s((\w+\.)?\*)(.*)from\s+(\w*)[^;]*;?/im)[5]
    schema = table(table_name).schema if table_name

    sql.gsub!(/^select(.*)\s((\w+\.)?\*)(.*)from/im) do |matches|
      %Q{SELECT #{$1.strip} #{schema.map{|c| "#{$3}#{c[0]}"}.join(', ')} #{$4.strip} FROM}
    end
  end

  crono = Time.now
  begin
    result = @pg.query("      \#{sql}\n    SQL\n    )\n  rescue PGError => e\n    raise CartoDB::Client::Error.new(nil, nil, nil, e.message)\n  end\n\n  CartoDB::Types::Metadata.from_hash({\n    :time => Time.now - crono,\n    :total_rows => result.cmd_tuples,\n    :rows       => result.map{|row| CartoDB::Types::Metadata.from_hash(row)}\n  })\nend\n"

#records(table_name, options = {}) ⇒ Object



211
212
213
214
215
216
217
218
219
220
221
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 211

def records(table_name, options = {})
  sql = "    SELECT \#{table_name}.cartodb_id AS id, \#{table_name}.*\n    FROM \#{table_name}\n  SQL\n\n  results = query(sql, options)\n\n  results[:name] = table_name\n  results\nend\n"

#row(table_name, row_id) ⇒ Object



158
159
160
161
162
163
164
165
166
167
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 158

def row(table_name, row_id)
  results = query("    SELECT \#{table_name}.cartodb_id as id, \#{table_name}.*\n    FROM \#{table_name}\n    WHERE cartodb_id = \#{row_id};\n  SQL\n  )\n\n  results.rows.first\nend\n"

#table(table_name) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 121

def table(table_name)
  pg_result = @pg.query("    SELECT columns.table_name, columns.column_name, columns.udt_name as data_type, geo_cols.type as geometry_type\n    FROM information_schema.tables tables\n    INNER JOIN information_schema.columns columns ON columns.table_name = tables.table_name\n    LEFT OUTER JOIN public.geometry_columns geo_cols ON geo_cols.f_table_schema = columns.table_schema AND geo_cols.f_table_name = columns.table_name AND geo_cols.f_geometry_column = columns.column_name\n    WHERE tables.table_schema = 'public' AND tables.table_name not IN ('spatial_ref_sys', 'geometry_columns', 'geography_columns') AND tables.table_name ilike '\#{table_name}'\n  SQL\n  )\n\n  if pg_result.to_a.empty?\n    non_existing_table = @pg.query(<<-SQL\n      SELECT tables.table_name\n      FROM information_schema.tables tables\n      WHERE tables.table_schema = 'public' AND tables.table_name not IN ('spatial_ref_sys', 'geometry_columns', 'geography_columns') AND tables.table_name ilike '\#{table_name}'\n    SQL\n    )\n    raise CartoDB::Client::Error.new if non_existing_table.to_a.empty?\n  end\n\n  table_result = nil\n  pg_result.each do |column|\n    table_result = CartoDB::Types::Metadata.from_hash({:name => column['table_name'], :schema => []}) unless table_result\n    table_result.schema << %W(\#{column['column_name']} \#{CartoDB::Client::Connection::PostgreSQL::DATA_TYPES_TRANSLATION_TABLE[column['data_type']]})\n    table_result.schema.last << CartoDB::Client::Connection::PostgreSQL::DATA_TYPES_TRANSLATION_TABLE[column['data_type']]  if column['geometry_type']\n    table_result.schema.last << column['geometry_type'].downcase if column['geometry_type']\n  end\n  table_result\nend\n"

#tablesObject



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 100

def tables
  pg_result = @pg.query("    SELECT columns.table_name, columns.column_name, columns.udt_name as data_type\n    FROM information_schema.tables tables\n    INNER JOIN information_schema.columns columns ON columns.table_name = tables.table_name\n    WHERE tables.table_schema = 'public' AND tables.table_name not IN ('spatial_ref_sys', 'geometry_columns', 'geography_columns')\n  SQL\n  )\n\n  result = CartoDB::Types::Metadata.new\n  tables = {}\n  pg_result.each do |column|\n    tables[column['table_name']] = CartoDB::Types::Metadata.from_hash({:name => column['table_name'], :schema => []}) unless tables[column['table_name']]\n    tables[column['table_name']].schema << %W(\#{column['column_name']} \#{CartoDB::Client::Connection::PostgreSQL::DATA_TYPES_TRANSLATION_TABLE[column['data_type']]})\n  end\n\n  result.total_entries = tables.to_a.length\n  result.tables = tables.to_a.map(&:last)\n  result\nend\n"

#update_row(table_name, row_id, row) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/cartodb-rb-client/cartodb/client/connection/postgres.rb', line 186

def update_row(table_name, row_id, row)
  row = prepare_data(row)

  results = query("    UPDATE \#{table_name}\n    SET (\#{row.keys.join(',')})\n    = (\#{row.values.join(',')})\n    WHERE cartodb_id = \#{row_id};\n    SELECT \#{table_name}.cartodb_id as id, \#{table_name}.*\n    FROM \#{table_name}\n    WHERE cartodb_id = currval('public.\#{table_name}_cartodb_id_seq');\n  SQL\n  )\n\n  results.rows.first\nend\n"