Module: ActiveRecord::ConnectionAdapters::PostgreSQL::SchemaStatements

Defined in:
lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb

Overview

:nodoc:

Constant Summary collapse

FUNCTIONAL_INDEX_REGEXP =

Regexp used to find the function name and function argument of a function call:

/(\w+)\(((?:'.+'(?:::\w+)?, *)*)(\w+)\)/
OPERATOR_REGEXP =

Regexp used to find the operator name (or operator string, e.g. “DESC NULLS LAST”):

/(.+?)\s([\w\s]+)$/
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 (.+)$/

Instance Method Summary collapse

Instance Method Details

#add_index(table_name, column_name, options = {}) ⇒ Object

Redefine original add_index method to handle :concurrently option.

Adds a new index to the table. column_name can be a single Symbol, or an Array of Symbols.

Creating a partial index
add_index(:accounts, [:branch_id, :party_id], :using => 'BTree'
 :unique => true, :concurrently => true, :where => 'active')

generates

CREATE UNIQUE INDEX CONCURRENTLY
 index_accounts_on_branch_id_and_party_id
ON
  accounts(branch_id, party_id)
WHERE
  active


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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb', line 131

def add_index(table_name, column_name, options = {})
  creation_method = options.delete(:concurrently) ? 'CONCURRENTLY' : nil

  # Whether to skip the quoting of columns. Used only for expressions like JSON indexes in which
  # the column is difficult to target for quoting.
  skip_column_quoting = options.delete(:skip_column_quoting) or false

  index_name,
  index_type,
  index_columns_and_opclasses,
  index_options,
  index_algorithm,
  index_using,
  comment = add_index_options(table_name, column_name, options)

  # GOTCHA:
  #   It ensures that there is no existing index only for the case when the index
  #   is created concurrently to avoid changing the error behavior for default
  #   index creation.
  #   -- zekefast 2012-09-25
  # GOTCHA:
  #   This check prevents invalid index creation, so after migration failed
  #   here there is no need to go to database and clean it from invalid
  #   indexes. But note that this handles only one of the cases when index
  #   creation can fail!!! All other case should be procesed manually.
  #   -- zekefast 2012-09-25
  if creation_method.present? && index_exists?(table_name, column_name, options)
    raise ::PgSaurus::IndexExistsError,
          "Index #{index_name} for `#{table_name}.#{column_name}` " \
          "column can not be created concurrently, because such index already exists."
  end

  statements = []
  statements << "CREATE #{index_type} INDEX"
  statements << creation_method      if creation_method.present?
  statements << index_algorithm      if index_algorithm.present?
  statements << quote_column_name(index_name)
  statements << "ON"
  statements << quote_table_name(table_name)
  statements << index_using          if index_using.present?
  statements << "(#{index_columns_and_opclasses})" if index_columns_and_opclasses.present? unless skip_column_quoting
  statements << "(#{column_name})"   if column_name.present? and skip_column_quoting
  statements << index_options        if index_options.present?

  sql = statements.join(' ')
  execute(sql)
end

#index_exists?(table_name, column_name, options = {}) ⇒ Boolean

Check to see if an index exists on a table for a given index definition.

Examples

# Check that a partial index exists
index_exists?(:suppliers, :company_id, :where => 'active')

# GIVEN: 'index_suppliers_on_company_id' UNIQUE, btree (company_id) WHERE active
index_exists?(:suppliers, :company_id, :unique => true, :where => 'active') => true
index_exists?(:suppliers, :company_id, :unique => true) => false

Returns:

  • (Boolean)


189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb', line 189

def index_exists?(table_name, column_name, options = {})
  column_names = Array.wrap(column_name)
  index_name = options.key?(:name) ? options[:name].to_s : index_name(table_name, column: column_names)

  # Always compare the index name
  default_comparator = lambda { |index| index.name == index_name }
  comparators = [default_comparator]

  # Add a comparator for each index option that is part of the query
  index_options = [:unique, :where]
  index_options.each do |index_option|
    comparators << if options.key?(index_option)
      lambda do |index|
        pg_where_clause = index.send(index_option)
        # pg does nothing to boolean clauses, e.g. 'where active' => 'where active'
        if pg_where_clause.is_a?(TrueClass) or pg_where_clause.is_a?(FalseClass)
          pg_where_clause == options[index_option]
        else
          # pg adds parentheses around non-boolean clauses, e.g. 'where color IS NULL' => 'where (color is NULL)'
          pg_where_clause.gsub!(/[()]/,'')
          # pg casts string comparison ::text. e.g. "where color = 'black'" => "where ((color)::text = 'black'::text)"
          pg_where_clause.gsub!(/::text/,'')
          # prevent case from impacting the comparison
          pg_where_clause.downcase == options[index_option].downcase
        end
      end
    else
      # If the given index_option is not an argument to the index_exists? query,
      # select only those pg indexes that do not have the component
      lambda { |index| index.send(index_option).blank? }
    end
  end

  # Search all indexes for any that match all comparators
  indexes(table_name).any? do |index|
    comparators.inject(true) { |ret, comparator| ret && comparator.call(index) }
  end
end

#index_name(table_name, options) ⇒ Object

Derive the name of the index from the given table name and options hash.



229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb', line 229

def index_name(table_name, options) #:nodoc:
  if Hash === options # legacy support
    if options[:column]
      column_names = Array.wrap(options[:column]).map {|c| expression_index_name(c)}
      "index_#{table_name}_on_#{column_names * '_and_'}"
    elsif options[:name]
      options[:name]
    else
      raise ArgumentError, "You must specify the index name"
    end
  else
    index_name(table_name, column: options)
  end
end

#indexes(table_name) ⇒ Object

Returns an array of indexes for the given table.

Patch 1:

Remove type specification from stored Postgres index definitions.

Patch 2:

Split compound functional indexes to array.



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
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
# File 'lib/core_ext/active_record/connection_adapters/postgresql/schema_statements.rb', line 41

def indexes(table_name)
  scope = quoted_scope(table_name)

  result = query("    SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid,\n                    pg_catalog.obj_description(i.oid, 'pg_class') AS comment\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    LEFT JOIN  pg_namespace n  ON n.oid = i.relnamespace\n    WHERE i.relkind = 'i'\n      AND d.indisprimary = 'f'\n      AND t.relname = \#{scope[:name]}\n      AND n.nspname = \#{scope[:schema]}\n    ORDER BY i.relname\n  SQL\n\n  result.map do |row|\n    index_name = row[0]\n    unique     = row[1]\n    indkey     = row[2].split(\" \").map(&:to_i)\n    inddef     = row[3]\n    oid        = row[4]\n    comment    = row[5]\n\n    using, expressions, where = inddef.scan(/ USING (\\w+?) \\((.+?)\\)(?: WHERE (.+))?\\z/m).flatten\n\n    orders = {}\n    opclasses = {}\n\n    if indkey.include?(0)\n      definition = inddef.sub(INDEX_WHERE_EXPRESSION, '')\n\n      if column_expression = definition.match(INDEX_COLUMN_EXPRESSION)[1]\n        columns = split_expression(expressions).map do |functional_name|\n          remove_type(functional_name)\n        end\n\n        columns = columns.size > 1 ? columns : columns[0]\n      end\n    else\n      columns = Hash[query(<<-SQL.strip_heredoc, \"SCHEMA\")].values_at(*indkey).compact\n        SELECT a.attnum, a.attname\n        FROM pg_attribute a\n        WHERE a.attrelid = \#{oid}\n        AND a.attnum IN (\#{indkey.join(\",\")})\n      SQL\n\n      # add info on sort order (only desc order is explicitly specified, asc is the default)\n      # and non-default opclasses\n      expressions.scan(/(?<column>\\w+)\"?\\s?(?<opclass>\\w+_ops)?\\s?(?<desc>DESC)?\\s?(?<nulls>NULLS (?:FIRST|LAST))?/).each do |column, opclass, desc, nulls|\n        opclasses[column] = opclass.to_sym if opclass\n        if nulls\n          orders[column] = [desc, nulls].compact.join(\" \")\n        else\n          orders[column] = :desc if desc\n        end\n      end\n    end\n\n    IndexDefinition.new(\n      table_name,\n      index_name,\n      unique,\n      columns,\n      orders:    orders,\n      opclasses: opclasses,\n      where:     where,\n      using:     using.to_sym,\n      comment:   comment.presence\n    )\n  end\nend\n", "SCHEMA")

#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/schema_statements.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] }