Module: Switchman::ActiveRecord::PostgreSQLAdapter

Defined in:
lib/switchman/active_record/postgresql_adapter.rb

Instance Method Summary collapse

Instance Method Details

#add_index_options(_table_name, _column_name) ⇒ Object



226
227
228
229
230
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 226

def add_index_options(_table_name, _column_name, **)
  index_name, index_type, index_columns, index_options, algorithm, using = super
  algorithm = nil if DatabaseServer.creating_new_shard && algorithm == "CONCURRENTLY"
  [index_name, index_type, index_columns, index_options, algorithm, using]
end

#columnsObject



254
255
256
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 254

def columns(*)
  with_local_table_name(false) { super }
end

#create_database(name, options = {}) ⇒ Object

copy/paste; use quote_local_table_name



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 7

def create_database(name, options = {})
  options = { encoding: 'utf8' }.merge!(options.symbolize_keys)

  option_string = options.sum do |key, value|
    case key
      when :owner
        " OWNER = \"#{value}\""
      when :template
        " TEMPLATE = \"#{value}\""
      when :encoding
        " ENCODING = '#{value}'"
      when :collation
        " LC_COLLATE = '#{value}'"
      when :ctype
        " LC_CTYPE = '#{value}'"
      when :tablespace
        " TABLESPACE = \"#{value}\""
      when :connection_limit
        " CONNECTION LIMIT = #{value}"
      else
        ""
    end
  end

  execute "CREATE DATABASE #{quote_local_table_name(name)}#{option_string}"
end

#current_schemasObject



39
40
41
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 39

def current_schemas
  select_values("SELECT * FROM unnest(current_schemas(false))")
end

#drop_database(name) ⇒ Object

copy/paste; use quote_local_table_name



35
36
37
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 35

def drop_database(name) #:nodoc:
  execute "DROP DATABASE IF EXISTS #{quote_local_table_name(name)}"
end

#extract_schema_qualified_name(string) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 43

def extract_schema_qualified_name(string)
  name = ::ActiveRecord::ConnectionAdapters::PostgreSQL::Utils.extract_schema_qualified_name(string.to_s)
  if string && !name.schema
    name.instance_variable_set(:@schema, shard.name)
  end
  [name.schema, name.identifier]
end

#foreign_keys(table_name) ⇒ Object



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
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 155

def foreign_keys(table_name)
  # mostly copy-pasted from AR - only change is to the nspname condition for qualified names support
  fk_info = select_all "    SELECT t2.oid::regclass::text AS to_table, a1.attname AS column, a2.attname AS primary_key, c.conname AS name, c.confupdtype AS on_update, c.confdeltype AS on_delete\n    FROM pg_constraint c\n    JOIN pg_class t1 ON c.conrelid = t1.oid\n    JOIN pg_class t2 ON c.confrelid = t2.oid\n    JOIN pg_attribute a1 ON a1.attnum = c.conkey[1] AND a1.attrelid = t1.oid\n    JOIN pg_attribute a2 ON a2.attnum = c.confkey[1] AND a2.attrelid = t2.oid\n    JOIN pg_namespace t3 ON c.connamespace = t3.oid\n    WHERE c.contype = 'f'\n      AND t1.relname = \#{quote(table_name)}\n      AND t3.nspname = '\#{shard.name}'\n    ORDER BY c.conname\n  SQL\n\n  fk_info.map do |row|\n    options = {\n      column: row['column'],\n      name: row['name'],\n      primary_key: row['primary_key']\n    }\n\n    options[:on_delete] = extract_foreign_key_action(row['on_delete'])\n    options[:on_update] = extract_foreign_key_action(row['on_update'])\n\n    # strip the schema name from to_table if it matches\n    to_table = row['to_table']\n    to_table_qualified_name = ::ActiveRecord::ConnectionAdapters::PostgreSQL::Utils.extract_schema_qualified_name(to_table)\n    if to_table_qualified_name.schema == shard.name\n      to_table = to_table_qualified_name.identifier\n    end\n\n    ::ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(table_name, to_table, options)\n  end\nend\n".strip_heredoc

#index_name_exists?(table_name, index_name, _default = nil) ⇒ Boolean

Returns:

  • (Boolean)


142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 142

def index_name_exists?(table_name, index_name, _default = nil)
  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_name}'\n        AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = '\#{shard.name}' )\n  SQL\nend\n", 'SCHEMA').rows.first[0].to_i > 0

#indexes(table_name) ⇒ Object



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
132
133
134
135
136
137
138
139
140
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 96

def indexes(table_name)
  result = query("    SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid\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 d.indisprimary = 'f'\n      AND t.relname = '\#{table_name}'\n      AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = '\#{shard.name}' )\n    ORDER BY i.relname\n  SQL\n\n\n  result.map do |row|\n    index_name = row[0]\n    unique = row[1] == true || row[1] == 't'\n    indkey = row[2].split(\" \")\n    inddef = row[3]\n    oid = row[4]\n\n    columns = Hash[query(<<-SQL, \"SCHEMA\")]\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    column_names = columns.stringify_keys.values_at(*indkey).compact\n\n    unless column_names.empty?\n      # add info on sort order for columns (only desc order is explicitly specified, asc is the default)\n      desc_order_columns = inddef.scan(/(\\w+) DESC/).flatten\n      orders = desc_order_columns.any? ? Hash[desc_order_columns.map {|order_column| [order_column, :desc]}] : {}\n      where = inddef.scan(/WHERE (.+)$/).flatten[0]\n      using = inddef.scan(/USING (.+?) /).flatten[0].to_sym\n\n      if ::Rails.version >= \"5.2\"\n        ::ActiveRecord::ConnectionAdapters::IndexDefinition.new(table_name, index_name, unique, column_names, orders: orders, where: where, using: using)\n      else\n        ::ActiveRecord::ConnectionAdapters::IndexDefinition.new(table_name, index_name, unique, column_names, [], orders, where, nil, using)\n      end\n    end\n  end.compact\nend\n", 'SCHEMA')

#quote_local_table_name(name) ⇒ Object



202
203
204
205
206
207
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 202

def quote_local_table_name(name)
  # postgres quotes tables and columns the same; just pass through
  # (differs from quote_table_name_with_shard below by no logic to
  # explicitly qualify the table)
  quote_column_name(name)
end

#quote_table_name(name) ⇒ Object



209
210
211
212
213
214
215
216
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 209

def quote_table_name(name)
  return quote_local_table_name(name) if @use_local_table_name
  name = ::ActiveRecord::ConnectionAdapters::PostgreSQL::Utils.extract_schema_qualified_name(name.to_s)
  if !name.schema
    name.instance_variable_set(:@schema, shard.name)
  end
  name.quoted
end

#quoted_scope(name = nil, type: nil) ⇒ Object

significant change: use the shard name if no explicit schema



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 52

def quoted_scope(name = nil, type: nil)
  schema, name = extract_schema_qualified_name(name)
  type = \
    case type
    when "BASE TABLE"
      "'r','p'"
    when "VIEW"
      "'v','m'"
    when "FOREIGN TABLE"
      "'f'"
    end
  scope = {}
  scope[:schema] = quote(schema || shard.name)
  scope[:name] = quote(name) if name
  scope[:type] = type if type
  scope
end

#rename_index(table_name, old_name, new_name) ⇒ Object



248
249
250
251
252
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 248

def rename_index(table_name, old_name, new_name)
  validate_index_length!(table_name, new_name)

  execute "ALTER INDEX #{quote_table_name(old_name)} RENAME TO #{quote_local_table_name(new_name)}"
end

#rename_table(table_name, new_name) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 232

def rename_table(table_name, new_name)
  clear_cache!
  execute "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_local_table_name(new_name)}"
  pk, seq = pk_and_sequence_for(new_name)
  if pk
    idx = "#{table_name}_pkey"
    new_idx = "#{new_name}_pkey"
    execute "ALTER INDEX #{quote_table_name(idx)} RENAME TO #{quote_local_table_name(new_idx)}"
    if seq && seq.identifier == "#{table_name}_#{pk}_seq"
      new_seq = "#{new_name}_#{pk}_seq"
      execute "ALTER TABLE #{seq.quoted} RENAME TO #{quote_local_table_name(new_seq)}"
    end
  end
  rename_table_indexes(table_name, new_name)
end

#tables(name = nil) ⇒ Object



71
72
73
74
75
76
77
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 71

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

#view_exists?(name) ⇒ Boolean

Returns:

  • (Boolean)


79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 79

def view_exists?(name)
  name = ::ActiveRecord::ConnectionAdapters::PostgreSQL::Utils.extract_schema_qualified_name(name.to_s)
  return false unless name.identifier
  if !name.schema
    name.instance_variable_set(:@schema, shard.name)
  end

  select_values("    SELECT c.relname\n    FROM pg_class c\n    LEFT JOIN pg_namespace n ON n.oid = c.relnamespace\n    WHERE c.relkind IN ('v','m') -- (v)iew, (m)aterialized view\n    AND c.relname = '\#{name.identifier}'\n    AND n.nspname = '\#{shard.name}'\n  SQL\nend\n", 'SCHEMA').any?

#with_local_table_name(enable = true) ⇒ Object



218
219
220
221
222
223
224
# File 'lib/switchman/active_record/postgresql_adapter.rb', line 218

def with_local_table_name(enable = true)
  old_value = @use_local_table_name
  @use_local_table_name = enable
  yield
ensure
  @use_local_table_name = old_value
end