Module: PostgresHelper
- Defined in:
- lib/db/postgres.rb
Class Method Summary collapse
- .connect_to_postgres(config) ⇒ Object
- .disconnect_from_postgres(pool) ⇒ Object
- .format_postgres_config(connection_string) ⇒ Object
- .get_columns_by_table_postgres(client, schema_name, table_name) ⇒ Object
- .get_foreign_keys_postgres(client, schema_name, table_name, primary_key) ⇒ Object
- .get_schema_column_info_postgres(client, schema_name, table_names) ⇒ Object
- .get_schemas_postgres(client) ⇒ Object
- .get_tables_by_schema_postgres(client, schema_names) ⇒ Object
- .run_query_postgres(sql, pool) ⇒ Object
Class Method Details
.connect_to_postgres(config) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/db/postgres.rb', line 9 def connect_to_postgres(config) # Create a connection pool that matches Puma's thread count ConnectionPool.new(size: 5, timeout: 5) do 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' ) end end |
.disconnect_from_postgres(pool) ⇒ Object
26 27 28 29 30 31 |
# File 'lib/db/postgres.rb', line 26 def disconnect_from_postgres(pool) return unless pool.respond_to?(:shutdown) pool.shutdown { |conn| conn.close if conn.respond_to?(:close) } rescue PG::Error => e puts "Error closing connection pool: #{e.}" end |
.format_postgres_config(connection_string) ⇒ Object
191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/db/postgres.rb', line 191 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
110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/db/postgres.rb', line 110 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
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 150 151 152 153 154 155 156 157 158 159 160 |
# File 'lib/db/postgres.rb', line 123 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
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
# File 'lib/db/postgres.rb', line 162 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
77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/db/postgres.rb', line 77 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
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
# File 'lib/db/postgres.rb', line 89 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, pool) ⇒ Object
33 34 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/db/postgres.rb', line 33 def run_query_postgres(sql, pool) pool.with do |client| result = client.exec(sql) fields = result.fields.map do |field| { name: field, dataTypeID: result.ftype(result.fields.index(field)) } end rows = result.values.map do |row| result.fields.zip(row).map do |field_name, value| # First convert all values to strings string_value = value.to_s # Then try to parse JSON if it looks like JSON parsed_value = begin if string_value.start_with?('[') || string_value.start_with?('{') json_value = JSON.parse(string_value) if json_value.is_a?(Array) json_value.map(&:to_s) else json_value end else string_value end rescue JSON::ParserError string_value end [field_name, parsed_value] end.to_h end { fields: fields, rows: rows } ensure result&.clear if result.respond_to?(:clear) end end |