Class: Postgres

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

Instance Method Summary collapse

Constructor Details

#initialize(dbconfig) ⇒ Postgres

Initialize Postgres instance

Parameters:

  • dbconfig (Hash)

    Database config



9
10
11
# File 'lib/pgcp/postgres.rb', line 9

def initialize(dbconfig)
  @dbconfig = dbconfig
end

Instance Method Details

#column_definitions(schema_name, table_name) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/pgcp/postgres.rb', line 137

def column_definitions(schema_name, table_name)
  with_connection do |conn|
    sql = <<-SQL.strip_heredoc
      SELECT 
        c.relname, a.attname AS column_name,
        pg_catalog.format_type(a.atttypid, a.atttypmod) as type,
        case 
          when a.attnotnull
        then 'NOT NULL' 
        else 'NULL' 
        END as not_null 
      FROM pg_class c,
       pg_attribute a,
       pg_type t,
       pg_namespace n
       WHERE c.relname = '#{table_name}'
       AND n.nspname = '#{schema_name}'
       AND a.attnum > 0
       AND a.attrelid = c.oid
       AND a.atttypid = t.oid
       AND c.relnamespace = n.oid
     ORDER BY a.attnum
    SQL

    rs = conn.exec sql

    rs.values.map do |col|
      {name: col[1], type: col[2], null: col[3]}
    end
  end
end

#copy_from_file(schema_name, table_name, csv_file, options = {}) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/pgcp/postgres.rb', line 122

def copy_from_file(schema_name, table_name, csv_file, options={})
  with_connection do |conn|
    schema_name = conn.escape_string(schema_name)
    table_name = conn.escape_string(table_name)

    conn.copy_data "COPY #{schema_name}.#{table_name} FROM STDIN CSV #{options[:header]?'HEADER':''}" do
      buf = ''
      while csv_file.read(256, buf)
        conn.put_copy_data(buf)
      end
    end

  end
end

#create_indexes(schema_name, table_name, indexes) ⇒ Object



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/pgcp/postgres.rb', line 243

def create_indexes(schema_name, table_name, indexes)
  with_connection do |conn|
    indexes.each do |index|
      if index['primary']
        sql = <<-SQL.strip_heredoc
          ALTER TABLE #{schema_name}.#{table_name} ADD PRIMARY KEY (#{index['columns'][0]})
        SQL
      else
        sql = <<-SQL.strip_heredoc
        CREATE #{index['unique'] ? 'UNIQUE': ''} INDEX #{index['name']}
        ON #{schema_name}.#{table_name} (#{index['columns'].join(', ')})
        #{index['where'] ? 'WHERE ' + index['where'] : ''}
        SQL
      end

      conn.exec(sql)
    end
  end
end

#create_table(schema_name, table_name, columns, options = {}) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/pgcp/postgres.rb', line 52

def create_table(schema_name, table_name, columns, options={})
  with_connection do |conn|
    if options[:temporary]
      table_name = conn.escape_string(table_name)
      create_sql = create_table_statement(conn, columns,
                                          table_name,
                                          options)
      conn.transaction do
        conn.exec create_sql
        conn.exec "DROP TABLE IF EXISTS #{table_name}"
      end

      true
    else
      unless _table_exists?(conn, schema_name, table_name)
        create_sql = create_table_statement(conn, columns,
                                            "#{schema_name}.#{table_name}",
                                            options)
        conn.exec create_sql

        true
      end

      false
    end
  end
end

#create_table_from_query(query, schema_name, table_name, columns, options = {}) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/pgcp/postgres.rb', line 80

def create_table_from_query(query, schema_name, table_name, columns, options={})
  with_connection do |conn|
    create_sql = create_table_statement(conn, columns,
                                        "#{schema_name}.#{table_name}",
                                        options)
    conn.transaction do
      conn.exec "DROP TABLE IF EXISTS #{schema_name}.#{table_name}"
      conn.exec create_sql
      conn.exec "INSERT INTO #{schema_name}.#{table_name}\n#{query}"
    end
  end
end

#drop_table(schema_name, table_name) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/pgcp/postgres.rb', line 38

def drop_table(schema_name, table_name)
  with_connection do |conn|
    if _table_exists?(conn, schema_name, table_name)
      fq_table_name = conn.escape_string("#{schema_name}.#{table_name}")

      sql = <<-SQL.strip_heredoc
        DROP TABLE #{fq_table_name}
      SQL

      conn.exec sql
    end
  end
end

#exec(sql, val = []) ⇒ Object



13
14
15
16
17
18
# File 'lib/pgcp/postgres.rb', line 13

def exec(sql, val=[])
  with_connection do |conn|
    conn.exec sql, val

  end
end

#get_create_table_statement(src_schema_name, src_table_name, dest_schema_name = nil, dest_table_name = nil) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/pgcp/postgres.rb', line 263

def get_create_table_statement(src_schema_name, src_table_name, dest_schema_name=nil, dest_table_name=nil)
  dest_schema_name ||= src_schema_name
  dest_table_name ||= dest_schema_name

  columns = column_definitions(src_schema_name, src_table_name)

  statement = "CREATE TABLE #{dest_schema_name}.#{dest_table_name} (\n"
  columns.each_with_index do |col, index|
    statement << "  #{col[:name]}  #{col[:type]}  #{col[:null]}"
    statement << ',' if index != columns.size - 1
    statement << "\n"
  end
  statement << ");\n"

  statement
end

#get_indexes(schema_name, table_name) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/pgcp/postgres.rb', line 192

def get_indexes(schema_name, table_name)
  idx_names = self.index_names(schema_name, table_name)

  with_connection do |conn|
    idx_names.map do |name|
      index_info = index_info(conn, name, schema_name)
      index_info['name'] = name
      index_info['columns'] = index_column_names conn, index_info['oid']

      index_info
    end
  end
end

#hotswap_table(schema_name, src_table_name, dst_table_name) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/pgcp/postgres.rb', line 93

def hotswap_table(schema_name, src_table_name, dst_table_name)
  with_connection do |conn|
    conn.transaction do
      schema_name = conn.escape_string(schema_name)
      dst_table_name = conn.escape_string(dst_table_name)
      conn.exec "DROP TABLE #{schema_name}.#{dst_table_name}" if _table_exists?(conn, schema_name, dst_table_name)
      conn.exec "ALTER TABLE #{schema_name}.#{src_table_name} RENAME TO #{dst_table_name}"
      #conn.exec "TRUNCATE TABLE #{schema_name}.#{dst_table_name}" if _table_exists?(conn, schema_name, dst_table_name)
      #conn.exec "INSERT INTO #{schema_name}.#{dst_table_name}\n(SELECT * FROM #{schema_name}.#{src_table_name})"
      #conn.exec "DROP TABLE #{schema_name}.#{src_table_name}"
    end

  end
end

#index_column_names(conn, oid) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/pgcp/postgres.rb', line 230

def index_column_names conn, oid
  sql = <<-SQL.strip_heredoc
  SELECT
       pg_catalog.pg_get_indexdef(A.attrelid, A.attnum, TRUE) AS "column_name"
  FROM pg_catalog.pg_attribute A
  WHERE A.attrelid = $1
    AND A.attnum > 0
    AND NOT A.attisdropped
  ORDER BY A.attnum;
  SQL
  conn.exec(sql, [oid]).map { |row| row['column_name'] }
end

#index_info(conn, index_name, schema_name) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/pgcp/postgres.rb', line 206

def index_info(conn, index_name, schema_name)
  sql = <<-SQL.strip_heredoc
  SELECT
      C.oid,
      I.indisunique AS "unique",
      I.indisprimary AS "primary",
      pg_get_expr(I.indpred, I.indrelid) AS "where"
  FROM pg_catalog.pg_class C,
       pg_catalog.pg_namespace N,
       pg_catalog.pg_index I
  WHERE C.relname = '#{index_name}'
    AND C.relnamespace = N.oid
    AND I.indexrelid = C.oid
    AND N.nspname = '#{schema_name}';
  SQL

  rs = conn.exec sql
  rs[0].tap do |info|
    info['unique'] = info['unique'] != 'f'
    info['primary'] = info['primary'] != 'f'
    info['where'] = info['where'][1..-2] if info['where'].present?
  end
end

#index_names(schema_name, table_name) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/pgcp/postgres.rb', line 169

def index_names(schema_name, table_name)
  with_connection do |conn|
    sql = <<-SQL.strip_heredoc
      SELECT
          C.relname AS "index_name"
      FROM pg_catalog.pg_class C,
           pg_catalog.pg_namespace N,
           pg_catalog.pg_index I,
           pg_catalog.pg_class C2
      WHERE C.relkind IN ( 'i', '' )
        AND N.oid = C.relnamespace
        AND N.nspname = '#{schema_name}'
        AND I.indexrelid = C.oid
        AND C2.oid = I.indrelid
        AND C2.relname = '#{table_name}';
    SQL

    rs = conn.exec sql

    rs.values.map(&:first)
  end
end

#list_tables(schema_name) ⇒ Object



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

def list_tables(schema_name)
  with_connection do |conn|
    sql = <<-SQL.strip_heredoc
      SELECT table_name
      FROM information_schema.tables
      WHERE table_type = 'BASE TABLE'
        AND table_schema NOT IN ('pg_catalog', 'information_schema')
        AND table_schema = '#{schema_name}'
      ORDER BY 1
    SQL

    rs = conn.exec sql

    rs.values.map(&:first)
  end

end

#schema_namesObject



108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/pgcp/postgres.rb', line 108

def schema_names
  with_connection do |conn|
    sql = <<-SQL.strip_heredoc
    SELECT schema_name
    FROM information_schema.schemata
    WHERE schema_name <> 'information_schema'
    AND schema_name NOT LIKE 'pg_%'
    SQL

    rs = conn.exec sql
    rs.values.map(&:first)
  end
end

#table_exist?(schema_name, table_name) ⇒ Boolean

Returns:

  • (Boolean)


280
281
282
283
284
# File 'lib/pgcp/postgres.rb', line 280

def table_exist?(schema_name, table_name)
  with_connection do |conn|
    _table_exists?(conn, schema_name, table_name)
  end
end