Class: OnlineMigrations::BackgroundMigrations::BackfillColumn

Inherits:
OnlineMigrations::BackgroundMigration show all
Defined in:
lib/online_migrations/background_migrations/backfill_column.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from OnlineMigrations::BackgroundMigration

named

Constructor Details

#initialize(table_name, updates, model_name = nil) ⇒ BackfillColumn

Returns a new instance of BackfillColumn.



9
10
11
12
13
# File 'lib/online_migrations/background_migrations/backfill_column.rb', line 9

def initialize(table_name, updates, model_name = nil)
  @table_name = table_name
  @updates = updates
  @model_name = model_name
end

Instance Attribute Details

#model_nameObject (readonly)

Returns the value of attribute model_name.



7
8
9
# File 'lib/online_migrations/background_migrations/backfill_column.rb', line 7

def model_name
  @model_name
end

#table_nameObject (readonly)

Returns the value of attribute table_name.



7
8
9
# File 'lib/online_migrations/background_migrations/backfill_column.rb', line 7

def table_name
  @table_name
end

#updatesObject (readonly)

Returns the value of attribute updates.



7
8
9
# File 'lib/online_migrations/background_migrations/backfill_column.rb', line 7

def updates
  @updates
end

Instance Method Details

#countObject



33
34
35
36
37
38
# File 'lib/online_migrations/background_migrations/backfill_column.rb', line 33

def count
  # Exact counts are expensive on large tables, since PostgreSQL
  # needs to do a full scan. An estimated count should give a pretty decent
  # approximation of rows count in this case.
  Utils.estimated_count(connection, table_name)
end

#process_batch(relation) ⇒ Object



29
30
31
# File 'lib/online_migrations/background_migrations/backfill_column.rb', line 29

def process_batch(relation)
  relation.update_all(updates)
end

#relationObject



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/online_migrations/background_migrations/backfill_column.rb', line 15

def relation
  column, value = updates.first

  if updates.size == 1 && !value.nil?
    # If value is nil, the generated SQL is correct (`WHERE column IS NOT NULL`).
    # Otherwise, the SQL is `WHERE column != value`. This condition ignores column
    # with NULLs in it, so we need to also manually check for NULLs.
    quoted_column = connection.quote_column_name(column)
    model.unscoped.where("#{quoted_column} != ? OR #{quoted_column} IS NULL", value)
  else
    model.unscoped.where.not(updates)
  end
end