Class: ColdStorage::SchemaMirror

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/cold_storage/schema_mirror.rb

Overview

Copies the table definitions of the archivable models (and of the tables they cascade into) from the primary database to the archive database, and keeps them in sync when migrations change them.

Deliberate differences from the source schema:

* no foreign keys       - an archive holds partial object graphs
* no NOT NULL, no default values (configurable) - a schema that got
stricter later must never reject rows archived before that
* columns are added, never dropped (configurable) - archived rows keep
the columns they were archived with
* one extra column, `archived_at`

Defined Under Namespace

Classes: Change

Constant Summary

Constants included from Logging

Logging::PREFIX

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(models: nil, dry_run: ColdStorage.config.dry_run, logger_prefix: nil) ⇒ SchemaMirror

Returns a new instance of SchemaMirror.

Parameters:

  • models (Array<Class>, nil) (defaults to: nil)

    defaults to every archivable model

  • dry_run (Boolean) (defaults to: ColdStorage.config.dry_run)

    plan only, never touch the archive database



31
32
33
34
35
36
# File 'lib/cold_storage/schema_mirror.rb', line 31

def initialize(models: nil, dry_run: ColdStorage.config.dry_run, logger_prefix: nil)
  @models  = models
  @dry_run = dry_run
  @logger_prefix = logger_prefix
  @changes = []
end

Instance Attribute Details

#changesObject (readonly)

Returns the value of attribute changes.



27
28
29
# File 'lib/cold_storage/schema_mirror.rb', line 27

def changes
  @changes
end

Instance Method Details

#planArray<Change> Also known as: check

Returns what sync! would apply; empty means "in sync".

Returns:

  • (Array<Change>)

    what sync! would apply; empty means "in sync"



45
46
47
# File 'lib/cold_storage/schema_mirror.rb', line 45

def plan
  run(apply: false)
end

#source_modelsObject



60
61
62
# File 'lib/cold_storage/schema_mirror.rb', line 60

def source_models
  @source_models ||= (@models || ColdStorage.models).map { |m| m.is_a?(String) ? m.constantize : m }
end

#sync!Array<Change>

Applies the changes.

Returns:

  • (Array<Change>)

    what was applied



40
41
42
# File 'lib/cold_storage/schema_mirror.rb', line 40

def sync!
  run(apply: !@dry_run)
end

#tablesHash{String => Class}

Tables the archive database is expected to hold, derived from the models.

Returns:

  • (Hash{String => Class})

    table name => source model



52
53
54
55
56
57
58
# File 'lib/cold_storage/schema_mirror.rb', line 52

def tables
  @tables ||= begin
    map = {}
    source_models.each { |model| collect_tables(model, map) }
    map
  end
end