Class: ConcurrentPipeline::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/concurrent_pipeline/store.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema:, version:) ⇒ Store

Returns a new instance of Store.



21
22
23
24
25
26
27
28
# File 'lib/concurrent_pipeline/store.rb', line 21

def initialize(schema:, version:)
  @schema = schema
  @version = version
  @klasses = {}

  # eagerly construct classes
  schema.records.each_value { class_for(_1) }
end

Instance Attribute Details

#schemaObject (readonly)

Returns the value of attribute schema.



20
21
22
# File 'lib/concurrent_pipeline/store.rb', line 20

def schema
  @schema
end

#versionObject (readonly)

Returns the value of attribute version.



20
21
22
# File 'lib/concurrent_pipeline/store.rb', line 20

def version
  @version
end

Class Method Details

.define(&block) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/concurrent_pipeline/store.rb', line 5

def self.define(&block)
  schema = Stores::Schema.new
  schema.instance_exec(&block)

  klass = Class.new(Store) do
    define_method(:schema) { schema }
  end

  schema.records.each do |name, spec|
    define_method(name) { class_for(spec) }
  end

  klass.new(schema:, version: :root)
end

Instance Method Details

#restoreObject



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
# File 'lib/concurrent_pipeline/store.rb', line 44

def restore
  raise "Can only restore from a version snapshot, not from root" if root?

  # Copy the version database to the main database
  main_db = File.join(schema.dir, "db.sqlite3")
  FileUtils.cp(db_path, main_db)

  # Renumber versions: keep all versions up to and including this one,
  # then create a new version snapshot for the restore
  version_files = Dir.glob(File.join(schema.dir, "versions", "*.sqlite3")).sort
  version_files.each do |file|
    file_version = File.basename(file, ".sqlite3").to_i
    if file_version > version
      FileUtils.rm(file)
    end
  end

  # Create a new version snapshot of the restored state
  new_version_num = version + 1
  version_file = File.join(schema.dir, "versions", "#{new_version_num}.sqlite3")
  FileUtils.cp(main_db, version_file)

  # Return a new root store for the restored state
  Store.new(schema: schema, version: :root)
end

#transactionObject



30
31
32
# File 'lib/concurrent_pipeline/store.rb', line 30

def transaction(&)
  base_class.transaction(&)
end

#versionsObject



34
35
36
37
38
39
40
41
42
# File 'lib/concurrent_pipeline/store.rb', line 34

def versions
  return [self] unless root?

  version_files = Dir.glob(File.join(schema.dir, "versions", "*.sqlite3")).sort
  version_files.map do |file|
    version_num = File.basename(file, ".sqlite3").to_i
    Store.new(schema: schema, version: version_num)
  end
end