Class: Hecks::Adapters::D1

Inherits:
Object
  • Object
show all
Includes:
SqlQueryBuilder, Sqlite::Codec, Sqlite::SchemaBuilder
Defined in:
lib/hecks/adapters/driven/d1.rb

Overview

Cloudflare D1 — SQLite, managed, reached over its REST API rather than a local file. D1 IS SQLite, dialect and all, so this file reuses Sqlite::SchemaBuilder and Sqlite::Codec UNCHANGED (the DDL and the column encode/decode) and SqlQueryBuilder's dialect hooks are copied near-verbatim from sqlite.rb — the only real difference is the transport (D1::Connection, an HTTP call per query, vs a persistent local sqlite3 handle). See sqlite.rb's own header comment: "this file supplies only SQLite's dialect" — true here too.

Defined Under Namespace

Classes: Connection

Constant Summary collapse

SQL_TYPES =
{ "Integer" => "INTEGER", "Float" => "REAL" }.freeze

Constants included from SqlQueryBuilder

SqlQueryBuilder::COMPARATORS

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from SqlQueryBuilder

#query

Constructor Details

#initialize(aggregate:, settings: {}, root: nil) ⇒ D1

Returns a new instance of D1.



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/hecks/adapters/driven/d1.rb', line 119

def initialize(aggregate:, settings: {}, root: nil)
  @aggregate = aggregate

    = settings.key?(:account_id)  ? settings[:account_id]  : settings["account_id"]
  database_id = settings.key?(:database_id) ? settings[:database_id] : settings["database_id"]
  api_token   = settings.key?(:api_token)   ? settings[:api_token]   : settings["api_token"]
  { "account_id" => , "database_id" => database_id, "api_token" => api_token }.each do |name, value|
    raise Runtime::WiringError, "D1 needs a #{name.inspect} in its world settings" if value.to_s.empty?
  end

  @db = Connection.new(account_id: , database_id: database_id, api_token: api_token)
  # THE OPTIONAL saga-persistence capability's own scoping column
  # (§2/§4) — D1's domain isolation is by whole-database identity
  # (one D1 database per domain in practice), so unlike Sqlite's
  # own per-aggregate-file default, there's no "which file does
  # this end up in" ambiguity here: every aggregate on D1 within a
  # domain already shares one database.
  @domain = (
    if settings.key?(:domain)
      settings[:domain]
    elsif settings.key?("domain")
      settings["domain"]
    else
      aggregate.name
    end
  ).to_s

  # No PRAGMA synchronous here, unlike Sqlite — D1 is a managed
  # durable service; there is no local fsync policy for a caller to
  # tune, and the query endpoint has no PRAGMA write-access to it.
  create_aggregate_table!
  create_entry_table!
  ensure_entry_operation_column!
  ensure_entry_mirrors_column!
  create_event_table!
  create_saga_table!
end

Instance Attribute Details

#aggregateObject (readonly)

Returns the value of attribute aggregate.



115
116
117
# File 'lib/hecks/adapters/driven/d1.rb', line 115

def aggregate
  @aggregate
end

Instance Method Details

#all(order_by: nil, direction: :asc) ⇒ Object

order_by IS A RUNTIME VALUE — see postgres.rb's own all for the full reasoning; whitelisted the identical way, same order_clause Sqlite's own all reuses (D1 speaks the identical dialect).



169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/hecks/adapters/driven/d1.rb', line 169

def all(order_by: nil, direction: :asc)
  order_sql = "ORDER BY id"
  if order_by
    name = order_by.to_s.split(".").first
    raise Runtime::WiringError, "#{@aggregate.name} has no attribute #{order_by.inspect} to order by" unless @aggregate.lifecycle&.field.to_s == name || @aggregate.attribute(name)

    spec = QuerySpecification::Common::OrderBy.new(field: order_by, direction: direction)
    order_sql = "ORDER BY #{order_clause(spec, nil)}"
  end

  @db.execute("SELECT * FROM #{quoted_table} #{order_sql}").map do |row|
    Runtime::Instance.new(aggregate: @aggregate, id: row["id"], state: decode(row))
  end
end

#append(entry) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/hecks/adapters/driven/d1.rb', line 186

def append(entry)
  @db.execute(
    "INSERT INTO #{quoted_entry_table} (aggregate_id, operation, state, mirrors) VALUES (?, ?, ?, ?)",
    # `mirrors` (unlike `state`) is a NULLABLE column — an absent
    # mirrors hash must bind a real SQL NULL, not the four-character
    # JSON text `"null"` (`JSON.generate(nil)`), or a future `IS NULL`
    # check against it would never match. Same guard `postgres_era.rb`
    # already uses for its own journal's `mirrors` column.
    [entry.id, entry.operation, JSON.generate(entry.state), entry.mirrors && JSON.generate(entry.mirrors)]
  )
  entry
end

#atomic_put(entry, insert_only: false) ⇒ Object

Classification, durable journal append and current-state projection are one D1 batch transaction and therefore one HTTP request. The first statement supplies the outcome from database state inside that same transaction; the runtime performs no preliminary find.

insert_only: used to spend a SEPARATE, EARLIER round trip finding out whether the row existed before ever building the batch — a real TOCTOU gap (two concurrent creates at the same identity could both pass that check before either wrote). D1's batch has no conditional BRANCH of its own, true, but it does not need one: a batch's own statements already execute in order, atomically, as one transaction (Connection#batch's own comment) — the exact guarantee the single- connection adapters' own @db.transaction do ... end gets locally. So the existence check moves INSIDE the batch as its own first statement, and the two writes are individually gated with WHERE NOT EXISTS (...) against that same table, evaluated in the same transaction — a row that already existed makes both writes into real, zero-row no-ops rather than skipping them from the Ruby side, matching Sqlite#atomic_put's next (skip append AND project both, together) with no second HTTP call and no gap for another writer to land in between the check and the write.



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
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
# File 'lib/hecks/adapters/driven/d1.rb', line 259

def atomic_put(entry, insert_only: false)
  instance = Runtime::Instance.new(aggregate: @aggregate, id: entry.id, state: entry.state)
  columns = (["id"] + persisted_fields.map { |field| field[:name].to_s }).map { |column| quote_ident(column) }
  values = [instance.id.to_s] + persisted_fields.map { |field| encode_field(field, instance[field[:name]]) }
  slots = Array.new(columns.size, "?").join(", ")
  not_exists = "WHERE NOT EXISTS (SELECT 1 FROM #{quoted_table} WHERE id = ?)"

  status_sql =
    if insert_only
      "SELECT CASE WHEN EXISTS (SELECT 1 FROM #{quoted_table} WHERE id = ?) " \
        "THEN 'conflicted' ELSE 'inserted' END AS status"
    else
      "SELECT CASE WHEN EXISTS (SELECT 1 FROM #{quoted_table} WHERE id = ?) " \
        "THEN 'replaced' ELSE 'inserted' END AS status"
    end

  # `mirrors` is NULLABLE (unlike `state`) — see `append`'s own comment.
  encoded_mirrors = entry.mirrors && JSON.generate(entry.mirrors)

  entry_sql, entry_binds =
    if insert_only
      [
        "INSERT INTO #{quoted_entry_table} (aggregate_id, operation, state, mirrors) " \
        "SELECT ?, ?, ?, ? #{not_exists}",
        [entry.id, entry.operation, JSON.generate(entry.state), encoded_mirrors, entry.id.to_s]
      ]
    else
      [
        "INSERT INTO #{quoted_entry_table} (aggregate_id, operation, state, mirrors) VALUES (?, ?, ?, ?)",
        [entry.id, entry.operation, JSON.generate(entry.state), encoded_mirrors]
      ]
    end

  aggregate_sql, aggregate_binds =
    if insert_only
      [
        "INSERT INTO #{quoted_table} (#{columns.join(', ')}) SELECT #{slots} #{not_exists}",
        values + [entry.id.to_s]
      ]
    else
      [
        "INSERT OR REPLACE INTO #{quoted_table} (#{columns.join(', ')}) VALUES (#{slots})",
        values
      ]
    end

  results = @db.batch([
                        [status_sql, [entry.id.to_s]],
                        [entry_sql, entry_binds],
                        [aggregate_sql, aggregate_binds]
                      ])

  results.fetch(0).fetch(0).fetch("status").to_sym
end

#countObject



184
# File 'lib/hecks/adapters/driven/d1.rb', line 184

def count = @db.get_first_value("SELECT COUNT(*) FROM #{quoted_table}").to_i

#delete(id) ⇒ Object



314
315
316
317
318
319
# File 'lib/hecks/adapters/driven/d1.rb', line 314

def delete(id)
  entry = Ports::Persistence::Entry.new(operation: "delete", id: id.to_s, state: nil)
  append(entry)
  project(entry)
  true
end

#delete_saga(process_manager:, correlation:) ⇒ Object



352
353
354
355
356
357
# File 'lib/hecks/adapters/driven/d1.rb', line 352

def delete_saga(process_manager:, correlation:)
  @db.execute(
    "DELETE FROM hecks_saga_instances WHERE domain = ? AND process_manager = ? AND correlation = ?",
    [@domain, process_manager.to_s, correlation.to_s]
  )
end

#each_sagaObject



359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/hecks/adapters/driven/d1.rb', line 359

def each_saga
  return enum_for(:each_saga) unless block_given?

  @db.execute(
    "SELECT process_manager, correlation, state, memory, completed_compensations FROM hecks_saga_instances WHERE domain = ?",
    [@domain]
  ).each do |row|
    yield row["process_manager"], row["correlation"], row["state"],
          JSON.parse(row["memory"], symbolize_names: true),
          JSON.parse(row["completed_compensations"] || "[]", symbolize_names: true)
  end
end

#entriesObject



214
215
216
217
218
219
220
221
222
223
224
# File 'lib/hecks/adapters/driven/d1.rb', line 214

def entries
  @db.execute("SELECT aggregate_id, operation, state, mirrors FROM #{quoted_entry_table} ORDER BY sequence").map do |row|
    state = JSON.parse(row["state"])
    Ports::Persistence::Entry.new(
      operation: row["operation"] || "save",
      id:        row["aggregate_id"],
      state:     state&.transform_keys(&:to_sym),
      mirrors:   row["mirrors"] && JSON.parse(row["mirrors"])
    )
  end
end

#eventsObject



328
329
330
331
332
333
334
335
336
337
338
# File 'lib/hecks/adapters/driven/d1.rb', line 328

def events
  @db.execute("SELECT * FROM events ORDER BY id").map do |row|
    Runtime::Event.new(
      name:        row["name"],
      aggregate:   row["aggregate"],
      id:          row["aggregate_id"],
      payload:     JSON.parse(row["payload"], symbolize_names: true),
      occurred_at: row["occurred_at"]
    )
  end
end

#find(id) ⇒ Object



159
160
161
162
163
164
# File 'lib/hecks/adapters/driven/d1.rb', line 159

def find(id)
  row = @db.get_first_row("SELECT * FROM #{quoted_table} WHERE id = ?", [id.to_s])
  return nil unless row

  Runtime::Instance.new(aggregate: @aggregate, id: row["id"], state: decode(row))
end

#persistence_capabilitiesObject



117
# File 'lib/hecks/adapters/driven/d1.rb', line 117

def persistence_capabilities = [:atomic_put]

#project(entry) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/hecks/adapters/driven/d1.rb', line 199

def project(entry)
  return @db.execute("DELETE FROM #{quoted_table} WHERE id = ?", [entry.id]) if entry.delete?

  instance = Runtime::Instance.new(aggregate: @aggregate, id: entry.id, state: entry.state)
  columns = (["id"] + persisted_fields.map { |field| field[:name].to_s }).map { |c| quote_ident(c) }
  values  = [instance.id.to_s] + persisted_fields.map { |field| encode_field(field, instance[field[:name]]) }
  slots   = Array.new(columns.size, "?").join(", ")

  @db.execute(
    "INSERT OR REPLACE INTO #{quoted_table} (#{columns.join(', ')}) VALUES (#{slots})",
    values
  )
  instance
end

#record_event(event) ⇒ Object



321
322
323
324
325
326
# File 'lib/hecks/adapters/driven/d1.rb', line 321

def record_event(event)
  @db.execute(
    "INSERT INTO events (name, aggregate, aggregate_id, payload, occurred_at) VALUES (?, ?, ?, ?, ?)",
    [event.name, event.aggregate, event.id.to_s, JSON.generate(event.payload), event.occurred_at]
  )
end

#reset!Object



226
227
228
229
230
# File 'lib/hecks/adapters/driven/d1.rb', line 226

def reset!
  @db.execute("DELETE FROM #{quoted_table}")
  @db.execute("DELETE FROM #{quoted_entry_table}")
  self
end

#save(instance) ⇒ Object



232
233
234
235
236
# File 'lib/hecks/adapters/driven/d1.rb', line 232

def save(instance)
  entry = Ports::Persistence::Entry.new(operation: "save", id: instance.id.to_s, state: instance.state.dup)
  append(entry)
  project(entry)
end

#save_saga(process_manager:, correlation:, state:, memory:, completed_compensations: []) ⇒ Object

── the OPTIONAL saga-persistence capability (§2) — reuses the DDL Sqlite::SchemaBuilder already shares with Sqlite (d1.rb's own file header). Same ?-placeholder shape every other write here already uses through Connection#execute.



344
345
346
347
348
349
350
# File 'lib/hecks/adapters/driven/d1.rb', line 344

def save_saga(process_manager:, correlation:, state:, memory:, completed_compensations: [])
  @db.execute(
    "INSERT OR REPLACE INTO hecks_saga_instances (domain, process_manager, correlation, state, memory, completed_compensations) " \
    "VALUES (?, ?, ?, ?, ?, ?)",
    [@domain, process_manager.to_s, correlation.to_s, state.to_s, JSON.generate(memory), JSON.generate(completed_compensations)]
  )
end

#tableObject



157
# File 'lib/hecks/adapters/driven/d1.rb', line 157

def table = @aggregate.storage_name