Module: PostgresHelper

Defined in:
lib/db/postgres.rb

Class Method Summary collapse

Class Method Details

.connect_to_postgres(config) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/db/postgres.rb', line 8

def connect_to_postgres(config)
  conn = PG.connect(
    host: config[:host],
    port: config[:port],
    dbname: config[:database],
    user: config[:username],
    password: config[:password],
    sslmode: config[:sslmode] || 'prefer',
    gssencmode: 'disable',  # Disable GSSAPI encryption
    krbsrvname: nil,        # Disable Kerberos service name
    target_session_attrs: 'read-write'
  )
  conn
end

.disconnect_from_postgres(client) ⇒ Object



23
24
25
# File 'lib/db/postgres.rb', line 23

def disconnect_from_postgres(client)
  client.close if client.respond_to?(:close)
end

.format_postgres_config(connection_string) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/db/postgres.rb', line 157

def format_postgres_config(connection_string)
  parsed = URI.parse(connection_string)
  
  {
    host: parsed.host,
    port: parsed.port || 5432,
    database: parsed.path[1..-1],
    username: parsed.user || 'postgres',
    password: parsed.password || '',
    sslmode: parsed.query&.split('&')&.find { |param| param.start_with?('sslmode=') }&.split('=')&.last || 'prefer'
  }
end

.get_columns_by_table_postgres(client, schema_name, table_name) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/db/postgres.rb', line 76

def get_columns_by_table_postgres(client, schema_name, table_name)
  sql = <<~SQL
    SELECT column_name 
    FROM information_schema.columns 
    WHERE table_schema = '#{schema_name}' 
    AND table_name = '#{table_name}'
    ORDER BY ordinal_position
  SQL
  
  results = run_query_postgres(sql, client)
  results[:rows].map { |row| row['column_name'] }
end

.get_foreign_keys_postgres(client, schema_name, table_name, primary_key) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/db/postgres.rb', line 89

def get_foreign_keys_postgres(client, schema_name, table_name, primary_key)
  depluralized_table_name = table_name.singularize
  
  sql = <<~SQL
    SELECT column_name 
    FROM information_schema.columns 
    WHERE table_schema = '#{schema_name}' 
    AND table_name != '#{table_name}' 
    AND (column_name = '#{primary_key}' 
      OR column_name = '#{depluralized_table_name}_#{primary_key}' 
      OR column_name = '#{depluralized_table_name}#{primary_key.capitalize}')
  SQL

  results = run_query_postgres(sql, client)
  foreign_keys = results[:rows].map { |key| key['column_name'] }
  
  foreign_keys = foreign_keys.reject { |key| ['id', '_id_'].include?(key) }
  foreign_keys = foreign_keys.uniq

  if foreign_keys.empty?
    sql = <<~SQL
      SELECT column_name 
      FROM information_schema.columns 
      WHERE table_schema = '#{schema_name}' 
      AND table_name != '#{table_name}' 
      AND (column_name LIKE '#{table_name}%' 
        OR column_name LIKE '%\\_id' 
        OR column_name LIKE '%Id' 
        OR column_name LIKE '%\\_#{primary_key}' 
        OR column_name LIKE '%#{primary_key.capitalize}')
    SQL

    results = run_query_postgres(sql, client)
    foreign_keys = results[:rows].map { |key| key['column_name'] }.uniq
  end

  foreign_keys
end

.get_schema_column_info_postgres(client, schema_name, table_names) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/db/postgres.rb', line 128

def get_schema_column_info_postgres(client, schema_name, table_names)
  table_names.map do |table_name|
    query = <<~SQL
      SELECT 
        column_name,
        udt_name as field_type,
        ordinal_position as sort_number
      FROM information_schema.columns
      WHERE table_schema = '#{table_name[:schemaName]}'
      AND table_name = '#{table_name[:tableName]}'
      ORDER BY sort_number
    SQL

    results = run_query_postgres(query, client)
    {
      tableName: "#{table_name[:schemaName]}.#{table_name[:tableName]}",
      displayName: "#{table_name[:schemaName]}.#{table_name[:tableName]}",
      columns: results[:rows].map do |row|
        {
          columnName: row['column_name'],
          displayName: row['column_name'],
          dataTypeID: get_pg_type_oid(row['field_type']),
          fieldType: row['field_type']
        }
      end
    }
  end
end

.get_schemas_postgres(client) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/db/postgres.rb', line 43

def get_schemas_postgres(client)
  sql = <<~SQL
    SELECT schema_name 
    FROM information_schema.schemata 
    WHERE schema_name NOT LIKE 'pg_%' 
    AND schema_name != 'information_schema'
  SQL
  
  results = run_query_postgres(sql, client)
  results[:rows].map { |row| row['schema_name'] }
end

.get_tables_by_schema_postgres(client, schema_names) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/db/postgres.rb', line 55

def get_tables_by_schema_postgres(client, schema_names)
  all_tables = schema_names.flat_map do |schema|
    sql = <<~SQL
      SELECT table_name, table_schema 
      FROM information_schema.tables 
      WHERE table_schema = '#{schema}'
      AND table_type = 'BASE TABLE'
    SQL
    
    results = run_query_postgres(sql, client)
    results[:rows].map do |row|
      {
        tableName: row['table_name'],
        schemaName: row['table_schema']
      }
    end
  end

  all_tables
end

.run_query_postgres(sql, client) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/db/postgres.rb', line 27

def run_query_postgres(sql, client)
  result = client.exec(sql)
  
  fields = result.fields.map do |field|
    {
      name: field,
      dataTypeID: result.ftype(result.fields.index(field))
    }
  end

  {
    fields: fields,
    rows: result.values.map { |row| result.fields.zip(row).to_h }
  }
end