Class: ActiveRecord::ConnectionAdapters::PostgreSQLAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/core_ext/active_record/connection_adapters/postgresql_adapter.rb

Overview

Patched version: 3.1.3

Patched methods
  • indexes

Constant Summary collapse

INDEX_COLUMN_EXPRESSION =

Regex to find columns used in index statements

/ON [\w\.]+(?: USING \w+ )?\((.+)\)/
INDEX_WHERE_EXPRESSION =

Regex to find where clause in index statements

/WHERE (.+)$/
INDOPTION_DESC =
1
INDOPTION_NULLS_FIRST =

NULLs are first instead of last

2

Instance Method Summary collapse

Instance Method Details

#find_column_names(table_name, index) ⇒ Array

Find column names from index attributes. If the columns are virtual (i.e. this is an expression index) then it will try to return the functions that represent each column.

Parameters:

  • table_name (String)

    the name of the table, possibly schema-qualified

  • index (Hash)

    index attributes

Returns:

  • (Array)


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
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/core_ext/active_record/connection_adapters/postgresql_adapter.rb', line 140

def find_column_names(table_name, index)
  columns = Hash[query("    SELECT a.attnum, a.attname\n    FROM pg_attribute a\n    WHERE a.attrelid = \#{index[:id]}\n    AND a.attnum IN (\#{index[:keys].join(\",\")})\n  SQL\n\n  column_names = columns.values_at(*index[:keys]).compact\n\n  if column_names.empty?\n    definition = index[:definition].sub(INDEX_WHERE_EXPRESSION, '')\n    if column_expression = definition.match(INDEX_COLUMN_EXPRESSION)[1]\n      column_names = split_expression(column_expression).map do |functional_name|\n        remove_type(functional_name)\n      end\n    end\n  else\n    # In case if column_names if not empty it contains list of column name taken from pg_attribute table.\n    # So we need to check indoption column and add DESC and NULLS LAST based on its value.\n    # https://stackoverflow.com/questions/18121103/how-to-get-the-index-column-orderasc-desc-nulls-first-from-postgresql/18128457#18128457\n    column_names = column_names.map.with_index do |column_name, column_index|\n      option = index[:options][column_index]\n\n      if option != 0\n        column_name << \" DESC\" if option & INDOPTION_DESC > 0\n\n        if option & INDOPTION_NULLS_FIRST > 0\n          column_name << \" NULLS FIRST\"\n        else\n          column_name << \" NULLS LAST\"\n        end\n      end\n\n      column_name\n    end\n  end\n\n  column_names\nend\n", "Columns for index #{index[:name]} on #{table_name}")]

#find_lengths(index) ⇒ Array

Find length of index TODO Update lengths once we merge in ActiveRecord code that supports it. -dresselm 20120305

Parameters:

  • index (Hash)

    index attributes

Returns:

  • (Array)


244
245
246
# File 'lib/core_ext/active_record/connection_adapters/postgresql_adapter.rb', line 244

def find_lengths(index)
  []
end

#find_operator_names(column_names, index) ⇒ Hash

Find non-default operator class names for columns from index.

Parameters:

  • column_names (Array)

    List of columns from index.

  • index (Hash)

    index index attributes

Returns:

  • (Hash)


186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/core_ext/active_record/connection_adapters/postgresql_adapter.rb', line 186

def find_operator_names(column_names, index)
  column_names.each_with_index.inject({}) do |class_names, (column_name, column_index)|
    result = query("      SELECT op.opcname, op.opcdefault\n      FROM pg_opclass op\n      WHERE op.oid = \#{index[:operators][column_index]};\n    SQL\n\n    row = result.first\n\n    if row && row[1] == \"f\"\n      class_names[column_name] = row[0]\n    end\n\n    class_names\n  end\nend\n", "Classes for columns for index #{index[:name]} for column #{column_name}")

#find_where_statement(index) ⇒ String

Find where statement from index definition

Parameters:

  • index (Hash)

    index attributes

Returns:

  • (String)

    where statement



235
236
237
# File 'lib/core_ext/active_record/connection_adapters/postgresql_adapter.rb', line 235

def find_where_statement(index)
  index[:definition].scan(INDEX_WHERE_EXPRESSION).flatten[0]
end

#index_name_exists?(table_name, index_name, default) ⇒ Boolean

Checks if index exists for given table.

Patch:

Search using provided schema if table_name includes schema name.

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/core_ext/active_record/connection_adapters/postgresql_adapter.rb', line 38

def index_name_exists?(table_name, index_name, default)
  postgre_sql_name = PostgreSQL::Utils.extract_schema_qualified_name(table_name)
  schema, table = postgre_sql_name.schema, postgre_sql_name.identifier
  schemas = schema ? "ARRAY['#{schema}']" : 'current_schemas(false)'

  exec_query("    SELECT COUNT(*)\n    FROM pg_class t\n    INNER JOIN pg_index d ON t.oid = d.indrelid\n    INNER JOIN pg_class i ON d.indexrelid = i.oid\n    WHERE i.relkind = 'i'\n      AND i.relname = '\#{index_name}'\n      AND t.relname = '\#{table}'\n      AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (\#{schemas}) )\n  SQL\nend\n", 'SCHEMA').rows.first[0].to_i > 0

#indexes(table_name, name = nil) ⇒ Object

Returns an array of indexes for the given table.

Patch 1 reason:

Since SchemaDumper#tables is patched to process tables with a schema prefix, the #indexes method receives table_name as “<schema>.<table>”. This patch allows it to handle table names with a schema prefix.

Patch 1:

Search using provided schema if table_name includes schema name.

Patch 2 reason:

#indexes is patched to support partial indexes using :where clause.

Patch 2:

Search the postgres indexdef for the where clause and pass the output to the custom PgSaurus::ConnectionAdapters::IndexDefinition



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
127
128
129
130
131
# File 'lib/core_ext/active_record/connection_adapters/postgresql_adapter.rb', line 74

def indexes(table_name, name = nil)
  postgre_sql_name = PostgreSQL::Utils.extract_schema_qualified_name(table_name)
  schema, table = postgre_sql_name.schema, postgre_sql_name.identifier
  schemas = schema ? "ARRAY['#{schema}']" : 'current_schemas(false)'

  result = query("    SELECT distinct i.relname,\n                    d.indisunique,\n                    d.indkey,\n                    pg_get_indexdef(d.indexrelid),\n                    t.oid,\n                    am.amname,\n                    d.indclass,\n                    d.indoption\n    FROM pg_class t\n    INNER JOIN pg_index d ON t.oid = d.indrelid\n    INNER JOIN pg_class i ON d.indexrelid = i.oid\n    INNER JOIN pg_am    am ON i.relam = am.oid\n    WHERE i.relkind = 'i'\n      AND d.indisprimary = 'f'\n      AND t.relname = '\#{table}'\n      AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (\#{schemas}) )\n   ORDER BY i.relname\n  SQL\n\n  result.map do |row|\n    index = {\n      :name          => row[0],\n      :unique        => row[1] == 't',\n      :keys          => row[2].split(\" \"),\n      :definition    => row[3],\n      :id            => row[4],\n      :access_method => row[5], \n      :operators     => row[6].split(\" \"),\n      :options       => row[7].split(\" \").map(&:to_i)\n    }\n\n    column_names = find_column_names(table_name, index)\n\n    operator_names = find_operator_names(column_names, index)\n\n    unless column_names.empty?\n      where   = find_where_statement(index)\n      lengths = find_lengths(index)\n\n      PgSaurus::ConnectionAdapters::IndexDefinition.new(\n        table_name,\n        index[:name],\n        index[:unique],\n        column_names,\n        lengths,\n        where,\n        index[:access_method],\n        operator_names\n      )\n    end\n  end.compact\nend\n", name)

#remove_type(column_with_type) ⇒ String

Remove type specification from stored Postgres index definitions

Examples:

remove_type("((col)::text")
=> "col"

Parameters:

  • column_with_type (String)

    the name of the column with type

Returns:

  • (String)


256
257
258
# File 'lib/core_ext/active_record/connection_adapters/postgresql_adapter.rb', line 256

def remove_type(column_with_type)
  column_with_type.sub(/\((\w+)\)::\w+/, '\1')
end

#split_expression(expression) ⇒ Object

Splits only on commas outside of parens



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

def split_expression(expression)
  result = []
  parens = 0
  buffer = ""

  expression.chars do |char|
    case char
    when ','
      if parens == 0
        result.push(buffer)
        buffer = ""
        next
      end
    when '('
      parens += 1
    when ')'
      parens -= 1
    end

    buffer << char
  end

  result << buffer unless buffer.empty?
  result
end

#tables(name = nil) ⇒ Object

Returns the list of all tables in the schema search path or a specified schema.

Patch:

If current user is not ‘postgres` original method return all tables from all schemas without schema prefix. This disables such behavior by querying only default schema. Tables with schemas will be queried later.



25
26
27
28
29
30
31
# File 'lib/core_ext/active_record/connection_adapters/postgresql_adapter.rb', line 25

def tables(name = nil)
  query("      SELECT tablename\n      FROM pg_tables\n      WHERE schemaname = ANY (ARRAY['public'])\n  SQL\nend\n", 'SCHEMA').map { |row| row[0] }