Module: StoryTeller::Snapshots

Defined in:
lib/story_teller/snapshots.rb

Overview

The Snapshots module

Constant Summary collapse

GzipMagicBytes =
[0x1F, 0x8B].freeze
TableExclusions =

Adjust exclusions as needed

%i[
  schema_migrations
  ar_internal_metadata
  sequel_migrations
].freeze
SelectSerialSequence =

rubocop: enable Metrics/AbcSize rubocop: enable Metrics/CyclomaticComplexity rubocop: enable Metrics/MethodLength rubocop: enable Metrics/PerceivedComplexity

'SELECT pg_get_serial_sequence(?, ?) AS seq'.freeze
SelectSetvalTemplate =
'SELECT setval(%<sequence>s, %<max_id>s, true)'.freeze

Class Method Summary collapse

Class Method Details

.denormalize_row(db, table, row) ⇒ Object

rubocop: enable Metrics/CyclomaticComplexity rubocop: enable Metrics/MethodLength



220
221
222
223
224
225
226
227
228
229
230
# File 'lib/story_teller/snapshots.rb', line 220

def denormalize_row(db, table, row)
  schema = db.schema(table)
  types = schema.to_h.transform_values { |info| info[:type] }

  out = {}
  row.each do |k, v|
    type = types[k.to_sym]
    out[k.to_sym] = parse_value(v, type)
  end
  out
end

.export_to_file(filename) ⇒ Object

rubocop: disable Metrics/AbcSize rubocop: disable Metrics/CyclomaticComplexity rubocop: disable Metrics/MethodLength



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/story_teller/snapshots.rb', line 284

def export_to_file(filename)
  db = Sequel::Model.db
  tables = ordered_world_tables(db)

  tables_payload = tables.map do |table|
    pk = primary_key_for_table(db, table)
    s_fk = self_fk_column(db, table)

    rows = db[table].all
    # Stable base order, then parent-first for self-FK if applicable.
    rows = rows.sort_by { |r| r[pk] || 0 } if pk
    rows = order_rows_by_self_fk(rows, pk, s_fk)
    rows = rows.map { |r| normalize_row(r) }

    {
      name: table.to_s,
      primary_key: pk&.to_s,
      self_foreign_key: s_fk&.to_s,
      rows: rows
    }
  end

  data = {
    version: 1,
    created_at: Time.now.utc.iso8601,
    tables: tables_payload
  }

  File.open(filename, 'wb') do |file|
    Zlib::GzipWriter.wrap(file) { |gz| gz.write(JSON.generate(data)) }
  end

  filename
end

.gzipped?(filename) ⇒ Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/story_teller/snapshots.rb', line 65

def gzipped?(filename)
  File.binread(filename, 2).bytes == GzipMagicBytes
end

.import_from_file(filename) ⇒ Object

rubocop: disable Metrics/AbcSize rubocop: disable Metrics/CyclomaticComplexity rubocop: disable Metrics/MethodLength rubocop: disable Metrics/PerceivedComplexity



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/story_teller/snapshots.rb', line 345

def import_from_file(filename)
  db = Sequel::Model.db
  data = read_snapshot_file(filename)

  unless data[:version] == 1
    raise "Unsupported snapshot version: #{data[:version].inspect}"
  end

  snapshot_tables = Array(data[:tables])
  table_rows_by_name = snapshot_tables.to_h do |t|
    [t[:name].to_s, Array(t[:rows])]
  end

  table_syms = snapshot_tables.map { |t| t[:name].to_sym }
  ordered = ordered_world_tables(db, only_tables: table_syms)

  db.transaction do
    truncate_tables(db, ordered)

    ordered.each do |table|
      rows = table_rows_by_name[table.to_s] || []
      next if rows.empty?
      next unless db.table_exists?(table)

      denorm = rows.map { |r| denormalize_row(db, table, r) }
      db[table].multi_insert(denorm) unless denorm.empty?
    end

    reseed_sequences(db, ordered)
  end

  filename
end

.normalize_row(row) ⇒ Object

rubocop: enable Metrics/MethodLength



192
193
194
# File 'lib/story_teller/snapshots.rb', line 192

def normalize_row(row)
  row.transform_values { |v| normalize_value(v) }
end

.normalize_value(value) ⇒ Object

rubocop: disable Metrics/MethodLength



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/story_teller/snapshots.rb', line 174

def normalize_value(value)
  case value
  when Time
    value.utc.iso8601
  when DateTime
    value.to_time.utc.iso8601
  when Date
    value.iso8601
  when BigDecimal
    value.to_s("F")
  when Sequel::SQL::Blob
    { __blob__: Base64.strict_encode64(value) }
  else
    value
  end
end

.order_rows_by_self_fk(rows, pk_col, parent_col) ⇒ Object

rubocop: disable Metrics/AbcSize rubocop: disable Metrics/CyclomaticComplexity rubocop: disable Metrics/MethodLength rubocop: disable Metrics/PerceivedComplexity



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/story_teller/snapshots.rb', line 236

def order_rows_by_self_fk(rows, pk_col, parent_col)
  return rows if rows.empty?
  return rows unless pk_col && parent_col

  by_id = {}
  rows.each { |r| by_id[r[pk_col]] = r }

  in_degree = Hash.new(0)
  children = Hash.new { |h, k| h[k] = [] }

  rows.each do |r|
    id = r[pk_col]
    parent_id = r[parent_col]
    next if parent_id.nil?
    next unless by_id.key?(parent_id)

    in_degree[id] += 1
    children[parent_id] << id
  end

  queue = rows.select { |r| in_degree[r[pk_col]].zero? }.map { |r| r[pk_col] }.sort

  ordered = []
  until queue.empty?
    id = queue.shift
    row = by_id[id]
    ordered << row if row

    children[id].sort.each do |child_id|
      in_degree[child_id] -= 1
      queue << child_id if in_degree[child_id].zero?
    end
  end

  # If cycle or missing nodes, append remaining deterministically.
  remaining_ids = by_id.keys - ordered.map { |r| r[pk_col] }
  remaining_ids.sort.each { |id| ordered << by_id[id] }

  ordered
end

.ordered_world_tables(db, only_tables: nil) ⇒ Object



83
84
85
86
87
# File 'lib/story_teller/snapshots.rb', line 83

def ordered_world_tables(db, only_tables: nil)
  tables = only_tables ? only_tables.map(&:to_sym) : world_tables(db)
  deps = table_dependencies(db, tables)
  topo_sort_tables(tables, deps)
end

.parse_value(value, type) ⇒ Object

rubocop: disable Metrics/CyclomaticComplexity rubocop: disable Metrics/MethodLength



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/story_teller/snapshots.rb', line 198

def parse_value(value, type)
  return nil if value.nil?

  if value.is_a?(Hash) && value.key?(:__blob__)
    return Sequel::SQL::Blob.new(Base64.decode64(value[:__blob__]))
  end

  case type
  when :datetime, :timestamp
    value.is_a?(String) ? Time.iso8601(value) : value
  when :date
    value.is_a?(String) ? Date.iso8601(value) : value
  else
    value
  end
rescue ArgumentError
  # If parsing fails, keep original value to avoid hard failure.
  value
end

.primary_key_for_table(db, table) ⇒ Object



154
155
156
157
158
159
160
161
162
# File 'lib/story_teller/snapshots.rb', line 154

def primary_key_for_table(db, table)
  pk = db.primary_key(table)
  return pk if pk.is_a?(Symbol)

  # Fallback: detect first PK column from schema
  schema = db.schema(table)
  pk_cols = schema.map { |name, info| info[:primary_key] ? name : nil }.compact
  pk_cols.length == 1 ? pk_cols.first : nil
end

.read_snapshot_file(filename) ⇒ Object



69
70
71
72
73
74
75
76
77
# File 'lib/story_teller/snapshots.rb', line 69

def read_snapshot_file(filename)
  data = if gzipped?(filename)
    Zlib::GzipReader.open(filename, &:read)
  else
    File.read(filename)
  end

  JSON.parse(data, symbolize_names: true)
end

.reseed_sequences(db, tables) ⇒ Object

rubocop: disable Metrics/CyclomaticComplexity rubocop: disable Metrics/MethodLength



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/story_teller/snapshots.rb', line 388

def reseed_sequences(db, tables)
  return unless db.database_type == :postgres

  tables.each do |table|
    next unless db.table_exists?(table)

    pk = primary_key_for_table(db, table)
    next unless pk

    max_id = db[table].max(pk)
    next unless max_id

    seq_row = db.fetch(SelectSerialSequence, table.to_s, pk.to_s).first
    seq_name = seq_row && seq_row[:seq]
    next unless seq_name

    db.run(format(SelectSetvalTemplate, sequence: db.literal(seq_name), max_id: max_id))
  end
end

.safe_foreign_key_list(db, table) ⇒ Object

rubocop: enable Metrics/AbcSize rubocop: enable Metrics/CyclomaticComplexity rubocop: enable Metrics/MethodLength rubocop: enable Metrics/PerceivedComplexity



148
149
150
151
152
# File 'lib/story_teller/snapshots.rb', line 148

def safe_foreign_key_list(db, table)
  db.foreign_key_list(table)
rescue Sequel::NotImplemented
  []
end

.self_fk_column(db, table) ⇒ Object



164
165
166
167
168
169
170
171
# File 'lib/story_teller/snapshots.rb', line 164

def self_fk_column(db, table)
  fks = safe_foreign_key_list(db, table)
  self_fk = fks.find { |fk| fk[:table].to_sym == table.to_sym }
  return nil unless self_fk

  cols = Array(self_fk[:columns])
  cols.length == 1 ? cols.first : nil
end

.table_dependencies(db, tables) ⇒ Object

rubocop: disable Metrics/AbcSize rubocop: disable Metrics/CyclomaticComplexity rubocop: disable Metrics/MethodLength rubocop: disable Metrics/PerceivedComplexity



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/story_teller/snapshots.rb', line 93

def table_dependencies(db, tables)
  table_set = tables.to_h { |t| [t, true] }
  deps = {}
  tables.each { |t| deps[t] = {} }

  tables.each do |table|
    fks = safe_foreign_key_list(db, table)
    fks.each do |fk|
      parent = fk[:table]&.to_sym
      next unless parent
      next unless table_set[parent]
      next if parent == table # self-FK handled at row ordering level

      deps[table][parent] = true
    end
  end

  deps
end

.topo_sort_tables(tables, deps) ⇒ Object

rubocop: disable Metrics/AbcSize rubocop: disable Metrics/CyclomaticComplexity rubocop: disable Metrics/MethodLength rubocop: disable Metrics/PerceivedComplexity



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/story_teller/snapshots.rb', line 121

def topo_sort_tables(tables, deps)
  remaining = tables.to_h { |t| [t, true] }
  incoming = deps.transform_values(&:dup)

  ordered = []
  loop do
    roots = remaining.keys.select { |t| incoming[t].empty? }.sort_by(&:to_s)
    break if roots.empty?

    roots.each do |root|
      ordered << root
      remaining.delete(root)
      incoming.delete(root)
      incoming.each_value { |parents| parents.delete(root) }
    end
  end

  return ordered if remaining.empty?

  cycle = remaining.keys.sort_by(&:to_s)
  raise "Foreign key table dependency cycle detected among: #{cycle.join(', ')}"
end

.truncate_tables(db, tables) ⇒ Object

rubocop: disable Metrics/MethodLength



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/story_teller/snapshots.rb', line 323

def truncate_tables(db, tables)
  if db.database_type == :postgres
    existing = tables.select { |t| db.table_exists?(t) }
    return if existing.empty?

    table_list = existing.map { |t| db.literal(t) }.join(", ")
    db.run("TRUNCATE TABLE #{table_list} RESTART IDENTITY CASCADE")
    return
  end

  # For other DBs, truncate/delete children first (reverse dependency order).
  tables.reverse_each do |table|
    next unless db.table_exists?(table)
    db[table].truncate
  end
end

.world_tables(db) ⇒ Object



79
80
81
# File 'lib/story_teller/snapshots.rb', line 79

def world_tables(db)
  db.tables.reject { |t| TableExclusions.include?(t) }
end